<?php /*

 ocPortal
 Copyright (c) ocProducts, 2004-2012

 See text/EN/licence.txt for full licencing information.


 NOTE TO PROGRAMMERS:
   Do not edit this file. If you need to make changes, save your changed file to the appropriate *_custom folder
   **** If you ignore this advice, then your website upgrades (e.g. for bug fixes) will likely kill your changes ****

*/

/**
 * @license		http://opensource.org/licenses/cpal_1.0 Common Public Attribution License
 * @copyright	ocProducts Ltd
 * @package		galleries
 */

require_code('aed_module');

/**
 * Module page class.
 */
class Module_cms_galleries extends standard_aed_module
{
	var $lang_type='IMAGE';
	var $select_name_description='DESCRIPTION_IMAGE';
	var $select_name='IMAGE';
	var $permissions_require='mid';
	var $permissions_cat_require='galleries';
	var $permissions_cat_name='cat';
	var $user_facing=true;
	var $seo_type='image';
	var $upload='image';
	var $award_type='image';
	var $javascript='standardAlternateFields(\'file\',\'url\'); standardAlternateFields(\'file2\',\'thumb_url\');';
	var $menu_label='GALLERIES';
	var $table='images';

	var $donext_type=NULL;

	/**
	 * Standard modular entry-point finder function.
	 *
	 * @return ?array	A map of entry points (type-code=>language-code) (NULL: disabled).
	 */
	function get_entry_points()
	{
		return array_merge(array('misc'=>'MANAGE_GALLERIES')+(has_specific_permission(get_member(),'mass_import','cms_galleries')?array('gimp'=>'GALLERY_IMPORT'):array()),parent::get_entry_points());
	}

	/**
	 * Standard modular privilege-overide finder function.
	 *
	 * @return array	A map of privileges that are overridable; sp to 0 or 1. 0 means "not category overridable". 1 means "category overridable".
	 */
	function get_sp_overrides()
	{
		require_lang('galleries');
		return array('mass_import'=>0,'have_personal_category'=>0,'submit_cat_midrange_content'=>array(0,'ADD_GALLERY'),'edit_own_cat_midrange_content'=>array(0,'EDIT_OWN_GALLERY'),'edit_cat_midrange_content'=>array(0,'EDIT_GALLERY'),'delete_own_cat_midrange_content'=>array(0,'DELETE_OWN_GALLERY'),'delete_cat_midrange_content'=>array(0,'DELETE_GALLERY'),'may_download_gallery'=>1,'submit_midrange_content'=>array(1,'ADD_MEDIA'),'bypass_validation_midrange_content'=>array(1,'BYPASS_VALIDATION_MEDIA'),'edit_own_midrange_content'=>array(1,'EDIT_OWN_MEDIA'),'edit_midrange_content'=>array(1,'EDIT_MEDIA'),'delete_own_midrange_content'=>array(1,'DELETE_OWN_MEDIA'),'delete_midrange_content'=>array(1,'DELETE_MEDIA'));
	}

	/**
	 * Standard aed_module run_start.
	 *
	 * @param  ID_TEXT		The type of module execution
	 * @return tempcode		The output of the run
	 */
	function run_start($type)
	{
		require_code('galleries');
		require_code('galleries2');
		require_lang('galleries');
		require_css('galleries');
		require_lang('dearchive');

		$GLOBALS['HELPER_PANEL_TUTORIAL']='tut_galleries';
		$GLOBALS['HELPER_PANEL_PIC']='pagepics/images';

		$this->cat_aed_module=new Module_cms_galleries_cat();
		$this->alt_aed_module=new Module_cms_galleries_alt();
		$GLOBALS['MODULE_CMS_GALLERIES']=$this;

		$this->alt_aed_module->add_text=new ocp_tempcode();

		global $NON_CANONICAL_PARAMS;
		$NON_CANONICAL_PARAMS[]='cat';

		$cat=get_param('cat','');
		if ($cat!='')
		{
			if (strpos($type,'d')!==false)
			{
				$remaining=$this->check_images_allowed($cat,true);
				if (!is_null($remaining))
				{
					$this->add_text=paragraph(do_lang_tempcode('X_ENTRIES_REMAINING',integer_format($remaining)));
				}
			} elseif (strpos($type,'v')!==false)
			{
				$remaining=$this->alt_aed_module->check_videos_allowed($cat,true);
				if (!is_null($remaining))
				{
					$this->alt_aed_module->add_text->attach(paragraph(do_lang_tempcode('X_ENTRIES_REMAINING',integer_format($remaining))));
				}
			}
		}
		if (get_option('allow_audio_videos')=='1')
		{
			$this->alt_aed_module->add_text->attach(paragraph(do_lang_tempcode('ALSO_AUDIO')));
		}

		if ($type=='ac')
		{
			require_javascript('javascript_ajax');
			$script=find_script('snippet');
			$this->cat_aed_module->javascript.="
				var form=document.getElementById('main_form');
				form.old_submit=form.onsubmit;
				form.onsubmit=function()
					{
						document.getElementById('submit_button').disabled=true;
						var url='".addslashes($script)."?snippet=exists_gallery&name='+window.encodeURIComponent(form.elements['name'].value);
						if (!do_ajax_field_test(url))
						{
							document.getElementById('submit_button').disabled=false;
							return false;
						}
						document.getElementById('submit_button').disabled=false;
						if (typeof form.old_submit!='undefined' && form.old_submit) return form.old_submit();
						return true;
					};
			";
		}

		// Decide what to do
		if ($type=='misc') return $this->misc();
		if ($type=='gimp') return $this->gimp();
		if ($type=='_gimp') return $this->_gimp();
		if ($type=='__gimp') return $this->__gimp();
		if ($type=='ss') return $this->ss();
		if ($type=='sa') return $this->sa();
		if ($type=='sd') return $this->sd();

		return new ocp_tempcode();
	}

	/**
	 * The do-next manager for before content management.
	 *
	 * @return tempcode		The UI
	 */
	function misc()
	{
		$allow_images=($GLOBALS['SITE_DB']->query_value('galleries','COUNT(*)',array('accept_images'=>1))>0);
		$allow_videos=($GLOBALS['SITE_DB']->query_value('galleries','COUNT(*)',array('accept_videos'=>1))>0);

		require_code('templates_donext');
		require_code('fields');
		return do_next_manager(get_page_title('MANAGE_GALLERIES'),comcode_lang_string('DOC_GALLERIES'),
					array_merge(array(
						/*	 type							  page	 params													 zone	  */
						has_specific_permission(get_member(),'submit_cat_midrange_content','cms_galleries')?array('add_one_category',array('_SELF',array('type'=>'ac'),'_SELF'),do_lang('ADD_GALLERY')):NULL,
						has_specific_permission(get_member(),'edit_own_cat_midrange_content','cms_galleries')?array('edit_one_category',array('_SELF',array('type'=>'ec'),'_SELF'),do_lang('EDIT_GALLERY')):NULL,
						has_specific_permission(get_member(),'mass_import','cms_galleries')?array('import',array('_SELF',array('type'=>'gimp'),'_SELF'),do_lang('GALLERY_IMPORT'),('DOC_GALLERY_IMPORT')):NULL,
						(!$allow_images)?NULL:has_specific_permission(get_member(),'submit_midrange_content','cms_galleries')?array('add_one_image',array('_SELF',array('type'=>'ad'),'_SELF'),do_lang('ADD_IMAGE')):NULL,
						(!$allow_images)?NULL:has_specific_permission(get_member(),'edit_own_midrange_content','cms_galleries')?array('edit_one_image',array('_SELF',array('type'=>'ed'),'_SELF'),do_lang('EDIT_IMAGE')):NULL,
						(!$allow_videos)?NULL:has_specific_permission(get_member(),'submit_midrange_content','cms_galleries')?array('add_one_video',array('_SELF',array('type'=>'av'),'_SELF'),do_lang('ADD_VIDEO')):NULL,
						(!$allow_videos)?NULL:has_specific_permission(get_member(),'edit_own_midrange_content','cms_galleries')?array('edit_one_video',array('_SELF',array('type'=>'ev'),'_SELF'),do_lang('EDIT_VIDEO')):NULL,
					),manage_custom_fields_donext_link('image'),manage_custom_fields_donext_link('video'),manage_custom_fields_donext_link('gallery')),
					do_lang('MANAGE_GALLERIES')
		);
	}

	/**
	 * The UI to choose a gallery to import into.
	 *
	 * @return tempcode		The UI
	 */
	function gimp()
	{
		$title=get_page_title('GALLERY_IMPORT');

		check_specific_permission('mass_import');

		breadcrumb_set_parents(array(array('_SELF:_SELF:misc',do_lang_tempcode('MANAGE_GALLERIES'))));

		breadcrumb_set_self(do_lang_tempcode('CHOOSE'));

		$condition='only_member_galleries_of_id';
		$member_id=get_param_integer('id',-1);
		if ($member_id==-1)
		{
			$condition='only_conventional_galleries';
			$member_id=NULL;
			$default='';
		} else
		{
			$default='';
		}
		$post_url=build_url(array('page'=>'_SELF','type'=>'_gimp'),'_SELF',NULL,false,true);
		require_code('form_templates');
		$fields=new ocp_tempcode();
		$fields->attach(form_input_tree_list(do_lang_tempcode('GALLERY'),'','name',NULL,'choose_gallery',array('purity'=>false,'filter'=>$condition,'member_id'=>$member_id),true,''));
		$submit_name=do_lang_tempcode('GALLERY_IMPORT');

		return do_template('FORM_SCREEN',array('_GUID'=>'5213edb75c8d534c121b587c555a3b9a','TITLE'=>$title,'SKIP_VALIDATION'=>true,'GET'=>true,'HIDDEN'=>'','TEXT'=>'','FIELDS'=>$fields,'URL'=>$post_url,'SUBMIT_NAME'=>$submit_name,'JAVASCRIPT'=>'standardAlternateFields(\'name\',\'name2\');'));
	}

