<?php

// -----------------------------------------------------------------------
// This file is part of AROUNDMe
// 
// Copyright (C) 2003 - 2006 Barnraiser
// http://www.barnraiser.org/
// info@barnraiser.org
// 
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option) any
// later version.
// 
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with program; see the file COPYING. If not, write to the Free
// Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
// 02110-1301, USA.
// -----------------------------------------------------------------------

include "inc/header.inc.php";


//ACS check
if (!empty($_REQUEST['group_id'])) { // page under group section
	$group_id = $_REQUEST['group_id'];
	include_once ('inc/header_group.inc.php');
	
    //ACS check
	if (!$group_acs->checkPermission($c_acs['arr_acs']['resource']['group']['quiz'], $c_acs['arr_acs']['privilege']['add_item'])) { //resourece_id, Priv_id
		header("Location: grp_view.php?group_id=" . $_REQUEST['group_id'] . "&" . strip_tags(SID));
		exit;
	}
}
else {
	if (!isset($me['user_id']) || !$user_acs->checkPermission($c_acs['arr_acs']['resource']['node']['quiz'], $c_acs['arr_acs']['privilege']['add_item'])) { //resourece_id, Priv_id
		header("Location: " . $_SESSION['user_homepage'] . "?" . strip_tags(SID));
		exit;
	}
	unset ($group_id);
}


// SETUP LANGUAGE --------------------------------------------------------
require_once($languagePath . 'common.lang.php');
require_once($languagePath . 'quz_view.lang.php');


//setup quiz ---------------------------------------------------------------
require_once('class/Quiz.class.php');
$quiz = new Quiz($db, null);


if (isset($_REQUEST['quiz_id'])) {
	$quiz->quiz_id = $_REQUEST['quiz_id'];
}

if (isset($group_id)) {
    $quiz->group_id = $group_id;
}


//SETUP RSP ---------------------------------------------------------
require_once('class/Rsp.class.php');
$rsp = new Rsp($db, $c_node['rsp']['item_type']['quiz']);
$rsp->user_id = $me['user_id'];

if (isset($group_id)) {
    $rsp->group_id = $group_id;
}


// SETUP WIKI ---------------------------------------------------------------
if (!empty($frmdata['group_id'])) { // page under group section
	$wiki_path = "lib_view.php?group_id=" . $frmdata['group_id'] . "&page=";
	$wiki_new_path = "lib_edit.php?group_id=" . $frmdata['group_id'] . "&page=";
}
else {
	$wiki_path = "lib_view.php?user_id=" . $me['user_id'] . "&page=";
	$wiki_new_path = "lib_edit.php?page=";
}

$wiki_image_base = "get_file.php?file=";

require_once('class/Wiki/Wiki.php');
$wiki = new Text_Wiki();
$wiki->setRenderConf('xhtml', 'wikilink', 'view_url', $wiki_path);
$wiki->setRenderConf('xhtml', 'wikilink', 'new_url', $wiki_new_path);
$wiki->setRenderConf('xhtml', 'image', 'base', $wiki_image_base);
	
	
// SETUP BOOKMARKS ---------------------------------------------------------
require_once('class/Bookmark.class.php');
$bookmark = new Bookmark($db, $c_node['rsp']['item_type']['quiz'], $me['user_id']);
$bookmark->bookmark_type = $c_node['bookmark']['type']['watch'];


