<?php
/* $Id: note.class.php,v 1.22 2004/06/28 18:07:42 k-fish Exp $ */

class Note{
    function opCreate() {
        global $conn, $smarty, $appconf;
	queryRights2('root_modules_notes_notes_create');

	    $id = mgw_genID('mgw__seq_notes');
	    $qtitle = $conn->QMagic($_POST['title']);
	    $qcontent = $conn->QMagic($_POST['content']);
	    $catid = (int) $_POST["catid"];
	    $public = (int) $_POST["public"];

	    $sql="INSERT INTO mgw_notes (id, title, content, catid, ispublic, owner, lu_user, lu_update) VALUES ($id, $qtitle, $qcontent, $catid, $public, ".$_SESSION["MGW"]->userid.", ".$_SESSION["MGW"]->userid.", ".$conn->DBTimeStamp(time()).")";

	    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	    return true;
	}

    function opComment() {
        global $conn, $smarty, $appconf;
	queryRights2('root_modules_notes_notes_comment');

	$id = mgw_genID('mgw__seq_notes_comments');
	$note_id = (int) $_POST["note_id"];
	$qcomment = $conn->QMagic($_POST['comment']);

	$sql="INSERT INTO mgw_notes_comments (id, note_id, comment, lu_user, lu_update) VALUES ($id, $note_id, $qcomment, ".$_SESSION["MGW"]->userid.", ".$conn->DBTimeStamp(time()).")";

	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	return true;
    }

    function editComment($id) {
        global $conn, $smarty, $appconf;
	queryRights2('root_modules_notes_notes_comment');

	$qcomment = $conn->QMagic($_POST['comment']);

	$sql="UPDATE mgw_notes_comments SET comment=$qcomment, lu_update=".$conn->DBTimeStamp(time())." WHERE id=".(int)$id;
	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	return true;
    }