	/**
	 * The UI to import into a gallery.
	 *
	 * @return tempcode		The UI
	 */
	function _gimp()
	{
		$cat=get_param('name','root');
		check_specific_permission('mass_import'/*,array('galleries',$cat)*/);

		if (substr($cat,0,7)!='member_')
		{
			$test=$GLOBALS['SITE_DB']->query_value_null_ok('galleries','name',array('name'=>$cat));
			if (is_null($test)) warn_exit(do_lang_tempcode('MISSING_RESOURCE'));
		}

		$title=get_page_title('GALLERY_IMPORT');

		require_code('form_templates');
		require_lang('trackbacks');

		// To choose to batch import from an attached tar or zip file (zip file only supported if zip module running on php install)
		$post_url=build_url(array('page'=>'_SELF','type'=>'__gimp','cat'=>$cat,'uploading'=>1,'redirect'=>get_param('redirect',NULL)),'_SELF');
		$fields=new ocp_tempcode();
		$supported='tar';
		if ((function_exists('zip_open')) || (get_option('unzip_cmd')!='')) $supported.=', zip';
		$fields->attach(form_input_upload_multi(do_lang_tempcode('UPLOAD'),do_lang_tempcode('DESCRIPTION_ARCHIVE_MEDIA',escape_html($supported),escape_html(str_replace(',',', ',get_option('valid_images').','.get_allowed_video_file_types()))),'file',true,NULL,NULL,true,str_replace(' ','',get_option('valid_images').','.$supported)));
		$hidden=new ocp_tempcode();
		handle_max_file_size($hidden);
		if (get_option('is_on_gd')=='1')
		{
			if ($this->has_at_least_one_watermark($cat))
				$fields->attach(form_input_tick(do_lang_tempcode('WATERMARK'),do_lang_tempcode('DESCRIPTION_WATERMARK'),'watermark',true));
		}
		// Feedback
		require_code('feedback2');
		$fields->attach(feedback_fields(true,true,true,false,''));
		// Max upload limit
		require_code('files2');
		$max=floatval(get_max_file_size())/floatval(1024*1024);
		if ($max<30.0)
		{
			$config_url=get_upload_limit_config_url();
			$text=paragraph(do_lang_tempcode(is_null($config_url)?'MAXIMUM_UPLOAD':'MAXIMUM_UPLOAD_STAFF',escape_html(($max>10.0)?integer_format(intval($max)):float_format($max)),escape_html($config_url)));
		} else $text=new ocp_tempcode();
		// Show form
		$hidden->attach(form_input_hidden('test','1'));
		$form=do_template('FORM',array('_GUID'=>'05de2bc134ed0b1ab703ac8bfbfabce4','TABINDEX'=>strval(get_form_field_tabindex()),'FIELDS'=>$fields,'SUBMIT_NAME'=>do_lang_tempcode('BATCH_IMPORT_ARCHIVE_CONTENTS'),'URL'=>$post_url,'TEXT'=>$text,'HIDDEN'=>$hidden));

		// Orphaned upload form
		// To choose to batch import what already exists in gallery directory, but is orphaned
		$orphaned_content=new ocp_tempcode();
		if (($GLOBALS['FORUM_DRIVER']->is_staff(get_member())) && ($GLOBALS['SITE_DB']->query_value('images','COUNT(*)')+$GLOBALS['SITE_DB']->query_value('videos','COUNT(*)')<4000))
		{
			require_code('images');
			$there=array();
			$_dir=opendir(get_custom_file_base().'/uploads/galleries/');
			while (false!==($file=readdir($_dir)))
				if (($file!='index.html') && (!is_dir(get_custom_file_base().'/uploads/galleries/'.$file)) && ((is_image($file)) || (is_video($file))))
					$there[$file]=filemtime(get_custom_file_base().'/uploads/galleries/'.$file);
			closedir($_dir);
			$_dir=@opendir(get_custom_file_base().'/uploads/galleries/'.filter_naughty($cat));
			if ($_dir!==false)
			{
				while (false!==($file=readdir($_dir)))
					if (($file!='index.html') && (!is_dir(get_custom_file_base().'/uploads/galleries/'.$cat.'/'.$file)) && ((is_image($file)) || (is_video($file))))
						$there[$cat.'/'.$file]=filemtime(get_custom_file_base().'/uploads/galleries/'.$cat.'/'.$file);
				closedir($_dir);
			}
			if (count($there)!=0)
			{
				asort($there);
				$test1=collapse_1d_complexity('url',$GLOBALS['SITE_DB']->query_select('images',array('url')));
				$test2=collapse_1d_complexity('url',$GLOBALS['SITE_DB']->query_select('videos',array('url')));
				arsort($there);
				$temp_keys=array_keys($there);
				$last_time=$there[$temp_keys[0]];
				foreach ($there as $file=>$time)
				{
					if ((!in_array('uploads/galleries/'.str_replace('%2F','/',rawurlencode($file)),$test1)) && (!in_array('uploads/galleries/'.str_replace('%2F','/',rawurlencode($file)),$test2)))
					{
						$orphaned_content->attach(form_input_list_entry($file,($time>=$last_time-60*60*3) || (strpos($file,'/')!==false),$file));
						$o_url=get_custom_base_url().'/uploads/galleries/'.rawurlencode($file);
					}
				}
			}
			$add_url=build_url(array('page'=>'_SELF','type'=>'ss'),'_SELF');
			if (!$orphaned_content->is_empty())
			{
				$fields_2=new ocp_tempcode();
				$hidden_2=new ocp_tempcode();

				if (get_param_integer('keep_de_orphan',0)==1)
				{
					$cats=nice_get_gallery_tree($cat,NULL,false,false,false,false,NULL,true);
					$fields_2->attach(form_input_list(do_lang_tempcode('GALLERY'),'','cat',$cats));
				} else
				{
					$hidden_2->attach(form_input_hidden('cat',$cat));
				}
				$fields_2->attach(form_input_multi_list(do_lang_tempcode('ENTRIES'),'','files',$orphaned_content));
				if ($this->has_at_least_one_watermark($cat))
					$fields_2->attach(form_input_various_ticks(array(array(do_lang_tempcode('WATERMARK'),'watermark',true,''),array(do_lang_tempcode('ALLOW_RATING'),'allow_rating',true,''),array(do_lang_tempcode('ALLOW_COMMENTS'),'allow_comments',true,''),array(do_lang_tempcode('ALLOW_REVIEWS'),'allow_reviews',false,''),array(do_lang_tempcode('ALLOW_TRACKBACKS'),'allow_trackbacks',true,''),),'',NULL,do_lang_tempcode('OPTIONS')));
				$radios=new ocp_tempcode();
				$radios->attach(form_input_radio_entry('type','sa',true,do_lang_tempcode('ADD_GALLERY_SELECTION')));
				$radios->attach(form_input_radio_entry('type','sd',false,do_lang_tempcode('DELETE_GALLERY_SELECTION')));
				$fields_2->attach(form_input_radio(do_lang_tempcode('ACTION'),'','type',$radios,true));
				// Feedback
				require_code('feedback2');
				$fields_2->attach(feedback_fields(true,true,true,false,''));

				$form2=do_template('FORM',array('SECONDARY_FORM'=>true,'TABINDEX'=>strval(get_form_field_tabindex()),'FIELDS'=>$fields_2,'SUBMIT_NAME'=>do_lang_tempcode('PROCEED'),'URL'=>$add_url,'TEXT'=>'','HIDDEN'=>$hidden_2));
			} else $form2=new ocp_tempcode();
		} else $form2=new ocp_tempcode();

		breadcrumb_set_parents(array(array('_SELF:_SELF:misc',do_lang_tempcode('MANAGE_GALLERIES')),array('_SELF:_SELF:gimp',do_lang_tempcode('GALLERY'))));
		breadcrumb_set_self(do_lang_tempcode('UPLOAD'));

		return do_template('GALLERY_IMPORT_SCREEN',array('_GUID'=>'607c819ff751268294e5e590a0d41533','TITLE'=>$title,'FORM2'=>$form2,'FORM'=>$form));
	}

	/**
	 * The actualiser to import a zip/tar into a gallery.
	 *
	 * @return tempcode		The UI
	 */
	function __gimp()
	{
		$cat=get_param('cat');

		require_code('images');

		check_specific_permission('mass_import'/*,array('galleries',$cat)*/);

		post_param('test'); // To pick up on max file size exceeded errors

		make_member_gallery_if_needed($cat);

		require_code('uploads');
		if ((!is_swf_upload(true)) && ((!array_key_exists('file_1',$_FILES)) || (!is_uploaded_file($_FILES['file_1']['tmp_name']))))
			warn_exit(do_lang_tempcode('NO_PARAMETER_SENT','file'));

		if (get_value('use_gallery_subdirs')=='1')
		{
			if (!file_exists(get_custom_file_base().'/uploads/galleries/'.$cat))
			{
				mkdir(get_custom_file_base().'/uploads/galleries/'.$cat,0777);
				fix_permissions(get_custom_file_base().'/uploads/galleries/'.$cat,0777);
				sync_file('uploads/galleries/'.$cat);
			}
			if (!file_exists(get_custom_file_base().'/uploads/galleries_thumbs/'.$cat))
			{
				@mkdir(get_custom_file_base().'/uploads/galleries_thumbs/'.$cat,0777) OR warn_exit(do_lang_tempcode('WRITE_ERROR_DIRECTORY',get_custom_file_base().'/uploads/galleries_thumbs'));
				fix_permissions(get_custom_file_base().'/uploads/galleries_thumbs/'.$cat,0777);
				sync_file('uploads/galleries_thumbs/'.$cat);
			}
		}

		foreach ($_FILES as $attach_name=>$__file)
		{
			$tmp_name=$__file['tmp_name'];
			$file=$__file['name'];
			if ($file=='') continue; // Not filled in this one

			switch (get_file_extension($file))
			{
				case 'zip':
					if ((!function_exists('zip_open')) && (get_option('unzip_cmd')=='')) warn_exit(do_lang_tempcode('ZIP_NOT_ENABLED'));
					if (!function_exists('zip_open'))
					{
						require_code('m_zip');
						$mzip=true;
					} else $mzip=false;
					$myfile=zip_open($tmp_name);
					if (!is_integer($myfile))
					{
						while (false!==($entry=zip_read($myfile)))
						{
							// Load in file
							zip_entry_open($myfile,$entry);
							$tmp_name_2=ocp_tempnam('bi');
							$myfile2=fopen($tmp_name_2,'wb') OR intelligent_write_error($tmp_name_2);
							$more=mixed();
							do
							{
								$more=zip_entry_read($entry);
								if ($more!==false)
								{
									if (fwrite($myfile2,$more)<strlen($more)) warn_exit(do_lang_tempcode('COULD_NOT_SAVE_FILE'));
								}
							}
							while (($more!==false) && ($more!=''));
							fclose($myfile2);

							// Strip off our slash to gimp right
							$_file=zip_entry_name($entry);
							$slash=strrpos($_file,'/');
							if ($slash===false) $slash=strrpos($_file,"\\");
							if ($slash!==false) $_file=substr($_file,$slash+1);

							if ((is_image($_file)) || (is_video($_file))) $this->store_from_archive($_file,$tmp_name_2,$cat);

							zip_entry_close($entry);
						}

						zip_close($myfile);
					} else
					{
						require_code('failure');
						warn_exit(zip_error($myfile,$mzip));
					}
					break;
				case 'tar':
					require_code('tar');
					$myfile=tar_open($tmp_name,'rb');
					if ($myfile!==false)
					{
						$directory=tar_get_directory($myfile);

						// See if there is a numbering system to sort by
						$all_are=NULL;
						foreach ($directory as $entry)
						{
							$this_are=strtolower(preg_replace('#\d#','',$entry['path']));
							if (is_null($all_are)) $all_are=$this_are;
							if ($all_are!=$this_are)
							{
								$all_are=NULL;
								break;
							}
						}
						if (!is_null($all_are))
						{
							global $M_SORT_KEY;
							$M_SORT_KEY='path';
							usort($directory,'multi_sort');
						}

						foreach ($directory as $entry)
						{
							$tmp_name_2=ocp_tempnam('bi');

							// Load in file
							$_in=tar_get_file($myfile,$entry['path'],false,$tmp_name_2);

							// Strip off our slash to gimp right
							$_file=$entry['path'];
							$slash=strrpos($_file,'/');
							if ($slash===false) $slash=strrpos($_file,"\\");
							if ($slash!==false) $_file=substr($_file,$slash+1);

							if ((is_image($_file)) || (is_video($_file))) $this->store_from_archive($_file,$tmp_name_2,$cat);
							unset($_in);
						}

						tar_close($myfile);
					}
					break;
				default:
					if ((is_image($file)) || (is_video($file)))
					{
						$tmp_name_2=ocp_tempnam('bi');

						if ($__file['type']!='swfupload')
						{
							$test=@move_uploaded_file($tmp_name,$tmp_name_2);
						} else
						{
							$test=@copy($tmp_name,$tmp_name_2); // We could rename, but it would hurt integrity of refreshes
						}

						$this->store_from_archive($file,$tmp_name_2,$cat);
					} else
					{
						attach_message(do_lang_tempcode('BAD_ARCHIVE_FORMAT'),'warn');
					}
			}
		}

		$title=get_page_title('GALLERY_IMPORT');

		breadcrumb_set_parents(array(array('_SELF:_SELF:misc',do_lang_tempcode('MANAGE_GALLERIES')),array('_SELF:_SELF:gimp',do_lang_tempcode('CHOOSE')),array('_SELF:_SELF:_gimp:name='.$cat,do_lang_tempcode('GALLERY_IMPORT'))));

		if (!is_null(get_param('redirect',NULL)))
		{
			$url=make_string_tempcode(get_param('redirect'));
			return redirect_screen($title,$url,do_lang_tempcode('SUCCESS'));
		}

		return $this->cat_aed_module->_do_next_manager($title,do_lang_tempcode('SUCCESS'),$cat);
	}