//RECEIVE POST AND PROCESS --------------------------------------------------
if (!empty($frmdata)) {
	$frmdata['quiz_title'] = htmlspecialchars($frmdata['quiz_title']);
	$frmdata['quiz_synopsis'] = htmlspecialchars($frmdata['quiz_synopsis']);
		
	if (isset($frmdata['preview'])) {
		$frmdata['quiz_title'] = stripslashes($frmdata['quiz_title']);
		$frmdata['quiz_synopsis'] = stripslashes($frmdata['quiz_synopsis']);
		
		$frmdata['quiz_body_intro_preview'] = $wiki->transform($frmdata['quiz_body_intro'], 'Xhtml');
		
		if (!isset($frmdata['rsp_public_featured'])) {
			$frmdata['rsp_public_featured'] = 0;
		}
		
		if (!empty($frmdata['rsp_node'])) {
			$frmdata['rsp'][] = array('level_id' => $c_node['rsp']['rsp_level']['node'], 'degree_id' => $frmdata['rsp_node'], 'rsp_featured' => $frmdata['rsp_public_featured']);
		}
		
		if (!empty($frmdata['rsp_public'])) {
			$frmdata['rsp'][] = array('level_id' => $c_node['rsp']['rsp_level']['public'], 'rsp_featured' => $frmdata['rsp_public_featured']);
		}
		
		if (!empty($frmdata['rsp_group'])) {
			$frmdata['rsp'][] = array('level_id' => $c_node['rsp']['rsp_level']['group']['home']);
		}
		
		$output_quiz = $frmdata;
		
		if (isset($output_quiz['quiz_id']) && $output_quiz['quiz_id'] < 1) {
			unset($output_quiz['quiz_id']);
		}
		
		$display = "allow_edit";
	}
	elseif (isset($frmdata['save']) || isset($frmdata['save_go'])) {
		if (empty($frmdata['quiz_title'])) {
			$GLOBALS['am_error_log'][] = array(37, null, null);
		}

		if (empty($frmdata['quiz_synopsis'])) {
		    $GLOBALS['am_error_log'][] = array(30, null, null);
		}

		if (empty($frmdata['language_id'])) {
		    $frmdata['language_id'] = $me['language_id'];
		}
		
		if (empty($GLOBALS['am_error_log'])) {
			// either the dates are indefinate or we format the dates
			if (isset($frmdata['date_indefinitely'])) {
				if (!empty($frmdata['date_indefinitely'])) { // indefinate
					$frmdata['quiz_start_datetime'] = "null";
				}
				else {
					if (!empty($frmdata['quiz_start_time'])) {
						$frmdata['quiz_start_datetime'] = $date->formatFormDateTime($frmdata['quiz_start_date'], $frmdata['quiz_start_time']);
					}
					else {
						$frmdata['quiz_start_datetime'] = $date->formatFormDateTime($frmdata['quiz_start_date']);
					}
				}
				
				if (!empty($frmdata['date_indefinitely'])) { // indefinate
					$frmdata['quiz_end_datetime'] = "null";
				}
				else {
					if (!empty($frmdata['quiz_end_time'])) {
						$frmdata['quiz_end_datetime'] = $date->formatFormDateTime($frmdata['quiz_end_date'], $frmdata['quiz_end_time']);
					}
					else {
						$frmdata['quiz_end_datetime'] = $date->formatFormDateTime($frmdata['quiz_end_date']);
					}
				}
			}
			
			// If we have an id we update the Quiz
			if (isset($frmdata['quiz_id']) && $frmdata['quiz_id'] > 0) {
				$quiz->updateQuiz($frmdata);
			}
			else { //we insert record
				$quiz->user_id = $me['user_id'];
				$quiz->insertQuiz($frmdata);
			}
			
			if (empty($GLOBALS['am_error_log'])) {
				//insert into setup rsp
				if (!empty($frmdata['group_id'])) {
				    $temp['language_id'] = $output_group['language_id'];
				}
				else {
					$temp['language_id'] = $me['language_id'];
				}
				
				$temp['item_id'] = $quiz->quiz_id;
				//delete all
				$rsp->deleteRspItem($quiz->quiz_id);
				
				//insert node rsp entry
				if (!empty($frmdata['rsp_node'])) {
				    $temp['level_id'] = $c_node['rsp']['rsp_level']['node'];
					if (!empty($frmdata['rsp_node_featured'])) {
					    $temp['rsp_featured'] = 1;
					}
					else {
						$temp['rsp_featured'] = "null";
					}
					
					if ($frmdata['rsp_node'] == "all" || !empty($frmdata['group_id'])) {
					    $temp['degree_id'] = "null";
					}
					else {
						$temp['degree_id'] = $frmdata['rsp_node'];
					}
					
					if($c_node['rsp']['node']['auto_publish'] == 1) {
						$rsp->status_id = $c_node['rsp']['status']['live'];
					}
					else {
						$rsp->status_id = $c_node['rsp']['status']['pending'];
					}
					
					$rsp->insertRspItem($temp);
				}
				
				if (isset($frmdata['rsp_group'])) {
				    $temp['level_id'] = $c_node['rsp']['rsp_level']['group']['home'];
					
					if($output_group['group_rsp_auto_publish'] == 1) {
						$rsp->status_id = $c_node['rsp']['status']['live'];
					}
					else {
						$rsp->status_id = $c_node['rsp']['status']['pending'];
					}

					$rsp->insertRspItem($temp);
				}
				
				if (!empty($frmdata['rsp_public'])) {
				    $temp['level_id'] = $c_node['rsp']['rsp_level']['public'];
					
					if (!empty($frmdata['rsp_public_featured'])) {
					    $temp['rsp_featured'] = 1;
					}
					else {
						$temp['rsp_featured'] = "null";
					}
					
					if($c_node['rsp']['public']['auto_publish'] == 1) {
						$rsp->status_id = $c_node['rsp']['status']['live'];
					}
					else {
						$rsp->status_id = $c_node['rsp']['status']['pending'];
					}
					
					$rsp->insertRspItem($temp);
				}
				
				// add bookmark tracking
				$bookmark->item_id = $quiz->quiz_id;
				$bookmark->deleteBookmark();
				if (!empty($frmdata['ins_mark'])) {
					$bookmark->insertBookmark(1);
				}
				
				//setup statistics
				require_once('class/Statistic.class.php');
				$statistic = new Statistic($db, $c_node['rsp']['item_type']['quiz'], $date);
				
				if (!empty($frmdata['group_id'])) { // page under group section
					unset($quiz->user_id);
					$statistic->group_id = $frmdata['group_id'];
					$statistic->statistic_type_id = $c_node['statistic']['group']['total_quizzes'];
				}
				else {
					$quiz->user_id = $me['user_id'];
					$statistic->user_id = $me['user_id'];
					$statistic->statistic_type_id = $c_node['statistic']['user']['total_quizzes'];
				}
				
				$statistic->setStatistic($quiz->selQuizCount());
				
				//get member quiz stats
				if (!empty($frmdata['group_id'])) { // page under group section
					$statistic->user_id = $me['user_id'];
					$statistic->statistic_type_id = $c_node['statistic']['group_member']['total_quizzes'];
					$statistic->setStatistic($quiz->selPollCount($me['user_id']));
				}
				
				if (isset($frmdata['save_go'])) {
					header("Location: quz_view.php?quiz_id=" . $quiz->quiz_id . "&". strip_tags(SID));
					exit;
				}
				else {
					if (!empty($frmdata['group_id'])) { // page under group section
						header("Location: quz_edit.php?group_id=" . $frmdata['group_id'] . "&quiz_id=" . $quiz->quiz_id . "&". strip_tags(SID));
						exit;
					}
					else {
						if (empty($frmdata['quiz_id'])) { // it is a new quiz
							header("Location: quz_edit.php?quiz_id=" . $quiz->quiz_id . "&add_question=1&". strip_tags(SID));
						}
						else {
							header("Location: quz_edit.php?quiz_id=" . $quiz->quiz_id . "&". strip_tags(SID));
						}
						exit;
					}
				}
			}
		}
		else { // something errored
			$output_quiz = $frmdata;
		}
		
		$display = "allow_edit";
		
	}
	elseif (isset($frmdata['update_question'])) {
		// we receive a question and associated options
		$option_count = 0;
		
		if (isset($frmdata['options'])) {
			foreach ($frmdata['options'] as $key => $i):
				if (!empty($i['option_body'])) {
					$option_count++;
				}
			endforeach;
		}
		
		if ($option_count < 2) { // we must have two or more anwsers
		    $GLOBALS['am_error_log'][] = array(54, null, null);
		}
		
		if (empty($GLOBALS['am_error_log'])) {
			if (!empty($frmdata['question_id'])) { // update
				$quiz->updateQuestion($frmdata);
			}
			else { // insert
				$quiz->user_id = $me['user_id'];
				$quiz->insertQuestion($frmdata);
				
			}
			
			if (isset($frmdata['options'])) {
				foreach ($frmdata['options'] as $key => $i):
					// remove any empty options
					if (empty($i['option_body'])) {
						if (!empty($i['option_id'])) {
							$quiz->deleteOption($i['option_id']);
						}
						unset($frmdata['options'][$key]);
					}
					elseif (!empty($i['option_id'])) { // update
						$quiz->updateOption($i);
						
						if ($frmdata['question_correct_option_id'] == $i['option_id']) {
							$question_correct_option_id = $i['option_id'];
						}
					}
					else { // insert
						$quiz->user_id = $me['user_id'];
						$quiz->insertOption($i);
						if ($frmdata['question_correct_option_id'] == $key) {
							$question_correct_option_id = $quiz->option_id;
						}
					}
				endforeach;
				
				// set the correct option id
				if (isset($question_correct_option_id)) {
					$question = $quiz->selQuestion($quiz->question_id);
					$question['question_correct_option_id'] = $question_correct_option_id;
					$quiz->updateQuestion($question);
				}
			}
			
			header("Location: quz_edit.php?quiz_id=" . $frmdata['quiz_id'] . "&". strip_tags(SID) . "#questions");
			exit;
		}
		else { // something errored
			$output_quiz = $frmdata;
			$output_quiz['question']['question_body'] = $output_quiz['question_body'];
			$output_quiz['question']['question_order'] = $output_quiz['question_order'];
			$output_quiz['question']['options'] = $output_quiz['options'];
			$_REQUEST['add_question'] = 1;
			
		}
		
		$display = "allow_edit";
	}
	elseif (isset($frmdata['delete_question'])) {
		$quiz->deleteOption(null, $frmdata['question_id']);
		$quiz->deleteQuestion($frmdata['question_id']);
		
		header("Location: quz_edit.php?quiz_id=" . $frmdata['quiz_id'] . "&". strip_tags(SID) . "#questions");
		exit;
	}
}
elseif (isset($_REQUEST['quiz_id']) && $_REQUEST['quiz_id'] > 0) {
	$output_quiz = $quiz->selQuiz(1, null);
	
	if (!empty($output_quiz['group_id'])) {
		// we check that I am in the group and that I have permissions to view
		$group_id = $output_quiz['group_id'];
		include_once ('inc/header_group.inc.php');
		
		if ($group_acs->checkPermission($c_acs['arr_acs']['resource']['group']['quiz'], $c_acs['arr_acs']['privilege']['add_item'])) { //resourece_id, Priv_id
			$display = "edit_quiz";
		}
		else {
			unset($output_quiz, $display);
		}
	}
	else {
		$display = "edit_quiz";
	}
	
	if (isset($output_quiz) && isset($_REQUEST['question_id'])) {
		$output_quiz['question'] = $quiz->selQuestion($_REQUEST['question_id']);
	}
	
	if (isset($output_quiz['quiz_id'])) {
		$output_quiz['questions'] = $quiz->selQuestions();
	}
}
else {
	$display = "add_quiz";
}


