<?php
// $Id: admin.menus.php,v 1.26 2004/02/26 23:27:35 rcastley Exp $
/**
* Administrator menu event handler
* @package Mambo Open Source
* @Copyright (C) 2000 - 2003 Miro International Pty Ltd
* @ All rights reserved
* @ Mambo Open Source is Free Software
* @ Released under GNU/GPL License: http://www.gnu.org/copyleft/gpl.html
* @version $Revision: 1.26 $
**/

// ensure this file is being included by a parent file
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

require_once( $mainframe->getPath( 'admin_html' ) );

$type = mosGetParam( $_REQUEST, 'type', false );
$menutype = mosGetParam( $_REQUEST, 'menutype', 'mainmenu' );
$task = mosGetParam( $_REQUEST, 'task', "" );

$access			= mosGetParam( $_POST, 'access', "" );
$utaccess		=mosGetParam( $_POST, 'utaccess', "");
$ItemName		= mosGetParam( $_POST, 'ItemName', "" );

$cid = mosGetParam( $_POST, 'cid', array(0) );
if (!is_array( $cid )) {
	$cid = array(0);
}

switch ($task) {

	case "new":
		addMenuItem( $cid, $menutype, $option );
		break;

	case "edit":
		$menu = new mosMenu( $database );
		if ($cid[0]) {
			$menu->load( $cid[0] );
		} else {
			$menu->type = $type;
		}

		if ($menu->type) {
			require( "$mosConfig_absolute_path/administrator/components/com_menus/$menu->type/$menu->type.menu.php" );
		}
		break;

	case "save":
		require( "$mosConfig_absolute_path/administrator/components/com_menus/$type/$type.menu.php" );
		break;

	case "publish":
	case "unpublish":
		if ($msg = publishMenuSection( $cid, ($task == 'publish') )) {
			// proceed no further if the menu item can't be published
			mosRedirect( "index2.php?option=$option&menutype=$menutype&mosmsg=$msg" );
		} else {
			mosRedirect( "index2.php?option=$option&menutype=$menutype" );
		}
		break;

	case "remove":
		if ($msg = removeMenusection( $cid )) {
			mosRedirect( "index2.php?option=$option&menutype=$menutype&mosmsg=$msg" );
		} else {
			mosRedirect( "index2.php?option=$option&menutype=$menutype" );
		}
		break;

	case "cancel":
		cancelMenu( $option );
		break;

	case "orderup":
		orderMenu( $cid[0], -1, $option );
		break;

	case "orderdown":
		orderMenu( $cid[0], 1, $option );
		break;

	default:
		$type = trim( mosGetParam( $_REQUEST, 'type', null ) );
		if ($type) {
			// adding a new item - type selection form
			require( "$mosConfig_absolute_path/administrator/components/com_menus/$type.php" );
		} else {
			viewMenuItems( $menutype, $option );
		}
		break;
}

/**
* Shows a list of items for a menu
*/
function viewMenuItems( $menutype, $option ) {
	global $database, $mainframe;

	$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', 10 );
	$limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart$menutype", 'limitstart', 0 );
	$levellimit = $mainframe->getUserStateFromRequest( "view{$option}limit$menutype", 'levellimit', 10 );
	$search = $mainframe->getUserStateFromRequest( "search{$option}$menutype", 'search', '' );
	$search = $database->getEscaped( trim( strtolower( $search ) ) );

	// select the records
	// note, since this is a tree we have to do the limits code-side
	if ($search) {
		$database->setQuery( "SELECT m.id"
			. "\nFROM #__menu AS m"
			//. "\nLEFT JOIN #__content AS c ON c.id = m.componentid AND type='content_typed'"
			. "\nWHERE menutype='$menutype'"
			." AND LOWER(m.name) LIKE '%" . strtolower( $search ) . "%'"
		);

		$search_rows = $database->loadResultArray();
		echo $database->getErrorMsg();
	}

	$database->setQuery( "SELECT m.*, u.name AS editor, g.name AS groupname,"
		. "\n	c.publish_up, c.publish_down"
		. "\nFROM #__menu AS m"
		. "\nLEFT JOIN #__users AS u ON u.id = m.checked_out"
		. "\nLEFT JOIN #__groups AS g ON g.id = m.access"
		. "\nLEFT JOIN #__content AS c ON c.id = m.componentid AND type='content_typed'"
		//. "\nLEFT JOIN #__core_acl_aro_groups AS g ON g.group_id = m.access" <-- this is how it will be done
		. "\nWHERE menutype='$menutype'"
		. "\nORDER BY parent,ordering"
	);
	$rows = $database->loadObjectList();
	echo $database->getErrorMsg();

// establish the hierarchy of the menu
	$children = array();
// first pass - collect children
	foreach ($rows as $v ) {
		$pt = $v->parent;
		$list = @$children[$pt] ? $children[$pt] : array();
		array_push( $list, $v );
		$children[$pt] = $list;
	}
// second pass - get an indent list of the items
	$list = mosTreeRecurse( 0, '', array(), $children, max( 0, $levellimit-1 ) );
	// eventually only pick out the searched items.
	if ($search) {
		$list1 = array();

		foreach ($search_rows as $sid ) {
			foreach ($list as $item) {
				if ($item->id == $sid) {
					$list1[] = $item;
				}
			}
		}
		// replace full list with found items
		$list = $list1;
	}

	$total = count( $list );

	require_once( "includes/pageNavigation.php" );
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );

	$levellist = mosHTML::integerSelectList( 1, 20, 1, 'levellimit', 'size="1" onchange="document.adminForm.submit();"', $levellimit );