	/**
	 * The actualiser to simple add/delete orphaned files in a gallery.
	 *
	 * @return tempcode		The UI
	 */
	function ss()
	{
		$cat=post_param('cat');

		require_code('images');
		require_code('exif');

		check_specific_permission('mass_import'/*,array('galleries',$cat)*/);

		if (!$GLOBALS['FORUM_DRIVER']->is_staff(get_member())) return new ocp_tempcode();

		make_member_gallery_if_needed($cat);

		if (array_key_exists('files',$_POST))
		{
			foreach ($_POST['files'] as $file)
			{
				$url='uploads/galleries/'.str_replace('%2F','/',rawurlencode($file));
				$thumb_url='uploads/galleries_thumbs/'.str_replace('%2F','/',rawurlencode($file));
				if (substr($thumb_url,-4,4)=='.gif') $thumb_url=substr($thumb_url,0,strlen($thumb_url)-4).'.png';
				if (is_video($url))
				{
					$ret=get_video_details(get_custom_file_base().'/uploads/galleries/'.filter_naughty($file),$file,true);
					if ($ret!==false)
					{
						list($width,$height,$length)=$ret;
						if (is_null($width)) $width=100;
						if (is_null($height)) $height=100;
						if (is_null($length)) $length=0;
						$exif=get_exif_data(get_custom_file_base().'/'.rawurldecode($url),$file);
						$id=add_video($exif['UserComment'],$cat,'',$url,'',1,post_param_integer('allow_rating',0),post_param_integer('allow_reviews',post_param_integer('allow_comments',0)),post_param_integer('allow_trackbacks',0),'',$length,$width,$height);
						store_exif('video',strval($id),$exif);

						if ((has_actual_page_access($GLOBALS['FORUM_DRIVER']->get_guest_id(),'galleries')) && (has_category_access($GLOBALS['FORUM_DRIVER']->get_guest_id(),'galleries',$cat)))
							syndicate_described_activity('galleries:ACTIVITY_ADD_VIDEO',($exif['UserComment']=='')?basename($url):$exif['UserComment'],'','','_SEARCH:galleries:video:'.strval($id),'','','galleries');
					}
				} else
				{
					$ok=true;
					if ((get_option('is_on_gd')=='1') && (function_exists('imagecreatefromstring')))
					{
						$subdirs=explode('/',rawurldecode($thumb_url));
						$subdir_buildup='';
						foreach ($subdirs as $subdir)
						{
							$subdir_buildup.=$subdir.'/';
							@mkdir(dirname(get_custom_file_base().'/'.$subdir_buildup),0777);
						}
						$ok=convert_image(get_custom_base_url().'/'.$url,get_custom_file_base().'/'.rawurldecode($thumb_url),-1,-1,intval(get_option('thumb_width')),false);
					}
					if ($ok)
					{
						$exif=get_exif_data(get_custom_file_base().'/'.rawurldecode($url),$file);
						$id=add_image($exif['UserComment'],$cat,'',$url,$thumb_url,1,post_param_integer('allow_rating',0),post_param_integer('allow_reviews',post_param_integer('allow_comments',0)),post_param_integer('allow_trackbacks',0),'');
						store_exif('image',strval($id),$exif);

						if ((has_actual_page_access($GLOBALS['FORUM_DRIVER']->get_guest_id(),'galleries')) && (has_category_access($GLOBALS['FORUM_DRIVER']->get_guest_id(),'galleries',$cat)))
							syndicate_described_activity('galleries:ACTIVITY_ADD_IMAGE',($exif['UserComment']=='')?basename($url):$exif['UserComment'],'','','_SEARCH:galleries:image:'.strval($id),'','','galleries');
					}
				}
			}
		}

		$title=get_page_title('GALLERY_IMPORT');

		breadcrumb_set_parents(array(array('_SELF:_SELF:misc',do_lang_tempcode('MANAGE_GALLERIES')),array('_SELF:_SELF:gimp',do_lang_tempcode('CHOOSE')),array('_SELF:_SELF:_gimp:name='.$cat,do_lang_tempcode('GALLERY_IMPORT'))));

		return $this->cat_aed_module->_do_next_manager($title,do_lang_tempcode('SUCCESS'),$cat);
	}

	/**
	 * Take some data and write it to be a file in the gallery uploads directory, and add it to a gallery.
	 *
	 * @param  string		The filename
	 * @param  PATH		Path to data file (will be copied from)
	 * @param  ID_TEXT	The gallery to add to
	 */
	function store_from_archive($file,&$in,$cat)
	{
		// Find where to store on server
		//  Hunt with sensible names until we don't get a conflict
		$place=get_custom_file_base().'/uploads/galleries'.((get_value('use_gallery_subdirs')=='1')?('/'.$cat):'').'/'.filter_naughty($file);
		$i=2;
		$_file=filter_naughty($file);
		while (file_exists($place))
		{
			$_file=strval($i).$file;
			$place=get_custom_file_base().'/uploads/galleries'.((get_value('use_gallery_subdirs')=='1')?('/'.$cat):'').'/'.$_file;
			$i++;
		}
		$place_thumb=get_custom_file_base().'/uploads/galleries_thumbs'.((get_value('use_gallery_subdirs')=='1')?('/'.$cat):'').'/'.filter_naughty($file);
		$i=2;
		$_file_thumb=filter_naughty($file);
		while (file_exists($place_thumb))
		{
			$_file_thumb=strval($i).$file;
			$place_thumb=get_custom_file_base().'/uploads/galleries_thumbs'.((get_value('use_gallery_subdirs')=='1')?('/'.$cat):'').'/'.$_file_thumb;
			$i++;
		}

		// Store on server
		if (rename($in,$place)===false) intelligent_write_error($place);
		fix_permissions($place);
		sync_file($place);

		$aurl='uploads/galleries'.((get_value('use_gallery_subdirs')=='1')?('/'.$cat):'').'/'.rawurlencode($_file);
		$thumb_url='uploads/galleries_thumbs'.((get_value('use_gallery_subdirs')=='1')?('/'.$cat):'').'/'.rawurlencode($_file_thumb);

		// Add to database
		$this->simple_add($aurl,$thumb_url,$_file,$cat);
	}

	/**
	 * The actualiser to simple add an orphan file to a gallery.
	 *
	 * @return tempcode		The UI
	 */
	function sa()
	{
		$cat=post_param('cat');

		check_specific_permission('mass_import'/*,array('galleries',$cat)*/);

		make_member_gallery_if_needed($cat);

		foreach ($_POST as $x=>$file)
		{
			if (!is_string($file)) continue;

			if (substr($x,0,5)=='file_')
			{
				$aurl='uploads/galleries/'.rawurlencode($file);

				$place_thumb=get_custom_file_base().'/uploads/galleries_thumbs/'.$file;
				$i=2;
				$_file_thumb=$file;
				while (file_exists($place_thumb))
				{
					$_file_thumb=strval($i).$file;
					$place_thumb=get_custom_file_base().'/uploads/galleries_thumbs/'.$_file_thumb;
					$i++;
				}
				$thumb_url='uploads/galleries_thumbs/'.rawurlencode($_file_thumb);

				$this->simple_add($aurl,$thumb_url,$file,$cat);
			}
		}

		$title=get_page_title('ADD_IMAGE');

		// Show it worked / Refresh
		$url=build_url(array('page'=>'_SELF','type'=>'_gimp','name'=>$cat),'_SELF');
		return redirect_screen($title,$url,do_lang_tempcode('SUCCESS'));
	}

	/**
	 * See if a gallery has any watermarks to use, or all galleries.
	 *
	 * @param  ?ID_TEXT	The gallery (NULL: all the current user has access to)
	 * @return boolean	Whether watermarks are available
	 */
	function has_at_least_one_watermark($cat=NULL)
	{
		$where='';
		if (!is_null($cat)) $where=db_string_equal_to('name',$cat).' AND ';
		$where.='('.db_string_not_equal_to('watermark_top_left','');
		$where.=' OR '.db_string_not_equal_to('watermark_top_left','');
		$where.=' OR '.db_string_not_equal_to('watermark_top_right','');
		$where.=' OR '.db_string_not_equal_to('watermark_bottom_left','');
		$where.=' OR '.db_string_not_equal_to('watermark_bottom_right','').')';
		$gals=$GLOBALS['SITE_DB']->query('SELECT name FROM '.get_table_prefix().'galleries WHERE '.$where);
		foreach ($gals as $guy)
		{
			$cat=$guy['name'];
			if (has_category_access(get_member(),'galleries',$cat)) return true;
		}

		return false;
	}

	/**
	 * Take a file in the gallery uploads directory, and add it to a gallery.
	 *
	 * @param  URLPATH	The URL to the file
	 * @param  URLPATH	The thumb URL to the file
	 * @param  string		The filename
	 * @param  ID_TEXT	The gallery to add to
	 */
	function simple_add($url,$thumb_url,$file,$cat)
	{
		require_code('exif');

		if (substr($thumb_url,-4,4)=='.gif') $thumb_url=substr($thumb_url,0,strlen($thumb_url)-4).'.png';
		if (is_video($url))
		{
			$ret=get_video_details(get_custom_file_base().'/'.rawurldecode($url),$file,true);
			if ($ret!==false)
			{
				list($width,$height,$length)=$ret;
				if (is_null($width)) $width=100;
				if (is_null($height)) $height=100;
				if (is_null($length)) $length=0;
				$exif=get_exif_data(get_custom_file_base().'/'.rawurldecode($url),$file);
				$id=add_video($exif['UserComment'],$cat,'',$url,'',1,post_param_integer('allow_rating',0),post_param_integer('allow_reviews',post_param_integer('allow_comments',0)),post_param_integer('allow_trackbacks',0),post_param('notes',''),$length,$width,$height);
				store_exif('video',strval($id),$exif);

				if ((has_actual_page_access($GLOBALS['FORUM_DRIVER']->get_guest_id(),'galleries')) && (has_category_access($GLOBALS['FORUM_DRIVER']->get_guest_id(),'galleries',$cat)))
					syndicate_described_activity('galleries:ACTIVITY_ADD_VIDEO',($exif['UserComment']=='')?basename($url):$exif['UserComment'],'','','_SEARCH:galleries:video:'.strval($id),'','','galleries');
			}
		} else
		{
			$ok=true;
			if ((get_option('is_on_gd')=='1') && (function_exists('imagecreatefromstring')))
			{
				require_code('images');
				$ok=convert_image(get_custom_base_url().'/'.$url,get_custom_file_base().'/'.rawurldecode($thumb_url),-1,-1,intval(get_option('thumb_width')),true);
			}
			if ($ok)
			{
				$exif=get_exif_data(get_custom_file_base().'/'.rawurldecode($url),$file);

				if ((get_option('is_on_gd')=='1') && (function_exists('imagecreatefromstring')))
				{
					// See if we need to resize the image
					constrain_gallery_image_to_max_size(get_custom_file_base().'/'.rawurldecode($url),$file,intval(get_option('maximum_image_size')));

					// See if we need to do watermarking
					$watermark=post_param_integer('watermark',0);
					if ($watermark==1)
					{
						watermark_gallery_image($cat,rawurldecode($url),$file);
					}
				}

				$id=add_image($exif['UserComment'],$cat,'',$url,$thumb_url,1,post_param_integer('allow_rating',0),post_param_integer('allow_reviews',post_param_integer('allow_comments',0)),post_param_integer('allow_trackbacks',0),post_param('notes',''));
				store_exif('image',strval($id),$exif);

				if ((has_actual_page_access($GLOBALS['FORUM_DRIVER']->get_guest_id(),'galleries')) && (has_category_access($GLOBALS['FORUM_DRIVER']->get_guest_id(),'galleries',$cat)))
					syndicate_described_activity('galleries:ACTIVITY_ADD_IMAGE',($exif['UserComment']=='')?basename($url):$exif['UserComment'],'','','_SEARCH:galleries:image:'.strval($id),'','','galleries');
			}
		}
	}

	/**
	 * The actualiser to simple delete an orphan file.
	 *
	 * @return tempcode		The UI
	 */
	function sd()
	{
		$cat=post_param('cat');

		check_specific_permission('mass_import'/*,array('galleries',$cat)*/);

		foreach ($_POST as $x=>$file)
		{
			if (!is_string($file)) continue;

			if (substr($x,0,5)=='file_')
			{
				$path=get_custom_file_base().'/uploads/galleries/'.filter_naughty($file);
				@unlink($path) OR intelligent_write_error($path);
				sync_file('uploads/galleries/'.$file);
			}
		}

		$title=get_page_title('DELETE_IMAGE');

		// Show it worked / Refresh
		$url=build_url(array('page'=>'_SELF','type'=>'_gimp','name'=>$cat),'_SELF');
		return redirect_screen($title,$url,do_lang_tempcode('SUCCESS'));
	}

	/**
	 * Filter any uploaded image such that it is watermarked.
	 */
	function handle_resizing_and_watermarking()
	{
		if (((is_swf_upload(true)) && (array_key_exists('file',$_FILES))) || ((array_key_exists('file',$_FILES)) && (array_key_exists('tmp_name',$_FILES['file'])) && (get_option('is_on_gd')=='1')))
		{
			// See if we need to resize the image
			constrain_gallery_image_to_max_size($_FILES['file']['tmp_name'],$_FILES['file']['name'],intval(get_option('maximum_image_size')));
			// See if we need to do watermarking
			$watermark=post_param_integer('watermark',0);
			if ($watermark==1)
			{
				watermark_gallery_image(post_param('cat'),$_FILES['file']['tmp_name'],$_FILES['file']['name']);
			}
		}
	}