    function opUpdate($id) {
        global $conn, $smarty, $appconf;

	$sql = "SELECT owner FROM mgw_notes WHERE id=".(int)$id." AND (ispublic=1 OR owner=".$_SESSION["MGW"]->userid.")";
	if(($row = $conn->GetRow($sql)) === false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	if((queryRights2_bool('root_modules_notes_notes_modify') && $row["owner"] == $_SESSION["MGW"]->userid) ||
	   (queryRights2_bool('root_modules_notes_notes_modifyothers') && $row["owner"] != $_SESSION["MGW"]->userid)){

	    $qtitle = $conn->QMagic($_POST['title']);
	    $qcontent = $conn->QMagic($_POST['content']);
	    $catid = (int) $_POST["catid"];
	    $public = (int) $_POST["public"];

	    $sql="UPDATE mgw_notes SET title=$qtitle, content=$qcontent, catid=$catid, lu_user=".$_SESSION["MGW"]->userid.", lu_update=".$conn->DBTimeStamp(time()).", ispublic=$public WHERE id=".(int)$id." AND (ispublic=1 OR owner=".$_SESSION["MGW"]->userid.")";

	    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	    return true;
	}
	else return false;
    }

    function viewDelete($id){
        global $smarty, $conn, $appconf;

	$sql = "SELECT * FROM mgw_notes WHERE id=".(int)$id;
	if(($row = $conn->GetRow($sql)) === false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	if((queryRights2_bool('root_modules_notes_notes_delete') && $row["owner"] == $_SESSION["MGW"]->userid) ||
	   (queryRights2_bool('root_modules_notes_notes_deleteothers') && $row["owner"] != $_SESSION["MGW"]->userid)){

	    $smarty->assign("menuid", "1");
	    $smarty->assign("itemid", $id);
	    $smarty->assign("parms", str_replace("delete","list",$_SERVER["QUERY_STRING"]));
	    $smarty->assign("deleteitem", Lang::getLanguageString("deleteitem"));
	    $smarty->assign("reallydeleteitem", Lang::getLanguageString("reallydeletenote"));
	    $smarty->assign("deleteheader", Lang::getLanguageString("deleteheader"));
	    $smarty->assign("deletedetail1", $row["title"]);
	    $smarty->assign("deletedetail2", nl2br(substr($row["content"],0,250))." ...");
	    $smarty->assign("deletedetail3", "");
	    $smarty->assign("suclass","submit");
	    $smarty->assign("js", "");
	    $smarty->display($appconf["gentemplates"] ."/delete_item.tpl");

	    return true;
	}
	else return false;
    }

    function opDelete($id){
	global $conn;

	$sql = "SELECT owner FROM mgw_notes WHERE id=".(int)$id;
	if(($row = $conn->GetRow($sql)) === false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	if((queryRights2_bool('root_modules_notes_notes_delete') && $row["owner"] == $_SESSION["MGW"]->userid) ||
	   (queryRights2_bool('root_modules_notes_notes_deleteothers') && $row["owner"] != $_SESSION["MGW"]->userid)){

	    $sql = "DELETE FROM mgw_notes WHERE id=".(int)$id." AND (ispublic=1 OR owner=".$_SESSION["MGW"]->userid.")";
	    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	    $sql = "DELETE FROM mgw_notes_comments WHERE note_id=".(int)$id;
	    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	    return true;
	}
	else return false;
    }

    function viewNewForm() {
        global $conn,$smarty, $appconf;
	queryRights2('root_modules_notes_notes_create');

	    include_once(INCLUDEPATH . "mSelectBox.class.php");

	    $sb = new mSelectBox("catid");
	    $sb->setContentType("sql");
	    $sb->setSQLvalue("catid");
	    $sb->setSQLcontent("name");
	    $sb->addContent("SELECT id AS catid, name FROM mgw_notes_categories ORDER BY name");
	    $sb->addOption("0",Lang::getLanguageString("nocategorymapping"), "pre");
	    $smarty->assign("categories", $sb->draw());

	    $smarty->assign("contentheader",Lang::getLanguageString("createnewnote"));
	    $smarty->assign("suname","create");
	    $smarty->assign("suclass","submit");
	    $smarty->assign("mode","new");
	    $smarty->assign("pubcheckedno", " checked");
	    $smarty->assign("pubcheckedyes", "");
	    $smarty->assign("js", "");
	    $smarty->display('notes_edit.tpl');

	    return true;
	}

    function viewDetails() {
        global $conn,$smarty;

	$id = (int) $_GET["id"];

	$sql = "SELECT a.*,b.name AS catname, c.username AS lu_username FROM mgw_notes a LEFT JOIN mgw_notes_categories b ON a.catid = b.id LEFT JOIN mgw_users c ON a.lu_user=c.id WHERE a.id=$id AND (ispublic=1 OR owner=".$_SESSION["MGW"]->userid.")";
	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row = $res->FetchRow();

	$row["content"] = nl2br(htmlspecialchars($row["content"]));
	$row["lu_update"] = $conn->UnixTimestamp($row["lu_update"]);

	if($_SESSION['MGW']->settings["notes_enable_comments"]){
	    $fn = $conn->Concat('b.lastname',"', '",'b.firstname');
	    $sql = "SELECT a.*, $fn AS lu_username FROM mgw_notes_comments a LEFT JOIN mgw_users b ON a.lu_user=b.id WHERE a.note_id=$id";
	    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	    $comments = $res->GetArray();
	    reset($comments);
	    for($i=0;$i < count($comments);$i++){
		$comments[$i]['comment'] = nl2br(htmlspecialchars($comments[$i]['comment']));
		$comments[$i]['lu_update'] = $conn->UnixTimestamp($comments[$i]['lu_update']);
	    }
	    $smarty->assign("comments", $comments);
	}

	$smarty->assign("userid", $_SESSION['MGW']->userid);
	if(isset($_GET['cidtoedit']))
	    $smarty->assign("cidtoedit", (int)$_GET['cidtoedit']);
	$smarty->assign("id", $id);
	$smarty->assign("td", $row);
	$smarty->assign("enable_comments", $_SESSION['MGW']->settings["notes_enable_comments"]);
	$smarty->assign("contentheader", Lang::getLanguageString("notedetail"));
	$smarty->assign("js", "");
	$smarty->display('notes_details.tpl');

	return true;
    }

    function viewEditForm($id) {
        global $conn, $smarty, $appconf;

	$sql = "SELECT * FROM mgw_notes WHERE id=".(int)$id." AND (ispublic=1 OR owner=".$_SESSION["MGW"]->userid.")";
	if(($row = $conn->GetRow($sql)) === false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	if((queryRights2_bool('root_modules_notes_notes_modify') && $row["owner"] == $_SESSION["MGW"]->userid) ||
	   (queryRights2_bool('root_modules_notes_notes_modifyothers') && $row["owner"] != $_SESSION["MGW"]->userid)){

	    include_once(INCLUDEPATH . "mSelectBox.class.php");

	    if($row["ispublic"] == 1)
		$smarty->assign("pubcheckedyes", " checked");
	    else
		$smarty->assign("pubcheckedno", " checked");

	    $smarty->assign("id", $id);
        
	    $smarty->assign("td", $row);

	    $sb = new mSelectBox("catid");
	    $sb->setContentType("sql");
	    $sb->setSQLvalue("catid");
	    $sb->setSQLcontent("name");
	    $sb->addContent("SELECT id AS catid, name FROM mgw_notes_categories ORDER BY name");
	    $sb->addOption("0",Lang::getLanguageString("nocategorymapping"), "pre");
	    $smarty->assign("categories", $sb->draw($row["catid"]));

	    if($row["ispublic"]=="1") {
		$pcy = " checked";
		$pcn = "";
	    }
	    else {
		$pcy = "";
		$pcn = " checked";
	    }

	    if($_SESSION['MGW']->settings["notes_enable_comments"]){
		$fn = $conn->Concat('b.lastname',"', '",'b.firstname');
		$sql = "SELECT a.*, $fn AS lu_username FROM mgw_notes_comments a LEFT JOIN mgw_users b ON a.lu_user=b.id WHERE a.note_id=".(int)$id;
		if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		$comments = $res->GetArray();
		$smarty->assign("comments", $comments);
	    }
	    $smarty->assign("enable_comments", $_SESSION['MGW']->settings["notes_enable_comments"]);

	    $smarty->assign("pubcheckedyes",$pcy);
	    $smarty->assign("pubcheckedno",$pcn);
	    $smarty->assign("suname","edit");
	    $smarty->assign("suclass","submit");
	    $smarty->assign("mode","edit");
	    $smarty->assign("js", "");

	    $smarty->assign("contentheader", Lang::getParmLang(Lang::getLanguageString("editnote"),array($row["title"])));
	    $smarty->display('notes_edit.tpl');

	    return true;
	}
    }

    function viewList() {
        global $conn, $smarty;

	$sqladd="";
	$counter = 0;
	$icons = getIconStrings();
	$smarty->assign("prevsym", $icons["prev"]);
	$smarty->assign("nextsym", $icons["next"]);

	if(isset($_GET["sort"])){
	    if($_GET["sort"] == $_SESSION["notes"]["prevorderby"]){
		$_SESSION["notes"]["sort_order"] = ($_SESSION["notes"]["sort_order"] == "DESC") ? "ASC" : "DESC";
	    }
	    else{
		$_SESSION["notes"]["sort_order"] = $_SESSION["MGW"]->settings["notes_order_dir"];
	    }
	    $_SESSION["notes"]["prevorderby"] = $_GET["sort"];

	    switch($_GET["sort"]){
	    case "title":
		$_SESSION["notes"]["sort_by"] = "a.title";
		break;
	    case "category":
		$_SESSION["notes"]["sort_by"] = "b.name";
		break;
	    default:
		$_SESSION["notes"]["sort_by"] = $_SESSION["MGW"]->settings["notes_orderby"];
	    }
	}
	elseif($_SESSION["notes"]["sort_by"] == ""){
	    $_SESSION["notes"]["sort_by"] = $_SESSION["MGW"]->settings["notes_orderby"];
	    $_SESSION["notes"]["sort_order"] = $_SESSION["MGW"]->settings["notes_order_dir"];
	}

	if(isset($_POST["searchterm"])) $_SESSION["notes"]["searchterm"] = $_POST["searchterm"];

	if($_SESSION["notes"]["searchterm"] != ""){
	    $qsearchterm = $conn->QMagic($_SESSION["notes"]["searchterm"]);
	    $sqladd = " AND (a.title LIKE $qsearchterm OR a.content LIKE $qsearchterm)";
	}

	if(isset($_SESSION["notes"]["sort_by"]) && $_SESSION["notes"]["sort_by"]!="") {
	    $sqladd .= " ORDER BY ".$_SESSION["notes"]["sort_by"];
	    if(isset($_SESSION["notes"]["sort_order"]) && $_SESSION["notes"]["sort_order"]!="") {
		$sqladd .= " ".$_SESSION["notes"]["sort_order"];
	    }
	    $sqladd .= ", a.title";
	}

	$sql = "SELECT a.id,a.title,a.ispublic,a.owner,b.name AS catname FROM mgw_notes a LEFT JOIN mgw_notes_categories b ON a.catid = b.id WHERE (a.ispublic=1 OR (a.ispublic=0 AND a.owner=".$_SESSION["MGW"]->userid."))".$sqladd;

	// paging part 1
	if(!isset($_SESSION["notes"]["curr_page"])) $_SESSION["notes"]["curr_page"] = 1;
	if (isset($_GET['ppage'])) $_SESSION["notes"]["curr_page"]--;
	if (isset($_GET['npage'])) $_SESSION["notes"]["curr_page"]++;
	// pagin part 1

	if(!$res = $conn->PageExecute($sql, $_SESSION["MGW"]->settings["list_items_number"], $_SESSION["notes"]["curr_page"]))
	    exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	// paging part 2
	// if NOT on first page
	if(!$res->AtFirstPage()) {
	    $smarty->assign("_prev", true);
	}

	// if NOT on last page
	if(!$res->AtLastPage()) {
	    $smarty->assign("_next", true);
	}
	// paging part 2
	if($res->EOF)
	    $smarty->assign("td","");

	if(!$res->AtFirstPage()){
	    $smarty->assign("_prev", true);
	}
	else{
	    $smarty->assign("_prev", 0);
	}
	// if NOT on last page
	if(!$res->AtLastPage()){
	    $smarty->assign("_next", true);
	}
	else{
	    $smarty->assign("_next", 0);
	}

	while($row = $res->FetchRow()){
	    $myid = $row["id"];
	    $smarty->append("td",$row);

	    // create action urls.
	    $detlink = "<a href=\"index.php?part=notes&amp;view=details&amp;id=$myid&amp;".SID."\" class=\"edit\">".$icons["details"]."</a>";
	    $editlink = ((queryRights2_bool('root_modules_notes_notes_modify') && $row["owner"] == $_SESSION["MGW"]->userid) || (queryRights2_bool('root_modules_notes_notes_modifyothers') && $row["owner"] != $_SESSION["MGW"]->userid)) ?
		"<a href=\"index.php?part=notes&amp;view=editform&amp;id=$myid&amp;".SID."\" class=\"edit\">".$icons["edit"]."</a>" :
		"";
	    $dellink = ((queryRights2_bool('root_modules_notes_notes_delete') && $row["owner"] == $_SESSION["MGW"]->userid) || (queryRights2_bool('root_modules_notes_notes_deleteothers') && $row["owner"] != $_SESSION["MGW"]->userid)) ?
		"<a href=\"index.php?part=notes&amp;view=delete&amp;id=$myid&amp;".SID."\" class=\"delete\">".$icons["delete"]."</a>" :
		"";

	    $urls[] = $detlink . $icons["space"] . $editlink . $icons["space"] . $dellink;

	    if($row["ispublic"]==1) $images[] = "&nbsp;";
	    else $images[] = $icons["private"];
	}

	// paging part 3
	$smarty->assign("urls", (isset($urls) ? $urls : ""));
	$smarty->assign("images", (isset($images) ? $images : ""));
	$smarty->assign("writeperm", queryRights2_bool('root_modules_notes_notes_create'));
	$smarty->assign("searchterm",$_SESSION["notes"]["searchterm"]);
	$smarty->assign("js", "");
	$smarty->display("notes_list.tpl");

	return true;
    }
}
?>