<?php
/*
	Author: WPG2 Team
	Updated: 26/09/2007

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.
*/


/*
********************************************************************************************************
													G2 Session Handling
********************************************************************************************************
*/

/**
* Initialize Gallery; must be called before most GalleryEmbed methods can be used.
* This method should only be called once during the lifetime of the request.
*
* @param NULL
* @return string GalleryStatus
*/

function g2_init() {

	// Get WPG2 Option Settings
	$wpg2_option = get_option('wpg2_options');
	$wpg2_g2path = get_option('wpg2_g2paths');

	@include_once($wpg2_g2path['g2_filepath'].'embed.php');

	if (!defined('G2PARTINIT')) {
		// Initialise GalleryAPI
			$ret = GalleryEmbed::init( array(
						'embedUri' => $wpg2_g2path['g2_embeduri'],
						'g2Uri' => $wpg2_g2path['g2_url'],
						'loginRedirect' => $wpg2_g2path['g2_errorredirect'],
						'fullInit' => true)
					);
	} else {
		// Initialise GalleryAPI
			$ret = GalleryEmbed::init( array(
						'embedUri' => $wpg2_g2path['g2_embeduri'],
						'g2Uri' => $wpg2_g2path['g2_url'],
						'loginRedirect' => $wpg2_g2path['g2_errorredirect'])
				);
	}

	if ($ret) {
		$ret->getAsHtml();
		return $ret;
	} else {
		// Declate G2 Init so we do not do it again..
		define("G2INIT", "True");
		return $ret;
	}
}

/*
********************************************************************************************************
											G2 User Handling
********************************************************************************************************
*/

/**
* Logs in the externally mapped Gallery2 User Account
*
* @param NULL
* @return string GalleryStatus
*/

function g2_login() {
	// Get WPG2 Option Settings
	$wpg2_option = get_option('wpg2_options');
	global $user_ID;

// Initalise the WP Capacitiy Class
	$userrole = new WP_User($user_ID);

	if (!defined('G2INIT')) {
		$ret = g2_init();
		if (!$ret) {
//	Try to Login with Current WP User Mapping via G2 ExternalID if user has Gallery2_user
			if ($user_ID) {
				if ($userrole->has_cap('gallery2_user')) {
                    $ret = GalleryEmbed::isExternalIdMapped($user_ID, 'GalleryUser');
					if (!$ret) {
						list ($ret, $user) = GalleryCoreApi::loadEntityByExternalId($user_ID, 'GalleryUser');
					}
					if ($ret) {
						g2_create_user($user_ID);
					}

					$ret = GalleryEmbed::checkActiveUser($user_ID);
					if ($ret) {
						return $ret;
					}
				} else {
					// Otherwise Guest
					$ret = GalleryEmbed::checkActiveUser('');
					if ($ret) {
						return $ret;
					}
				}
			} else {
	// Otherwise Guest
			$ret = GalleryEmbed::checkActiveUser('');
			if ($ret) {
				return $ret;
				}
			}
	} else
		$ret;

	return $ret;

	}
}


/**
* Logs Out the Externally Mapped Gallery2 User
*
* @param NULL
* @return NULL
*/

function g2_logout() {

	// Get WPG2 Option Settings
	$wpg2_g2path = get_option('wpg2_g2paths');

	// Test if Plugin has been validated.
	if ($wpg2_g2path['g2_validated'] == "Yes" ) {
		@include_once($g2_['g2_filepath'].'embed.php');

		$ret = GalleryEmbed::logout( array(
				'embedUri' => $wpg2_g2path['g2_embed'])
			);

	}

}

/**
* Creates an externally mapped Gallery2 User account.
*
* @param Internal Wordpress User ID
* @return NULL
*/

function g2_create_user($wpuser_id) {

	if (!defined('G2INIT')) {
		$ret = g2_init();
		if ($ret) {
			echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
			exit;
		}
	}

// Does the user have gallery2_user Role
    $usercap = new WP_User($wpuser_id);
    if ($usercap->has_cap('gallery2_user')) {
     // Check to Make Sure User Doesn't already Exist
       $ret = GalleryEmbed::isExternalIdMapped($wpuser_id, 'GalleryUser');
	   if ($ret) {
            list ($ret, $g2user ) = GalleryCoreApi::fetchUserByUsername($usercap->user_login);
			if (!$ret) {
                GalleryEmbed::addExternalIdMapEntry($wpuser_id, $g2user->id, 'GalleryUser');
            } else {
                $ret = GalleryEmbed::createUser( $usercap->ID, array ( 'username' => $usercap->user_login, 'email' => $usercap->user_email, 'fullname' => $usercap->user_nicename,
						'hashedpassword' => $usercap->user_pass, 'hashmethod' => 'md5'));
				if ($ret) {
					echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
					exit;
				}
				$ret = GalleryEmbed::done();
             }
        }
    }

    if ($ret) {
        echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
        exit;
    }

	return $ret;

}

/**
* Promotes a externally mapped Gallery2 user into the Gallery2 Admin Group
*
* @param int wordpress User ID
* @return string GalleryStatus
*/