	/**
	 * Kills ocPortal if someone is trying to add an image to a gallery that does not support images.
	 *
	 * @param  ID_TEXT		The gallery
	 * @param  boolean		Whether to tolerate the non-existance of the gallery
	 * @return ?integer		Number allowed remaining (NULL: no limit)
	 */
	function check_images_allowed($cat,$tolerate_non_exist=false)
	{
		// Check this cat allows images
		$gallery=$GLOBALS['SITE_DB']->query_select('galleries',array('accept_videos','accept_images','is_member_synched'),array('name'=>$cat),'',1);
		$owner=get_member_id_from_gallery_name($cat);
		if (!array_key_exists(0,$gallery))
		{
			if ($tolerate_non_exist)
			{
				$limit=mixed();
				if ((!has_specific_permission(get_member(),'no_personal_gallery_limit')) && ($owner==get_member()))
				{
					$limit=has_specific_permission(get_member(),'high_personal_gallery_limit')?intval(get_option('max_personal_gallery_images_high')):intval(get_option('max_personal_gallery_images_low'));
				}
				return $limit;
			}
			warn_exit(do_lang_tempcode('MISSING_RESOURCE'));
		}
		if (($gallery[0]['accept_images']==0) || ($gallery[0]['is_member_synched']==1)) warn_exit(do_lang_tempcode(($gallery[0]['accept_images']==1)?'ERROR_NOT_ACCEPT_CONTAINER':'ERROR_NOT_ACCEPT_IMAGES'));

		if ((!has_specific_permission(get_member(),'no_personal_gallery_limit')) && ($owner==get_member()))
		{
			$limit=has_specific_permission(get_member(),'high_personal_gallery_limit')?intval(get_option('max_personal_gallery_images_high')):intval(get_option('max_personal_gallery_images_low'));
			$count_already=$GLOBALS['SITE_DB']->query_value('images','COUNT(*)',array('cat'=>$cat));
			if ($count_already>=$limit)
				warn_exit(do_lang_tempcode('TOO_MANY_GALLERY_IMAGES'));

			return $limit-$count_already;
		}

		return NULL;
	}

	/**
	 * Standard aed_module list function.
	 *
	 * @return array				A triple: The tree field (tempcode), Search URL, Archive URL
	 */
	function nice_get_ajax_tree()
	{
		if ($GLOBALS['SITE_DB']->query_value('images','COUNT(*)')==0) warn_exit(do_lang_tempcode('NO_ENTRIES'));

		$search_url=build_url(array('page'=>'search','id'=>'images'),get_module_zone('search'));
		$archive_url=build_url(array('page'=>'galleries'),get_module_zone('galleries'));

		$only_owned=has_specific_permission(get_member(),'edit_midrange_content','cms_galleries')?NULL:get_member();
		$tree=form_input_tree_list(do_lang_tempcode('IMAGE'),do_lang_tempcode('DESCRIPTION_IMAGE'),'id',NULL,'choose_image',array('filter'=>'only_conventional_galleries','only_owned'=>$only_owned,'editable_filter'=>true),true);
		return array($tree,$search_url,$archive_url);
	}

	/**
	 * Get tempcode for an image adding/editing form.
	 *
	 * @param  SHORT_TEXT			The title
	 * @param  ID_TEXT			The gallery
	 * @param  LONG_TEXT			The image description
	 * @param  URLPATH			URL to the image
	 * @param  URLPATH			URL to the image thumbnail
	 * @param  BINARY				Image validation status
	 * @param  ?BINARY			Whether rating is allowed (NULL: decide statistically, based on existing choices)
	 * @param  ?SHORT_INTEGER	Whether comments are allowed (0=no, 1=yes, 2=review style) (NULL: decide statistically, based on existing choices)
	 * @param  ?BINARY			Whether trackbacks are allowed (NULL: decide statistically, based on existing choices)
	 * @param  LONG_TEXT			Notes for the image
	 * @param  boolean			Whether this form will be used for adding a new image
	 * @return array				A pair: the tempcode for the visible fields, and the tempcode for the hidden fields
	 */
	function get_form_fields($title='',$cat='',$comments='',$url='',$thumb_url='',$validated=1,$allow_rating=NULL,$allow_comments=NULL,$allow_trackbacks=NULL,$notes='',$adding=true)
	{
		list($allow_rating,$allow_comments,$allow_trackbacks)=$this->choose_feedback_fields_statistically($allow_rating,$allow_comments,$allow_trackbacks);

		global $NON_CANONICAL_PARAMS;
		$NON_CANONICAL_PARAMS[]='cat';
		$NON_CANONICAL_PARAMS[]='validated';

		if ($adding)
		{
			$cat=get_param('cat','');
		}

		require_code('images');
		$fields=new ocp_tempcode();
		$hidden=new ocp_tempcode();
		require_code('form_templates');
		handle_max_file_size($hidden,'image');
		if (strpos($cat,'?')!==false) $cat=str_replace('?',strval(get_member()),$cat);
		$filters=array('must_accept_images'=>true,'addable_filter'=>true);
		if (substr($cat,0,9)!='download_') $filters['filter']='only_conventional_galleries';
		$fields->attach(form_input_line(do_lang_tempcode('TITLE',do_lang_tempcode('TITLE')),do_lang_tempcode('DESCRIPTION_TITLE'),'title',$title,false));

		$fields->attach(form_input_tree_list(do_lang_tempcode('GALLERY'),do_lang_tempcode('DESCRIPTION_GALLERY'),'cat',NULL,'choose_gallery',$filters,true,$cat));
		$fields->attach(form_input_upload(do_lang_tempcode('UPLOAD'),do_lang_tempcode('DESCRIPTION_UPLOAD'),'file',false,NULL,NULL,true,str_replace(' ','',get_option('valid_images'))));
		$fields->attach(form_input_line(do_lang_tempcode('ALT_FIELD',do_lang_tempcode('URL')),do_lang_tempcode('DESCRIPTION_ALTERNATE_URL'),'url',$url,false));
		if (get_option('is_on_gd')=='0')
		{
			$thumb_width=get_option('thumb_width');
			$fields->attach(form_input_upload(do_lang_tempcode('THUMBNAIL'),do_lang_tempcode('DESCRIPTION_THUMBNAIL',escape_html($thumb_width)),'file2',false,NULL,NULL,true,str_replace(' ','',get_option('valid_images'))));
			$fields->attach(form_input_line(do_lang_tempcode('ALT_FIELD',do_lang_tempcode('URL')),do_lang_tempcode('DESCRIPTION_ALTERNATE_URL'),'thumb_url',$thumb_url,false));
		}
		$fields->attach(form_input_text_comcode(do_lang_tempcode('DESCRIPTION'),do_lang_tempcode('DESCRIPTION_DESCRIPTION_ACCESSIBILITY'),'comments',$comments,false));
		if ($validated==0)
		{
			$validated=get_param_integer('validated',0);
			if ($validated==1) attach_message(do_lang_tempcode('WILL_BE_VALIDATED_WHEN_SAVING'));
		}
		if (has_some_cat_specific_permission(get_member(),'bypass_validation_'.$this->permissions_require.'range_content',NULL,$this->permissions_cat_require))
			$fields->attach(form_input_tick(do_lang_tempcode('VALIDATED'),do_lang_tempcode('DESCRIPTION_VALIDATED'),'validated',$validated==1));

		$fields->attach(do_template('FORM_SCREEN_FIELD_SPACER',array('SECTION_HIDDEN'=>true,'TITLE'=>do_lang_tempcode('ADVANCED'))));
		if (get_option('is_on_gd')=='1')
		{
			$fields->attach(form_input_tick(do_lang_tempcode('WATERMARK'),do_lang_tempcode('DESCRIPTION_WATERMARK'),'watermark',true)); // Only applies to new uploads, so can't be watermarked twice
		}
		if (($cat=='') || (has_edit_permission('cat_mid',get_member(),get_member_id_from_gallery_name($cat),'cms_galleries',array('galleries',$cat))))
		{
			$fields->attach(form_input_tick(do_lang_tempcode('REPRESENTATIVE_IMAGE'),do_lang_tempcode('_DESCRIPTION_REPRESENTATIVE_IMAGE'),'rep_image',false));
		}

		require_code('feedback2');
		$fields->attach(feedback_fields($allow_rating==1,$allow_comments==1,$allow_trackbacks==1,false,$notes,$allow_comments==2));

		return array($fields,$hidden);
	}

	/**
	 * Standard aed_module submitter getter.
	 *
	 * @param  AUTO_LINK		The entry for which the submitter is sought
	 * @return array			The submitter, and the time of submission (null submission time implies no known submission time)
	 */
	function get_submitter($id)
	{
		$rows=$GLOBALS['SITE_DB']->query_select('images',array('submitter','add_date'),array('id'=>intval($id)),'',1);
		if (!array_key_exists(0,$rows)) return array(NULL,NULL);
		return array($rows[0]['submitter'],$rows[0]['add_date']);
	}

	/**
	 * Standard aed_module cat getter.
	 *
	 * @param  AUTO_LINK		The entry for which the cat is sought
	 * @return mixed			The cat
	 */
	function get_cat($id)
	{
		$temp=$GLOBALS['SITE_DB']->query_value_null_ok('images','cat',array('id'=>$id));
		if (is_null($temp)) warn_exit(do_lang_tempcode('MISSING_RESOURCE'));
		return $temp;
	}

	/**
	 * Standard aed_module edit form filler.
	 *
	 * @param  ID_TEXT		The entry being edited
	 * @return array			A tuple of lots of info
	 */
	function fill_in_edit_form($_id)
	{
		$id=intval($_id);

		$rows=$GLOBALS['SITE_DB']->query_select('images',array('*'),array('id'=>$id),'',1);
		if (!array_key_exists(0,$rows))
		{
			warn_exit(do_lang_tempcode('MISSING_RESOURCE'));
		}
		$myrow=$rows[0];
		$comments=get_translated_text($myrow['comments']);
		$cat=$myrow['cat'];
		$validated=$myrow['validated'];

		if (has_delete_permission('mid',get_member(),$myrow['submitter'],'cms_galleries',array('galleries',$cat)))
		{
			$radios=form_input_radio_entry('delete','0',true,do_lang_tempcode('LEAVE'));
			$radios->attach(form_input_radio_entry('delete','1',false,do_lang_tempcode('DELETE_PARTIAL')));
			$radios->attach(form_input_radio_entry('delete','2',false,do_lang_tempcode('DELETE_FULL')));
			$delete_fields=form_input_radio(do_lang_tempcode('DELETE_STATUS'),do_lang_tempcode('DESCRIPTION_DELETE_STATUS'),'delete',$radios);
		} else $delete_fields=new ocp_tempcode();

		list($fields,$hidden)=$this->get_form_fields(get_translated_text($myrow['title']),$cat,$comments,$myrow['url'],$myrow['thumb_url'],$validated,$myrow['allow_rating'],$myrow['allow_comments'],$myrow['allow_trackbacks'],$myrow['notes'],false);

		return array($fields,$hidden,$delete_fields,'',true);
	}

	/**
	 * Standard aed_module add actualiser.
	 *
	 * @return ID_TEXT		The ID of the entry added
	 */
	function add_actualisation()
	{
		$cat=post_param('cat');
		if (can_submit_to_gallery($cat)===false) access_denied('SUBMIT_HERE');
		make_member_gallery_if_needed($cat);
		$this->check_images_allowed($cat);

		$title=post_param('title');
		$validated=post_param_integer('validated',0);
		$allow_rating=post_param_integer('allow_rating',0);
		$allow_comments=post_param_integer('allow_comments',0);
		$notes=post_param('notes','');
		$allow_trackbacks=post_param_integer('allow_trackbacks',0);
		$this->handle_resizing_and_watermarking();

		$urls=get_url('url','file','uploads/galleries'.((get_value('use_gallery_subdirs')=='1')?('/'.$cat):''),0,OCP_UPLOAD_IMAGE,true,'thumb_url','file2');

		if (($urls[0]=='') || ($urls[1]==''))
		{
			warn_exit(do_lang_tempcode('IMPROPERLY_FILLED_IN_UPLOAD'));
		}

		if ((substr($urls[0],0,8)!='uploads/') && (is_null(http_download_file($urls[0],0,false))) && (!is_null($GLOBALS['HTTP_MESSAGE_B'])))
			attach_message($GLOBALS['HTTP_MESSAGE_B'],'warn');

		$comments=post_param('comments');

		$this->donext_type=$cat;

		$id=add_image($title,$cat,$comments,$urls[0],$urls[1],$validated,$allow_rating,$allow_comments,$allow_trackbacks,$notes);

		if ($validated==1)
		{
			if ((has_actual_page_access($GLOBALS['FORUM_DRIVER']->get_guest_id(),'galleries')) && (has_category_access($GLOBALS['FORUM_DRIVER']->get_guest_id(),'galleries',$cat)))
				syndicate_described_activity('galleries:ACTIVITY_ADD_IMAGE',($title=='')?basename($urls[0]):$title,'','','_SEARCH:galleries:image:'.strval($id),'','','galleries');
		}

		if ((has_edit_permission('cat_mid',get_member(),get_member_id_from_gallery_name($cat),'cms_galleries',array('galleries',$cat))) && (post_param_integer('rep_image',0)==1))
		{
			$GLOBALS['SITE_DB']->query_update('galleries',array('rep_image'=>$urls[1]),array('name'=>$cat),'',1);
		}

		return strval($id);
	}

