<?php
/**************************************************
  Coppermine Plugin - Random Select
  *************************************************
  Copyright (c) 2006 Paul Van Rompay
  *************************************************
  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.
  *************************************************/

global $CONFIG, $lang_meta_album_names, $lang_yes, $lang_no;
global $lang_plugin_randsel, $lang_plugin_randsel_config;
require('include/init.inc.php');

if (!GALLERY_ADMIN_MODE) cpg_die(ERROR, $lang_errors['access_denied'], __FILE__, __LINE__);

require('plugins/random_select/include/init.inc.php');

// ----------------------------------------------------------------------------
// Album-Dropdown Function Stolen from upload.php and modified for this plugin
// ----------------------------------------------------------------------------
function randsel_albums_dropdown ($sel_album) {

    // Pull the $CONFIG array and the GET array into the function
    global $CONFIG, $lang_plugin_randsel_config;

    // Also pull the album lists into the function
    // global $user_albums_list, $public_albums_list;

    if (GALLERY_ADMIN_MODE) {
        $public_albums = cpg_db_query("SELECT aid, title FROM {$CONFIG['TABLE_ALBUMS']} WHERE category < " . FIRST_USER_CAT . " ORDER BY title");
    } else {
	    $public_albums = cpg_db_query("SELECT aid, title FROM {$CONFIG['TABLE_ALBUMS']} WHERE category < " . FIRST_USER_CAT . " AND uploads='YES' AND (visibility = '0' OR visibility IN ".USER_GROUP_SET.") ORDER BY title");
    }
    if (mysql_num_rows($public_albums)) {
        $public_albums_list = cpg_db_fetch_rowset($public_albums);
    } else {
        $public_albums_list = array();
    }

    if (USER_ID) {
        $user_albums = cpg_db_query("SELECT aid, title FROM {$CONFIG['TABLE_ALBUMS']} WHERE category='" . (FIRST_USER_CAT + USER_ID) . "' ORDER BY title");
        if (mysql_num_rows($user_albums)) {
            $user_albums_list = cpg_db_fetch_rowset($user_albums);
        } else {
            $user_albums_list = array();
        }
    } else {
        $user_albums_list = array();
    }

    // Create the opening of the drop down box
    echo <<<EOT
            {$lang_plugin_randsel_config['dropdown_label']}
            <select name="album_choice" class="listbox">

EOT;

    // Get the ancestry of the categories
    $vQuery = "SELECT cid, parent, name FROM " . $CONFIG['TABLE_CATEGORIES'] . " WHERE 1";
    $vResult = cpg_db_query($vQuery);
    $vRes = cpg_db_fetch_rowset($vResult);
    mysql_free_result($vResult);
    foreach ($vRes as $vResI => $vResV) {
        $vResRow = $vRes[$vResI];
        $catParent[$vResRow['cid']] = $vResRow['parent'];
        $catName[$vResRow['cid']] = $vResRow['name'];
    }
    $catAnces = array();
    foreach ($catParent as $cid => $cid_parent) {
        $catAnces[$cid] = '';
        while ($cid_parent != 0) {
            $catAnces[$cid] = $catName[$cid_parent] . ($catAnces[$cid]?' - '.$catAnces[$cid]:'');
            $cid_parent = $catParent[$cid_parent];
        }
    }

    // Reset counter
    $list_count = 0;

    // Cycle through the User albums
    foreach($user_albums_list as $album) {

        // Add to multi-dim array for later sorting
        $listArray[$list_count]['cat'] = $lang_plugin_randsel_config['personal_albums'];
        $listArray[$list_count]['aid'] = $album['aid'];
        $listArray[$list_count]['title'] = $album['title'];
        $list_count++;
    }

    // Cycle through the public albums
    foreach($public_albums_list as $album) {

        // Set $album_id to the actual album ID
        $album_id = $album['aid'];

        // Get the category name
        $vQuery = "SELECT cat.name, cat.cid FROM " . $CONFIG['TABLE_CATEGORIES'] . " cat, " . $CONFIG['TABLE_ALBUMS'] . " alb WHERE alb.aid='" . $album_id . "' AND cat.cid=alb.category";
        $vResult = cpg_db_query($vQuery);
        $vRes = cpg_db_fetch_row($vResult);
        mysql_free_result($vResult);

        // Add to multi-dim array for sorting later
        if ($vRes['name']) {
            $listArray[$list_count]['cat'] = $catAnces[$vRes['cid']] . ' - ' . $vRes['name'];
            $listArray[$list_count]['cid'] = $vRes['cid'];
        } else {
            $listArray[$list_count]['cat'] = $lang_plugin_randsel_config['albums_no_category'];
            $listArray[$list_count]['cid'] = 0;
        }
        $listArray[$list_count]['aid'] = $album['aid'];
        $listArray[$list_count]['title'] = $album['title'];
        $list_count++;
    }

    // Sort the pulldown options by category and album name
    $listArray = array_csort($listArray,'cat','title');
    // $listArray = array_csort($listArray,'cid','title');
    // print_r($listArray);exit;

    // Finally, print out the nicely sorted and formatted drop down list
    $alb_cat = '';
    echo '                <option value="">' . $lang_plugin_randsel_config['select_album'] . "</option>\n";
    foreach ($listArray as $val) {
        //if ($val['cat'] != $alb_cat) {       
        if ($val['cid'] != $alb_cat) {
            if ($alb_cat) echo "                </optgroup>\n";
            echo '                <optgroup label="' . $val['cat'] . '">' . "\n";
            $alb_cat = $val['cid'];
        }
        echo '                <option value="' . $val['aid'] . '"' . ($val['aid'] == $sel_album ? ' selected' : '') . '>   ' . $val['title'] . "</option>\n";
    }
    if ($alb_cat) echo "                </optgroup>\n";

    // Close the drop down
    echo <<<EOT
            </select>

EOT;
}

// -------------------------------------------
// Main Code
// -------------------------------------------

if (count($_POST) > 0) {
	if (isset($_POST['update_config'])) {
		$sql = "UPDATE {$CONFIG['TABLE_CONFIG']} SET value = '{$_POST['album_choice']}' WHERE name = 'plugin_randsel_album'";
		cpg_db_query($sql);
		if ($CONFIG['log_mode'] == CPG_LOG_ALL) {
			log_write('CONFIG UPDATE SQL: '.$sql.";\n"
				.'TIME: '.date("F j, Y, g:i a")."\n"
				.'USER: '.$USER_DATA['user_name'],
				CPG_DATABASE_LOG
				);
		}
	}
        pageheader($lang_plugin_randsel['display_name']);
        msg_box($lang_plugin_randsel['display_name'], $lang_plugin_randsel['page_success'], $lang_continue, 'index.php');
	pagefooter();
        exit;
}

pageheader($lang_plugin_randsel['display_name']);
starttable('100%');
echo <<< EOT
	<tr>
	<td class="tableh1" width="90%"><b>{$lang_plugin_randsel['display_name']}</b> 
		- <a href="pluginmgr.php" class="admin_menu">Plugin Manager</a>
	</td>
	</tr>
	<tr><td class="tableb">
	<form action="{$_SERVER['REQUEST_URI']}" method="post">
	<br />
EOT;

randsel_albums_dropdown($CONFIG['plugin_randsel_album']);

echo <<< EOT
		<br />
		<br />
		<input type="submit" value="{$lang_plugin_randsel_config['button_done']}" name="update_config"/>
		</form>
EOT;

echo '</td></tr>'."\n";
endtable();
pagefooter();
ob_end_flush();
?>
