<?php
// scan page's URL and setup media grid deeplinked values in a global variable 

add_action('template_redirect', 'gg_deeplinks_retrieval', 9999);

function gg_deeplinks_retrieval() {
	
	$GLOBALS['gg_deeplinks'] = array();
	$to_use = array();
	
	$curr_url = urldecode(gg_static::curr_url());
	$dl_vars = (array)get_option('gg_deeplinked_elems', array());
	
	// GG-FILTER - allow custom deeplink parameters to be setup in $GLOBALS['gg_deeplinks']
	$dl_vars = apply_filters('gg_dl_vars', $dl_vars);
	
	// if has no query vars or durign an ajax call - stop here
	if(strpos($curr_url, '?') === false || ((isset($_POST['gg_type']) && $_POST['gg_type'] == 'gg_pagination'))) {
		return false;
	}
	
	$raw_url_arr = explode('?', $curr_url);
	$qvars = explode('&', $raw_url_arr[1]); 
	
	// detect MG-related part
	$found_qvars = array();
	foreach($dl_vars as $dlv) {
		if(empty($dlv)) {
            continue;    
        }
        
		foreach($qvars as $part) {
			if(strpos($part, $dlv) !== false) {
				$raw = explode('=', $part);
				if(count($raw) == 1) {
                    continue;
                }
				
				$val_arr 	= explode('/', $raw[1]);
				$found_qvars[ $raw[0] ] = $val_arr[0]; 	
			}
		}
	}
	
	// if none is found - stop here
	if(empty($found_qvars)) {
        return false;
    }
	
	// refine and populate global 
	foreach($found_qvars as $qv => $val) {
		$qv_arr = explode('_', $qv);
		
		// allow params having underscores
		if(count($qv_arr) > 2) {
			$end = end($qv_arr);
			unset( $qv_arr[ (count($qv_arr) - 1) ] );
				
			$qv_arr = array(
				implode('_', $qv_arr),
				$end
			);
		}
		
		
		// gallery/collection difference
		$prefix = (in_array($qv_arr[0], array('gcc', 'gcg'))) ? 'cid_' : 'gid_';

		if(!isset($to_use[ $prefix.$qv_arr[1] ])) {
			$to_use[ $prefix.$qv_arr[1] ] = array();	
		}
		
		$to_use[ $prefix.$qv_arr[1] ][ $qv_arr[0] ] = $val;	
	}
    
	$GLOBALS['gg_deeplinks'] = $to_use;
}