	/**
	 * Standard aed_module edit actualiser.
	 *
	 * @param  ID_TEXT		The entry being edited
	 */
	function edit_actualisation($_id)
	{
		$id=intval($_id);

		$cat=post_param('cat');
		if (can_submit_to_gallery($cat)===false) access_denied('SUBMIT_HERE');
		make_member_gallery_if_needed($cat);
		$this->check_images_allowed($cat);
		$this->handle_resizing_and_watermarking();
		$validated=post_param_integer('validated',0);
		$urls=get_url('url','file','uploads/galleries'.((get_value('use_gallery_subdirs')=='1')?('/'.$cat):''),0,OCP_UPLOAD_IMAGE,true,'thumb_url','file2');
		if ($urls[0]=='')
		{
			$rows=$GLOBALS['SITE_DB']->query_select('images',array('url','thumb_url'),array('id'=>$id),'',1);
			$urls=$rows[0];

			$url=$urls['url'];
			$thumb_url=$urls['thumb_url'];
		} else
		{
			$url=$urls[0];
			$thumb_url=$urls[1];
		}

		if ((substr($urls[0],0,8)!='uploads/') && ($urls[0]!='') && (is_null(http_download_file($urls[0],0,false))) && (!is_null($GLOBALS['HTTP_MESSAGE_B'])))
			attach_message($GLOBALS['HTTP_MESSAGE_B'],'warn');

		$comments=post_param('comments');
		$allow_rating=post_param_integer('allow_rating',0);
		$allow_comments=post_param_integer('allow_comments',0);
		$notes=post_param('notes','');
		$allow_trackbacks=post_param_integer('allow_trackbacks',0);
		$title=post_param('title');

		$this->donext_type=$cat;

		if (($validated==1) && ($GLOBALS['SITE_DB']->query_value('images','validated',array('id'=>$id))==0)) // Just became validated, syndicate as just added
		{
			if ((has_actual_page_access($GLOBALS['FORUM_DRIVER']->get_guest_id(),'galleries')) && (has_category_access($GLOBALS['FORUM_DRIVER']->get_guest_id(),'galleries',$cat)))
				syndicate_described_activity('galleries:ACTIVITY_ADD_IMAGE',($title=='')?basename($urls[0]):$title,'','','_SEARCH:galleries:image:'.strval($id),'','','galleries',1,$GLOBALS['SITE_DB']->query_value('images','submitter',array('id'=>$id)));
		}

		edit_image($id,$title,$cat,$comments,$url,$thumb_url,$validated,$allow_rating,$allow_comments,$allow_trackbacks,$notes,post_param('meta_keywords',''),post_param('meta_description',''));

		if ((has_edit_permission('cat_mid',get_member(),get_member_id_from_gallery_name($cat),'cms_galleries',array('galleries',$cat))) && (post_param_integer('rep_image',0)==1))
		{
			$GLOBALS['SITE_DB']->query_update('galleries',array('rep_image'=>$thumb_url),array('name'=>$cat),'',1);
		}
	}

	/**
	 * Standard aed_module delete actualiser.
	 *
	 * @param  ID_TEXT		The entry being deleted
	 */
	function delete_actualisation($_id)
	{
		$id=intval($_id);

		$delete_status=post_param('delete','leave');

		$this->donext_type=post_param('cat');

		delete_image($id,$delete_status=='2');
	}

	/**
	 * The do-next manager for after content management.
	 *
	 * @param  tempcode		The title (output of get_page_title)
	 * @param  tempcode		Some description to show, saying what happened
	 * @param  ?AUTO_LINK	The ID of whatever was just handled (NULL: N/A)
	 * @return tempcode		The UI
	 */
	function do_next_manager($title,$description,$id)
	{
		return $this->cat_aed_module->_do_next_manager($title,$description,$this->donext_type,is_null($id)?NULL:intval($id));
	}

}

/**
 * Module page class.
 */
class Module_cms_galleries_alt extends standard_aed_module
{
	var $lang_type='VIDEO';
	var $select_name='NAME';
	var $permissions_require='mid';
	var $permissions_cat_require='galleries';
	var $permissions_cat_name='cat';
	var $user_facing=true;
	var $seo_type='video';
	var $upload='file';
	var $javascript='standardAlternateFields(\'file\',\'url\'); standardAlternateFields(\'file2\',\'thumb_url\');';
	var $award_type='video';
	var $menu_label='GALLERIES';
	var $table='videos';

	var $donext_type=NULL;

	/**
	 * Kills ocPortal if someone is trying to add a video to a gallery that does not support videos.
	 *
	 * @param  ID_TEXT		The gallery
	 * @param  boolean		Whether to tolerate the non-existance of the gallery
	 * @return ?integer		Number allowed remaining (NULL: no limit)
	 */
	function check_videos_allowed($cat,$tolerate_non_exist=false)
	{
		// Check this cat allows images
		$gallery=$GLOBALS['SITE_DB']->query_select('galleries',array('accept_videos','accept_images','is_member_synched'),array('name'=>$cat),'',1);
		$owner=get_member_id_from_gallery_name($cat);
		if (!array_key_exists(0,$gallery))
		{
			if ($tolerate_non_exist)
			{
				$limit=mixed();
				if ((!has_specific_permission(get_member(),'no_personal_gallery_limit')) && ($owner==get_member()))
				{
					$limit=has_specific_permission(get_member(),'high_personal_gallery_limit')?intval(get_option('max_personal_gallery_videos_high')):intval(get_option('max_personal_gallery_videos_low'));
				}
				return $limit;
			}
			warn_exit(do_lang_tempcode('MISSING_RESOURCE'));
		}
		if (($gallery[0]['accept_videos']==0) || ($gallery[0]['is_member_synched']==1)) warn_exit(do_lang_tempcode(($gallery[0]['accept_videos']==1)?'ERROR_NOT_ACCEPT_CONTAINER':'ERROR_NOT_ACCEPT_VIDEOS'));

		if ((!has_specific_permission(get_member(),'no_personal_gallery_limit')) && ($owner==get_member()))
		{
			$limit=has_specific_permission(get_member(),'high_personal_gallery_limit')?intval(get_option('max_personal_gallery_videos_high')):intval(get_option('max_personal_gallery_videos_low'));
			$count_already=$GLOBALS['SITE_DB']->query_value('videos','COUNT(*)',array('cat'=>$cat));
			if ($count_already>=$limit)
				warn_exit(do_lang_tempcode('TOO_MANY_GALLERY_VIDEOS'));

			return $limit-$count_already;
		}

		return NULL;
	}

	/**
	 * Extract video meta info from any uploaded video.
	 *
	 * @return array		A triplet of 3 "?integer"'s: video width, video height, video length
	 */
	function get_special_video_info()
	{
		$video_length=post_param_integer('video_length',0);
		$video_width=post_param_integer('video_width',0);
		$video_height=post_param_integer('video_height',0);
		if (($video_width==0) || ($video_height==0) || ($video_length==0))
		{
			require_code('uploads');
			if (((is_swf_upload(true)) && (array_key_exists('file',$_FILES))) || ((array_key_exists('file',$_FILES)) && (is_uploaded_file($_FILES['file']['tmp_name']))))
			{
				list($_video_width,$_video_height,$_video_length)=get_video_details($_FILES['file']['tmp_name'],$_FILES['file']['name']);
			} else
			{
				$url=post_param('url','');
				if ($url=='') return array(NULL,NULL,NULL);
				$download_test=NULL;
				$temp_path='';
				if ($url!='')
				{
					$temp_path=ocp_tempnam('ocpafm');
					$write_to_file=fopen($temp_path,'wb');
					$download_test=http_download_file($url,1024*50,false,false,'ocPortal',NULL,NULL,NULL,NULL,NULL,$write_to_file);
					rewind($write_to_file);
					fclose($write_to_file);
				}
				if (!is_null($download_test))
				{
					list($_video_width,$_video_height,$_video_length)=get_video_details($temp_path,is_null($GLOBALS['HTTP_FILENAME'])?basename(urldecode($url)):$GLOBALS['HTTP_FILENAME']);
				} else
				{
					list($_video_width,$_video_height,$_video_length)=array(NULL,NULL,NULL);
				}
				if ($temp_path!='') @unlink($temp_path);
			}
			if ($video_width==0)
				$video_width=(is_null($_video_width))?intval(get_option('default_video_width')):$_video_width;
			if ($video_height==0)
				$video_height=(is_null($_video_height))?intval(get_option('default_video_height')):$_video_height;
			if ($video_length==0)
				$video_length=(is_null($_video_length))?0:$_video_length;
		}

		return array($video_width,$video_height,$video_length);
	}

	/**
	 * Standard aed_module list function.
	 *
	 * @return array				A triple: The tree field (tempcode), Search URL, Archive URL
	 */
	function nice_get_ajax_tree()
	{
		if ($GLOBALS['SITE_DB']->query_value('videos','COUNT(*)')==0) warn_exit(do_lang_tempcode('NO_ENTRIES'));

		$search_url=build_url(array('page'=>'search','id'=>'videos'),get_module_zone('search'));
		$archive_url=build_url(array('page'=>'galleries'),get_module_zone('galleries'));

		$only_owned=has_specific_permission(get_member(),'edit_midrange_content','cms_galleries')?NULL:get_member();
		$tree=form_input_tree_list(do_lang_tempcode('VIDEO'),'','id',NULL,'choose_video',array('only_owned'=>$only_owned,'editable_filter'=>true),true);
		return array($tree,$search_url,$archive_url);
	}

