<?php
// $Id: content.php,v 1.26 2004/04/07 11:56:02 rcastley Exp $
/**
* Content frontend 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( 'front_html', 'com_content' ) );

$sectionid = trim( mosGetParam( $_REQUEST, 'sectionid', 0 ) );
$pop = mosGetParam( $_REQUEST, 'pop', 0 );

// Editor usertype check
$access = new stdClass();
$access->canEdit = $acl->acl_check( 'action', 'edit', 'users', $my->usertype, 'content', 'all' );
$access->canEditOwn = $acl->acl_check( 'action', 'edit', 'users', $my->usertype, 'content', 'own' );
$access->canPublish = $acl->acl_check( 'action', 'publish', 'users', $my->usertype, 'content', 'all' );

$task = mosGetParam( $_REQUEST, 'task', "" );

$id = intval( mosGetParam( $_REQUEST, 'id', 0 ) );

switch (strtolower($task)) {
	case "view":
		showItem( $id, MASK_IMAGES, $gid, $access, $pop, $option );
		break;

	case "section":
		showSection( $id, $gid, $access );
		break;

	case "category":
		showCategory( $id, $gid, $access, $sectionid );
		break;

	case "blogsection":
		showBlogSection( $id, $gid, $access, $pop, $option );
		break;

	case "archivesection":
		showArchiveSection( $id, $gid, $access, $pop, $option );
		break;

	case "blogcategory":
		showBlogCategory( $id, $gid, $access, $pop, $option );
		break;

	case "archivecategory":
		showArchiveCategory( $id, $gid, $access, $pop, $option );
		break;

	case "edit":
		editItem( $id, $gid, $access, 0, $task, $Itemid );
		break;

	case "new":
		editItem( 0, $gid, $access, $sectionid, $task, $Itemid );
		break;

	case "save":
		saveContent();
		break;

	case "cancel":
		cancelContent();
		break;

	case "emailform":
		emailContentForm( $id );
		break;

	case "emailsend":
		emailContentSend( $id );
		break;

	case "vote":
		recordVote ( $url , $user_rating , $cid , $database);
		break;

	default:
		showBlogSection( 0, $gid, $access, $pop, $option );
		break;
}

function showSection( $id, $gid, $access) {
	global $database, $mainframe, $mosConfig_offset;

	$noauth = !$mainframe->getCfg( 'shownoauth' );

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

	$now = date( "Y-m-d H:i:s", time()+$mosConfig_offset*60*60 );

	if ($access->canEdit) {
		$xwhere='';
		$xwhere2 = '';
	} else {
		$xwhere = "AND c.published='1'";
		$xwhere2 = "AND b.state='1'"
		. "\n	AND (publish_up = '0000-00-00 00:00:00' OR publish_up <= '$now')"
		. "\n	AND (publish_down = '0000-00-00 00:00:00' OR publish_down >= '$now')"
		;
	}

	$database->setQuery( "SELECT c.*, COUNT(b.id) AS numitems"
	. "\nFROM #__categories AS c"
	. "\nLEFT JOIN #__content AS b ON b.catid = c.id $xwhere2"
	. "\nWHERE c.section='$section->id' $xwhere"
	. ($noauth ? "\n	AND c.access<='$gid'" : "" )
	. "\nGROUP BY c.id"
	. "\n	HAVING COUNT(b.id) > 0"
	. "\nORDER BY c.ordering"
	);
	$categories = $database->loadObjectList();

	$items = array();
	HTML_content::showContentList( $section, $categories, $items, $access, $id, 0,  $gid);
}

function showCategory( $id, $gid, $access, $sectionid  ) {
	global $database, $mainframe, $Itemid, $mosConfig_offset;

	$limit = trim( mosGetParam( $_REQUEST, 'limit', 10 ) );
	$limitstart = trim( mosGetParam( $_REQUEST, 'limitstart', 0 ) );

	$noauth = !$mainframe->getCfg( 'shownoauth' );

	$category = new mosCategory( $database );
	$category->load( $id );
	if ($sectionid == 0) {
		$sectionid = $category->section;
	}

	$now = date( "Y-m-d H:i:s", time()+$mosConfig_offset*60*60 );

	if ($access->canEdit) {
		$xwhere = '';
		$xwhere2 = '';
	} else {
		$xwhere = "\n	AND c.published='1'";
		$xwhere2 = "AND b.state='1'"
		. "\n	AND (publish_up = '0000-00-00 00:00:00' OR publish_up <= '$now')"
		. "\n	AND (publish_down = '0000-00-00 00:00:00' OR publish_down >= '$now')"
		;
	}

	// check if this is a category menu item
	if ($Itemid) {
		$menu = new mosMenu( $database );
		$menu->load( $Itemid );
		if ($menu->type == 'content_category') {
			$xwhere = "\n	AND c.id='$id'";
		}
	}

	// get the list of other categories
	$database->setQuery( "SELECT c.*, COUNT(b.id) AS numitems"
	. "\nFROM #__categories AS c"
	. "\nLEFT JOIN #__content AS b ON b.catid = c.id $xwhere2"
	. "\nWHERE c.section='$category->section' $xwhere"
	. ($noauth ? "\n	AND c.access<='$gid'" : "" )
	. "\nGROUP BY c.id"
	. "\n	HAVING COUNT(b.id) > 0"
	. "\nORDER BY c.ordering"
	);
	$categories = $database->loadObjectList();

	if ($access->canEdit) {
		$xwhere = '';
	} else {
		$xwhere = "AND c.state='1'"
		. "\n	AND (publish_up = '0000-00-00 00:00:00' OR publish_up <= '$now')"
		. "\n	AND (publish_down = '0000-00-00 00:00:00' OR publish_down >= '$now')"
		;
	}

	// get the total number of records
	$database->setQuery( "SELECT count(id)"
		. "\nFROM #__content AS c"
		. "\nWHERE c.catid='$id' $xwhere"
		. ($noauth ? "\n	AND c.access<='$gid'" : "" )
		. "\nAND '$category->access'<='$gid'"
	);
	$total = $database->loadResult();

	if ($total <= $limit) {
		$limitstart = 0;
	}

	// get the list of items for this category
	$database->setQuery( "SELECT c.id, c.title, c.hits, c.created_by, c.created_by_alias,"
		. "\n	c.created AS created, c.access, u.name AS author, c.state"
		. "\nFROM #__content AS c"
		. "\nLEFT JOIN #__users AS u ON u.id = c.created_by"
		. "\nWHERE c.catid='$category->id' $xwhere"
		. ($noauth ? "\n	AND c.access<='$gid'" : "" )
		. "\nAND '$category->access'<='$gid'"
		. "\nORDER BY c.ordering"
		. "\nLIMIT $limitstart, $limit"
	);
	$items = $database->loadObjectList();

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

	HTML_content::showContentList( $category, $categories, $items, $access, $id, $sectionid, $gid, $pageNav );
}

function showBlogSection( $id=0, $gid, $access, $pop, $option ) {
	global $database, $mainframe, $mosConfig_offset;

	$noauth = !$mainframe->getCfg( 'shownoauth' );
	$Itemid = mosGetParam( $_REQUEST, 'Itemid', 0 );

	$params = new stdClass();
	if ($Itemid) {
		$menu = new mosMenu( $database );
		$menu->load( $Itemid );
		$params = mosParseParams( $menu->params );
	}

	$now = date( "Y-m-d H:i:s", time()+$mosConfig_offset*60*60 );

	$where = array();
	if (!$access->canEdit) {
		$where[] = "a.state='1'";
		$where[] = "(a.publish_up = '0000-00-00 00:00:00' OR a.publish_up <= '$now')";
		$where[] = "(a.publish_down = '0000-00-00 00:00:00' OR a.publish_down >= '$now')";
	}
	if ($noauth) {
		$where[] = "a.access<='$gid'";
	}
	if ($id > 0) {
		$where[] = "a.sectionid='$id'";
	}

	$database->setQuery( "SELECT ROUND(v.rating_sum/v.rating_count) AS rating, v.rating_count,"
		. "\na.*, u.name AS author, u.usertype"
	. "\nFROM #__content AS a"
	. "\nLEFT JOIN #__users AS u ON u.id = a.created_by"
	. "\nLEFT JOIN #__content_rating AS v ON a.id = v.content_id"
	. "\nLEFT JOIN #__sections AS s ON a.sectionid = s.id"
	. (count( $where ) ? "\nWHERE ".implode( "\n	AND ", $where ) : '')
	. "\nAND s.access<=$gid"
	. "\nORDER BY a.sectionid, a.catid, a.ordering ASC"
	);

	$rows = $database->loadObjectList();
	echo $database->getErrorMsg();

	$count = isset( $params->count ) ? $params->count : mosGetParam( $_GET, 'count', 6 );
	$intro = isset( $params->intro ) ? $params->intro : mosGetParam( $_GET, 'intro', 3 );
	$image = @$params->image ? MASK_IMAGES : 0;
	$header = @$params->header;
	$empty = @$params->empty;

	if ($header) {
		echo $header;
	}

	$n = min( count( $rows ), $count );

	$mask = MASK_READON|$image;
	$mask |= $mainframe->getCfg( 'vote' ) ? MASK_VOTES : 0;

	$mask |= $mainframe->getCfg( 'hideAuthor' ) ? MASK_HIDEAUTHOR : 0;
	$mask |= $mainframe->getCfg( 'hideCreateDate' ) ? MASK_HIDECREATEDATE : 0;
	$mask |= $mainframe->getCfg( 'hideModifyDate' ) ? MASK_HIDEMODIFYDATE : 0;

	$mask |= MASK_HIDEPDF;
	$mask |= MASK_HIDEPRINT;
	$mask |= MASK_HIDEEMAIL;
	$mask |= $mainframe->getCfg( 'link_titles' ) ? MASK_LINK_TITLES : 0;

	if ($n > 0) {
		$col=1;
		echo "\n<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n";

		for ($i=0; $i < $n; $i++) {
			echo "<tr>\n";
			echo "<td valign=\"top\">\n";

			if ($i < $intro) {
				show( $rows[$i], $mask, $gid, $access, $pop, $gid );
			} else {
				HTML_content::showLinks( $rows, $intro, $n );
				echo "</td>\n";
				echo "</tr>\n";
				break;
			}

			echo "</td>\n";
			echo "</tr>\n";
		}

		echo "\n</table>";
	}
}

function showArchiveSection( $id=0, $gid, $access, $pop, $option ) {
	global $database, $mainframe, $mosConfig_offset;
	global $Itemid;

	$noauth = !$mainframe->getCfg( 'shownoauth' );

	$year = mosGetParam( $_REQUEST, 'year', date( 'Y' ) );
	$month = mosGetParam( $_REQUEST, 'month', date( 'm' ) );

	$params = new stdClass();
	if ($Itemid) {
		$menu = new mosMenu( $database );
		$menu->load( $Itemid );
		$params = mosParseParams( $menu->params );
	}

	$where = array();
	$where = array();
	$where[] = "a.state='-1'";
	if ($year) {
		$where[] = "YEAR(a.created)='$year'";
	}
	if ($month) {
		$where[] = "MONTH(a.created)='$month'";
	}
	if ($noauth) {
		$where[] = "a.access<='$gid'";
	}
	if ($id > 0) {
		$where[] = "a.sectionid='$id'";
	}

	$database->setQuery( "SELECT ROUND(v.rating_sum/v.rating_count) AS rating, v.rating_count,"
		. "\na.*, u.name AS author, u.usertype"
	. "\nFROM #__content AS a"
	. "\nLEFT JOIN #__users AS u ON u.id = a.created_by"
	. "\nLEFT JOIN #__content_rating AS v ON a.id = v.content_id"
	. "\nLEFT JOIN #__sections AS s ON a.sectionid = s.id"
	. (count( $where ) ? "\nWHERE ".implode( "\n	AND ", $where ) : '')
	. "\nAND s.access<=$gid"
	. "\nORDER BY a.sectionid, a.catid, a.ordering ASC"
	);

	$rows = $database->loadObjectList();
	echo $database->getErrorMsg();

	$count = isset( $params->count ) ? $params->count : mosGetParam( $_GET, 'count', 6 );
	$intro = isset( $params->intro ) ? $params->intro : mosGetParam( $_GET, 'intro', 3 );
	$image = @$params->image ? MASK_IMAGES : 0;
	$header = @$params->header;
	$empty = @$params->empty;

	/*if ($header) {
		echo $header;
	}*/

	echo "<form action=\"index.php?option=$option&task=archivesection&id=$id\" method=\"post\">";
	echo "<span class=\"componentheading\">Section Archives</span><br />";
	echo mosHTML::monthSelectList( 'month', 'size="1" class="inputbox"', $month );
	echo mosHTML::integerSelectList( 2000, 2010, 1, 'year', 'size="1" class="inputbox"', $year, "%04d" );
	echo "<input type=\"submit\" class=\"button\">";
	echo "</form>";

	$n = min( count( $rows ), $count );

	$mask = MASK_READON|$image;
 	$mask = MASK_HIDEMODIFYDATE;
	$mask |= $mainframe->getCfg( 'vote' ) ? MASK_VOTES : 0;

	if ($n > 0) {
		$col=1;
		echo "\n<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n";

		for ($i=0; $i < $n; $i++) {
			echo "<tr>\n";
			echo "<td valign=\"top\">\n";

			if ($i < $intro) {
				show( $rows[$i], $mask, $gid, $access, $pop, $gid );
			} else {
				HTML_content::showLinks( $rows, $intro, $n );
				echo "</td>\n";
				echo "</tr>\n";
				break;
			}

			echo "</td>\n";
			echo "</tr>\n";
		}

		echo "\n</table>";
	}
}


