<?php
// $Id: modules.php,v 1.20 2004/03/08 13:59:30 rcastley Exp $
/**
* Modules admin 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.20 $
**/

// 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( "classes/html/HTML_modules.php" );

switch ( $task ) {
	case "new":
		editModule( $option, 0 );
		break;

	case "edit":
		editModule( $option, $cid[0] );
		break;

	case "save":
		saveModule( $option );
		break;

	case "remove":
		removeModule( $cid, $option );
		break;

	case "publish":
		publishModule( $id, $cid, 1, $option );
		break;

	case "unpublish":
		publishModule( $id, $cid, 0, $option );
		break;

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

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

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

	default:
		viewModules( $option );
		break;
}

/**
* Compiles a list of installed or defined modules
*/
function viewModules( $option ) {
	global $database, $my, $mainframe;

	$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', 10 );
	$limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );

	// get the total number of records
	$database->setQuery( "SELECT count(*) FROM #__modules" );
	$total = $database->loadResult();
	echo $database->getErrorMsg();

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

	$database->setQuery( "SELECT m.*, u.name AS editor, g.name AS groupname"
		. "\nFROM #__modules AS m"
		. "\nLEFT JOIN #__users AS u ON u.id = m.checked_out"
		. "\nLEFT JOIN #__groups AS g ON g.id = m.access"
		. "\nORDER BY position, ordering"
		. "\nLIMIT $pageNav->limitstart,$pageNav->limit"
	);
	$rows = $database->loadObjectList();
	if ($database->getErrorNum()) {
		echo $database->stderr();
		return false;
	}

	HTML_modules::showModules( $rows, $my->id, $pageNav, $option );
}

/**
* Saves the module after an edit form submit
*/
function saveModule( $option ) {
	global $database;

	$row = new mosModule( $database );
	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( "position='$row->position'" );

	$menus = mosGetParam( $_POST, 'selections', array() );

	$database->setQuery( "DELETE FROM #__modules_menu WHERE moduleid='$row->id'" );
	$database->query();

	foreach ($menus as $menuid){
		$database->setQuery( "INSERT INTO #__modules_menu"
			. "\nSET moduleid='$row->id', menuid='$menuid'"
		);
		$database->query();
	}

	$limit = intval( mosGetParam( $_REQUEST, 'limit', 10 ) );
	$limitstart = intval( mosGetParam( $_REQUEST, 'limitstart', 0 ) );
	mosRedirect( "index2.php?option=$option&limit=$limit&limitstart=$limitstart" );
}

/**
* Compiles information to add or edit a module
* @param string The current GET/POST option
* @param integer The unique id of the record to edit
*/
function editModule( $option, $uid ) {
	global $database, $my;

	$row = new mosModule( $database );
	// load the row from the db table
	$row->load( $uid );

	// fail if checked out not by 'me'
	if ($row->checked_out && $row->checked_out <> $my->id) {
		echo "<script>alert('The module $row->title is currently being edited by another administrator'); document.location.href='index2.php?option=$option'</script>\n";
		exit(0);
	}

	if ($uid) {
		$row->checkout( $my->id );
	}

	$database->setQuery( "SELECT position, ordering, showtitle, title FROM #__modules"
		. "\nORDER BY ordering"
	);
	if (!($orders = $database->loadObjectList())) {
		echo $database->stderr();
		return false;
	}

// build the order lists to be used to make the javascript arrays

	// hard code options for now
	$orders2 = array();
	$orders2['left'] = array();
	$orders2['right'] = array();
	$orders2['top'] = array();
	$orders2['bottom'] = array();
	$orders2['inset'] = array();
	$orders2['user1'] = array();
	$orders2['user2'] = array();

	$l = 0;
	$r = 0;
	for ($i=0, $n=count( $orders ); $i < $n; $i++) {
		$ord = 0;
		if (array_key_exists( $orders[$i]->position, $orders2 )) {
			$ord =count( array_keys( $orders2[$orders[$i]->position] ) ) + 1;
		}

		$orders2[$orders[$i]->position][] = mosHTML::makeOption( $ord, $ord.'::'.addslashes( $orders[$i]->title ) );

		##if ($orders[$i]->position == 'left') {
		##	$leftorder[$l] = mosHTML::makeOption( ++$l, $l.' before '.$orders[$i]->title );
		##} else {
		##	$rightorder[$r] = mosHTML::makeOption( ++$r, $r.' before '.$orders[$i]->title );
		##}
	}

// if a new record we must still prime the mosModule object with a default
// position and the order; also add an extra item to the order list to
// place the 'new' record in last position if desired
	if ($uid == 0) {
		$row->position = 'left';
		$row->showtitle = true;
		$row->ordering = $l;
	}

// make an array for the left and right positions
	foreach ( array_keys( $orders2 ) as $v ) {
		$ord = count( array_keys( $orders2[$v] ) ) + 1;
		$orders2[$v][] = mosHTML::makeOption( $ord, $ord.'::last' );
		##$pos[] = mosHTML::makeOption( 'left' );
		##$pos[] = mosHTML::makeOption( 'right' );
		$pos[] = mosHTML::makeOption( $v );
	}

// build the html select list
	$poslist = mosHTML::selectList( $pos, 'position',
		'class="inputbox" size="1" onchange="changeDynaList(\'ordering\',orders,document.adminForm.position.options[document.adminForm.position.selectedIndex].value, originalPos, originalOrder)"',
		'value', 'text', $row->position ? $row->position : 'left' );

// 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="1"',
		'value', 'text', intval( $row->access ) );

