PageRenderTime 473ms CodeModel.GetById 80ms app.highlight 279ms RepoModel.GetById 103ms app.codeStats 1ms

/wp-content/plugins/file-gallery/includes/templating.php

https://bitbucket.org/Wallynm/iptb
PHP | 987 lines | 723 code | 194 blank | 70 comment | 220 complexity | 08269103d2671d71f31d8bd249918916 MD5 | raw file
  1<?php
  2
  3/**
  4 * Collects template names from theme folder
  5 */
  6function file_gallery_get_templates( $where = NULL )
  7{
  8	$options = get_option('file_gallery');
  9	
 10	if( isset($options['cache']) && true == $options['cache'] )
 11	{		
 12		$transient = 'filegallery_templates';
 13		$cache = get_transient($transient);
 14		
 15		if( $cache )
 16			return $cache;
 17	}
 18
 19	$file_gallery_templates = array();
 20	
 21	// check if file gallery templates folder exists within theme folder
 22	if( is_readable(FILE_GALLERY_THEME_TEMPLATES_ABSPATH) )
 23	{
 24		$opendir = opendir(FILE_GALLERY_THEME_TEMPLATES_ABSPATH);
 25		
 26		while( false !== ($files = readdir($opendir)) )
 27		{
 28			if( '.' != $files && '..' != $files )
 29			{
 30				$tf = FILE_GALLERY_THEME_TEMPLATES_ABSPATH . '/' . $files;
 31		
 32				if( is_readable($tf . '/gallery.php') && is_readable($tf . '/gallery.css') )
 33					$file_gallery_templates[] = $files;
 34			}
 35		}
 36		
 37		closedir($opendir);
 38	}
 39
 40	// check if file gallery templates folder exists within wp-content/file-gallery-templates folder
 41	if( is_readable(FILE_GALLERY_CONTENT_TEMPLATES_ABSPATH) )
 42	{
 43		$opendir = opendir(FILE_GALLERY_CONTENT_TEMPLATES_ABSPATH);
 44		
 45		while( false !== ($files = readdir($opendir)) )
 46		{
 47			if( '.' != $files && '..' != $files )
 48			{
 49				$tf = FILE_GALLERY_CONTENT_TEMPLATES_ABSPATH . '/' . $files;
 50		
 51				if( is_readable($tf . '/gallery.php') && is_readable($tf . '/gallery.css') )
 52					$file_gallery_templates[] = $files;
 53			}
 54		}
 55		
 56		closedir($opendir);
 57	}
 58	
 59	$file_gallery_templates = array_unique($file_gallery_templates);
 60	
 61	$default_templates = unserialize(FILE_GALLERY_DEFAULT_TEMPLATES);
 62	
 63	foreach( $default_templates as $df )
 64	{
 65		$file_gallery_templates[] = $df;
 66	}
 67	
 68	if( isset($options['cache']) && true == $options['cache'] )
 69		set_transient($transient, $file_gallery_templates, $options['cache_time']);
 70
 71	return $file_gallery_templates;
 72}
 73
 74
 75
 76/**
 77 * Injects CSS links via 'stylesheet_uri' filter, if mobile theme is active
 78 */
 79function file_gallery_mobile_css( $stylesheet_url )
 80{
 81	$options = get_option('file_gallery');
 82	
 83	if( isset($options['disable_shortcode_handler']) && true == $options['disable_shortcode_handler'] )
 84		return $stylesheet_url;
 85
 86	file_gallery_css_front( true );
 87	
 88	$mobiles = maybe_unserialize(FILE_GALLERY_MOBILE_STYLESHEETS);
 89
 90	if( !empty($mobiles) )
 91	{
 92		array_push($mobiles, $stylesheet_url);
 93		$glue = '" type="text/css" media="screen" charset="utf-8" />' . "\n\t" . '<link rel="stylesheet" href="';
 94		return implode($glue, $mobiles);
 95	}
 96	
 97	return $stylesheet_url;	
 98}
 99