// slice out elements based on limits
	$list = array_slice( $list, $pageNav->limitstart, $pageNav->limit );
	HTML_menusections::showMenusections( $list, $pageNav, $search, $levellist, $menutype, $option );
}

/**
* Displays a selection list for menu item types
*/
function addMenuItem( &$cid, $menutype, $option ) {
	global $database, $mosConfig_absolute_path;

	$types = array();

	$dirs = mosReadDirectory( "$mosConfig_absolute_path/administrator/components/com_menus" );
	foreach ($dirs as $dir) {
		$dir = "$mosConfig_absolute_path/administrator/components/com_menus/$dir";
		if (is_dir( $dir )) {
			$files = mosReadDirectory( $dir, ".\.menu\.php$" );
			foreach ($files as $file) {
				require_once( "$dir/$file" );
			}
		}
	}

// build the html select list
	$tlist = mosHTML::selectList( $types, 'type', 'class="inputbox" size="12"',
		'value', 'text', null );

// get list of groups
	$database->setQuery( "SELECT id AS value, name AS text FROM #__groups ORDER BY id" );
	$groups = $database->loadObjectList();

// build the html select list
	$glist = mosHTML::selectList( $groups, 'access', 'class="inputbox" size="8"',
		'value', 'text', null );

	HTML_menusections::addMenuItem( $cid, $glist, $tlist, $menutype, $option );
}

/**
* Generic function to save the menu
*/
function saveMenu( $option ) {
	global $database;

	$row = new mosMenu( $database );

	//Set default usertype access to 'user' for MainMenu items
	if (!isset($row->utaccess)){
		$row->utaccess=3;
	}

	if (!$row->bind( $_POST )) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	if (!$row->check()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	if (!$row->store()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	$row->checkin();
	$row->updateOrder( "menutype='$row->menutype' AND parent='$row->parent'" );
	mosRedirect( "index2.php?option=$option&menutype=$row->menutype" );
}

/**
* Publishes or Unpublishes one or more menu sections
* @param database A database connector object
* @param string The name of the category section
* @param array An array of id numbers
* @param integer 0 if unpublishing, 1 if publishing
*/
function publishMenuSection( $cid=null, $publish=1 ) {
	global $database, $mosConfig_absolute_path;

	if (!is_array( $cid ) || count( $cid ) < 1) {
		return 'Select an item to ' . ($publish ? 'publish' : 'unpublish');
	}

	$menu = new mosMenu( $database );
	foreach ($cid as $id) {
		$menu->load( $id );
		$menu->published = $publish;

		if (!$menu->check()) {
			return $menu->getError();
		}
		if (!$menu->store()) {
			return $menu->getError();
		}

		if ($menu->type) {
			$database = &$database;
			$task = $publish ? 'publish' : 'unpublish';
			require( "$mosConfig_absolute_path/administrator/components/com_menus/$menu->type/$menu->type.menu.php" );
		}
	}
	return null;
}

/**
* Removes a menu record
*/
function removeMenuSection( $cid=null ) {
	global $database;
	global $mosConfig_absolute_path;

	$menu = new mosMenu( $database );
	foreach ($cid as $id) {
		// must cycle through each menu item as a menu `type` may do extra work
		if ($menu->load( $id )) {
			$database->setQuery( "SELECT COUNT(*) FROM #__menu"
				. "\nWHERE parent='$menu->id' AND menutype='$menu->menutype'"
			);
			echo $database->getErrorMsg();

			$children = intval( $database->loadResult() );
			if ($children > 0) {
				echo "<script>alert('You cannot delete $menu->name as it has sub-levels.');</script>\n";
			} else {
				if ($menu->type) {
					$database = &$database;
					$task = 'remove';
					require( "$mosConfig_absolute_path/administrator/components/com_menus/$menu->type/$menu->type.menu.php" );
				}

				$menu->delete();
			}
		}
	}
	return null;
}

/**
* Cancels an edit operation
*/
function cancelMenu( $option ) {
	global $database;

	$row = new mosMenu( $database );
	$row->bind( $_POST );
	$menuid = mosGetParam( $_POST, 'menuid', 0 );
	if ($menuid) {
		$row->id = $menuid;
	}
	$row->checkin();
	mosRedirect( "index2.php?option=$option&menutype=$row->menutype" );
}

/**
* Moves the order of a record
* @param integer The increment to reorder by
*/
function orderMenu( $uid, $inc, $option ) {
	global $database;

	$row = new mosMenu( $database );
	$row->load( $uid );
	$row->move( $inc, "menutype='$row->menutype' AND parent='$row->parent'" );
	mosRedirect( "index2.php?option=$option&menutype=$row->menutype" );
}
?>
