<?php
/*************************
  Coppermine Photo Gallery
  ************************
  Copyright (c) 2003-2005 Coppermine Dev Team
  v1.1 originaly written by Gregory DEMAR

  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.
  ********************************************
  Coppermine version: 1.4.2
**********************************************/
/*  Unwanted Meta Albums plug-in
	 Version 1.2 by donnoman@donovanbray.com 
	 version 1.3 by djduffy@windyweather.net	
 */

if (!defined('IN_COPPERMINE')) die('Not in Coppermine...');

require_once 'include/init.inc.php';

// Add an install action
$thisplugin->add_action('plugin_install','remove_meta_install');

// Add a configure action
$thisplugin->add_action('plugin_configure','remove_meta_configure');

// Add a filter for the gallery header
$thisplugin->add_filter('gallery_header','remove_meta_header'); // test
$thisplugin->add_filter('plugin_block','remove_meta_albs'); //index.php
$thisplugin->add_filter('post_breadcrumb','remove_meta_albs'); //thumbnails.php
$thisplugin->add_filter('displayimage_init','remove_meta_albs'); //displayimage.php (MODDED PLUGIN HOOK)

// name of the table
global $CONFIG;
$REMOVE_META_TABLE = $CONFIG['TABLE_PREFIX'].'plugin_remove_meta';
$RM_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS '.$REMOVE_META_TABLE.
		'( aidlist TEXT(1024) NOT NULL DEFAULT \'\','.
		'  aidindex INTEGER PRIMARY KEY )'.
		'TYPE=MyISAM COMMENT=\'Table stores album ids of tables to remove from random and last uploaded\';';
$RM_DROP_TABLE = 'DROP TABLE IF EXISTS '.$REMOVE_META_TABLE.';';
// global to bring these into the functions below didn't seem towork.		

function filter_meta_album() {
    global $META_ALBUM_SET,$ALBUM_SET;
	global $CONFIG;
	$REMOVE_META_TABLE = $CONFIG['TABLE_PREFIX'].'plugin_remove_meta';

	$result = cpg_db_query('SELECT aidlist FROM '.$REMOVE_META_TABLE.' WHERE aidindex=1 ;' );
	$rowset = cpg_db_fetch_rowset($result);
	$rows = $rowset[0];
	$unwanted_albs = explode(',',$rows[0]);
	// now we have an array of the indices
	// old way was to manually edit the following list.
    //$unwanted_albs=array(1,25,14);
    //$unwanted_albs=array(1);
	
	if ( !is_array($unwanted_albs) || sizeof($unwanted_albs) < 1 )
	{	return;
	}
    if ($META_ALBUM_SET) {
        $parts=explode('(',$META_ALBUM_SET);
        $head=$parts[0];
        $parts=explode(')',$parts[1]);
        $albums=explode(',',$parts[0]);
        $new_albums=array_diff($albums,$unwanted_albs);
		// if we end up with no albums in the array, then put one bogus album
		// in the array to satisfy the syntax.
		if ( sizeof($new_albums) < 1 ) { $new_albums = array(99999); }
        $META_ALBUM_SET=$head.'('.implode(',',$new_albums).')';
    } else {	
        $META_ALBUM_SET='AND aid NOT IN ('.implode(',',$unwanted_albs).')';
    }
    if (defined('DISPLAYIMAGE_PHP')) $ALBUM_SET = $META_ALBUM_SET;
}

function remove_meta_albs($return) {
    
    static $run_once;
    if (!$run_once) {
        filter_meta_album();
        $run_once=true;
    }
    return $return;
}


// Install function
// install the plugin
// configuration function is called before this function.
function remove_meta_install() {
	global $CONFIG;
	// not sure why global didn't work here. But didn't seem to work.
	//global $RM_CREATE_TABLE;
	//global $REMOVE_META_TABLE;
	$REMOVE_META_TABLE = $CONFIG['TABLE_PREFIX'].'plugin_remove_meta';
	$RM_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS '.$REMOVE_META_TABLE.
			'( aidlist TEXT(1024) NOT NULL DEFAULT \'\','.
			'  aidindex INTEGER PRIMARY KEY )'.
			'TYPE=MyISAM COMMENT=\'Table stores album ids of tables to remove from random and last uploaded\';';
	$RM_DROP_TABLE = 'DROP TABLE IF EXISTS '.$REMOVE_META_TABLE.';';		
	// Install
	// return true for success
	// return 1 for failure to try again
	// setup to fail the first time
	$albs2remove = $_POST['albums'];
	if ( $_POST['cancelled'] == 1 )
	{	return true;		// no albums, so user just cancelled
	}
	
    if ( is_array($albs2remove) && count($albs2remove) > 0 )
	{
		// store the data for the plug-in to use
		// create the table if it does not exist
		// delete all the rows of the table
		// add one row with the imploded data
		$result = cpg_db_query( $RM_DROP_TABLE );
		$result = cpg_db_query($RM_CREATE_TABLE );
		$aidlist = implode(',',$albs2remove);
		$result = cpg_db_query( 'DELETE FROM '.$REMOVE_META_TABLE.';' );
		$result = cpg_db_query( 'INSERT INTO '.$REMOVE_META_TABLE.' VALUES '.
					'( \''.$aidlist.'\', 1 );' );
		
        return true;
    } else
	{    // Loop again
        return 1;
    }
}