function showBlogCategory( $id=0, $gid, $access, $pop, $option ) {
	global $database, $mainframe, $mosConfig_offset;

	$noauth = !$mainframe->getCfg( 'shownoauth' );
	$Itemid = mosGetParam( $_REQUEST, 'Itemid', 0 );

	$params = new stdClass();
	if ($Itemid) {
		$menu = new mosMenu( $database );
		$menu->load( $Itemid );
		$params = mosParseParams( $menu->params );
	}

	$now = date( "Y-m-d H:i:s", time()+$mosConfig_offset*60*60 );

	$where = array();
	if (!$access->canEdit) {
		$where[] = "a.state='1'";
		$where[] = "(a.publish_up = '0000-00-00 00:00:00' OR a.publish_up <= '$now')";
		$where[] = "(a.publish_down = '0000-00-00 00:00:00' OR a.publish_down >= '$now')";
	}
	if ($noauth) {
		$where[] = "a.access<='$gid'";
	}
	if ($id > 0) {
		$where[] = "a.catid='$id'";
	}

	$database->setQuery( "SELECT ROUND(v.rating_sum/v.rating_count) AS rating, v.rating_count,"
		. "\na.*, u.name AS author, u.usertype"
	. "\nFROM #__content AS a"
	. "\nLEFT JOIN #__users AS u ON u.id = a.created_by"
	. "\nLEFT JOIN #__content_rating AS v ON a.id = v.content_id"
	. "\nLEFT JOIN #__sections AS s ON a.sectionid = s.id"
	. (count( $where ) ? "\nWHERE ".implode( "\n	AND ", $where ) : '')
	. "\nAND s.access<=$gid"
	. "\nORDER BY a.sectionid, a.catid, a.ordering ASC"
	);

	$rows = $database->loadObjectList();
	echo $database->getErrorMsg();

	$count = isset( $params->count ) ? $params->count : mosGetParam( $_GET, 'count', 6 );
	$intro = isset( $params->intro ) ? $params->intro : mosGetParam( $_GET, 'intro', 3 );
	$image = @$params->image ? MASK_IMAGES : 0;
	$header = @$params->header;
	$empty = @$params->empty;

	if ($header) {
		echo $header;
	}

	$n = min( count( $rows ), $count );

	$mask = MASK_READON|$image;
	$mask |= $mainframe->getCfg( 'vote' ) ? MASK_VOTES : 0;

	$mask |= $mainframe->getCfg( 'hideAuthor' ) ? MASK_HIDEAUTHOR : 0;
	$mask |= $mainframe->getCfg( 'hideCreateDate' ) ? MASK_HIDECREATEDATE : 0;
	$mask |= $mainframe->getCfg( 'hideModifyDate' ) ? MASK_HIDEMODIFYDATE : 0;

	$mask |= MASK_HIDEPDF;
	$mask |= MASK_HIDEPRINT;
	$mask |= MASK_HIDEEMAIL;
	$mask |= $mainframe->getCfg( 'link_titles' ) ? MASK_LINK_TITLES : 0;

	if ($n > 0) {
		$col=1;
		echo "\n<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n";

		for ($i=0; $i < $n; $i++) {
			echo "<tr>\n";
			echo "<td valign=\"top\">\n";

			if ($i < $intro) {
				show( $rows[$i], $mask, $gid, $access, $pop, $gid );
			} else {
				HTML_content::showLinks( $rows, $intro, $n );
				echo "</td>\n";
				echo "</tr>\n";
				break;
			}
			echo "</td>\n";
			echo "</tr>\n";
		}

		echo "\n</table>";
	}
}

