<?PHP
/**
 * view.php - This page prints a particular instance of Register
 * Modified by Lorenzo Nicora <fad@nicus.it>
 * @package Register
 * @version $Id: view.php,v 1.2 2007-07-27 10:59:27 nicus Exp $;
 * @author Domenico Pontari <blueagle@tim.it>
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 * @link http://moodle.org/mod/newmodule_template.zip here you can download the template
 */

    require_once("../../config.php");
    require_once("lib.php");

    $userid = optional_param('userid');                 // if $userid = 0 you'll see all logs
    $id = optional_param('id');                     // Course Module ID, or
    $a = optional_param('a');                      // register ID

    $cancelcertification = optional_param('cancelcertification');    // true when you're deleting an offline ceritification
    
    $recalc = optional_param('recalc');                 // true when you want to recalculate all logs
    $log = optional_param('log');                    // when recalc is true, this var indicas what is the first log
    
    $printable = optional_param('printable');				// True for printable popup version	
    
    // these variables are used by register_insert_offline_certification to write a new offline certification
    $fromyear = optional_param('fromyear');
    $frommonth = optional_param('frommonth');
    $fromday = optional_param('fromday');
    $fromhour = optional_param('fromhour');
    $frommin = optional_param('frommin');
    $tohour = optional_param('tohour');
    $tomin = optional_param('tomin');
    $comments = optional_param('comments');
    $refcourse = optional_param('refcourse');

    // Retrieve CourseModule, Course and Register objects
    // Retrieve by CourseModule ID
    if ($id) {
        if (! $cm = get_record("course_modules", "id", $id)) {
            error("Course Module ID was incorrect");
        }
    
        if (! $course = get_record("course", "id", $cm->course)) {
            error("Course is misconfigured");
        }
    
        if (! $register = get_record("register", "id", $cm->instance)) {
            error("Course module is incorrect");
        }

	// Retrieve by Register ID
    } else {
        if (! $register = get_record("register", "id", $a)) {
            error("Course module is incorrect");
        }
        if (! $course = get_record("course", "id", $register->course)) {
            error("Course is misconfigured");
        }
        if (! $cm = get_coursemodule_from_instance("register", $register->id, $course->id)) {
            error("Course Module ID was incorrect");
        }
    }

    // Login required
    require_login($course->id);

    // Get Context
	$context = get_context_instance(CONTEXT_MODULE, $cm->id);
    
	

/// Print the page header 

	// Not printable (standard) page version
	if (!$printable) {
	    if ($course->category) {
	        $navigation = "<a href=\"../../course/view.php?id=$course->id\">$course->shortname</a> ->";
	    } else 
	    	$navigation ="";
	
	    $strregisters = get_string("modulenameplural", "register");
	    $strregister  = get_string("modulename", "register");
	
	    print_header("$course->shortname: $register->name", "$course->fullname",
	                 "$navigation <a href=\"index.php?id=$course->id\">$strregisters</a> -> $register->name", 
	                  "", "", true, update_module_button($cm->id, $course->id, $strregister), 
	                  navmenu($course, $cm));
	}
	// Printable version
	else {
		register_print_printable_header($register, $userid);
	}
	
/// Print the main part of the page


    if (empty($userid)) {
//        // if you are a teacher, you'll be able to see logs of your students
//        // otherwise you'll see only your logs
//        if (isteacher($course->id)) 
//        	$userid = 0;
//        else 
//        	$userid = $USER -> id;

		// Check if the user may view registers of other people (will ignore 'doanything' capability!)
		if ( has_capability('mod/register:viewotherregisters', $context, $USER->id, FALSE)) {
			$userid = 0; // View all user's Registers
		} 
		// otherwise, check if user can view his own Register or print permission error
		else {
			require_capability('mod/register:viewownregister', $context,$USER->id, FALSE );
			$userid = $USER->id; // View own Register only
		} 
    }
    // If $userid has been defined... 
	else {
		// If it corresponds to current user (may happen?), check capability to view own Register
		if ( $userid == $USER->id ) {
			require_capability('mod/register:viewownregister', $context,$USER->id, FALSE );
		// otherwise check capability to view other's Registers
		} else {
			require_capability('mod/register:viewotherregisters', $context, $USER->id, FALSE);	 
		}
	}