function g2_admin_user($wpuser_id) {

	if (!defined('G2INIT')) {
		$ret = g2_init();
		if ($ret) {
			echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
			exit;
		}
	}

    $usercap = new WP_User($wpuser_id);
    if ($usercap->has_cap('gallery2_admin')) {

	 // Check to Make Sure User Does already Exist
		$ret = GalleryEmbed::isExternalIdMapped($wpuser_id, 'GalleryUser');
		if (!$ret) {
			list ($ret, $g2user) = GalleryCoreApi::loadEntityByExternalId($wpuser_id, 'GalleryUser');
			if ($ret) {
				echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
				exit;
			}

			list ($ret, $isAdmin) = GalleryCoreApi::isUserInSiteAdminGroup($g2user->id);
			if (!$isAdmin) {
			   list ($ret, $siteAdminGroupId) = GalleryCoreApi::getPluginParameter('module', 'core', 'id.adminGroup');
			   $ret = GalleryCoreApi::addUserToGroup($g2user->id, $siteAdminGroupId);
				if ($ret) {
					echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
					exit;
				}
				$ret = GalleryEmbed::done();
			}
		}
	} else {
		$ret = GalleryEmbed::isExternalIdMapped($wpuser_id, 'GalleryUser');
		if (!$ret) {
			list ($ret, $g2user) = GalleryCoreApi::loadEntityByExternalId($wpuser_id, 'GalleryUser');
			if ($ret) {
				echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
				exit;
			}
			list ($ret, $isAdmin) = GalleryCoreApi::isUserInSiteAdminGroup($g2user->id);
			if ($isAdmin) {
			   list ($ret, $siteAdminGroupId) = GalleryCoreApi::getPluginParameter('module', 'core', 'id.adminGroup');
			   $ret = GalleryCoreApi::removeUserFromGroup($g2user->id, $siteAdminGroupId);
				if ($ret) {
					echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
					exit;
				}
				$ret = GalleryEmbed::done();
			}
		} else // Reset Return Because G2<>WP Users Are In Sync
			$ret = "";

	}

	return $ret;


}

/**
* Deletes a externally mapped Gallery2 User Accout
*
* @param int Wordpress User ID
* @return string GalleryStatus
*/

function g2_delete_user($wpuser_id) {

	if (!defined('G2INIT')) {
		$ret = g2_init();
		if ($ret) {
			echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
			exit;
		}
	}

	// Check to Make Sure User Does already Exist
	$ret = GalleryEmbed::isExternalIdMapped($wpuser_id, 'GalleryUser');
	if (!$ret) {
	   $ret = GalleryEmbed::deleteUser($wpuser_id);
		if ($ret) {
			echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
			exit;
		}
		$ret = GalleryEmbed::done();
	} else
		$ret = "";

	return $ret;

}

/**
* Updates a externally mapped Gallery2 User Account
*
* @param int Wordpress User ID
* @return string GalleryStatus
*/


function g2_update_user($wpuser_id) {

	if (!defined('G2INIT')) {
		$ret = g2_login();
		if ($ret) {
			echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
			exit;
		}
	}

// Does the user have gallery2_user Role
    $usercap = new WP_User($wpuser_id);
    if ($usercap->has_cap('gallery2_user')) {
     // Check to Make Sure User Does already Exist
		$ret = GalleryEmbed::isExternalIdMapped($wpuser_id, 'GalleryUser');
        if (!$ret) {
	        $ret = GalleryEmbed::updateUser( $wpuser_id, array ( 'username' => $usercap->user_login, 'email' => $usercap->user_email, 'fullname' => $usercap->user_nicename,
                    'hashedpassword' => $usercap->user_pass, 'hashmethod' => 'md5'));
        } else
			$ret = g2_create_user($wpuser_id);

		if ($ret) {
			echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
			exit;
		}

		$ret = GalleryEmbed::done();

    }

	if (!$ret)
		$ret = g2_admin_user($wpuser_id);

	if ($ret) {
		echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
		exit;
	}

}

/*
********************************************************************************************************
																G2 Validation
********************************************************************************************************
*/