	/**
	 * Get tempcode for a video adding/editing form.
	 *
 	 * @param  SHORT_TEXT		The title
	 * @param  ID_TEXT			The gallery
	 * @param  LONG_TEXT			The video description
	 * @param  URLPATH			The URL to the video file (blank: not yet added)
	 * @param  URLPATH			The URL to the thumbnail
	 * @param  BINARY				Video validation status
	 * @param  ?BINARY			Whether rating is allowed (NULL: decide statistically, based on existing choices)
	 * @param  ?SHORT_INTEGER	Whether comments are allowed (0=no, 1=yes, 2=review style) (NULL: decide statistically, based on existing choices)
	 * @param  ?BINARY			Whether trackbacks are allowed (NULL: decide statistically, based on existing choices)
	 * @param  LONG_TEXT			Notes for the video
	 * @param  ?integer			The length of the video (NULL: not yet added, so not yet known)
	 * @param  ?integer			The width of the video (NULL: not yet added, so not yet known)
	 * @param  ?integer			The height of the video (NULL: not yet added, so not yet known)
	 * @return array				A pair: the tempcode for the visible fields, and the tempcode for the hidden fields
	 */
	function get_form_fields($title='',$cat='',$comments='',$url='',$thumb_url='',$validated=1,$allow_rating=NULL,$allow_comments=NULL,$allow_trackbacks=NULL,$notes='',$video_length=NULL,$video_width=NULL,$video_height=NULL)
	{
		list($allow_rating,$allow_comments,$allow_trackbacks)=$this->choose_feedback_fields_statistically($allow_rating,$allow_comments,$allow_trackbacks);

		global $NON_CANONICAL_PARAMS;
		$NON_CANONICAL_PARAMS[]='cat';
		$NON_CANONICAL_PARAMS[]='validated';

		$no_thumb_needed=(get_option('ffmpeg_path')!='') || (class_exists('ffmpeg_movie'));
		if (!$no_thumb_needed)
			$this->javascript='standardAlternateFields(\'file\',\'url\'); standardAlternateFields(\'file2\',\'thumb_url\',null,true);';
		else
			$this->javascript='standardAlternateFields(\'file\',\'url\');';

		if ($cat=='')
		{
			$cat=get_param('cat','');
		}

		$fields=new ocp_tempcode();
		$hidden=new ocp_tempcode();
		require_code('form_templates');
		handle_max_file_size($hidden);
		if (strpos($cat,'?')!==false) $cat=str_replace('?',strval(get_member()),$cat);
		$fields->attach(form_input_line(do_lang_tempcode('TITLE',do_lang_tempcode('TITLE')),do_lang_tempcode('DESCRIPTION_TITLE'),'title',$title,false));

		$fields->attach(form_input_tree_list(do_lang_tempcode('GALLERY'),do_lang_tempcode('DESCRIPTION_GALLERY'),'cat',NULL,'choose_gallery',array('filter'=>'only_conventional_galleries','must_accept_videos'=>true,'addable_filter'=>true),true,$cat));
		$supported=get_allowed_video_file_types();
		$fields->attach(form_input_upload(do_lang_tempcode('UPLOAD'),do_lang_tempcode('DESCRIPTION_UPLOAD'),'file',false,NULL,NULL,true,$supported));
		$fields->attach(form_input_line(do_lang_tempcode('ALT_FIELD',do_lang_tempcode('URL')),do_lang_tempcode('DESCRIPTION_ALTERNATE_URL'),'url',$url,false));
		if ($validated==0)
		{
			$validated=get_param_integer('validated',0);
			if ($validated==1) attach_message(do_lang_tempcode('WILL_BE_VALIDATED_WHEN_SAVING'));
		}
		$thumb_width=intval(get_option('thumb_width'));
		$validated_field=new ocp_tempcode();
		if (has_some_cat_specific_permission(get_member(),'bypass_validation_'.$this->permissions_require.'range_content',NULL,$this->permissions_cat_require))
			if (addon_installed('unvalidated'))
				$validated_field=form_input_tick(do_lang_tempcode('VALIDATED'),do_lang_tempcode('DESCRIPTION_VALIDATED'),'validated',$validated==1);
		$description_field=form_input_text_comcode(do_lang_tempcode('DESCRIPTION'),do_lang_tempcode('DESCRIPTION_DESCRIPTION_ACCESSIBILITY'),'comments',$comments,false);
		if ($no_thumb_needed)
		{
			$fields->attach($description_field);
			$fields->attach($validated_field);
			$temp=do_template('FORM_SCREEN_FIELD_SPACER',array('TITLE'=>do_lang_tempcode('ADVANCED'),'SECTION_HIDDEN'=>true));
			$fields->attach($temp);
		}
		$fields->attach(form_input_upload(do_lang_tempcode('THUMBNAIL'),do_lang_tempcode('_DESCRIPTION_THUMBNAIL',integer_format($thumb_width)),'file2',false,NULL,NULL,true,str_replace(' ','',get_option('valid_images'))));
		$fields->attach(form_input_line(do_lang_tempcode('ALT_FIELD',do_lang_tempcode('URL')),do_lang_tempcode('DESCRIPTION_ALTERNATE_URL'),'thumb_url',$thumb_url,false));
		if (!$no_thumb_needed)
		{
			$fields->attach($description_field);
		}
		$fields->attach(form_input_integer(do_lang_tempcode('VIDEO_LENGTH'),do_lang_tempcode('DESCRIPTION_VIDEO_LENGTH'),'video_length',$video_length,false));
		$fields->attach(form_input_integer(do_lang_tempcode('WIDTH'),do_lang_tempcode('DESCRIPTION_VIDEO_WIDTH'),'video_width',$video_width,false));
		$fields->attach(form_input_integer(do_lang_tempcode('HEIGHT'),do_lang_tempcode('DESCRIPTION_VIDEO_HEIGHT'),'video_height',$video_height,false));
		if (!$no_thumb_needed)
		{
			$fields->attach($validated_field);
		}

		require_code('feedback2');
		$fields->attach(feedback_fields($allow_rating==1,$allow_comments==1,$allow_trackbacks==1,false,$notes,$allow_comments==2));

		return array($fields,$hidden);
	}

	/**
	 * Standard aed_module submitter getter.
	 *
	 * @param  ID_TEXT		The entry for which the submitter is sought
	 * @return array			The submitter, and the time of submission (null submission time implies no known submission time)
	 */
	function get_submitter($id)
	{
		$rows=$GLOBALS['SITE_DB']->query_select('videos',array('submitter','add_date'),array('id'=>intval($id)),'',1);
		if (!array_key_exists(0,$rows)) return array(NULL,NULL);
		return array($rows[0]['submitter'],$rows[0]['add_date']);
	}

	/**
	 * Standard aed_module cat getter.
	 *
	 * @param  AUTO_LINK		The entry for which the cat is sought
	 * @return mixed			The cat
	 */
	function get_cat($id)
	{
		$temp=$GLOBALS['SITE_DB']->query_value_null_ok('videos','cat',array('id'=>$id));
		if (is_null($temp)) warn_exit(do_lang_tempcode('MISSING_RESOURCE'));
		return $temp;
	}

	/**
	 * Standard aed_module edit form filler.
	 *
	 * @param  ID_TEXT		The entry being edited
	 * @return array			A tuple of lots of info
	 */
	function fill_in_edit_form($_id)
	{
		$id=intval($_id);

		$rows=$GLOBALS['SITE_DB']->query_select('videos',array('*'),array('id'=>$id),'',1);
		if (!array_key_exists(0,$rows))
		{
			warn_exit(do_lang_tempcode('MISSING_RESOURCE'));
		}
		$myrow=$rows[0];
		$comments=get_translated_text($myrow['comments']);
		$url=$myrow['url'];
		$cat=$myrow['cat'];
		$validated=$myrow['validated'];

		if (has_delete_permission('mid',get_member(),$myrow['submitter'],'cms_galleries',array('galleries',$cat)))
		{
			$radios=form_input_radio_entry('delete','0',true,do_lang_tempcode('LEAVE'));
			$radios->attach(form_input_radio_entry('delete','1',false,do_lang_tempcode('DELETE_PARTIAL')));
			$radios->attach(form_input_radio_entry('delete','2',false,do_lang_tempcode('DELETE_FULL')));
			$delete_fields=form_input_radio(do_lang_tempcode('DELETE_STATUS'),do_lang_tempcode('DESCRIPTION_DELETE_STATUS'),'delete',$radios);
		} else $delete_fields=new ocp_tempcode();

		list($fields,$hidden)=$this->get_form_fields(get_translated_text($myrow['title']),$cat,$comments,$url,$myrow['thumb_url'],$validated,$myrow['allow_rating'],$myrow['allow_comments'],$myrow['allow_trackbacks'],$myrow['notes'],$myrow['video_length'],$myrow['video_width'],$myrow['video_height']);

		return array($fields,$hidden,$delete_fields,'',true);
	}

	/**
	 * Standard aed_module add actualiser.
	 *
	 * @return ID_TEXT		The ID of the entry added
	 */
	function add_actualisation()
	{
		$cat=post_param('cat');
		if (can_submit_to_gallery($cat)===false) access_denied('SUBMIT_HERE');
		make_member_gallery_if_needed($cat);
		$this->check_videos_allowed($cat);
		$validated=post_param_integer('validated',0);
		$allow_rating=post_param_integer('allow_rating',0);
		$allow_comments=post_param_integer('allow_comments',0);
		$notes=post_param('notes','');
		$allow_trackbacks=post_param_integer('allow_trackbacks',0);
		$title=post_param('title');

		list($video_width,$video_height,$video_length)=$this->get_special_video_info();
		$urls=get_url('url','file','uploads/galleries'.((get_value('use_gallery_subdirs')=='1')?('/'.$cat):''),0,OCP_UPLOAD_VIDEO,true,'thumb_url','file2');

		if (($urls[1]=='') && ($urls[0]!=''))
		{
			$urls[1]=create_video_thumb($urls[0]);
			if ($urls[1]=='') warn_exit(do_lang_tempcode('IMPROPERLY_FILLED_IN_THUMBNAIL'));
		}

		if (($urls[0]=='') || ($urls[1]==''))
		{
			warn_exit(do_lang_tempcode('IMPROPERLY_FILLED_IN_UPLOAD'));
		}

		if ((substr($urls[0],0,8)!='uploads/') && (is_null(http_download_file($urls[0],0,false))) && (!is_null($GLOBALS['HTTP_MESSAGE_B'])))
			attach_message($GLOBALS['HTTP_MESSAGE_B'],'warn');

		$comments=post_param('comments');

		$this->donext_type=$cat;

		$id=add_video($title,$cat,$comments,$urls[0],$urls[1],$validated,$allow_rating,$allow_comments,$allow_trackbacks,$notes,$video_length,$video_width,$video_height);

		if ($validated==1)
		{
			if ((has_actual_page_access($GLOBALS['FORUM_DRIVER']->get_guest_id(),'galleries')) && (has_category_access($GLOBALS['FORUM_DRIVER']->get_guest_id(),'galleries',$cat)))
				syndicate_described_activity('galleries:ACTIVITY_ADD_VIDEO',($title=='')?basename($urls[0]):$title,'','','_SEARCH:galleries:video:'.strval($id),'','','galleries');
		}

		return strval($id);
	}

	/**
	 * Standard aed_module edit actualiser.
	 *
	 * @param  ID_TEXT		The entry being edited
	 */
	function edit_actualisation($_id)
	{
		$id=intval($_id);

		$cat=post_param('cat');
		if (can_submit_to_gallery($cat)===false) access_denied('SUBMIT_HERE');
		make_member_gallery_if_needed($cat);
		$this->check_videos_allowed($cat);
		$validated=post_param_integer('validated',0);
		$title=post_param('title');
		$urls=get_url('url','file','uploads/galleries'.((get_value('use_gallery_subdirs')=='1')?('/'.$cat):''),0,OCP_UPLOAD_VIDEO,true,'thumb_url','file2');
		if ($urls[0]=='')
		{
			warn_exit(do_lang_tempcode('IMPROPERLY_FILLED_IN_UPLOAD'));
		}
		$url=$urls[0];
		if ((!array_key_exists(1,$urls)) || ($urls[1]==''))
		{
			$thumb_url='';
		} else
		{
			$thumb_url=$urls[1];
		}

		if ((substr($url,0,8)!='uploads/') && ($url!='') && (is_null(http_download_file($url,0,false))) && (!is_null($GLOBALS['HTTP_MESSAGE_B'])))
			attach_message($GLOBALS['HTTP_MESSAGE_B'],'warn');

		if (($thumb_url=='') && ($url!=''))
			$thumb_url=create_video_thumb($url);

		if ($thumb_url=='')
		{
			$rows=$GLOBALS['SITE_DB']->query_select('videos',array('url','thumb_url'),array('id'=>$id),'',1);
			$thumb_url=$rows[0]['thumb_url'];
		}

		if (($url=='') || ($thumb_url==''))
		{
			warn_exit(do_lang_tempcode('IMPROPERLY_FILLED_IN_UPLOAD'));
		}

		$comments=post_param('comments');
		$allow_rating=post_param_integer('allow_rating',0);
		$allow_comments=post_param_integer('allow_comments',0);
		$notes=post_param('notes','');
		$allow_trackbacks=post_param_integer('allow_trackbacks',0);
		list($video_width,$video_height,$video_length)=$this->get_special_video_info();

		$this->donext_type=$cat;

		if (($validated==1) && ($GLOBALS['SITE_DB']->query_value('videos','validated',array('id'=>$id))==0)) // Just became validated, syndicate as just added
		{
			if ((has_actual_page_access($GLOBALS['FORUM_DRIVER']->get_guest_id(),'galleries')) && (has_category_access($GLOBALS['FORUM_DRIVER']->get_guest_id(),'galleries',$cat)))
				syndicate_described_activity('galleries:ACTIVITY_ADD_VIDEO',($title=='')?basename($urls[0]):$title,'','','_SEARCH:galleries:video:'.strval($id),'','','galleries',1,$GLOBALS['SITE_DB']->query_value('videos','submitter',array('id'=>$id)));
		}

		edit_video($id,$title,$cat,$comments,$url,$thumb_url,$validated,$allow_rating,$allow_comments,$allow_trackbacks,$notes,$video_length,$video_width,$video_height,post_param('meta_keywords',''),post_param('meta_description',''));
	}

	/**
	 * Standard aed_module delete actualiser.
	 *
	 * @param  ID_TEXT		The entry being deleted
	 */
	function delete_actualisation($_id)
	{
		$id=intval($_id);

		$delete_status=post_param('delete','leave');

		$this->donext_type=post_param('cat');

		delete_video($id,$delete_status=='2');
	}

	/**
	 * The do-next manager for after content management.
	 *
	 * @param  tempcode		The title (output of get_page_title)
	 * @param  tempcode		Some description to show, saying what happened
	 * @param  ?AUTO_LINK	The ID of whatever was just handled (NULL: N/A)
	 * @return tempcode		The UI
	 */
	function do_next_manager($title,$description,$id)
	{
		return $GLOBALS['MODULE_CMS_GALLERIES']->cat_aed_module->_do_next_manager($title,$description,$this->donext_type,is_null($id)?NULL:intval($id),true);
	}

}

/**
 * Module page class.
 */