// SETUP LIBRARY ---------------------------------------------------------
require_once('class/Library.class.php');
$library = new Library($db, null);

if (!empty($output_quiz['group_id'])) {
	$file->group_id = $output_quiz['group_id'];
	$library->group_id = $output_quiz['group_id'];
	unset($file->user_id);
}
else {
	$file->user_id = $me['user_id'];
	unset($file->group_id);
}

$output_wikipages = $library->getPages();
$output_filenames = $file->getFiles();

//setup file ----------------------------------------------------------------
$file->noimage = $c_node['file']['image']['thumb'][1]['noimage'];
$file->thumb = $c_node['file']['image']['thumb'][1]['name'];
$file->type_ids[] = $c_node['file']['mime'][1]['suffix']; //jpg
$file->type_ids[] = $c_node['file']['mime'][2]['suffix']; //png
$file->type_ids[] = $c_node['file']['mime'][3]['suffix']; //gif

$output_images = $file->getFiles();


//format dates
if (isset($output_quiz['quiz_start_datetime'])) {
	$output_quiz['quiz_start_date'] = substr($output_quiz['quiz_start_datetime'], 0,10);
	$output_quiz['quiz_end_date'] = substr($output_quiz['quiz_end_datetime'], 0,10);
	$output_quiz['quiz_start_time'] = substr($output_quiz['quiz_start_datetime'], 11,15);
	$output_quiz['quiz_end_time'] = substr($output_quiz['quiz_end_datetime'], 11,15);
}
else {
	$output_quiz['quiz_start_date'] = date('Y-m-d');
	$output_quiz['quiz_end_date'] = date('Y-m-d');
	$output_quiz['quiz_start_time'] = date('H:i');
	$output_quiz['quiz_end_time'] = date('H:i');
}