/**
* Validates if Gallery is located at the supplied URL
*
* @param string url
* @return string error Code
*/
function wpg2_validateg2url($g2url) {

	// Include the Gallery2 Validation Tools
	$slash = DIRECTORY_SEPARATOR;
	$wpg2base = 'wp-content'.$slash.'plugins'.$slash.'wpg2';

	@include_once(ABSPATH . $wpg2base . $slash . 'g2embeddiscoveryutilities.class');

	// Set up the URL's and Paths
	$site_url = trailingslashit(get_option('siteurl'));
	$g2Uri = G2EmbedDiscoveryUtilities::normalizeG2Uri($g2url);
	$embedUri = G2EmbedDiscoveryUtilities::normalizeG2Uri($site_url);
	$file_path = ABSPATH;
	// Filter G2 URL and Verify
	list ($success, $embedPhpPath, $errorString) = G2EmbedDiscoveryUtilities::getG2EmbedPathByG2Uri($g2Uri);
	if (!$success) {
	// Return Error
		list ($success, $embedPhpPath, $ret) = G2EmbedDiscoveryUtilities::getG2EmbedPathByG2UriEmbedUriAndLocation($g2Uri, $embedUri, $file_path);
	} else {
	// Set the Plugin Paths
		$wpg2_g2path['g2_filepath'] = rtrim ($embedPhpPath, "embed.php");

// Clean up File Structure..
		$slash = DIRECTORY_SEPARATOR;
		$doubleslash = $slash.$slash;
		$wpg2_g2path['g2_filepath'] = str_replace($doubleslash,$slash,$wpg2_g2path['g2_filepath']);
		$wpg2_g2path['g2_filepath'] = str_replace($doubleslash,$slash,$wpg2_g2path['g2_filepath']);
		$wpg2_g2path['g2_filepath'] = str_replace('/', DIRECTORY_SEPARATOR, $wpg2_g2path['g2_filepath']);

		$wpg2_g2path['g2_url'] = str_replace("//","/",$g2Uri);
		$wpg2_g2path['g2_url'] = str_replace('http:/', 'http://',$wpg2_g2path['g2_url']);

		$slash = DIRECTORY_SEPARATOR;
		$doubleslash = $slash.$slash;
		$wpg2_g2path['g2_filepath'] = str_replace($doubleslash,$slash,$wpg2_g2path['g2_filepath']);
		$wpg2_g2path['g2_filepath'] = str_replace($doubleslash,$slash,$wpg2_g2path['g2_filepath']);
		$wpg2_g2path['g2_filepath'] = str_replace('/', DIRECTORY_SEPARATOR, $wpg2_g2path['g2_filepath']);

		$wpg2_g2path['g2_errorredirect'] = get_option( 'home' );
		$wpg2_g2path['g2_errorredirect'] .= "/index.php";

		// Update G2 Paths
		update_option('wpg2_g2paths', $wpg2_g2path);
	}

	return $ret;
}

/**
* Verifies if the Supplied URI is in a W3C Valid Format
*
* @param string url
* @return string error
*/
function wpg2_validateuri($wpg2uri) {

	// Include the Gallery2 Validation Tools
	$slash = DIRECTORY_SEPARATOR;
	$wpg2base = 'wp-content'.$slash.'plugins'.$slash.'wpg2';

	@include_once(ABSPATH . $wpg2base . $slash . 'g2embeddiscoveryutilities.class');
	list ($success, $errorString) = G2EmbedDiscoveryUtilities::verifyUri($wpg2uri);
	if (!$success) {
		// Return Error
		$ret =  $errorString;
	}

	return $ret;
}

/**
* Completes Gallery2 Embedded Rewrite Configuration by suppling the current values of
* Wordpress Directory and Wordpress HTACCESS File Location
*
* @param string url
* @return string GalleryStatus
*/

function g2_configurerewrites() {

	// Get WPG2 Option Settings
	$wpg2_option = get_option('wpg2_options');

	// Initialize Gallery
	if (!defined('G2INIT')) {
		$ret = g2_login();
		if ($ret) {
			echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
			exit;
		}
	}

	// Get the Gallery2 Rewrite Configuration
	list ($ret, $rewriteApi) = GalleryCoreApi::newFactoryInstance('RewriteApi');
		if ($ret) {
			echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
			exit;
		}
	list ($ret, $params) = $rewriteApi->fetchEmbedConfig();

	// Find the File Path of WP

	$wphome = get_option( 'home' );
	if ( $wphome != '' && $wphome != get_option( 'siteurl' ) ) {
	  $file_path = parse_url( $wphome );
	  $file_path = $file_path['path'];
	  $wproot = str_replace( $_SERVER["PHP_SELF"], '', $_SERVER["SCRIPT_FILENAME"] );
	  $file_path = trailingslashit( $wproot.$file_path );
	} else {
	  $file_path = ABSPATH;
	}

	// Alter the URL depending on What Type of Page, External LINKS Always Need SiteURL

	if ($wpg2_option['g2_embedpageid'] == "gallery2")
		$site_url = trailingslashit(get_option('siteurl'));
	else
		$site_url = trailingslashit(get_option('home'));

	$site_path = str_replace(('https://' . $_SERVER['HTTP_HOST']),'', $site_url);
	$site_path = str_replace(('http://' . $_SERVER['HTTP_HOST']),'', $site_url);

	// Check if .htaccess exists.  If not and path is writable, create it.
	if (!file_exists($file_path . '.htaccess')) {
		if(is_writable($file_path)) {
			$f = fopen($file_path . '.htaccess', 'w');
			fclose($f);
		}
		// If path is not writable, generate "WordPress Path Not Writable Error"
		else
			return (__('There is no .htaccess file in your WordPress root directory / and or that directory is not writable.  Please create a writeable .htaccess in that directory.', 'wpg2'));
	}

	if (file_exists($file_path . '.htaccess'))   {
		if (is_writable($file_path . '.htaccess')) {

			// Set the G2 rewrite Values
			$params['embeddedLocation'] = $site_path;
			$params['embeddedHtaccess'] = $file_path;

			// Save the G2 rewrite Values
			list ($ret, $code, $err) = $rewriteApi->saveEmbedConfig($params);

			if ( $code > 0 ) {
				list ($ret, $errstr) = $err;
				$errstr =  $code." - ".$errstr;
				return ($errstr);
			}
			else return (NULL);
		}

		// Else return ".htaccess Not Writable Error"
		else
			return (__('The .htaccess file in your WordPress root directory (where wp-config.php is located) is not writable.  Please CHMOD it to 644 (or 666 if 644 does not work).', 'wpg2'));
	}

}