class Module_cms_galleries_cat extends standard_aed_module
{
	var $lang_type='GALLERY';
	var $select_name='NAME';
	var $permissions_require='cat_mid';
	var $permission_module='galleries';
	var $seo_type='gallery';
	var $upload='image';
	var $non_integer_id=true;
	var $award_type='gallery';
	var $menu_label='GALLERIES';
	var $table='galleries';
	var $javascript="var fn=document.getElementById('fullname'); if (fn) { var form=fn.form; fn.onchange=function() { if ((form.elements['name']) && (form.elements['name'].value=='')) form.elements['name'].value=fn.value.toLowerCase().replace(/[^\w\d\.\-]/g,'_').replace(/\_+\$/,''); }; }";

	/**
	 * Standard aed_module list function.
	 *
	 * @return array				A triple: The tree field (tempcode), Search URL, Archive URL
	 */
	function nice_get_ajax_tree()
	{
		$purity=true;
		$_member_id=NULL;

		$search_url=build_url(array('page'=>'search','id'=>'galleries'),get_module_zone('search'));
		$archive_url=build_url(array('page'=>'galleries'),get_module_zone('galleries'));

		$tree=form_input_tree_list(do_lang_tempcode('GALLERY'),'','id',NULL,'choose_gallery',array('purity'=>$purity,'member_id'=>$_member_id,'editable_filter'=>true),true);
		return array($tree,$search_url,$archive_url);
	}

	/**
	 * Get tempcode for a gallery adding/editing form.
	 *
	 * @param  ID_TEXT			The gallery codename
	 * @param  SHORT_TEXT		The full human-readeable name of the gallery
	 * @param  LONG_TEXT			The description of the gallery
	 * @param  SHORT_TEXT		Teaser text for the gallery
	 * @param  LONG_TEXT			Hidden notes associated with the gallery
	 * @param  ID_TEXT			The parent gallery (blank: no parent)
	 * @param  BINARY				Whether images may be put in this gallery
	 * @param  BINARY				Whether videos may be put in this gallery
	 * @param  BINARY				Whether the gallery serves as a container for automatically created member galleries
	 * @param  ?BINARY			Whether the gallery uses the flow mode interface (NULL: pick statistically based on current usage of other galleries)
	 * @param  ?URLPATH			The representative image of the gallery (NULL: none)
	 * @param  ?URLPATH			Watermark (NULL: none)
	 * @param  ?URLPATH			Watermark (NULL: none)
	 * @param  ?URLPATH			Watermark (NULL: none)
	 * @param  ?URLPATH			Watermark (NULL: none)
	 * @param  ?BINARY			Whether rating is allowed (NULL: decide statistically, based on existing choices)
	 * @param  ?SHORT_INTEGER	Whether comments are allowed (0=no, 1=yes, 2=review style) (NULL: decide statistically, based on existing choices)
	 * @return array				A pair: the tempcode for the visible fields, and the tempcode for the hidden fields
	 */
	function get_form_fields($name='',$fullname='',$description='',$teaser='',$notes='',$parent_id='',$accept_images=1,$accept_videos=1,$is_member_synched=0,$flow_mode_interface=NULL,$rep_image=NULL,$watermark_top_left=NULL,$watermark_top_right=NULL,$watermark_bottom_left=NULL,$watermark_bottom_right=NULL,$allow_rating=NULL,$allow_comments=NULL)
	{
		list($allow_rating,$allow_comments,)=$this->choose_feedback_fields_statistically($allow_rating,$allow_comments,1);

		global $NON_CANONICAL_PARAMS;
		$NON_CANONICAL_PARAMS[]='cat';
		$NON_CANONICAL_PARAMS[]='validated';

		if (is_null($flow_mode_interface))
		{
			$cnt=$GLOBALS['SITE_DB']->query_value('galleries','COUNT(*)');
			if ($cnt<5000)
			{
				$flow_mode_interface=intval(round($GLOBALS['SITE_DB']->query_value('galleries','AVG(flow_mode_interface)'))); // Determine default based on what is 'the norm' currently. Sometimes maths is beautiful :)
			} else
			{
				$flow_mode_interface=intval(round($GLOBALS['SITE_DB']->query_value('galleries','AVG(flow_mode_interface)',array('parent_id'=>'root')))); // Determine default based on what is 'the norm' currently. Sometimes maths is beautiful :)
			}
		}

		$fields=new ocp_tempcode();
		require_code('form_templates');
		$fields->attach(form_input_line(do_lang_tempcode('TITLE'),do_lang_tempcode('DESCRIPTION_TITLE'),'fullname',$fullname,true));
		if ($name!='root')
			$fields->attach(form_input_codename(do_lang_tempcode('CODENAME'),do_lang_tempcode('DESCRIPTION_CODENAME'),'name',$name,true));
		$fields->attach(form_input_text_comcode(do_lang_tempcode('DESCRIPTION'),do_lang_tempcode('DESCRIPTION_DESCRIPTION'),'description',$description,false));
		if ($parent_id=='') $parent_id=get_param('cat','');
		if ($name!='root')
			$fields->attach(form_input_tree_list(do_lang_tempcode('PARENT'),do_lang_tempcode('DESCRIPTION_PARENT'),'parent_id',NULL,'choose_gallery',array('filter'=>'only_conventional_galleries','purity'=>true),true,$parent_id));
		$fields->attach(form_input_various_ticks(array(array(do_lang_tempcode('ACCEPT_IMAGES'),'accept_images',$accept_images==1,do_lang_tempcode('DESCRIPTION_ACCEPT_IMAGES')),array(do_lang_tempcode('ACCEPT_VIDEOS'),'accept_videos',$accept_videos==1,do_lang_tempcode('DESCRIPTION_ACCEPT_VIDEOS'))),new ocp_tempcode(),NULL,do_lang_tempcode('ACCEPTED_MEDIA_TYPES')));
		$fields->attach(form_input_tick(do_lang_tempcode('FLOW_MODE_INTERFACE'),do_lang_tempcode('DESCRIPTION_FLOW_MODE_INTERFACE'),'flow_mode_interface',$flow_mode_interface==1));
		$fields->attach(do_template('FORM_SCREEN_FIELD_SPACER',array('SECTION_HIDDEN'=>($rep_image=='') && ($teaser=='') && ($is_member_synched==0),'TITLE'=>do_lang_tempcode('ADVANCED'))));
		$fields->attach(form_input_upload(do_lang_tempcode('REPRESENTATIVE_IMAGE'),do_lang_tempcode('DESCRIPTION_REPRESENTATIVE_IMAGE_GALLERY'),'rep_image',false,$rep_image,NULL,true,str_replace(' ','',get_option('valid_images'))));

		// Only show tease option if tease block being used
		$teaser_shows=false;
		$zones=find_all_zones(false,true);
		$pages=array();
		foreach ($zones as $_zone)
		{
			$pages[$_zone[0]]=find_all_pages_wrap($_zone[0],true);
		}
		foreach ($pages as $zone=>$under)
		{
			foreach ($under as $filename=>$type)
			{
				if (substr(strtolower($filename),-4)=='.txt')
				{
					$matches=array();
					$contents=file_get_contents(zone_black_magic_filterer(((substr($type,0,15)=='comcode_custom/')?get_custom_file_base():get_file_base()).'/'.(($zone=='')?'':($zone.'/')).'pages/'.$type.'/'.$filename));
					$fallback=get_file_base().'/'.(($zone=='')?'':($zone.'/')).'pages/comcode/'.fallback_lang().'/'.$filename;
					if (file_exists($fallback)) $contents.=file_get_contents($fallback);
					if (preg_match('#\[block[^\]]*\]main_gallery_tease\[/block\]#',$contents,$matches)!=0)
					{
						$teaser_shows=true;
					}
				}
			}
		}
		if ($teaser_shows)
			$fields->attach(form_input_line_comcode(do_lang_tempcode('TEASER'),do_lang_tempcode('DESCRIPTION_TEASER'),'teaser',$teaser,false));

		$fields->attach(form_input_tick(do_lang_tempcode('IS_MEMBER_SYNCHED'),do_lang_tempcode('DESCRIPTION_IS_MEMBER_SYNCHED_GALLERY'),'is_member_synched',$is_member_synched==1));

		$fields->attach(do_template('FORM_SCREEN_FIELD_SPACER',array('SECTION_HIDDEN'=>is_null($watermark_top_left) && is_null($watermark_top_right) && is_null($watermark_bottom_left) && is_null($watermark_bottom_right),'TITLE'=>do_lang_tempcode('WATERMARKING'))));
		$fields->attach(form_input_upload(do_lang_tempcode('_WATERMARK',do_lang_tempcode('TOP_LEFT')),do_lang_tempcode('_DESCRIPTION_WATERMARK',do_lang_tempcode('TOP_LEFT')),'watermark_top_left',false,$watermark_top_left,NULL,true,str_replace(' ','',get_option('valid_images'))));
		$fields->attach(form_input_upload(do_lang_tempcode('_WATERMARK',do_lang_tempcode('TOP_RIGHT')),do_lang_tempcode('_DESCRIPTION_WATERMARK',do_lang_tempcode('TOP_RIGHT')),'watermark_top_right',false,$watermark_top_right,NULL,true,str_replace(' ','',get_option('valid_images'))));
		$fields->attach(form_input_upload(do_lang_tempcode('_WATERMARK',do_lang_tempcode('BOTTOM_LEFT')),do_lang_tempcode('_DESCRIPTION_WATERMARK',do_lang_tempcode('BOTTOM_LEFT')),'watermark_bottom_left',false,$watermark_bottom_left,NULL,true,str_replace(' ','',get_option('valid_images'))));
		$fields->attach(form_input_upload(do_lang_tempcode('_WATERMARK',do_lang_tempcode('BOTTOM_RIGHT')),do_lang_tempcode('_DESCRIPTION_WATERMARK',do_lang_tempcode('BOTTOM_RIGHT')),'watermark_bottom_right',false,$watermark_bottom_right,NULL,true,str_replace(' ','',get_option('valid_images'))));
		$hidden=new ocp_tempcode();
		handle_max_file_size($hidden,'image');

		require_code('feedback2');
		$fields->attach(feedback_fields($allow_rating==1,$allow_comments==1,NULL,false,$notes,$allow_comments==2,true));

		// Permissions
		$fields->attach($this->get_permission_fields($name,NULL,($name=='')));

		return array($fields,$hidden);
	}

	/**
	 * Standard aed_module submitter getter.
	 *
	 * @param  ID_TEXT		The entry for which the submitter is sought
	 * @return array			The submitter, and the time of submission (null submission time implies no known submission time)
	 */
	function get_submitter($id)
	{
		$rows=$GLOBALS['SITE_DB']->query_select('galleries',array('add_date','g_owner'),array('name'=>$id),'',1);
		if (!array_key_exists(0,$rows)) return array(get_member_id_from_gallery_name($id),NULL);
		return array(get_member_id_from_gallery_name($id,$rows[0]),$rows[0]['add_date']);
	}

	/**
	 * Standard aed_module edit form filler.
	 *
	 * @param  ID_TEXT		The entry being edited
	 * @return tempcode		The edit form
	 */
	function fill_in_edit_form($id)
	{
		$rows=$GLOBALS['SITE_DB']->query_select('galleries',array('*'),array('name'=>$id),'',1);
		if (!array_key_exists(0,$rows))
		{
			warn_exit(do_lang_tempcode('MISSING_RESOURCE'));
		}
		$myrow=$rows[0];

		$gallery_owner	=	$GLOBALS['FORUM_DRIVER']->get_username($myrow['g_owner']);

		return $this->get_form_fields($id,get_translated_text($myrow['fullname']),get_translated_text($myrow['description']),get_translated_text($myrow['teaser']),$myrow['notes'],$myrow['parent_id'],$myrow['accept_images'],$myrow['accept_videos'],$myrow['is_member_synched'],$myrow['flow_mode_interface'],$myrow['rep_image'],$myrow['watermark_top_left'],$myrow['watermark_top_right'],$myrow['watermark_bottom_left'],$myrow['watermark_bottom_right'],$myrow['allow_rating'],$myrow['allow_comments'],$gallery_owner);
	}