//    if ((! isteacher($course->id)) && ($userid != $USER -> id)) {
//        error("Only teachers can view other logs");
//        die;
//    }

	if (!$printable) {
	    if ($recalc == 1) {
	    	
	    	// check if user have capability for recalculating
			require_capability('mod/register:recalcsessions', $context, $USER->id, FALSE);
	    	
	//        // when you want to recalculate all logs you'll see a different page
	//        if (! isteacher($course->id)) {
	//            error("Only teachers can recalc all logs");
	//            die;
	//        }
	        if (!isset($log)) { 
	        	$log = 0;
	        }
	        register_recalc_all_logs ($register, $userid, $log);
	        redirect("view.php?a=$register->id&userid=$userid",get_string ("continue"),1);
	    }
	}

    $recalc = 0;

    // update sessions for this user
    if ($userid != 0) { 
    	register_calc_log ($register, $userid);
    }

    // Process inserting and deleting offline session self-cert only if !printable
	if (!$printable) {    
    
	    // you have to insert a new offline session?
		if ($register -> offlinesessions && $fromhour && $tohour && $frommin && $tomin && $fromday && $fromyear && $frommonth  ) {
	
			// Check if user may insert own self-cert (and user is the _real_ user)
			if ( has_capability('mod/register:addownselfcert',$context,NULL, FALSE) ) {
				// Check he is the real user
				if (!isset($USER->realuser)) {				
					// Insert Self-certification
					$error_certification = register_insert_offline_certification ($register, $USER->id, 
								$fromyear, $frommonth, $fromday, $fromhour, $frommin, $tohour, $tomin, $comments, $refcourse);
		
		        	// Log offline session insert
				    add_to_log($course->id, "register", "add offline", "view.php?a=$register->id&userid=$USER->id", "$register->id", $cm->id, $USER->id );
				} else {
					print_error("onlyrealusercanaddofflinesessions","register");					
				}
			} else {
		        $capabilityname = get_capability_string('mod/register:addownselfcert');
		        print_error('nopermissions', 'register', '', $capabilityname);				
			}
					
//	        if (!isset ($USER -> realuser)) {
//	        	$error_certification = register_insert_offline_certification ($register,$USER -> id,$fromyear,$frommonth,$fromday,$fromhour,$frommin,$tohour,$tomin,$comments,$refcourse);
//	
//	        	// Log offline session insert
//			    add_to_log($course->id, "register", "add offline", "view.php?a=$register->id&userid=$USER->id", "$register->id", $cm->id, $USER->id );
//	        	
//	        } else { 
//	        	$error_certification = get_string ("onlyrealusercanaddofflinesessions","register");
//	        }
	    } else {
	    	$error_certification = '';
	    }
        
    
    	// have to deleted an offline session?
	    if (($register -> offlinesessions) && ($cancelcertification != 0)) {
	    	
	    	// Get Session to be deleted
	        $session = get_record ("register_logs", "id", "$cancelcertification");	        
	        if (!isset ($session)) {
	            error("Certification ID is incorrect");
	            die;
	        }
	        
	        // Trying to delete own self-cert
	        if ( $session->userid == $USER->id ) {
	        	// User must have capability 
				require_capability('mod/register:deleteownselfcert',$context, $USER->id, FALSE);
				// And must be the _real_ user
				if ( isset($USER->realuser) ) {
					print_error('onlyrealusercandeleteofflinesessions', 'register');
					die;
				}
	        }
	        // otherwise (trying to delete offline self-cert of another user), must have the capability
			else{
				require_capability('mod/register:deleteotherselfcert',$context, $USER->id, FALSE);
			}
	        
//	        if ($USER -> id != $session -> userid) {
//	            error("You cannot delete certifications of other people");
//	            die;
//	        } else {
            if (!register_updatablesession ($session, $register->dayscertificable )) {
                error ("You cannot modify this session");
                die;
            }
            delete_records("register_logs", "id", "$cancelcertification");
            
            // Log offline session deletion
            add_to_log($course->id, "register", "delete offline", "view.php?a=$register->id&userid=$USER->id", "$register->id", $cm->id, $USER->id );
            
            redirect("view.php?a=$register->id&userid=$userid",get_string("certificationdeleted", "register"), 1);
//	        }
	    }
	}
	
	
	// Log 'view' action
    add_to_log($course->id, "register", "view", "view.php?id=$cm->id", "$register->id", $cm->id, $USER->id  );
	
/// Now we start to print data about user's session

	register_display_main_contents($register, $userid, $printable, $error_certification);    
    
    // Unfreeze register (when it has been frozen???)
    $register -> freezed = 0;
    update_record("register", $register);

/// Finish the page
	// Not printable (standard) version
	if (!$printable) 
	    print_footer($course);
	// Printable version
	else
		register_print_printable_footer();
?>