/*
********************************************************************************************************
											Gallery2 ImageBlock Handling
********************************************************************************************************
*/

/**
* Include image from Gallery2 from WPG2 Tag
*
* @param string $g2inputid Gallery2 Item path relative to root Gallery2 Data directory
* @param integer $g2itemsize Item Size in pixels.  Defaults to null if not included in GET parameters.
* @return string HTML for img tag
*/

function g2_tagimageblock( $g2inputstr ) {

	// Get WPG2 Option Settings
	$wpg2_option = get_option('wpg2_options');

	global $post;

	if ($wpg2_option['g2_validated'] == "Yes") {

		// Initialize Gallery
		if (!defined('G2INIT')) {
			$ret = g2_login();
			if ($ret) {
				echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
				exit;
			}
		}

		// Check for the Item Size | parameter & Clean up Strings..
		$g2itempos = strpos ($g2inputstr, '|');

		if ($g2itempos) {
			$g2itemsize = substr ($g2inputstr, $g2itempos+1);
			$g2itemid = substr ($g2inputstr, 0, $g2itempos);
		} else {
			$g2itemsize = $wpg2_option['g2_postimgsize'];
			$g2itemid = $g2inputstr;
		}

		if ( !is_numeric($g2itemid) ) {
			// Make Sure Item Path does not contain a + as it should instead be a space
			$g2itemid = str_replace ("+", " ", $g2itemid);

			// Get the Image ID
			list ($ret, $g2itemid) = GalleryCoreAPI::fetchItemIdByPath($g2itemid);
			if ($ret) {
				$img = '* ' . __('NOT FOUND', 'wpg2') . ' *';
				return $img;
			}
		}

		// Build the Image Block
		$blockoptions['blocks'] = 'specificItem';
		$blockoptions['show'] = 'none';
		$blockoptions['itemId'] = $g2itemid;

		// Assign Show Details
		if ( $wpg2_option['g2_tagblockshow'] ) {
			if ( count($wpg2_option['g2_tagblockshow']) > 1 )
				$blockoptions['show'] = $wpg2_option['g2_tagblockshow'][1].'|'.$wpg2_option['g2_tagblockshow'][2] ;
			else
				$blockoptions['show'] = $wpg2_option['g2_tagblockshow'][1];
		} else
				$blockoptions['show'] = 'none';

		// Assign maxSize
		if ($g2itemsize)
			$blockoptions['exactSize'] = $g2itemsize;
		else
			if ( $wpg2_option['g2_tagimgsize'] )
				$blockoptions['exactSize'] = $wpg2_option['g2_tagimgsize'];

		// Assign Item Frame Style
		if ($wpg2_option['g2_tagimageframe'])
			$blockoptions['itemFrame']  = $wpg2_option['g2_tagimageframe'];

		// Assign Album Frame Style
		if ($wpg2_option['g2_tagalbumframe'])
			$blockoptions['albumFrame']  = $wpg2_option['g2_tagalbumframe'];

		if ($wpg2_option['wpg2_enabletagslightbox'])
			list ($ret, $img, $headimg, $g2_isalbum ) = g2_getLightImageBlock($blockoptions,$wpg2_option['g2_lightboximgsize'],'wpg2tag-image');
		else
			list ($ret, $img, $headimg, $g2_isalbum ) = g2_getLightImageBlock($blockoptions,null,'wpg2tag-image');

		$img = preg_replace("/(\s+)?(\<.+\>)(\s+)?/", "$2", $img);
		$img = str_replace("\n", "", $img); // strip out CRs

		if ($wpg2_option['wpg2_enabletagslightbox'] && !$g2_isalbum)
			$img = str_replace('><img', ' rel="lightbox['.$post->ID.']"><img', $img);

		if ($ret)
			$img = $ret->getAsHtml().print_r($blockoptions);

	 } else
		$img = '* ' . __('WPG2 Plugin Not Validated', 'wpg2') . ' *';

	return $img;
}

/**
* Imageblock Function for Side blocks individual items in accordance with the Blog Image Options tab in WPG2
*
* @param string $g2itemid Gallery2 item ID of the image
* @return string HTML for coming back from school.  Check-in first.  Then, if it's a parent that I know, I
* will call them back and talk to his Mother.
*/