// Configure function
// Displays the form
function remove_meta_configure()
{
	global $CONFIG;
	$rowset = array();
    $result = cpg_db_query("SELECT aid, title FROM {$CONFIG['TABLE_ALBUMS']} ORDER BY pos ASC");
	$rowset = cpg_db_fetch_rowset($result);
	if (count ($rowset) > 0)
	{
	echo <<< EOT
    <h3>Select the albums that you would like left out of "Random" and "Last Uploaded" lists.</h3>
    <form action="{$_SERVER['REQUEST_URI']}" method="post">
		<select class="listbox" name="albums[]" size=10 multiple >
EOT;
		foreach ($rowset as $album)
		{	echo "<option value=\"".$album['aid']."\"> ".$album['title'];
		};
	echo <<<EOT
		</select>
		&nbsp;<br />
        <input class="admin_menu" type="submit" value="Install" />
    </form>
	<h3>Or Cancel the installation and then Uninstall the plug-in.</h3>
	<form action="{$_SERVER['REQUEST_URI']}" method="post">
        <input type=hidden name="cancelled" value="1" />
        <input class="admin_menu" type="submit" value="Cancel" />
    </form>
EOT;
	}
	else
	{
	echo <<< EOT
    <h3>There are no albums.</h3>
	<p>Uninstall, and re-Install after there are albums.</p>
	<br />
    <form action="{$_SERVER['REQUEST_URI']}" method="post">
        <input type=hidden name="cancelled" value="1" />
        <input class="admin_menu" type="submit" value="Cancel" />
    </form>
EOT;
	}
}

// make HTML to display an array
// for debugging to figure out rowsets etc.
function display_array( $aArray )
{
	$html = '';
	if ( is_array( $aArray ) && ( count( $aArray ) > 0 ) )
	{
		$html .= "<table border=\"1\">";
		$html .=  "<tr><th>Key</th><th>Value</th></tr>";
		foreach ($aArray as $aKey => $aValue )
		{
			$html .=  '<tr>';
			if ( !is_array( $aValue ) )
			{
				if (empty($aValue) )
				{	$html .=  "<td>$aKey</td><td><i>empty</i></td>";
				}
				else
				{	$html .=  "<td>$aKey</td><td>$aValue</td>";
				}
			}
			else
			{	$html .=  "<td>$aKey(array)</td><td>";
				$html .= display_array( $aValue );
				$html .=  "</td>";
			}
			$html .=  "</tr>";
		}
		$html .=  "</table>";
	}
	else
	{
		$html .=  "<i>empty or invalid</i>";
	}
	return $html;
}


// Modify the gallery header with some debug information if debug is turned on.
function remove_meta_header($html) {
    global $thisplugin;
	global $CONFIG;
	$REMOVE_META_TABLE = $CONFIG['TABLE_PREFIX'].'plugin_remove_meta';
	$returnstring = '';
	$html = '';
	if (isset($CONFIG['debug_mode']) && (($CONFIG['debug_mode']==1) || ($CONFIG['debug_mode']==2) ))
	{
		// test the query and write the album index string to the gallery header
		$result = cpg_db_query('SELECT aidlist FROM '.$REMOVE_META_TABLE.' WHERE aidindex=1 ;' );
		$rowset = cpg_db_fetch_rowset($result);
		$rows = $rowset[0];
		$unwanted = $rows[0];
		//$unwanted_albs = explode(',',$rows[0]);
		$unwanted_albs = explode(',',$unwanted);
		// the following is optional if you have trouble with the array stuff.
		//$html = display_array($unwanted_albs);
		$returnstring = '<p style="color:red;"><b>Debug data from "'.$thisplugin->name.'".</b>'.
				'<br />Unwanted Album Indices: '. $unwanted .'</p>'.$html;
	}
	return $returnstring;
}

?>
