<?php
// $Id: admin.sections.php,v 1.3 2003/10/02 12:08:05 eddieajau Exp $
/**
* Sections 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.3 $
**/

// 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' ) );

// get parameters from the URL or submitted form
$scope = mosGetParam( $_REQUEST, 'scope', '' );
$cid = mosGetParam( $_REQUEST, 'cid', array(0) );
if (!is_array( $cid )) {
	$cid = array(0);
}

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

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

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

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

	case "publish":
		publishSections( $scope, $cid, 1, $option );
		break;

	case "unpublish":
		publishSections( $scope, $cid, 0, $option );
		break;

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

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

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

	default:
		showSections( $scope, $option );
		break;
}

/**
* Compiles a list of categories for a section
* @param database A database connector object
* @param string The name of the category section
* @param string The name of the current user
*/
function showSections( $scope, $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 #__sections WHERE scope='$scope'" );
	$total = $database->loadResult();
	echo $database->getErrorMsg();

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

	$database->setQuery( "SELECT COUNT(cc.sectionid) AS num, c.*, g.name AS groupname, u.name AS editor"
	. "\nFROM #__sections AS c"
	. "\nLEFT JOIN #__content AS cc ON c.id = cc.sectionid"
	. "\nLEFT JOIN #__users AS u ON u.id = c.checked_out"
	. "\nLEFT JOIN #__groups AS g ON g.id = c.access"
	. "\nWHERE scope='$scope'"
	. "\nGROUP BY c.id"
	. "\nORDER BY c.ordering, c.name"
	. "\nLIMIT $pageNav->limitstart,$pageNav->limit"
	);

	$rows = $database->loadObjectList();
	if ($database->getErrorNum()) {
		echo $database->stderr();
		return false;
	}

	sections_html::show( $rows, $scope, $my->id, $pageNav, $option );
}

/**
* Compiles information to add or edit a section
* @param database A database connector object
* @param string The name of the category section
* @param integer The unique id of the category to edit (0 if new)
* @param string The name of the current user
*/
function editSection( $uid=0, $scope='', $option ) {
	global $database, $my;
	global $mosConfig_absolute_path, $mosConfig_live_site;

	$row = new mosSection( $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) {
		mosRedirect( "index2.php?option=$option&scope=$row->scope&mosmsg=The section $row->title is currently being edited by another administrator" );
	}

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

	// make order list
	$orders = mosGetOrderingList( "SELECT ordering AS value, title AS text"
		. "\nFROM #__sections"
		. "\nWHERE scope='$row->scope' ORDER BY ordering"
	);
	$orderlist = mosHTML::selectList( $orders, 'ordering', 'class="inputbox" size="1"',
	'value', 'text', intval( $row->ordering ) );


	$ipos[] = mosHTML::makeOption( 'left' );
	$ipos[] = mosHTML::makeOption( 'right' );

	$iposlist = mosHTML::selectList( $ipos, 'image_position', 'class="inputbox" size="1"',
	'value', 'text', $row->image_position ? $row->image_position : 'left' );

	$imgFiles = mosReadDirectory( "$mosConfig_absolute_path/images/stories" );
	$images = array( mosHTML::makeOption( '', 'Select Image') );
	foreach ($imgFiles as $file) {
		if (eregi( "bmp|gif|jpg|png", $file )) {
			$images[] = mosHTML::makeOption( $file );
		}
	}

	$imagelist = mosHTML::selectList( $images, 'image', "class=\"inputbox\" size=\"1\""
	. " onchange=\"javascript:if (document.forms[0].image.options[selectedIndex].value!='') {document.imagelib.src='../images/stories/' + document.forms[0].image.options[selectedIndex].value} else {document.imagelib.src='../images/M_images/blank.png'}\"",
	'value', 'text', $row->image );

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

	$glist = mosHTML::selectList( $groups, 'access', 'class="inputbox" size="1"',
	'value', 'text', intval( $row->access ) );

	sections_html::edit( $row, $imagelist, $iposlist, $orderlist, $glist, $option );
}

/**
* Saves the catefory after an edit form submit
* @param database A database connector object
* @param string The name of the category section
*/
function saveSection( $option ) {
	global $database;

	$row = new mosSection( $database );
	if (!$row->bind( $_POST )) {
		echo "<script> alert('".$row->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit();
	}
	if (!$row->check()) {
		echo "<script> alert('".$row->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit();
	}
	if ($oldtitle = mosGetParam( $_POST, 'oldtitle', null )) {
		if ($oldtitle != $row->title) {
			$database->setQuery( "UPDATE #__menu SET name='$row->title' WHERE name='$oldtitle' AND type='content_section'" );
			$database->query();
		}
	}

	if (!$row->store()) {
		echo "<script> alert('".$row->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit();
	}
	$row->checkin();
	$row->updateOrder( "scope='$row->scope'" );
	mosRedirect( "index2.php?option=$option&scope=$row->scope" );
}
/**
* Deletes one or more categories from the categories table
* @param database A database connector object
* @param string The name of the category section
* @param array An array of unique category id numbers
*/
function removeSections( $cid, $scope, $option ) {
	global $database;

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

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

	$database->setQuery( "SELECT s.id, s.name, COUNT(c.id) AS numcat"
	. "\nFROM #__sections AS s"
	. "\nLEFT JOIN #__categories AS c ON c.section=s.id"
	. "\nWHERE s.id IN ($cids)"
	. "\nGROUP BY s.id"
	);
	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->numcat == 0) {
			$cid[] = $row->id;
		} else {
			$err[] = $row->name;
		}
	}

	if (count( $cid )) {
		$cids = implode( ',', $cid );
		$database->setQuery( "DELETE FROM #__sections WHERE id IN ($cids)" );
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}
	}

	if (count( $err )) {
		$cids = implode( "\', \'", $err );
		echo "<script>alert('Sections(s): \'$cids\' cannot be removed as they contain categories');</script>\n";

	}
	mosRedirect( "index2.php?option=$option&scope=$scope" );
}

/**
* Publishes or Unpublishes one or more categories
* @param database A database connector object
* @param string The name of the category section
* @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
* @param string The name of the current user
*/
function publishSections( $scope, $cid=null, $publish=1, $option ) {
	global $database, $my;

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

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

	if ($publish){
		$database->setQuery( "SELECT count FROM #__sections WHERE id IN ($cids)" );
		$count = $database->loadResult();
		if ($count <= 0){
			echo "<script> alert('Cannot Publish an Empty Section'); window.history.go(-1);</script>\n";
			return;
		}
	}

	$database->setQuery( "UPDATE #__sections 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 mosSection( $database );
		$row->checkin( $cid[0] );
	}

	// check if section linked to menu items if unpublishing
	if ($publish == 0) {
		$database->setQuery( "SELECT id FROM #__menu WHERE type='content_section' AND componentid IN ($cids)" );
		$menus = $database->loadObjectList();

		if ($menus) {
			foreach ($menus as $menu) {
				$database->setQuery( "UPDATE #__menu SET published=$publish WHERE id=$menu->id" );
				$database->query();
			}
		}
	}

	mosRedirect( "index2.php?option=$option&scope=$scope" );
}

/**
* Cancels an edit operation
* @param database A database connector object
* @param string The name of the category section
* @param integer A unique category id
*/
function cancelSection( $option ) {
	global $database;
	$row = new mosSection( $database );
	$row->bind( $_POST );
	$row->checkin();
	mosRedirect( "index2.php?option=$option&scope=$row->scope" );
}

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

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