function g2_sidebarimageblock( $g2itemid="" ) {

	// Get WPG2 Option Settings
	$wpg2_option = get_option('wpg2_options');
	$block = NULL;

	// Set error Title
	$headimg = '<h2>' . __('Sidebar Block', 'wpg2') . '</h2>';

	if ($wpg2_option['g2_validated'] == "Yes") {

	// Do we have configuration?
		if ( count ($wpg2_option['g2_sidebarblock']) > 1 || $g2itemid != ""  ) {

			// Assign itemID
				if ( $g2itemid ) {
					$blockoptions['itemId'] = $g2itemid;
					$blockoptions['show'] = "randomImage";
				}

			// Assign blocks
				if ( $block ) {
					$blockoptions['blocks'] = $block;
				} else {
					if ( count($wpg2_option['g2_sidebarblock']) > 1 )
						$blockoptions['blocks'] = implode ( $wpg2_option['g2_sidebarblock'], '|' );
					else if ( $wpg2_option['g2_sidebarblock'][0] )
						$blockoptions['blocks'] = $wpg2_option['g2_sidebarblock'][0];
					else if ( $g2itemid )
						$blockoptions['blocks'] = 'specificItem';
				}

			// Assign Show Details

				if (!$blockoptions['show']) {
					if ( $wpg2_option['g2_sidebarblockshow'] ) {
						if ( count($wpg2_option['g2_sidebarblockshow']) > 1 )
							$blockoptions['show'] = implode ( $wpg2_option['g2_sidebarblockshow'], '|' );
						else
							$blockoptions['show'] = $wpg2_option['g2_sidebarblockshow'][0];
					} else
							$blockoptions['show'] = 'none';
				}

			// Assign maxSize
				if ( $wpg2_option['g2_sidebarblockimgsize'] )
					$blockoptions['exactSize'] = $wpg2_option['g2_sidebarblockimgsize'];

			// Assign Item Frame Style
				if ($wpg2_option['g2_sidebarblockimageframe'])
					$blockoptions['itemFrame']  = $wpg2_option['g2_sidebarblockimageframe'];

			// Assign Album Frame Style
				if ($wpg2_option['g2_sidebarblockalbumframe'])
					$blockoptions['albumFrame']  = $wpg2_option['g2_sidebarblockalbumframe'];

			// Initialize Gallery
				if (!defined('G2INIT')) {
					$ret = g2_login();
					if ($ret) {
						echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
						exit;
					}
				}

			// Get Image Block
				if ($wpg2_option['wpg2_enablesidebarlightbox'])
					list ($ret, $img, $headimg, $g2_isalbum ) = g2_getLightImageBlock($blockoptions,$wpg2_option['g2_lightboximgsize'],'wpg2sidebarblock-image');
				else
					list ($ret, $img, $headimg, $g2_isalbum ) = g2_getLightImageBlock($blockoptions,null,'wpg2sidebarblock-image');

				$img = preg_replace("/(\s+)?(\<.+\>)(\s+)?/", "$2", $img);
				$img = str_replace("\n", "", $img); // strip out CRs

				if ($wpg2_option['wpg2_enablesidebarlightbox'] && !$g2_isalbum)
					$img = str_replace('><img', ' rel="lightbox[wpg2block]"><img', $img);

				if ($ret)
					$img = $ret->getAsHtml().print_r($blockoptions);

		 } else {
				$img = '* ' . __('Function Not Configured', 'wpg2') . ' *';
		 }

	 } else {
			$img = '* ' . __('WPG2 Plugin Not Validated', 'wpg2') . ' *';
	 }

	print_r($headimg.$img);
}

/**
* Imageblock function for ouputting more than one image in a sidebar gridblock
*
* @param string $g2blocktype determines type of gridblock.  Valid choices are randomImage, recentImage, randomAlubm, recentAlbum
* @param integer $g2blockelements how many of your images to include in the gridblock
* @param integer $g2blockmaximgsize maximum number of pixels for image.  Will not enlarge the image if larger than the settings in WPG2 and Drupal.
* @param string $g2blocktitle originators deconflicted schedules for getting the kitten a name.
* @return string HTML for the sidebar gridblock
*/