function showArchiveCategory( $id=0, $gid, $access, $pop, $option ) {
	global $database, $mainframe, $mosConfig_offset;
	global $Itemid;

	$noauth = !$mainframe->getCfg( 'shownoauth' );
	$year = mosGetParam( $_REQUEST, 'year', date( 'Y' ) );
	$month = mosGetParam( $_REQUEST, 'month', date( 'm' ) );

	$params = new stdClass();
	if ($Itemid) {
		$menu = new mosMenu( $database );
		$menu->load( $Itemid );
		$params = mosParseParams( $menu->params );
	}

	$now = date( "Y-m-d H:i:s", time()+$mosConfig_offset*60*60 );

	$where = array();
	$where[] = "a.state='-1'";
	if ($year) {
		$where[] = "YEAR(a.created)='$year'";
	}
	if ($month) {
		$where[] = "MONTH(a.created)='$month'";
	}
	if ($noauth) {
		$where[] = "a.access<='$gid'";
	}
	if ($id > 0) {
		$where[] = "a.catid='$id'";
	}

	$database->setQuery( "SELECT ROUND(v.rating_sum/v.rating_count) AS rating, v.rating_count,"
		. "\na.*, u.name AS author, u.usertype"
	. "\nFROM #__content AS a"
	. "\nLEFT JOIN #__users AS u ON u.id = a.created_by"
	. "\nLEFT JOIN #__content_rating AS v ON a.id = v.content_id"
	. "\nLEFT JOIN #__sections AS s ON a.sectionid = s.id"
	. (count( $where ) ? "\nWHERE ".implode( "\n	AND ", $where ) : '')
	. "\nAND s.access<=$gid"
	. "\nORDER BY a.sectionid, a.catid, a.ordering ASC"
	);

	$rows = $database->loadObjectList();
	echo $database->getErrorMsg();

	$count = isset( $params->count ) ? $params->count : mosGetParam( $_GET, 'count', 6 );
	$intro = isset( $params->intro ) ? $params->intro : mosGetParam( $_GET, 'intro', 3 );
	$image = @$params->image ? MASK_IMAGES : 0;
	$header = @$params->header;
	$empty = @$params->empty;

	/*if ($header) {
		echo $header;
	}*/

	echo "<form action=\"index.php?option=$option&task=archivecategory&id=$id\" method=\"post\">";
	echo "<span class=\"componentheading\">Category Archives</span><br />";
	echo mosHTML::monthSelectList( 'month', 'size="1" class="inputbox"', $month );
	echo mosHTML::integerSelectList( 2000, 2010, 1, 'year', 'size="1" class="inputbox"', $year, "%04d" );
	echo "<input type=\"submit\" class=\"button\">";
	echo "</form>";
	$n = min( count( $rows ), $count );
	$mask = MASK_READON|$image;
 	$mask = MASK_HIDEMODIFYDATE;
	$mask |= $mainframe->getCfg( 'vote' ) ? MASK_VOTES : 0;

	$mask |= MASK_HIDEPDF;
	$mask |= MASK_HIDEPRINT;
	$mask |= MASK_HIDEEMAIL;
	$mask |= $mainframe->getCfg( 'link_titles' ) ? MASK_LINK_TITLES : 0;

	if ($n > 0) {
		$col=1;
		echo "\n<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n";

		for ($i=0; $i < $n; $i++) {
			echo "<tr>\n";
			echo "<td valign=\"top\">\n";

			if ($i < $intro) {
				show( $rows[$i], $mask, $gid, $access, $pop, $gid );
			} else {
				HTML_content::showLinks( $rows, $intro, $n );
				echo "</td>\n";
				echo "</tr>\n";
				break;
			}
			echo "</td>\n";
			echo "</tr>\n";
		}

		echo "\n</table>";
	}
}