if (isset($output_quiz['quiz_id'])) {
	//get bookmark
	$bookmark->item_id = $output_quiz['quiz_id'];
	$output_quiz['bookmark'] = $bookmark->getBookmark(1);
}

//RSP items
if (!empty($output_quiz['quiz_id'])) {
	$output_quiz['rsp'] = $rsp->selRspItem($output_quiz['quiz_id']);
}

$display = "quiz";
//move to template
if (!empty($output_wikipages)) {
	$body->set('wikipages', $output_wikipages);
}

if (!empty($output_filenames)) {
	$body->set('filenames', $output_filenames);
}

if (!empty($display)) {
	$body->set('display', $display);
}

if (!empty($output_quizzes)) {
   $body->set('quizzes', $output_quizzes);
}

if (!empty($output_quiz)) {
   $body->set('quiz', $output_quiz);
}

if (!empty($output_group)) {
	$body->set('group', $output_group);
	$tpl->set('group', $output_group);
}

if (!empty($output_option)) {
   $body->set('option', $output_option);
}

if (!empty($output_images)) {
	$body->set('images', $output_images);
	$body->set('image_thumbs', $c_node['file']['image']['thumb']);
}

if (isset($_REQUEST['add_question'])) {
   $body->set('add_question', 1);
}

$body->set('languagePath', $languagePath);

$body->set('rspconfig', $c_node['rsp']);

include "inc/footer.inc.php";

?>