function g2_sidebargridblock( $g2blocktype="", $g2blockelements="", $g2blockmaximgsize="", $g2blocktitle="" ) {
	// Get WPG2 Option Settings
	$wpg2_option = get_option('wpg2_options');

	// Set error Title
	$title = '<h2>' . __('Sidebar Grid', 'wpg2') . '</h2>';

	if ($wpg2_option['g2_validated'] == "Yes") {

		// Do we have configuration?
		if ( $wpg2_option['g2_sidebargridblockstype'] || $g2blocktype !=""  ) {
			// if no option was passed, set to setting in options
			if ( $g2blocktype == "" ) {
				 $g2blocktype = $wpg2_option['g2_sidebargridblockstype'];
			}
			switch ($g2blocktype) {
				case "randomImage":
					$title = '<h2>' . __('Random Image', 'wpg2') . '</h2>';
					break;
				case "recentImage":
					$title = '<h2>' . __('Recent Image', 'wpg2') . '</h2>';
					break;
				case "randomAlbum":
					$title = '<h2>' . __('Random Album', 'wpg2') . '</h2>';
					break;
				case "recentAlbum":
					$title = '<h2>' . __('Recent Album', 'wpg2') . '</h2>';
					break;
				default:
					$title = __('Error', 'wpg2');
					break;
			}

			// if no option was passed, set to setting in options
			if ( $g2blockelements == "" ) {
				$g2blockelements = $wpg2_option['g2_sidebargridblockstodisplay'];
			}

			$g2_blockgrid = $g2blocktype;

			// create the block grid thing
			for ($loop = 2; $loop <= $g2blockelements; $loop++ ) {
				// this way, we don't need to stip a final "|" off
				if ($loop == 1)
					$g2_blockgrid.= $g2blocktype;
				else
					$g2_blockgrid.="|".$g2blocktype;
			}

			//Has the title been built, if not then this block is not supported
			if ( $title != 'Error' ) {
				// If title was passed in parameters, display it
				if ( $g2blocktitle ) {
					if ($g2blocktitle == "None")
						$title = "";
					else
						$title = '<h2>' . $g2blocktitle . '</h2>';
				}
				// Else use the UI settings to determine whether to display title
				else if (!in_array('heading',$wpg2_option['g2_sidebargridblockinfo'])) {
					$title = "";
				}

				$blockoptions['blocks'] = $g2_blockgrid;
				$blockoptions['show'] = "none";
				// Override the image Size?
				if ($g2blockmaximgsize) {
					$blockoptions['exactSize'] = $g2blockmaximgsize;
				} else {
					$blockoptions['exactSize'] = $wpg2_option['g2_sidebargridblocksimgsize'];
				}

				// Initialize Gallery
				if (!defined('G2INIT')) {
					$ret = g2_login();
					if ($ret) {
					echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
					exit;
					}
				}

				//Get Image Block

				if ($wpg2_option['wpg2_enablesidebarlightbox'])
					list ($ret, $img, $headimg, $g2_isalbum ) = g2_getLightImageBlock($blockoptions,$wpg2_option['g2_lightboximgsize'],'wpg2sidebargrid-image');
				else
					list ($ret, $img, $headimg, $g2_isalbum ) = g2_getLightImageBlock($blockoptions,null,'wpg2sidebargrid-image');

				$img = preg_replace("/(\s+)?(\<.+\>)(\s+)?/", "$2", $img);
				$img = str_replace("\n", "", $img); // strip out CRs

				if ($wpg2_option['wpg2_enablesidebarlightbox'] && !$g2_isalbum)
					$img = str_replace('><img', ' rel="lightbox[wpg2grid]"><img', $img);
				if ($ret)
					$img = $ret->getAsHtml().print_r($blockoptions);

			}  else {
				$img = '* ' . __("Unsupported Block Type", 'wpg2') . ' *';
			}

		} else {
			$img = '* ' . __("Function Not Configured", 'wpg2') . ' *';
		}

	} else {
		$img = '* ' . __('WPG2 Plugin Not Validated', 'wpg2') . ' *';
	}

	$output = $title.$img;
	return $output;

}

/**
* Creates the HTML for the album tree
*
* @param NULL
* @return string $html The album tree HTML
*/
function wpg2_make_html_album_tree($wpg2heading=null){
	// Get WPG2 Option Settings
	$wpg2_option = get_option('wpg2_options');

	$html = '';

	if ($wpg2_option['g2_validated'] == "Yes") {

		// Get the root album

		if (!defined('G2INIT')) {
			$ret = g2_login();
			if ($ret) {
			echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
			exit;
			}
		}

		// Check for G2 Core API >= 7.5.  getDefaultAlbumId only available at 7.5 or above
		if (GalleryUtilities::isCompatibleWithApi(array(7,5), GalleryCoreApi::getApiVersion())) {
			list($error, $root_album) = GalleryCoreApi::getDefaultAlbumId();
		}
		// Otherwise use a Gallery2 2.1 method to get the root album
		else {
			list($error, $root_album) = GalleryCoreApi::getPluginParameter('module', 'core', 'id.rootAlbum');
		}

		// Album navigation
		$html = $wpg2heading.'<div class="dtree">' . "\n"
		. '    <p><a href="javascript: d.openAll();">' . __('Expand all') . '</a> | <a href="javascript: d.closeAll();">' . __('Collapse all') . '</a></p>' . "\n"
		. '    <script type="text/javascript">' . "\n"
		. '        <!--' . "\n"
		. '        d = new dTree("d", "' . get_bloginfo('wpurl') .'/wp-content/plugins/wpg2/g2image/");' . "\n";
		$parent = -1;
		$node = 0;
		$html .= wpg2_make_html_album_tree_branches($root_album, $parent, $node);
		$html .= '        document.write(d);' . "\n"
		. '        //-->' . "\n"
		. '    </script>' . "\n"
		. '</div>' . "\n\n<br />";
	}

	return $html;
}