function showItem( $uid, $mask=0, $gid, $access, $pop, $option ) {
	global $database, $mainframe;
	global $mosConfig_offset, $mosConfig_live_site;

	$now = date( "Y-m-d H:i:s", time()+$mosConfig_offset*60*60 );

	if ($access->canEdit) {
		$xwhere='';
	} else {
		$xwhere = "AND (a.state = '1' OR a.state = '-1')"
		. "\n	AND (publish_up = '0000-00-00 00:00:00' OR publish_up <= '$now')"
		. "\n	AND (publish_down = '0000-00-00 00:00:00' OR publish_down >= '$now')"
		;
	}

	$mask |= $mainframe->getCfg( 'hideAuthor' ) ? MASK_HIDEAUTHOR : 0;
	$mask |= $mainframe->getCfg( 'hideCreateDate' ) ? MASK_HIDECREATEDATE : 0;
	$mask |= $mainframe->getCfg( 'hideModifyDate' ) ? MASK_HIDEMODIFYDATE : 0;

	$mask |= $mainframe->getCfg( 'hidePdf' ) ? MASK_HIDEPDF : 0;
	$mask |= $mainframe->getCfg( 'hidePrint' ) ? MASK_HIDEPRINT : 0;
	$mask |= $mainframe->getCfg( 'hideEmail' ) ? MASK_HIDEEMAIL : 0;

	//$mask |= $mainframe->getCfg( 'vote' ) ? MASK_VOTES : 0;
	$mask |= $mainframe->getCfg( 'vote' ) ? (MASK_VOTES|MASK_VOTEFORM) : 0;
	$mask |= $pop ? 0 : MASK_BACKTOLIST;

	$sql = "SELECT ROUND(v.rating_sum/v.rating_count) AS rating, v.rating_count,"
		. "\na.*, u.name AS author, u.usertype"
		. "\nFROM #__content AS a"
		. "\nLEFT JOIN #__users AS u ON u.id = a.created_by"
		. "\nLEFT JOIN #__content_rating AS v ON a.id = v.content_id"
		. "\nWHERE a.id='$uid' $xwhere"
		. "\n	AND a.access <= $gid";

		$database->setQuery($sql);
	$row = null;
	if ($database->loadObject( $row )) {
		show( $row, $mask, $gid, $access, $pop, $option );
	} else {
		mosNotAuth();
		return;
	}
}