// get a list of the menu items
	$database->setQuery( "SELECT m.*"
		. "\nFROM #__menu m"
		. "\nWHERE menutype='mainmenu' AND type != 'url' AND type != 'separator'"
		. "\nORDER BY ordering, parent"
	);
	$mitems = $database->loadObjectList();

// get selected pages
	if ($uid) {
		$database->setQuery( "SELECT menuid AS value FROM #__modules_menu WHERE moduleid=$row->id" );
		$lookup = $database->loadObjectList();
	} else {
		$lookup = array( mosHTML::makeOption( 0, 'All' ) );
	}

// establish the hierarchy of the menu
	$children = array();
// first pass - collect children
	foreach ($mitems as $v ) {
		$id = $v->id;
		$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( intval( $mitems[0]->parent ), '', array(), $children );

// prepare an array with 'all' as the first item
	$mitems = array( mosHTML::makeOption( 0, 'All' ) );
// append the rest of the menu items to the array
	foreach ($list as $item) {
		$mitems[] = mosHTML::makeOption( $item->id, $item->treename );
	}

// build the html select list
	$menulist = mosHTML::selectList( $mitems, 'selections[]', 'class="inputbox" size="10" multiple="multiple"',
		'value', 'text', $lookup );

// make the select list for the image positions
	$yesno[] = mosHTML::makeOption( '0', 'No' );
	$yesno[] = mosHTML::makeOption( '1', 'Yes' );

// build the html select list
	$titlelist = mosHTML::selectList( $yesno, 'showtitle', 'class="inputbox" size="1"', 'value', 'text', $row->showtitle );

	$publishlist = mosHTML::selectList( $yesno, 'published', 'class="inputbox" size="1"', 'value', 'text', $row->published );

	$row->content = htmlspecialchars( str_replace( '&amp;', '&', $row->content ) );
	HTML_modules::editModule( $row, $orders2, $glist, $menulist, $poslist, $titlelist, $publishlist, $option );
}

/**
* Deletes one or more modules
*
* Also deletes associated entries in the mos_module_menu table.
* @param array An array of unique category id numbers
*/
function removeModule( &$cid, $option ) {
	global $database, $my;

	if (count( $cid ) < 1) {
		echo "<script> alert('Select a module to delete'); window.history.go(-1);</script>\n";
		exit;
	}

	$cids = implode( ',', $cid );

	$database->setQuery( "SELECT id, module, title FROM #__modules WHERE id IN ($cids)" );
	if (!($rows = $database->loadObjectList())) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
	}

	$err = array();
	$cid = array();
	foreach ($rows as $row) {
		if ($row->module == '') {
			$cid[] = $row->id;
		} else {
			$err[] = $row->title;
		}
	}

	if (count( $cid )) {
		$cids = implode( ',', $cid );
		$database->setQuery( "DELETE FROM #__modules WHERE id IN ($cids)" );
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
			exit;
		}
		$database->setQuery( "DELETE from #__modules_menu WHERE moduleid IN ($cids)" );
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."');</script>\n";
			exit;
		}
		$mod = new mosModule( $database );
		$mod->ordering = 0;
		$mod->updateOrder( "position='left'" );
		$mod->updateOrder( "position='right'" );
	}

	if (count( $err )) {
		$cids = addslashes( implode( "', '", $err ) );
		echo "<script>alert('Module(s): \'$cids\' cannot be deleted they can only be un-installed as they are Mambo modules.');</script>\n";
	}

	$limit = intval( mosGetParam( $_REQUEST, 'limit', 10 ) );
	$limitstart = intval( mosGetParam( $_REQUEST, 'limitstart', 0 ) );
	mosRedirect( "index2.php?option=$option&limit=$limit&limitstart=$limitstart" );
}

/**
* Publishes or Unpublishes one or more modules
* @param integer A unique category id (passed from an edit form)
* @param array An array of unique category id numbers
* @param integer 0 if unpublishing, 1 if publishing
*/
function publishModule( $id=null, $cid=null, $publish=1, $option ) {
	global $database;

	if (!is_array( $cid )) {
		$cid = array();
	}
	if ($id) {
		$cid[] = $id;
	}

	if (count( $cid ) < 1) {
		$action = $publish ? 'publish' : 'unpublish';
		echo "<script> alert('Select a module to $action'); window.history.go(-1);</script>\n";
		exit;
	}

	$cids = implode( ',', $cid );

	$database->setQuery( "UPDATE #__modules SET published='$publish'"
		. "\nWHERE id IN ($cids) AND (checked_out=0 OR (checked_out='$my->id'))"
	);
	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit();
	}

	if (count( $cid ) == 1) {
		$row = new mosModule( $database );
		$row->checkin( $cid[0] );
	}

	$limit = intval( mosGetParam( $_REQUEST, 'limit', 10 ) );
	$limitstart = intval( mosGetParam( $_REQUEST, 'limitstart', 0 ) );
	mosRedirect( "index2.php?option=$option&limit=$limit&limitstart=$limitstart" );
}

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

	$row = new mosModule( $database );
	$row->bind( $_POST );
	$row->checkin();
	$limit = intval( mosGetParam( $_REQUEST, 'limit', 10 ) );
	$limitstart = intval( mosGetParam( $_REQUEST, 'limitstart', 0 ) );
	mosRedirect( "index2.php?option=$option&limit=$limit&limitstart=$limitstart" );
}

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

	$row = new mosModule( $database );
	$row->load( $uid );
	$row->move( $inc, "position='$row->position'"  );
	$limit = intval( mosGetParam( $_REQUEST, 'limit', 10 ) );
	$limitstart = intval( mosGetParam( $_REQUEST, 'limitstart', 0 ) );
	mosRedirect( "index2.php?option=$option&limit=$limit&limitstart=$limitstart" );
}

?>