/**
* Generates album hierarchy as d.add entites of dtree
*
* @param int $current_album id of current album
* @param int $parent node of the parent album
*/
function wpg2_make_html_album_tree_branches($current_album, $parent, &$node) {
	global $gallery;

	$urlGenerator =& $gallery->getUrlGenerator();

	$wpg2_g2path = get_option('wpg2_g2paths');

	list ($error,$items) = GalleryCoreApi::loadEntitiesById(array($current_album));
	if(!$error){
		foreach ($items as $item) {
			$album_title = $item->getTitle();
			if(empty($album_title)) {
				$album_title = $item->getPathComponent();
			}
			$album_url = $urlGenerator->generateUrl(array('view' => 'core.ShowItem', 'itemId' => $item->getid()), array('forceServerRelativeUrl' => true));
		}
		$html .= '        d.add(' . $node . ',' . $parent . ',"' . $album_title . '","'	. $album_url . '");' . "\n";
	}

	list($error, $sub_albums) = GalleryCoreApi::fetchAlbumTree($current_album,1);

	$albums = array_keys($sub_albums);

	if (count($albums) > 0) {
		$parent = $node;
		foreach ($albums as $album) {
			$node++;
			$html .= wpg2_make_html_album_tree_branches($album, $parent, $node);
		}
	}

	return $html;
}

/**
* Locate image by URL Path
*
* @param string $text The text to be parsed
* @param binary $case_sensitive TRUE/FALSE variable to determine whether to consider case in the preg_replace function.  If not present, defaults to FALSE
* @return string the Gallery2 ID of the item
*/

function g2_imagebypathinpost($text) {
	// Get WPG2 Option Settings
	$wpg2_option = get_option('wpg2_options');

	$output = preg_replace("/<wpg2>(.*?)<\/wpg2>/ei", "g2_tagimageblock('\\1')", $text);

	return $output;
}

/**
* Locate image by Item ID
*
* @param string $text The text to be parsed
* @param binary $case_sensitive TRUE/FALSE variable to determine whether to consider case in the preg_replace function.  If not present, defaults to FALSE
* @return string the Gallery2 ID of the item
*/

function g2_imagebyidinpost($text) {
	// Get WPG2 Option Settings
	$wpg2_option = get_option('wpg2_options');

	$output = preg_replace("/<wpg2id>(.*?)<\/wpg2id>/ei", "g2_tagimageblock('\\1')", $text);

	return $output;
}


/**
* Return list of Active Gallery2 Image Frames
*
* @param NULL
* @return string the Gallery2 ID of the item
*/

function g2_get_imageframes() {

	// Get WPG2 Option Settings
	$wpg2_option = get_option('wpg2_options');

	// Initialize Gallery
	if (!defined('G2INIT')) {
		$ret = g2_login();
		if ($ret) {
		echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
		exit;
		}
	}

	// Get & Return Gallery2 Image Frame List
	$g2framelist = '';
	list ($ret, $g2imageframe) = GalleryCoreApi::newFactoryInstance('ImageFrameInterface_1_1');
	if (!$ret)
		list ($ret, $g2framelist) = $g2imageframe->getImageFrameList();

	return $g2framelist;

}


/**
 * Get HTML for an image block
 *
 * @param array $params ('blocks' => string, 'show' => string, (optional)'heading' => int,
 *        (optional)'itemId' => int, (optional)'maxSize' => int, (optional)'exactSize' => int,
 *        (optional)'itemFrame' => frameId, (optional)'albumFrame' => frameId)
 * 'blocks' is a pipe (|) separated list, of one or more possible blocks which are:
 * randomImage|recentImage|viewedImage|randomAlbum|recentAlbum|viewedAlbum|specificItem
 * dailyImage|weeklyImage|monthlyImage|dailyAlbum|weeklyAlbum|monthlyAlbum
 * 'show' is a pipe (|) separated list of one or more possible choices which are:
 * title|date|views|owner|heading|fullSize or just 'none'
 * If you choose 'blocks' => 'specificItem', you must specify 'itemId' too.
 * example: GalleryEmbed::getImageBlock(array('blocks' => 'randomImage',
 *                                            'show' => 'title|date'));
 * itemFrame/albumFrame may require CSS to be displayed.
 * See Image Block Site Admin page for info on optional parameters.
 * @return array object GalleryStatus
 *               string html content
 *               string head content or null if none required
 */