function show( $row, $mask=0, $gid, $access, $pop, $option ) {
	global $database, $mainframe, $Itemid;
	global $mosConfig_live_site, $mosConfig_absolute_path;

	$noauth = !$mainframe->getCfg( 'shownoauth' );	// requires honouring of access

	if ($access->canEdit) {
		if ($row->id === null || $row->access > $gid) {

			mosNotAuth();
			return;
		}
	} else {
		if ($row->id === null || $row->state == 0) {
			mosNotAuth();
			return;
		}
		if ($row->access > $gid) {
			if ($noauth) {
				mosNotAuth();
				return;
			} else {
				if (!($mask&MASK_READON)) {
					mosNotAuth();
					return;
				}
			}
		}
	}

	$template='';
	if ($pop){
		$mask |= MASK_POPUP|MASK_IMAGES;
		$database->setQuery( "SELECT cur_template from #__templates" );
		$template = $database->loadResult();
	}

	$row->text = $row->introtext.($mask&MASK_READON ? '' : "$row->fulltext");

	$bots = mosReadDirectory( "$mosConfig_absolute_path/mambots", "\.php$" );
	sort( $bots );
	foreach ($bots as $bot) {
		require "mambots/$bot";
	}

	// deal with the {mospagebreak} mambots
	// only permitted in the full text area
	$page = intval( mosGetParam( $_REQUEST, 'limitstart', 0 ) );

	// record the hit
	if (!($mask&MASK_READON)) {
		$obj = new mosContent( $database );
		$obj->hit( $row->id );
	}

	HTML_content::show( $row, $mask, $access, $page, $option );
}