100
101
102/**
103 * Enqueues stylesheets for each gallery template
104 */
105function file_gallery_css_front( $mobile = false )
106{
107	global $wp_query, $file_gallery;
108
109	$options = get_option('file_gallery');
110	
111	if( isset($options['disable_shortcode_handler']) && true == $options['disable_shortcode_handler'] )
112		return;
113
114	// if option to show galleries in excerpts is set to false
115	if( ! is_singular() && ( ! isset($options['in_excerpt']) || true != $options['in_excerpt']) && false == $mobile )
116		return;
117
118	$gallery_matches = 0;
119	$galleries = array();
120	$missing = array();
121	$mobiles = array();
122	$columns_required = false;
123	$default_templates = unserialize(FILE_GALLERY_DEFAULT_TEMPLATES);
124	
125	// check for gallery shortcode in all posts
126	if( ! empty($wp_query->posts) )
127	{
128		foreach( $wp_query->posts as $post )
129		{
130			$m = preg_match_all("#\[gallery([^\]]*)\]#is", $post->post_content, $g);
131
132			// if there's a match...
133			if( false !== $m && 0 < $m )
134			{
135				$gallery_matches += $m;    // ...add the number of matches to global count...
136				$galleries = array_merge($galleries, $g[1]); // ...and add the match to galleries array
137			}
138		}
139	}
140	
141	// no matches...
142	if( 0 === $gallery_matches )
143		return;
144	
145	// automaticaly enqueue predefined scripts and styles
146	$aqs = explode(',', $options['auto_enqueued_scripts']);
147	$aqs = array_map('trim', $aqs);
148	$aq_linkclasses = array();
149
150	// collect template names
151	foreach( $galleries as $gallery )
152	{
153		if( false === $columns_required )
154		{
155			$zc = preg_match("#\columns=(['\"])0\\1#is", $gallery);
156				
157			if( false !== $zc && 0 < $zc ) // no error and match found
158				$columns_required = false;
159			else
160				$columns_required = true;
161		}
162		
163		$tm = preg_match("#\stemplate=(['\"])([^'\"]+)\\1#is", $gallery, $gm);
164
165		if( isset($gm[2]) )
166			$templates[] = $gm[2];
167		
168		$gcm = preg_match("#\slinkclass=(['\"])([^'\"]+)\\1#is", $gallery, $gcg);
169
170		if( isset($gcg[2]) && '' != $gcg[2] )
171		{
172			$glc = explode(' ', $gcg[2]);
173
174			foreach( $glc as $glcs )
175			{
176				$glcs = trim($glcs);
177
178				if( in_array($glcs, $aqs) )//if( false !== strpos( implode(' ', $aqs), $glcs) )
179					$aq_linkclasses[] = $glcs;
180			}
181		}
182	}
183
184	$aq_linkclasses = apply_filters('file_gallery_lightbox_classes', array_unique($aq_linkclasses));
185
186	// auto enqueue scripts
187	if( ! empty($aq_linkclasses) )
188	{
189		if( ! defined('FILE_GALLERY_LIGHTBOX_CLASSES') )
190			define('FILE_GALLERY_LIGHTBOX_CLASSES', serialize($aq_linkclasses));
191
192		file_gallery_print_scripts( true );
193	}
194	
195	if( empty($templates) )
196	{
197		// enqueue only the default stylesheet if no template names are found
198		if( ! $mobile )
199			wp_enqueue_style('file_gallery_default', FILE_GALLERY_DEFAULT_TEMPLATE_URL . '/gallery.css', false, FILE_GALLERY_VERSION);
200		else
201			$mobiles[] = FILE_GALLERY_DEFAULT_TEMPLATE_URL . '/gallery.css';
202	}
203	else
204	{
205		if( count($templates) < count($galleries) )
206			$templates[] = 'default';
207
208		// eliminate duplicate entries
209		$templates = array_unique($templates);
210		
211		// if none of default templates are needed, don't include the 'columns.css' file
212		if( array() == array_intersect($templates, $default_templates) )
213			$columns_required = false;
214
215		// walk through template names
216		foreach($templates as $template)
217		{
218			$js_dependencies = isset($aq_linkclasses) ? $aq_linkclasses : array();
219
220			// check if file exists in theme's folder
221			if( is_readable(FILE_GALLERY_THEME_TEMPLATES_ABSPATH . '/' . $template . '/gallery.css') )
222			{
223				if( ! $mobile )
224					wp_enqueue_style('file_gallery_' . str_replace(' ', '-', $template), FILE_GALLERY_THEME_TEMPLATES_URL . '/' . str_replace(' ', '%20', $template) . '/gallery.css', false, FILE_GALLERY_VERSION);
225				else
226					$mobiles[] = FILE_GALLERY_THEME_TEMPLATES_URL . '/' . str_replace(' ', '%20', $template) . '/gallery.css';
227				
228				if( is_readable(FILE_GALLERY_THEME_TEMPLATES_ABSPATH . '/' . $template . '/gallery.js') )
229				{
230					$overriding = true;
231					ob_start();
232						include(FILE_GALLERY_THEME_TEMPLATES_ABSPATH . '/' . $template . '/gallery.php');					
233					ob_end_clean();
234					$overriding = false;
235
236					wp_enqueue_script('file_gallery_' . str_replace(' ', '-', $template), FILE_GALLERY_THEME_TEMPLATES_URL . '/' . str_replace(' ', '%20', $template) . '/gallery.js', $js_dependencies, FILE_GALLERY_VERSION, true);	
237				}
238			}
239			// check if file exists in wp-content/file-gallery-templates folder
240			elseif( is_readable(FILE_GALLERY_CONTENT_TEMPLATES_ABSPATH . '/' . $template . '/gallery.css') )
241			{
242				if( ! $mobile )
243					wp_enqueue_style('file_gallery_' . str_replace(' ', '-', $template), FILE_GALLERY_CONTENT_TEMPLATES_URL . '/' . str_replace(' ', '%20', $template) . '/gallery.css', false, FILE_GALLERY_VERSION);
244				else
245					$mobiles[] = FILE_GALLERY_CONTENT_TEMPLATES_URL . '/' . str_replace(' ', '%20', $template) . '/gallery.css';
246				
247				if( is_readable(FILE_GALLERY_CONTENT_TEMPLATES_ABSPATH . '/' . $template . '/gallery.js') )
248				{
249					$overriding = true;
250					ob_start();
251						include(FILE_GALLERY_CONTENT_TEMPLATES_ABSPATH . '/' . $template . '/gallery.php');					
252					ob_end_clean();
253					$overriding = false;
254
255					wp_enqueue_script('file_gallery_' . str_replace(' ', '-', $template), FILE_GALLERY_CONTENT_TEMPLATES_URL . '/' . str_replace(' ', '%20', $template) . '/gallery.js', $js_dependencies, FILE_GALLERY_VERSION, true);	
256				}
257			}
258			// check plugin templates folder
259			elseif( is_readable(FILE_GALLERY_ABSPATH . "/templates/" . $template . "/gallery.css") )
260			{				
261				if( ! $mobile )
262					wp_enqueue_style('file_gallery_' . $template, FILE_GALLERY_URL . '/templates/' . $template . '/gallery.css', false, FILE_GALLERY_VERSION);
263				else
264					$mobiles[] = FILE_GALLERY_URL . '/templates/' . $template . '/gallery.css';
265				
266				if( is_readable(FILE_GALLERY_ABSPATH . '/templates/' . $template . '/gallery.js') )
267				{
268					$overriding = true;
269					ob_start();
270						include(FILE_GALLERY_ABSPATH . '/templates/' . $template . '/gallery.php');
271					ob_end_clean();
272					$overriding = false;
273
274					wp_enqueue_script('file_gallery_' . str_replace(' ', '-', $template), FILE_GALLERY_URL . '/templates/' . str_replace(' ', '%20', $template) . '/gallery.js', $js_dependencies, FILE_GALLERY_VERSION, true );
275				}
276			}
277			// template does not exist, enqueue default one
278			else
279			{
280				$missing[] = $template;
281				wp_enqueue_style('file_gallery_default', FILE_GALLERY_URL . '/templates/default/gallery.css', false, FILE_GALLERY_VERSION);
282				
283				echo '<!-- ' . __('file does not exist:', 'file-gallery') . ' ' . $template . '/gallery.css - ' . __('using default style', 'file-gallery') . '-->\n';
284			}
285		}
286	}
287	
288	if( $columns_required )
289	{
290		if( ! $mobile )
291			wp_enqueue_style('file_gallery_columns', FILE_GALLERY_URL . '/templates/columns.css', false, FILE_GALLERY_VERSION);
292		else
293			$mobiles[] = FILE_GALLERY_URL . '/templates/columns.css';
294	}
295
296	if( $mobile && ! defined('FILE_GALLERY_MOBILE_STYLESHEETS') )
297		define('FILE_GALLERY_MOBILE_STYLESHEETS', serialize($mobiles));
298}
299add_action('wp_print_styles',  'file_gallery_css_front');
300add_action('wp_print_scripts', 'file_gallery_css_front');
301
302
303
304/**
305 * prints scripts and styles for auto enqueued linkclasses
306 */
307function file_gallery_print_scripts( $styles = false )
308{
309	$options = get_option('file_gallery');
310	
311	if( isset($options['disable_shortcode_handler']) && true == $options['disable_shortcode_handler'] )
312		return;
313
314	if( defined('FILE_GALLERY_LIGHTBOX_CLASSES') )
315	{
316		$linkclasses = maybe_unserialize(FILE_GALLERY_LIGHTBOX_CLASSES);
317
318		if( ! empty($linkclasses) )
319		{
320			foreach( $linkclasses as $lc )
321			{
322				if( $styles )
323				{
324					wp_enqueue_style( $lc );
325				}
326				else
327				{
328					if( 'thickbox' == $lc )
329					{
330echo "\n" . 
331'<script type="text/javascript">
332	var tb_pathToImage = "' . includes_url() . 'js/thickbox/loadingAnimation.gif";
333	var tb_closeImage  = "' . includes_url() . 'js/thickbox/tb-close.png";
334</script>'
335. "\n";
336					}
337					
338					wp_enqueue_script( $lc );
339				}
340			}
341		}
342	}
343}
344add_action('wp_print_scripts', 'file_gallery_print_scripts');
345
346
347/**
348 * For easy inline overriding of shortcode-set options
349 *
350 * @since 1.6.5.1
351 */
352function file_gallery_overrides( $args )
353{
354	global $file_gallery;
355
356	if( is_string($args) )
357		$args = wp_parse_args($args);
358	
359	$file_gallery->overrides = $args;
360}
361
362
363/**
364 * Main shortcode function
365 *
366 * @since 0.1
367 */
368function file_gallery_shortcode( $content = false, $attr = false )
369{
370	global $file_gallery, $wpdb, $post;
371
372	// if the function is called directly, not via shortcode
373	if( false !== $content && false === $attr )
374		$attr = $content;
375		
376	if( ! isset($file_gallery->gallery_id) )
377		$file_gallery->gallery_id = 1;
378	else
379		$file_gallery->gallery_id++;
380	
381	$options = get_option('file_gallery');
382
383	if( isset($options['cache']) && true == $options['cache'] )
384	{
385		if( 'html' == $attr['output_type'] || ( isset($options['cache_non_html_output']) && true == $options['cache_non_html_output'] ) )
386		{
387			$transient = 'filegallery_' . md5( $post->ID . "_" . serialize($attr) );
388			$cache     = get_transient($transient);
389			
390			if( $cache )
391				return $cache;
392		}
393	}
394
395	// if option to show galleries in excerpts is set to false...
396	// ...replace [gallery] with user selected text
397	if( ! is_singular() && ( ! isset($options['in_excerpt']) || true != $options['in_excerpt']) )
398		return $options['in_excerpt_replace_content'];
399	
400	$default_templates = unserialize(FILE_GALLERY_DEFAULT_TEMPLATES);
401	
402	// We're trusting author input, so let's at least make sure it looks like a valid orderby statement
403	if( isset($attr['orderby']) )
404	{
405		$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
406		
407		if( ! $attr['orderby'] )
408			unset($attr['orderby']);
409	}
410	
411	// extract the defaults...
412	extract(
413		shortcode_atts(
414			array(
415				/* default values: */
416			//  'itemtag'    => 'dl',
417			//  'icontag'    => 'dt',
418			//  'captiontag' => 'dd',
419	
420				'order'				=> 'ASC',
421				'orderby'			=> '',
422				'id'				=> $post->ID,
423				'columns'			=> 3,
424				'size'				=> 'thumbnail',
425				'link'				=> 'attachment',
426				'include'			=> '',
427				'exclude'			=> '',
428	
429				/* added by file gallery: */
430				'template'			=> 'default',
431				'linkclass'			=> '',
432				'imageclass'		=> '',
433				'galleryclass'		=> '',
434				'rel'				=> 1,
435				'tags'				=> '',
436				'tags_from'			=> 'current',
437				'output_type'		=> 'html',
438				'output_params'		=> 1,				// needed when outputting html
439				'attachment_ids'	=> '',				// alias of 'include'
440				'mimetype'			=> '',
441				'limit' 			=> -1,
442				'offset'			=> -1,
443				'paginate'			=> 0,
444				'link_size'			=> 'full'
445			)
446		, $attr)
447	);
448
449	if( ! in_array($template, $default_templates) )
450	{
451		$template_file = FILE_GALLERY_THEME_TEMPLATES_ABSPATH . '/' . $template . '/gallery.php';
452		
453		if( ! is_readable($template_file) )
454			$template_file = FILE_GALLERY_CONTENT_TEMPLATES_ABSPATH . '/' . $template . '/gallery.php';
455	}
456	else
457	{
458		if( 'default' == $template )
459		{
460			$template_file = FILE_GALLERY_DEFAULT_TEMPLATE_ABSPATH . '/gallery.php';
461			$template      = FILE_GALLERY_DEFAULT_TEMPLATE_NAME;
462		}
463		else
464		{
465			$template_file = FILE_GALLERY_ABSPATH . '/templates/' . $template . '/gallery.php';
466		}
467	}
468
469	// check if template exists and replace with default if it does not
470	if( ! is_readable($template_file) )
471	{
472		$template_file = FILE_GALLERY_ABSPATH . '/templates/default/gallery.php';
473		$template      = 'default';
474	}
475	
476	// get overriding variables from the template file
477	$overriding = true;
478	ob_start();
479		include($template_file);
480	ob_end_clean();
481	$overriding = false;
482
483	if( is_array($file_gallery->overrides) && ! empty($file_gallery->overrides) )
484	{
485		extract($file_gallery->overrides);
486		$file_gallery->overrides = NULL;
487	}
488
489	$limit  = (int) $limit;	
490	$offset = (int) $offset;
491	$page   = (int) get_query_var('page');
492
493	if( 'false' === $rel || (is_numeric($rel) && 0 === (int) $rel) )
494		$_rel = false;
495	elseif( 1 === $rel )
496		$_rel = true;
497	else
498		$_rel = $rel;
499
500	if( 'false' === $output_params || (is_numeric($output_params) && 0 === (int) $output_params) )
501		$output_params = false;
502	else
503		$output_params = true;
504	
505	if( 'false' === $paginate || (is_numeric($paginate) && 0 === (int) $paginate) || 0 > $limit )
506	{
507		$paginate   = false;
508		$found_rows = '';
509	}
510	else
511	{
512		$paginate   = true;
513		$found_rows = 'SQL_CALC_FOUND_ROWS';
514		
515		if( 0 === $page )
516			$page = 1;
517
518		if( is_singular() && 1 < $page )
519			$offset = $limit * ($page - 1);
520	}
521	
522	$file_gallery->debug_add('pagination', compact('paginate', 'page'));
523
524	if( '' != $include && '' == $attachment_ids )
525		$attachment_ids = $include;
526	
527	if( ! isset( $linkto ) )
528		$linkto = $link;
529	
530	$sql_mimetype = '';
531	
532	if( '' != $mimetype )
533	{
534		$mimetype     = file_gallery_get_mime_type($mimetype);
535		$sql_mimetype = wp_post_mime_type_where($mimetype);
536	}
537
538	$approved_attachment_post_statuses = apply_filters('file_gallery_approved_attachment_post_statuses', array('inherit', 'draft'));
539	$ignored_attachment_post_statuses  = apply_filters('file_gallery_ignored_attachment_post_statuses', array('trash', 'private', 'pending', 'future'));
540	
541	if( ! empty($approved_attachment_post_statuses) )
542		$post_statuses = " AND ($wpdb->posts.post_status IN ('" . implode("', '", $approved_attachment_post_statuses) . "') ) ";
543	elseif( ! empty($ignored_attachment_post_statuses) )
544		$post_statuses = " AND ($wpdb->posts.post_status NOT IN ('" . implode("', '", $ignored_attachment_post_statuses) . "') ) ";
545	else
546		$post_statuses = "";
547	
548	$file_gallery_query = new stdClass();
549
550	// start with tags because they negate everything else
551	if( '' != $tags )
552	{
553		if( '' == $orderby || 'file_gallery' == $orderby )
554			$orderby = "menu_order ID";
555
556		$query = array(
557			'post_status'		=> implode(',', $approved_attachment_post_statuses), 
558			'post_type'			=> 'attachment', 
559			'order'				=> $order, 
560			'orderby'			=> $orderby,
561			'posts_per_page'	=> $limit,
562			'post_mime_type'	=> $mimetype,
563			FILE_GALLERY_MEDIA_TAG_NAME => $tags
564		);
565		
566		if( 'current' == $tags_from )
567			$query['post_parent'] = $id;
568		
569		if ( ! empty($exclude) )
570			$query['post__not_in'] = explode(',', preg_replace( '/[^0-9,]+/', '', $exclude ));
571		
572		if( 0 < $offset )
573			$query['offset'] = $offset;
574
575		$file_gallery_query = new WP_Query( $query );
576		$attachments = $file_gallery_query->posts;
577		
578		unset($query);
579	}
580	elseif( '' != $attachment_ids )
581	{
582		$attachment_ids = trim($attachment_ids, ',');
583		$attachment_ids = explode(',', $attachment_ids);
584		$sql_limit      = count($attachment_ids);
585
586		if( 'rand' == $orderby )
587			shuffle($attachment_ids);
588			
589		$attachment_ids = implode(',', $attachment_ids);
590
591		if( '' == $orderby || 'rand' == $orderby )
592		{
593			$orderby = sprintf("FIELD(ID,'%s')", str_replace(",", "','", $attachment_ids));
594			$order   = '';
595		}
596		elseif( 'title' == $orderby )
597		{
598			$orderby = "$wpdb->posts.post_title";
599		}
600		
601		$query = sprintf(
602			"SELECT " . $found_rows . " * FROM $wpdb->posts 
603			 WHERE $wpdb->posts.ID IN (%s) 
604			 AND $wpdb->posts.post_type = 'attachment' 
605			" . $post_statuses . " ", 
606		$attachment_ids);
607		
608		$query .= $sql_mimetype;
609		$query .= sprintf(" ORDER BY %s %s ", $orderby, $order);
610		
611		if( true !== $paginate )
612			$limit = $sql_limit;
613	}
614	else
615	{
616		if( '' == $orderby )
617			$orderby = "menu_order ID";
618
619		$query = array(
620			'post_parent'		=> $id,
621			'post_status'		=> implode(',', $approved_attachment_post_statuses), 
622			//'post_status'		=> $approved_attachment_post_statuses, 
623			'post_type'			=> 'attachment', 
624			'order'				=> $order, 
625			'orderby'			=> $orderby,
626			//'numberposts'		=> $limit,
627			'posts_per_page'	=> $limit,
628			'post_mime_type'	=> $mimetype
629		);
630
631		if ( ! empty($exclude) )
632			$query['post__not_in'] = explode(',', preg_replace( '/[^0-9,]+/', '', $exclude ));
633		
634		if( 0 < $offset )
635			$query['offset'] = $offset;
636
637		$file_gallery_query = new WP_Query( $query );
638		$attachments = $file_gallery_query->posts;
639		
640		unset($query);
641	}
642	
643	if( isset($query) )
644	{		
645		if( 0 < $limit )
646			$query .= " LIMIT " . $limit;
647		
648		if( 0 < $offset )
649			$query .= " OFFSET " . $offset;
650
651		$attachments = $wpdb->get_results( $query );
652
653		if( '' != $found_rows )
654		{
655			$file_gallery_query->found_posts = $wpdb->get_var("SELECT FOUND_ROWS()");
656			$file_gallery_query->max_num_pages = ceil($file_gallery_query->found_posts / $limit);
657		}
658	}
659
660	if( empty($attachments) )
661		return '<!-- "File Gallery" plugin says: - No attachments found for the following shortcode arguments: "' . json_encode($attr) . '" -->';
662
663	// feed
664	if( is_feed() )
665	{
666		$output = "\n";
667
668		foreach( $attachments as $attachment )
669		{
670			$output .= wp_get_attachment_link($attachment->ID, $size, true) . "\n";
671		}
672		
673		return $output;
674	}
675	
676	$i = 0;
677	$unique_ids = array();
678	$gallery_items = '';
679	
680	if( 'object' == $output_type || 'array' == $output_type )
681		$gallery_items = array();
682	
683	$autoqueueclasses = array();
684	
685	if( defined('FILE_GALLERY_LIGHTBOX_CLASSES') )
686		$autoqueueclasses = maybe_unserialize(FILE_GALLERY_LIGHTBOX_CLASSES);
687	else
688		$autoqueueclasses = explode(',', $options['auto_enqueued_scripts']);
689	
690	$file_gallery_this_template_counter = 1;
691
692	// create output
693	foreach($attachments as $attachment)
694	{
695		$param = array(
696			'image_class' => $imageclass,
697			'link_class'  => $linkclass,
698			'rel'         => $_rel,
699			'title'       => '',
700			'caption'     => '',
701			'description' => '',
702			'thumb_alt'   => ''
703		);
704
705		$attachment_file = get_attached_file($attachment->ID);
706		$attachment_is_image = file_gallery_file_is_displayable_image($attachment_file);
707		$endcol = '';
708		$x = '';
709
710		if( $output_params )
711		{			
712			$plcai = array_intersect($autoqueueclasses, explode(' ', trim($linkclass)));
713
714			if( ! empty($plcai) )
715			{
716				if( $attachment_is_image )
717				{
718					if( true === $param['rel'] )
719					{
720						$param['rel'] = $plcai[0] . '[' .  $file_gallery->gallery_id . ']';
721					}
722					elseif( ! is_bool($param['rel']) )
723					{
724						if( false !== strpos($_rel, '$GID$') )
725							$param['rel'] = str_replace('$GID$', $file_gallery->gallery_id, $_rel);
726						else
727							$param['rel'] = $_rel . '[' .  $file_gallery->gallery_id . ']';
728					}
729					
730					$filter_args = array(
731						'gallery_id' => $file_gallery->gallery_id, 
732						'linkrel'    => $param['rel'],
733						'linkclass'  => $param['link_class'],
734						'imageclass' => $param['image_class']
735					);
736
737					if( $param['rel'] )
738						$param['rel'] = apply_filters('file_gallery_lightbox_linkrel',    $param['rel'],         'linkrel',    $filter_args);
739					
740					$param['link_class']  = apply_filters('file_gallery_lightbox_linkclass',  $param['link_class'],  'linkclass',  $filter_args);
741					$param['image_class'] = apply_filters('file_gallery_lightbox_imageclass', $param['image_class'], 'imageclass', $filter_args);
742				}
743				else
744				{
745					$param['link_class'] = str_replace( trim(implode(' ', $plcai)), '', trim($linkclass));
746				}
747			}
748			
749			// if rel is still true or false
750			if( is_bool($param['rel']) )
751				$param['rel'] = '';
752
753			switch( $linkto )
754			{
755				case 'parent_post' :
756					$param['link'] = get_permalink( $wpdb->get_var("SELECT post_parent FROM $wpdb->posts WHERE ID = '" . $attachment->ID . "'") );
757					break;
758				case 'file' :
759					$param['link'] = wp_get_attachment_url($attachment->ID);
760					break;
761				case 'attachment' :
762					$param['link'] = get_attachment_link($attachment->ID);
763					break;
764				case 'none' :
765					$param['link'] = '';
766					break;
767				default : // external url
768					$param['link'] = urldecode($linkto);
769					break;
770			}
771						
772			$param['title'] 		= $attachment->post_title;
773			$param['caption'] 		= $attachment->post_excerpt;
774			$param['description'] 	= $attachment->post_content;
775			
776			if( $attachment_is_image )
777			{
778				$thumb_src             = wp_get_attachment_image_src($attachment->ID, $size);
779				$param['thumb_link']   = $thumb_src[0];
780				$param['thumb_width']  = 0 == $thumb_src[1] ? file_gallery_get_image_size($param['thumb_link'])       : $thumb_src[1];
781				$param['thumb_height'] = 0 == $thumb_src[2] ? file_gallery_get_image_size($param['thumb_link'], true) : $thumb_src[2];	
782				
783				if( '' != $param['link'] && 'full' != $link_size && in_array($link_size, file_gallery_get_intermediate_image_sizes()) )
784				{
785					$full_src = wp_get_attachment_image_src($attachment->ID, $link_size);
786					$param['link'] = $full_src[0];
787				}
788			}
789			else
790			{
791				$param['thumb_link']   = file_gallery_https( FILE_GALLERY_CRYSTAL_URL ) . '/' . file_gallery_get_file_type($attachment->post_mime_type) . '.png';
792				$param['thumb_link']   = apply_filters('file_gallery_non_image_thumb_link', $param['thumb_link'], $attachment->post_mime_type, $attachment->ID);
793				$param['thumb_width']  = '46';
794				$param['thumb_height'] = '60';
795			}
796
797			if( $thumb_alt = get_post_meta($attachment->ID, '_wp_attachment_image_alt', true) )
798				$param['thumb_alt'] = $thumb_alt;
799			
800			$param['attachment_id'] = $attachment->ID;
801		}
802		
803		$param = array_map('trim', $param);
804		
805		if( 'object' == $output_type )
806		{
807			if( $output_params )
808				$attachment->params = (object) $param;
809			
810			$gallery_items[] = $attachment;
811		}
812		elseif( 'array' == $output_type || 'json' == $output_type)
813		{
814			if( $output_params )
815				$attachment->params = $param;
816			
817			$gallery_items[] = get_object_vars($attachment);
818		}
819		else
820		{
821			// add the column break class and append a line break...
822			if ( $columns > 0 && ++$i % $columns == 0 )
823				$endcol = ' gallery-endcol';
824
825			// parse template
826			ob_start();
827				extract( $param );
828				include($template_file);
829				$x = ob_get_contents();
830			ob_end_clean();
831			
832			$file_gallery_this_template_counter++;
833			
834			if ( $columns > 0 && $i % $columns == 0 )
835				$x .= $cleartag;
836			
837			$gallery_items .= $x;
838		}
839	}
840
841	// handle data types
842	if( 'object' == $output_type || 'array' == $output_type )
843	{
844		$output = $gallery_items;
845	}
846	elseif( 'json' == $output_type )
847	{
848		$output = json_encode($gallery_items);
849	}
850	else
851	{
852		$stc = '';
853		$cols = '';
854		$pagination_html = '';
855
856		if( 0 < (int) $columns )
857			$cols = ' columns_' . $columns;
858		
859		if( isset($starttag_class) && '' != $starttag_class )
860			$stc = ' ' . $starttag_class;
861		
862		$trans_append = "\n<!-- file gallery output cached on " . date('Y.m.d @ H:i:s', time()) . "-->\n";
863		
864		if( is_singular() && isset($file_gallery_query->max_num_pages) && 1 < $file_gallery_query->max_num_pages )
865			$pagination_html = file_gallery_do_pagination( $file_gallery_query->max_num_pages, $page );
866
867		$gallery_class = apply_filters('file_gallery_galleryclass', 'gallery ' . str_replace(' ', '-', $template) . $cols . $stc . ' ' . $galleryclass);
868		
869		$output = '<' . $starttag . ' id="gallery-' . $file_gallery->gallery_id . '" class="' . $gallery_class . '">' . "\n" . $gallery_items . "\n" . $pagination_html . "\n</" . $starttag . '>';
870	}
871	
872	if( isset($options['cache']) && true == $options['cache'] )
873	{
874		if( 'html' == $output_type )
875			set_transient($transient, $output . $trans_append, $options['cache_time']); // with a comment appended to the end of cached output
876		elseif( isset($options['cache_non_html_output']) && true == $options['cache_non_html_output'] )
877			set_transient($transient, $output, $options['cache_time']);
878	}
879	
880	return apply_filters('file_gallery_output', $output, $post->ID, $file_gallery->gallery_id);
881}
882
883
884/**
885 * Built-in pagination for galleries
886 *
887 * @since 1.6.5.1
888 */
889function file_gallery_do_pagination( $total = 0, $page = 0 )
890{
891	if( 0 < $total && 0 < $page )
892	{
893		remove_query_arg('page');
894
895		$options = get_option('file_gallery');
896		$out = array('<span class="current">' . $page . '</span>');
897
898		if( ! isset($options['pagination_count']) || empty($options['pagination_count']) || 0 >= $options['pagination_count'] )
899			$limit = 9;
900		else
901			$limit = $options['pagination_count'];
902
903		$c = 0;
904		$l = $limit;
905		$end = false;
906		$start = false;
907		$current = $page;
908
909		$sides = ($limit - 1) / 2;
910		$sl = ceil($sides);
911		$sr = floor($sides);
912		
913		// skip to first page link
914		if( ($limit - $sl) < $current )
915			$start = true;
916		
917		// skip to last page link
918		if( ($total - $sr) > $current )
919			$end = true;
920
921		// left side
922		if( 1 < $current )
923		{
924			$current--;
925
926			while( 0 < $current && 0 < $sl)
927			{
928				array_unshift($out, str_replace('<a ', '<a class="page"', _wp_link_page($current)) . $current . '</a>');
929				
930				$current--;
931				$sl--;
932				$limit--;
933			}
934			
935			$c = $current;
936		}
937
938		$current = $page + 1;
939		$sr += $sl;
940		
941		// right side
942		while( $current <= $total && 0 < $sr )
943		{
944			array_push($out, str_replace('<a ', '<a class="page"', _wp_link_page($current)) . $current . '</a>');
945			
946			$current++;
947			$sr--;
948			$limit--;
949		}
950		
951		// leftovers
952		while( 1 < $limit && 0 < $c )
953		{
954			array_unshift($out, str_replace('<a ', '<a class="page"', _wp_link_page($c)) . $c . '</a>');
955
956			$c--;
957			$limit--;
958		}
959		
960		if( $start )
961			array_unshift($out, str_replace('<a ', '<a title="' . __('Skip to first page', 'file-gallery') . '" class="page"', _wp_link_page(1)) . '&laquo;</a>');
962		
963		if( $end )
964			array_push($out, str_replace('<a ', '<a title="' . __('Skip to last page', 'file-gallery') . '" class="page"', _wp_link_page($total)) . '&raquo;</a>');
965		
966		if( 'rtl' == get_bloginfo('text_direction') )
967			$out = array_reverse($out);
968		
969		return '<div class="wp-pagenavi">' . "\n" . implode("\n", $out) . "\n</div>";
970	}
971	
972	return '';
973}
974
975
976function file_gallery_register_shortcode_handler()
977{
978	$options = get_option('file_gallery');
979
980	if( isset($options['disable_shortcode_handler']) && true == $options['disable_shortcode_handler'] )
981		return;
982
983	add_filter('post_gallery', 'file_gallery_shortcode', 10, 2);
984}
985add_action('init', 'file_gallery_register_shortcode_handler');
986
987?>