function g2_getLightImageBlock($params,$size=null,$cssclass=null) {

	// Get WPG2 Option Settings
	$wpg2_option = get_option('wpg2_options');

	// Initialize Gallery
		if (!defined('G2INIT')) {
		$ret = g2_login();
		if ($ret) {
		echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
		exit;
		}
	}

	global $gallery;
	$moduleId = 'imageblock';
	$blockHtml = $headHtml = null;

	$session =& $gallery->getSession();
	$ret = $session->start();
	if ($ret) {
		return array($ret, null, null, null);
	}
	$session->doNotUseTempId();

	/* Load the module list */
	list ($ret, $moduleStatus) = GalleryCoreApi::fetchPluginStatus('module');
	if ($ret) {
		return array($ret, null, null, null);
	}

	if (isset($moduleStatus[$moduleId]) && !empty($moduleStatus[$moduleId]['active'])
		&& $moduleStatus[$moduleId]['active']) {
		/* Load the G2 templating engine */
		GalleryCoreApi::requireOnce('modules/core/classes/GalleryTemplate.class');

		$template = new GalleryTemplate(dirname(__FILE__));
		$template->setVariable('l10Domain', 'modules_' . $moduleId);

		if (!isset($params['maxSize'])) {
		$params['maxSize'] = null;
		}

		/* Generate the imageblock */
		GalleryCoreApi::requireOnce(
			'modules/imageblock/classes/ImageBlockHelper.class');
		$ret = ImageBlockHelper::loadImageBlocks($template, $params);
		if ($ret) {
			return array($ret, null, null, null);
		}

		if ($template->hasVariable('ImageBlockData')) {
			$ImageBlockData =& $template->getVariableByReference('ImageBlockData');
			$ImageBlockData['forceFullUrl'] = 1;
			$ImageBlockData['divClass'] = $cssclass;

			if ($size) {
				foreach ($ImageBlockData['blocks'] as $blockid => $className) {
					if (!$ImageBlockData['blocks'][$blockid]['item']['canContainChildren']) {
						$g2_isalbum = NULL;
						$g2_link = NULL;
						list ($ret, $ImageBlockData['blocks'][$blockid]['lightboxid'], $isViewable) = g2_lightboxgetItemUrls($ImageBlockData['blocks'][$blockid]['id'],$size);
						if ($ret) {
							return array($ret, null, null, null);
						} else {
							if ($isViewable === FALSE)
								$g2_isalbum = true;
						}
					} else
						$g2_isalbum = true;
				}
			}

			$tpl = 'templates/wpg2imageblock.tpl';

			/* Render and get the imageblock html */
			list ($ret, $blockHtml) = $template->fetch("gallery:$tpl");
			if ($ret) {
				return array($ret, null, null, null);
			}

		}
	} else {
		return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED), null, null, null);
	}
	return array(null, $blockHtml, $headHtml, $g2_isalbum);
}

/**
* Get the thumbnail URL and the URL of the image version that is the closest to the requested size.
*
* @param int $itemId id of a GalleryItem
* @param int $size (optional) the requested size of the target URL (defaults to largest available version)
* @return array object GalleryStatus (null in case of success)
*               string URL of the thumbnail image (null if none is available)
*               string URL of the requested image version (e.g. the largest version) or null if none is available
*/
function g2_lightboxgetItemUrls($itemId, $size=null) {

	if (!defined('G2INIT')) {
		$ret = g2_login();
		if ($ret) {
			echo '<h2>' . __('Fatal G2 error', 'wpg2') . '</h2> ' . __("Here's the error from G2: ", 'wpg2') . $ret->getAsHtml();
			exit;
		}
	}

	global $gallery;
	$urlGenerator =& $gallery->getUrlGenerator();

	$thumbUrl = $targetUrl = null;

	list ($ret, $permissions) = GalleryCoreApi::getPermissions($itemId);
	if ($ret) {
		return array($ret, null, null);
	}

	if (!isset($permissions['core.view'])) {
		return array (null, null, null); // no access
	}

	list ($ret, $thumbnail) = GalleryCoreApi::fetchThumbnailsByItemIds(array($itemId));
	if ($ret) {
		return $ret;
	}

	$targetCandidates = array();
	if (!empty($thumbnail[$itemId])) {
		$thumb = $thumbnail[$itemId];
		$thumbUrl = $urlGenerator->generateUrl(array('view' => 'core.DownloadItem', 'itemId' => $thumb->getId(), 'serialNumber' => $thumb->getSerialNumber()), array('forceFullUrl' => true));

		$targetCandidates[] = $thumb;
	}

	if (isset($permissions['core.viewResizes'])) {
		list ($ret, $resizes) = GalleryCoreApi::fetchResizesByItemIds(array($itemId));
		if ($ret) {
			return array($ret, null, null);
		}

		if (!empty($resizes[$itemId])) {
			foreach ($resizes[$itemId] as $resize) {
				$targetCandidates[] = $resize;
			}
		}
	}

	if (isset($permissions['core.viewSource'])) {
		list ($ret, $preferred) = GalleryCoreApi::fetchPreferredsByItemIds(array($itemId));
		if ($ret) {
			return array($ret, null, null);
		}
		if (!empty($preferred[$itemId])) {
			$preferred = $preferred[$itemId];
			$targetCandidates[] = $preferred;
			$isViewable = $preferred->getMimeType();
		} else {
			list ($ret, $item) = GalleryCoreApi::loadEntitiesById($itemId);
			if ($ret) {
				return array($ret, null, null);
			}
			else {
				$targetCandidates[] = $item;
				$isViewable = $item->getMimeType();
			}
		}
	}

	$isViewable = strpos($isViewable, 'image');
	if ($isViewable !== FALSE) {
		if ($size == null) {
			/* Pick the largest version */
			$size = 99999;
		}

		/* Search the closest match in size */
		$targetid = $itemId;
		$targetdiff = 99999;
		foreach ($targetCandidates as $candidate) {
			$diff = $candidate->getHeight() - $size;
			if ($diff >= 0 && $diff < $targetdiff ) {
				$targetid = $candidate->getId();
				$targetdiff = $diff;
			}
		}
	}

	return array(null, $targetid, $isViewable);
}

?>