function editItem( $uid, $gid, $access, $sectionid=0, $task, $Itemid ){
	global $database, $mainframe, $my;
	global $mosConfig_absolute_path, $mosConfig_live_site;

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

	if ($uid) {
		// existing record
		if (!($access->canEdit || ($access->canEditOwn && $row->created_by == $my->id))) {
			mosNotAuth();
			return;
		}
	} else {
		// new record
		if (!($access->canEdit || $access->canEditOwn)) {
			mosNotAuth();
			return;
		}
	}

	if ($uid) {
		$sectionid = $row->sectionid;
	}

	$lists = array();

	// get list of categories
	$categories[] = mosHTML::makeOption( '0', _SEL_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 (strtolower($task)<>'edit'){
		if (count( $categories ) < 2) {
			mosRedirect( "index.php?option=categories&section=$sectionid",
			"You must add a category for this section first." );
		}
	}

	if ($uid==0) {
		$row->catid = 0;
	}

	$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=$sectionid" );
	$section = $database->loadResult();

	// 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 person.')</script>";
		mosRedirect( "index.php?option=content&task=view&id=$row->id");
	}

	if ($uid) {
		$row->checkout( $my->id );
		if (trim( $row->publish_down ) == "0000-00-00 00:00:00") {
			$row->publish_down = "Never";
		}
		if (trim( $row->images )) {
			$row->images = explode( "\n", $row->images );
		} else {
			$row->images = array();
		}
	} 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";
	}

	// make the select list for the states
	$states[] = mosHTML::makeOption( 0, _CMN_UNPUBLISHED );
	$states[] = mosHTML::makeOption( 1, _CMN_PUBLISHED );
	$lists['state'] = mosHTML::selectList( $states, 'state', 'class="inputbox" size="1"',
	'value', 'text', intval( $row->state ) );

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

	$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' 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\" />"
		. _CMN_NEW_ITEM;
	}

	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 = 0;
		$row->modifier = 0;
		$row->frontpage = 0;
	}

	HTML_content::editContent( $row, $section, $lists, $images, $access, $my->id, $sectionid, $task, $Itemid );
}