	/**
	 * Standard aed_module add actualiser.
	 *
	 * @return ID_TEXT		The entry added
	 */
	function add_actualisation()
	{
		$name=post_param('name');
		$fullname=post_param('fullname');
		$description=post_param('description');
		$teaser=post_param('teaser','');
		$notes=post_param('notes','');
		$parent_id=post_param('parent_id');
		$accept_images=post_param_integer('accept_images',0);
		$accept_videos=post_param_integer('accept_videos',0);
		$is_member_synched=post_param_integer('is_member_synched',0);
		$flow_mode_interface=post_param_integer('flow_mode_interface',0);
		$urls=get_url('image_url','rep_image','uploads/grepimages',0,OCP_UPLOAD_IMAGE);
		$url=$urls[0];
		$watermark_top_left=get_url('','watermark_top_left','uploads/watermarks',0,OCP_UPLOAD_IMAGE);
		$watermark_top_right=get_url('','watermark_top_right','uploads/watermarks',0,OCP_UPLOAD_IMAGE);
		$watermark_bottom_left=get_url('','watermark_bottom_left','uploads/watermarks',0,OCP_UPLOAD_IMAGE);
		$watermark_bottom_right=get_url('','watermark_bottom_right','uploads/watermarks',0,OCP_UPLOAD_IMAGE);
		$allow_rating=post_param_integer('allow_rating',0);
		$allow_comments=post_param_integer('allow_comments',0);
		$g_owner_name=post_param('g_owner',NULL);

		if(is_null($g_owner_name))
			$g_owner	=	get_member();
		else
			$g_owner=$GLOBALS['FORUM_DRIVER']->get_member_from_username($g_owner_name);

		add_gallery($name,$fullname,$description,$teaser,$notes,$parent_id,$accept_images,$accept_videos,$is_member_synched,$flow_mode_interface,$url,$watermark_top_left[0],$watermark_top_right[0],$watermark_bottom_left[0],$watermark_bottom_right[0],$allow_rating,$allow_comments,false,time(),$g_owner);
		$this->set_permissions($name);

		return $name;
	}

	/**
	 * Standard aed_module edit actualiser.
	 *
	 * @param  ID_TEXT		The entry being edited
	 */
	function edit_actualisation($id)
	{
		$name=post_param('name',fractional_edit()?$id:'root');

		$parent_id=post_param('parent_id',STRING_MAGIC_NULL);
		$accept_images=post_param_integer('accept_images',fractional_edit()?INTEGER_MAGIC_NULL:0);
		$accept_videos=post_param_integer('accept_videos',fractional_edit()?INTEGER_MAGIC_NULL:0);
		$is_member_synched=post_param_integer('is_member_synched',fractional_edit()?INTEGER_MAGIC_NULL:0);
		$flow_mode_interface=post_param_integer('flow_mode_interface',fractional_edit()?INTEGER_MAGIC_NULL:0);
		if (!fractional_edit())
		{
			$urls=get_url('image_url','rep_image','uploads/grepimages',0,OCP_UPLOAD_IMAGE);
			$url=$urls[0];
			if (($url=='') && (post_param_integer('rep_image_unlink',0)!=1)) $url=NULL;

			$watermark_top_left=get_url('','watermark_top_left','uploads/watermarks',0,OCP_UPLOAD_IMAGE);
			if (($watermark_top_left[0]=='') && (post_param_integer('watermark_top_left_unlink',0)!=1)) $watermark_top_left[0]=NULL;
			$watermark_top_right=get_url('','watermark_top_right','uploads/watermarks',0,OCP_UPLOAD_IMAGE);
			if (($watermark_top_right[0]=='') && (post_param_integer('watermark_top_right_unlink',0)!=1)) $watermark_top_right[0]=NULL;
			$watermark_bottom_left=get_url('','watermark_bottom_left','uploads/watermarks',0,OCP_UPLOAD_IMAGE);
			if (($watermark_bottom_left[0]=='') && (post_param_integer('watermark_bottom_left_unlink',0)!=1)) $watermark_bottom_left[0]=NULL;
			$watermark_bottom_right=get_url('','watermark_bottom_right','uploads/watermarks',0,OCP_UPLOAD_IMAGE);
			if (($watermark_bottom_right[0]=='') && (post_param_integer('watermark_bottom_right_unlink',0)!=1)) $watermark_bottom_right[0]=NULL;
		} else
		{
			$url=STRING_MAGIC_NULL;
			$watermark_top_left=NULL;
			$watermark_top_right=NULL;
			$watermark_bottom_left=NULL;
			$watermark_bottom_right=NULL;
		}
		$allow_rating=post_param_integer('allow_rating',fractional_edit()?INTEGER_MAGIC_NULL:0);
		$allow_comments=post_param_integer('allow_comments',fractional_edit()?INTEGER_MAGIC_NULL:0);
		$g_owner_name=post_param('g_owner',NULL);
		if(is_null($g_owner_name))
			$g_owner	=	$GLOBALS['SITE_DB']->query_value('galleries','g_owner',array('name'=>$name));
		else
			$g_owner=$GLOBALS['FORUM_DRIVER']->get_member_from_username($g_owner_name);


		edit_gallery($id,$name,post_param('fullname'),post_param('description',STRING_MAGIC_NULL),post_param('teaser',STRING_MAGIC_NULL),post_param('notes',STRING_MAGIC_NULL),$parent_id,$accept_images,$accept_videos,$is_member_synched,$flow_mode_interface,$url,$watermark_top_left[0],$watermark_top_right[0],$watermark_bottom_left[0],$watermark_bottom_right[0],post_param('meta_keywords',STRING_MAGIC_NULL),post_param('meta_description',STRING_MAGIC_NULL),$allow_rating,$allow_comments,$g_owner);

		$this->new_id=$name;

		if (!fractional_edit())
		{
			$this->set_permissions($name);
		}
	}

	/**
	 * Standard aed_module delete possibility checker.
	 *
	 * @param  ID_TEXT		The entry being potentially deleted
	 * @return boolean		Whether it may be deleted
	 */
	function may_delete_this($id)
	{
		return $id!='root';
	}

	/**
	 * Standard aed_module delete actualiser.
	 *
	 * @param  ID_TEXT		The entry being deleted
	 */
	function delete_actualisation($id)
	{
		delete_gallery($id);
	}

	/**
	 * The do-next manager for after download content management (event types only).
	 *
	 * @param  tempcode		The title (output of get_page_title)
	 * @param  tempcode		Some description to show, saying what happened
	 * @param  ?ID_TEXT		The ID of whatever was just handled (NULL: N/A)
	 * @return tempcode		The UI
	 */
	function do_next_manager($title,$description,$id)
	{
		return $this->_do_next_manager($title,$description,is_null($id)?NULL:$id);
	}

	/**
	 * The do-next manager for after image/video content management.
	 *
	 * @param  tempcode		The title (output of get_page_title)
	 * @param  tempcode		Some description to show, saying what happened
	 * @param  ?ID_TEXT		The gallery we were working in (NULL: deleted)
	 * @param  ?AUTO_LINK	The ID of whatever was just handled (NULL: N/A)
	 * @param  boolean		Whether we were working with a video
	 * @return tempcode		The UI
	 */
	function _do_next_manager($title,$description,$cat=NULL,$id=NULL,$video=false)
	{
		breadcrumb_set_self(do_lang_tempcode('DONE'));

		$extra=array();
		if (!is_null($cat))
		{
			$hooks=find_all_hooks('modules','galleries_users');
			foreach (array_keys($hooks) as $hook)
			{
				require_code('hooks/modules/galleries_users/'.filter_naughty_harsh($hook));
				$object=object_factory('Hook_gu_'.filter_naughty_harsh($hook),true);
				if (is_null($object)) continue;
				$extra=array_merge($extra,$object->new_donext_icons($cat));
			}
		}

		require_code('templates_donext');

		if ((is_null($id)) && (is_null($cat)))
		{
			return do_next_manager($title,$description,
						NULL,
						NULL,
						/*		TYPED-ORDERED LIST OF 'LINKS'		*/
						/*	 page	 params				  zone	  */
						NULL,							// Add one
						NULL,							 // Edit this
						has_specific_permission(get_member(),'edit_own_midrange_content','cms_galleries')?array('_SELF',array('type'=>'ed'),'_SELF',do_lang('EDIT_IMAGE')):NULL,											// Edit one
						NULL,							// View this
						array('galleries',array('type'=>'misc'),get_module_zone('galleries'),do_lang_tempcode('GALLERIES')),									 // View archive
						NULL,	  // Add to category
						has_specific_permission(get_member(),'submit_cat_midrange_content','cms_galleries')?array('_SELF',array('type'=>'ac'),'_SELF',do_lang('ADD_GALLERY')):NULL,					  // Add one category
						has_specific_permission(get_member(),'edit_own_cat_midrange_content','cms_galleries')?array('_SELF',array('type'=>'ec'),'_SELF',do_lang('EDIT_GALLERY')):NULL,					  // Edit one category
						is_null($cat)?NULL:array('_SELF',array('type'=>'_ec','id'=>$cat),'_SELF'),			 // Edit this category
						is_null($cat)?NULL:array('galleries',array('type'=>'misc','id'=>$cat),get_module_zone('galleries')),																						 // View this category
						/*	  SPECIALLY TYPED 'LINKS'				  */
						array_merge($extra,array(
							/*	 type																page	 params													 zone	  */
							array('add_one_video',array('_SELF',array('type'=>'av'),'_SELF')),
							array('add_one_image',array('_SELF',array('type'=>'ad'),'_SELF')),
						)),
						NULL,
						NULL,
						NULL,
						NULL,
						NULL,
						do_lang_tempcode('GALLERIES')
			);
		}

		$support_videos=false;
		$support_images=false;
		if (!is_null($cat))
		{
			$cat_row=$GLOBALS['SITE_DB']->query_select('galleries',array('accept_images','accept_videos','is_member_synched'),array('name'=>$cat),'',1);
			if ((array_key_exists(0,$cat_row)) && ($cat_row[0]['is_member_synched']==0))
			{
				if ($cat_row[0]['accept_videos']==1) $support_videos=true;
				if ($cat_row[0]['accept_images']==1) $support_images=true;
			}
		}

		return do_next_manager($title,$description,
					NULL,
					NULL,
					/*		TYPED-ORDERED LIST OF 'LINKS'		*/
					/*	 page	 params				  zone	  */
					NULL,				 // Add one
					(is_null($id) || (!has_specific_permission(get_member(),'edit_own_midrange_content','cms_galleries',array('galleries',$cat))))?NULL:array('_SELF',array('type'=>$video?'_ev':'_ed','id'=>$id),'_SELF'),			// Edit this
					has_specific_permission(get_member(),'edit_own_midrange_content','cms_galleries')?array('_SELF',array('type'=>$video?'ev':'ed'),'_SELF',do_lang($video?'EDIT_VIDEO':'EDIT_IMAGE')):NULL,							// Edit one
					is_null($id)?NULL:array('galleries',array('type'=>$video?'video':'image','id'=>$id,'wide'=>1),get_module_zone('galleries')),	  // View this
					array('galleries',array('type'=>'misc'),get_module_zone('galleries'),do_lang_tempcode('GALLERIES')),							// View archive
					array('_SELF',array('type'=>$video?'av':'ad'),'_SELF',do_lang($video?'ADD_VIDEO':'ADD_IMAGE')),		// Add to category
					has_specific_permission(get_member(),'submit_cat_midrange_content','cms_galleries')?array('_SELF',array('type'=>'ac'),'_SELF',do_lang('ADD_GALLERY')):NULL,				// Add one category
					has_specific_permission(get_member(),'edit_own_cat_midrange_content','cms_galleries')?array('_SELF',array('type'=>'ec'),'_SELF',do_lang('EDIT_GALLERY')):NULL,				// Edit one category
					has_specific_permission(get_member(),'edit_own_cat_midrange_content','cms_galleries')?array('_SELF',array('type'=>'_ec','id'=>$cat),'_SELF'):NULL,		 // Edit this category
					array('galleries',array('type'=>'misc','id'=>$cat),get_module_zone('galleries')),					  // View this category
					/*	  SPECIALLY TYPED 'LINKS'				  */
					array_merge($extra,array(
						/*	 type																page	 params													 zone	  */
						$support_videos?array('add_video_to_this',array('_SELF',array('type'=>'av','cat'=>$cat),'_SELF')):NULL,
						$support_images?array('add_image_to_this',array('_SELF',array('type'=>'ad','cat'=>$cat),'_SELF')):NULL,
						(($video && !$support_images) || (!$video && !$support_videos))?NULL:array($video?'add_one_image':'add_one_video',array('_SELF',array('type'=>$video?'ad':'av'),'_SELF'),do_lang($video?'ADD_IMAGE':'ADD_VIDEO')),		// Add to category
						has_specific_permission(get_member(),'mass_import','cms_galleries')?array('import',array('_SELF',array('type'=>'_gimp','name'=>$cat),'_SELF'),do_lang('GALLERY_IMPORT')):NULL
					)),
					NULL,
					NULL,
					NULL,
					NULL,
					NULL,
					do_lang_tempcode('GALLERIES')
		);
	}

}


