<?php
// $Id: content.php,v 1.37 2004/02/19 21:36:12 ronbakker Exp $
/**
* Administrator content 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.37 $
**/

// 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_content.php");

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

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

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

	case "save":
		saveContent( $sectionid, $option );
		break;

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

	case "publish":
		changeContent( $cid, 1, $sectionid, $option );
		break;

	case "unpublish":
		changeContent( $cid, 0, $sectionid, $option );
		break;

	case "toggle_frontpage":
		toggleFrontPage( $cid, $sectionid, $option );
		break;

	case "archive":
		changeContent( $cid, -1, $sectionid, $option );
		break;

	case "unarchive":
		changeContent( $cid, 0, $sectionid, $option );
		break;

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

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

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

	case "showarchive":
		viewArchive( $sectionid, $option );
		break;

	case "movesect":
		moveSection( $cid, $sectionid, $option );
		break;

	case "movesectsave":
		moveSectionSave( $cid, $sectionid, $option );
		break;

	default:
		viewContent( $sectionid, $option );
	break;
}

/**
* Compiles a list of installed or defined modules
* @param database A database connector object
*/
function viewContent( $sectionid, $option ) {
	global $database, $mainframe;

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

	$where = array(
	"c.state >= 0",
	"c.catid=cc.id",
	"cc.section=s.id",
	"s.scope='content'",
	"c.sectionid='$sectionid'"
	);

	if ($catid > 0) {
		$where[] = "c.catid='$catid'";
	}
	if ($search) {
		$where[] = "LOWER(c.title) LIKE '%$search%'";
	}

	// get the total number of records
	$database->setQuery( "SELECT count(*) FROM #__content AS c, #__categories AS cc, #__sections AS s"
	. (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
	);
	$total = $database->loadResult();
	echo $database->getErrorMsg();

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

	$database->setQuery( "SELECT c.*, g.name AS groupname, cc.name, u.name AS editor, f.content_id AS frontpage"
	. "\nFROM #__content AS c, #__categories AS cc, #__sections AS s"
	. "\nLEFT JOIN #__groups AS g ON g.id = c.access"
	. "\nLEFT JOIN #__users AS u ON u.id = c.checked_out"
	. "\nLEFT JOIN #__content_frontpage AS f ON f.content_id = c.id"
	. (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
	. "\nORDER BY catid, ordering"
	. "\nLIMIT $pageNav->limitstart,$pageNav->limit"
	);

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

	$lists = array();
	// get list of categories
	$categories[] = mosHTML::makeOption( '0', 'All Categories' );
	$database->setQuery( "SELECT id AS value, title AS text FROM #__categories"
	. "\nWHERE section='$sectionid' ORDER BY ordering" );
	$categories = array_merge( $categories, $database->loadObjectList() );

	$lists['catid'] = mosHTML::selectList( $categories, 'catid', 'class="inputbox" size="1" onchange="document.adminForm.submit();"',
	'value', 'text', $catid );

	$section = new mosSection( $database );
	$section->load( $sectionid );

	HTML_content::showContent( $rows, $section, $lists, $search, $pageNav, $option );
}

/**
* Shows a list of archived content items
* @param int The section id
*/
function viewArchive( $sectionid, $option ) {
	global $database, $mainframe;

	$catid = $mainframe->getUserStateFromRequest( "catidarc{$option}{$sectionid}", 'catid', 0 );
	$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', 10 );
	$limitstart = $mainframe->getUserStateFromRequest( "viewarc{$option}{$sectionid}limitstart", 'limitstart', 0 );
	$search = $mainframe->getUserStateFromRequest( "searcharc{$option}{$sectionid}", 'search', '' );
	$search = $database->getEscaped( trim( strtolower( $search ) ) );

	$where = array(
	"c.state < 0",
	"c.catid=cc.id",
	"cc.section=s.id",
	"s.scope='content'",
	"c.sectionid='$sectionid'"
	);

	if ($catid > 0) {
		$where[] = "c.catid='$catid'";
	}
	if ($search) {
		$where[] = "LOWER(c.title) LIKE '%$search%'";
	}

	// get the total number of records
	$database->setQuery( "SELECT count(*) FROM #__content AS c, #__categories AS cc, #__sections AS s"
	. (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
	);
	$total = $database->loadResult();
	echo $database->getErrorMsg();

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

	$database->setQuery( "SELECT c.*, g.name AS groupname, cc.name"
	. "\nFROM #__content AS c, #__categories AS cc, #__sections AS s"
	. "\nLEFT JOIN #__groups AS g ON g.id = c.access"
	. (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
	. "\nORDER BY catid, ordering"
	. "\nLIMIT $pageNav->limitstart,$pageNav->limit"
	);

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

	$lists = array();
	// get list of categories
	$categories[] = mosHTML::makeOption( '0', 'All Categories' );
	$database->setQuery( "SELECT id AS value, title AS text FROM #__categories"
	. "\nWHERE section='$sectionid' ORDER BY ordering" );
	$categories = array_merge( $categories, $database->loadObjectList() );

	$lists['catid'] = mosHTML::selectList( $categories, 'catid', 'class="inputbox" size="1" onchange="document.adminForm.submit();"',
	'value', 'text', $catid );

	$section = new mosSection( $database );
	$section->load( $sectionid );

	HTML_content::showArchive( $rows, $section, $lists, $search, $pageNav, $option );
}

/**
* Compiles information to add or edit the record
* @param database A database connector object
* @param integer The unique id of the record to edit (0 if new)
* @param integer The id of the content section
*/
function editContent( $uid, $sectionid=0, $option ) {
	global $database, $my;
	global $mosConfig_absolute_path, $mosConfig_live_site, $mosConfig_editor;

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

	if ($uid) {
		$sectionid = $row->sectionid;
		if ($row->state < 0) {
			mosRedirect( "index2.php?option=content&sectionid=$row->sectionid&mosmsg=You cannot edit an archived item" );
		}
	}

	$lists = array();
	// get list of categories
	$categories[] = mosHTML::makeOption( '0', 'Select Category' );
	$database->setQuery( "SELECT id AS value, name AS text FROM #__categories"
	. "\nWHERE section='$sectionid' ORDER BY ordering" );
	$categories = array_merge( $categories, $database->loadObjectList() );

	if (count( $categories ) < 2) {
		mosRedirect( "index2.php?option=categories&section=$sectionid",
		"You must add a category for this section first." );
	}

	$lists['catid'] = mosHTML::selectList( $categories, 'catid', 'class="inputbox" size="1"',
	'value', 'text', intval( $row->catid ) );

	// get the type name - which is a special category
	$database->setQuery( "SELECT name FROM #__sections WHERE id=$row->sectionid" );
	$section = $database->loadResult();

	// fail if checked out not by 'me'
	if ($row->checked_out && $row->checked_out <> $my->id) {
		mosRedirect( "index2.php?option=content",
		"The module $row->title is currently being edited by another administrator" );
	}

	if ($uid) {
		$row->checkout( $my->id );
		if (trim( $row->images )) {
			$row->images = explode( "\n", $row->images );
		} else {
			$row->images = array();
		}
		if (trim( $row->publish_down ) == "0000-00-00 00:00:00") {
			$row->publish_down = "Never";
		}
	} else {
		$row->sectionid = $sectionid;
		$row->version = 0;
		$row->state = 0;
		$row->ordering = 9999;
		$row->images = array();
		$row->publish_up = date( "Y-m-d", time() );
		$row->publish_down = "Never";
	}

	// get list of images
	$imgFiles = mosReadDirectory( "$mosConfig_absolute_path/images/stories" );
	$images = array();
	$folders = array();
	$folders[] = mosHTML::makeOption( "/" );
	foreach ($imgFiles as $file) {
		if (is_dir( "$mosConfig_absolute_path/images/stories/$file" )) {
			$folders[] = mosHTML::makeOption( "/$file" );
			$folder = mosReadDirectory( "$mosConfig_absolute_path/images/stories/$file" );
			foreach ($folder as $file2) {
				if (eregi( "bmp|gif|jpg|png", $file2 )
						&& is_file( "$mosConfig_absolute_path/images/stories/$file/$file2" )) {
					$images["/$file"][] = mosHTML::makeOption( "$file/$file2" );
				}
			}

		} else if (eregi( "bmp|gif|jpg|png", $file )
				&& is_file( "$mosConfig_absolute_path/images/stories/$file" )) {
			$images['/'][] = mosHTML::makeOption( $file );
		}
	}

	if ( ! isset($images['/']) ) {
		$images['/'][] = mosHTML::makeOption( '' );
		}
	
	$lists['imagefiles'] = mosHTML::selectList( $images['/'], 'imagefiles', "class=\"inputbox\" size=\"10\" multiple=\"multiple\""
	. " onchange=\"previewImage('imagefiles','view_imagefiles','$mosConfig_live_site/images/stories/')\"",
	'value', 'text', null );

	$lists['folders'] = mosHTML::selectList( $folders, 'folders', "class=\"inputbox\" size=\"1\" "
	."onchange=\"changeDynaList('imagefiles',folderimages,document.adminForm.folders.options[document.adminForm.folders.selectedIndex].value, 0, 0)\"",
	'value', 'text', '/' );

	// make the list of saved images
	$images2 = array();
	foreach ($row->images as $file) {
		$temp = explode( '|', $file );
		$images2[] = mosHTML::makeOption( $file, $temp[0] );
	}

	$lists['imagelist'] = mosHTML::selectList( $images2, 'imagelist', "class=\"inputbox\" size=\"10\""
	. " onchange=\"showImageProps('$mosConfig_live_site/images/stories/')\"",
	'value', 'text', null );

	// make the select list for the image positions
	$pos[] = mosHTML::makeOption( '', _CMN_NONE );
	$pos[] = mosHTML::makeOption( 'left', _CMN_LEFT );
	$pos[] = mosHTML::makeOption( 'center', _CMN_CENTER );
	$pos[] = mosHTML::makeOption( 'right', _CMN_RIGHT );

	// build the html select list
	$lists['_align'] = mosHTML::selectList( $pos, '_align', 'class="inputbox" size="4"',
	'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
	$lists['access'] = mosHTML::selectList( $groups, 'access', 'class="inputbox" size="1"',
	'value', 'text', intval( $row->access ) );

	// get list of other menu items by order

	if ($uid) {
		// build the html select list for ordering
		$order = mosGetOrderingList( "SELECT ordering AS value, title AS text"
			. "\nFROM #__content"
			. "\nWHERE catid='$row->catid' AND state >= 0 ORDER BY ordering"
		);
		$lists['ordering'] = mosHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"',
		'value', 'text', intval( $row->ordering ) );
	} else {
		$lists['ordering'] = "<input type=\"hidden\" name=\"ordering\" value=\"$row->ordering\" />"
		. " New items default to the last place";
	}

	if ($uid) {
		$database->setQuery( "SELECT name from #__users"
			. "\nWHERE id=$row->created_by"
		);
		$row->creator = $database->loadResult();

		$database->setQuery( "SELECT name from #__users"
			. "\nWHERE id=$row->modified_by"
		);
		$row->modifier = $database->loadResult();

		$database->setQuery( "SELECT content_id from #__content_frontpage"
			. "\nWHERE content_id=$row->id"
		);
		$row->frontpage = $database->loadResult();
	} else {
		$row->creator = '';
		$row->modifier = '';
		$row->frontpage = 0;
	}

	// get list of users
	$database->setQuery( "SELECT id AS value, name AS text from #__users"
		. "\nORDER BY name"
	);
	$users = $database->loadObjectList();
	$lists['created_by'] = mosHTML::selectList( $users, 'created_by', 'class="inputbox" size="1"',
	'value', 'text', intval( $row->created_by ) ? intval( $row->created_by ) : $my->id);

	HTML_content::editContent( $row, $section, $lists, $images, $my->id, $mosConfig_editor, $option );
}

/**
* Saves the content item an edit form submit
* @param database A database connector object
*/
function saveContent( $sectionid, $option ) {
	global $database, $my, $mainframe;

	$row = new mosContent( $database );
	if (!$row->bind( $_POST )) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	$isNew = ($row->id < 1);
	if ($isNew) {
		$row->created = $row->created ? $row->created : date( "Y-m-d H:i:s" );
		$row->created_by = $row->created_by ? $row->created_by : $my->id;
	} else {
		$row->modified = date( "Y-m-d H:i:s" );
		$row->modified_by = $my->id;
		$row->created = $row->created ? $row->created : date( "Y-m-d H:i:s" );
		$row->created_by = $row->created_by ? $row->created_by : $my->id;
	}
	if (trim( $row->publish_down ) == "Never") {
		$row->publish_down = "0000-00-00 00:00:00";
	}

	$row->mask = 0;
	$row->mask |= intval( mosGetParam( $_POST, 'mask_hide_title', 0 ) );
	echo intval( $row->mask );

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

	$msg = '';

	// manage frontpage items

	require_once( $mainframe->getPath( 'class', 'com_frontpage' ) );
	$fp = new mosFrontPage( $database );

	if (mosGetParam( $_REQUEST, 'frontpage', 0 )) {

		// toggles go to first place
		if (!$fp->load( $row->id )) {
			// new entry
			$database->setQuery( "INSERT INTO #__content_frontpage VALUES ('$row->id','1')" );
			if (!$database->query()) {
				echo "<script> alert('".$database->stderr()."');</script>\n";
				exit();
			}
			$fp->ordering = 1;
		}
	} else {
		// no frontpage mask
		if (!$fp->delete( $row->id )) {
			$msg .= $fp->stderr();
		}
		$fp->ordering = 0;
	}
	$fp->updateOrder();

	$row->checkin();
	$row->updateOrder( "catid='$row->catid' AND state >= 0" );

	mosRedirect( "index2.php?option=content&sectionid=$row->sectionid", $msg );
}

/**
* Changes the state of one or more content pages
* @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 changeContent( $cid=null, $state=0, $section, $option ) {
	global $database;

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

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

	$database->setQuery( "UPDATE #__content SET state='$state'"
	. "\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 mosContent( $database );
		$row->checkin( $cid[0] );
	}

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

/**
* Changes the state of one or more content pages
* @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 toggleFrontPage( $cid, $section, $option ) {
	global $database, $my, $mainframe;

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

	$msg = '';
	require_once( $mainframe->getPath( 'class', 'com_frontpage' ) );

	$fp = new mosFrontPage( $database );
	foreach ($cid as $id) {
		// toggles go to first place
		if ($fp->load( $id )) {
			if (!$fp->delete( $id )) {
				$msg .= $fp->stderr();
			}
			$fp->ordering = 0;
		} else {
			// new entry
			$database->setQuery( "INSERT INTO #__content_frontpage VALUES ('$id','1')" );
			if (!$database->query()) {
				echo "<script> alert('".$database->stderr()."');</script>\n";
				exit();
			}
			$fp->ordering = 1;
		}
		$fp->updateOrder();
	}

	mosRedirect( "index2.php?option=$option&sectionid=$section", $msg );
}

function removeContent( &$cid, $sectionid, $option ) {
	global $database, $mainframe;

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

	require_once( $mainframe->getPath( 'class', 'com_frontpage' ) );

	$msg = '';
	$obj = new mosContent( $database );
	foreach ($cid as $id) {
		$id = intval( $id );
		$obj->delete( $id );
		$msg .= $obj->getError();

		// cleanup frontpage items
		$fp = new mosFrontPage( $database );
		if (!$fp->delete( $id )) {
			$msg .= $fp->getError();
		}
		$fp->ordering = 0;
		$fp->updateOrder();
	}

	mosRedirect( "index2.php?option=$option&sectionid=$sectionid", $msg );
}

/**
* Cancels an edit operation
* @param database A database connector object
*/
function cancelContent( $option ) {
	global $database;

	$row = new mosContent( $database );
	$row->bind( $_POST );
	$row->checkin();
	mosRedirect( "index2.php?option=$option&sectionid=$row->sectionid" );
}

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

	$row = new mosContent( $database );
	$row->load( $uid );
	$row->move( $inc, "catid='$row->catid' AND state >= 0" );

	mosRedirect( "index2.php?option=$option&sectionid=$row->sectionid" );
}

/**
* Form for moving item(s) to a different section and category
*/
function moveSection( &$cid, $sectionid, $option ) {
	global $database;

	if (!is_array( $cid ) || count( $cid ) < 1) {
		echo "<script> alert('Select an item to move'); window.history.go(-1);</script>\n";
		exit;
	}

	$database->setQuery( "SELECT CONCAT_WS(',',s.id,c.id) AS `value`,"
		. "\n	CONCAT_WS('/',s.name,c.name) AS `text`"
		. "\nFROM #__sections AS s"
		. "\nINNER JOIN #__categories AS c ON c.section = s.id"
		. "\nWHERE s.scope='content'"
		. "\nORDER BY s.name,c.name"
	);
	$rows = $database->loadObjectList();

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

	HTML_content::moveSection( $cid, $sectCatList, $option, $sectionid );
}

/**
* Save the changes to move item(s) to a different section and category
*/
function moveSectionSave( &$cid, $sectionid, $option ) {
	global $database, $my;

	$sectcat = mosGetParam( $_POST, 'sectcat', '' );
	list( $newsect, $newcat ) = explode( ',', $sectcat );

	if (!$newsect && !$newcat ) {
		mosRedirect( "index.php?option=content&sectionid=$sectionid&mosmsg=An error has occurred" );
	}
	$cids = implode( ',', $cid );

	$database->setQuery( "UPDATE #__content SET sectionid='$newsect', catid='$newcat'"
		. "\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();
	}
	mosRedirect( "index2.php?option=$option&sectionid=$sectionid" );
}
?>