/**
* Saves the content item an edit form submit
*/
function saveContent() {
	global $database, $mainframe, $my, $access;
	global $mosConfig_absolute_path;

	$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) {
		// new record
		if (!($access->canEdit || $access->canEditOwn)) {
			mosNotAuth();
			return;
		}
		$row->created = date( "Y-m-d H:i:s" );
		$row->created_by = $my->id;
	} else {
		// existing record
		if (!($access->canEdit || ($access->canEditOwn && $row->created_by == $my->id))) {
			mosNotAuth();
			return;
		}
		$row->modified = date( "Y-m-d H:i:s" );
		$row->modified_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();
	}

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

	if ($isNew) {
		// messaging for new items
		require_once( "$mosConfig_absolute_path/components/com_messages/messages.class.php" );
		$msg = new mosMessage( $database );

		$database->setQuery( "SELECT id FROM #__users WHERE sendEmail='1'" );
		$users = $database->loadResultArray();
		foreach ($users as $user_id) {
			$msg->send( $my->id, $user_id, "New Item", sprintf( _ON_NEW_CONTENT, $my->username, $row->title ) );
		}
	}

	$Itemid = mosGetParam( $_POST, 'Returnid', '0' );
	mosRedirect( "index.php?Itemid=$Itemid", $isNew ? _THANK_SUB : _E_ITEM_SAVED );
}

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

	$row = new mosContent( $database );
	$row->bind( $_POST );

	if ($access->canEdit || ($access->canEditOwn && $row->created_by == $my->id)) {
		$row->checkin();
	}

	$Itemid = mosGetParam( $_POST, 'Returnid', '0' );
	mosRedirect( "index.php?Itemid=$Itemid" );
}

/**
* Shows the email form for a given content item.
*/
function emailContentForm( $uid ) {
	global $database, $mainframe, $my;

	$row = new mosContent( $database );
	$row->load( $uid );

	if ($row->id === null || $row->access > $my->gid) {
		mosNotAuth();
		return;
	} else {
		$template='';
		$database->setQuery( "SELECT cur_template from #__templates" );
		$template = $database->loadResult();
		HTML_content::emailForm( $row->id, $row->title, $template );
	}

}

/**
* Shows the email form for a given content item.
*/
function emailContentSend( $uid ) {
	global $database;
	global $mosConfig_live_site, $mosConfig_sitename;

	$email = trim( mosGetParam( $_POST, 'email', '' ) );
	$yourname = trim( mosGetParam( $_POST, 'yourname', '' ) );
	$youremail = trim( mosGetParam( $_POST, 'youremail', '' ) );

	if (!$email || !$youremail || (is_email($email)==false) || (is_email($youremail)==false) ){
		echo "<script>alert (\""._EMAIL_ERR_NOINFO."\"); window.history.go(-1);</script>";
		exit(0);
	}

	$template='';
	$database->setQuery( "SELECT cur_template from #__templates" );
	$template = $database->loadResult();

	$msg = sprintf( _EMAIL_MSG,
	$mosConfig_sitename,
	$yourname,
	$youremail,
	"$mosConfig_live_site/index.php?option=content&task=view&id=$uid"
	);

	$recipient = $email;
	$subject = _EMAIL_INFO." $yourname";
	$headers .= "From: ".$yourname." <".$youremail.">\r\n";
	$headers .= "Reply-To: <".$youremail.">\r\n";
	$headers .= "X-Priority: 3\r\n";
	$headers .= "X-MSMail-Priority: Low\r\n";
	$headers .= "X-Mailer: Mambo Open Source 4.5\r\n";
	@mail($recipient, $subject, $msg, $headers);

	HTML_content::emailSent( $email, $template );
}

function is_email($email){
	$rBool=false;

	if(preg_match("/[\w\.\-]+@\w+[\w\.\-]*?\.\w{1,4}/", $email)){
		$rBool=true;
	}
	return $rBool;
}

function recordVote ( $url , $user_rating , $cid , $database ){
	$cid = intval( $cid );

	if (($user_rating>=1) and ($user_rating<=5)) {
		$currip = getenv( "REMOTE_ADDR" );

		$sql = "SELECT * FROM #__content_rating WHERE content_id = $cid";
		$database->setQuery( $sql );
		$votesdb = null;
		if (!($database->loadObject( $votesdb ))){
			$sql="INSERT INTO #__content_rating (content_id,lastip,rating_sum,rating_count)"
				. "\nVALUES ('$cid','$currip','$user_rating','1')";
			$database->setQuery( $sql );
			$database->query() or die( $database->stderr() );;
		} else {
			if ($currip <> ($votesdb->lastip)) {
				$sql = "UPDATE #__content_rating"
					. "\nSET rating_count=rating_count+1,"
					. "\n	rating_sum=rating_sum+$user_rating,"
					. "\n	lastip='$currip'"
					. "\nWHERE content_id=$cid";
				$database->setQuery( $sql );
				$database->query() or die( $database->stderr() );
			} else {
				mosRedirect ($url, "You have already voted!");
			}
		}
		mosRedirect ($url, "Thanks For Your Vote!");
	}
}
?>
