<?php //$Id: restorelib.php,v 1.2 2007-07-27 10:59:27 nicus Exp $
    //This php script contains all the stuff to backup/restore
    //register mods

    //This function executes all the restore procedure about this mod
    function register_restore_mods($mod,$restore) {

        global $CFG;

        $status = true;

        //Get record from backup_ids
        $data = backup_getid($restore->backup_unique_code,$mod->modtype,$mod->id);

        if ($data) {
            //Now get completed xmlized object
            $info = $data->info;
            //traverse_xmlize($info);                                                                     //Debug
            //print_object ($GLOBALS['traverse_array']);                                                  //Debug
            //$GLOBALS['traverse_array']="";                                                              //Debug

            //Now, build the register record structure
            $register->course = $restore->course_id;
            $register->name = backup_todb($info['MOD']['#']['NAME']['0']['#']);
            $register->type = backup_todb($info['MOD']['#']['TYPE']['0']['#']);
            $register->offlinesessions = backup_todb($info['MOD']['#']['OFFLINESESSIONS']['0']['#']);
            $register->lastlogscalc = backup_todb($info['MOD']['#']['LASTLOGSCALC']['0']['#']);
            $register->toleranceevaluation = backup_todb($info['MOD']['#']['TOLERANCEEVALUATION']['0']['#']);
            $register->sessiontimeout = backup_todb($info['MOD']['#']['SESSIONTIMEOUT']['0']['#']);
            $register->dayscertificable = backup_todb($info['MOD']['#']['DAYSCERTIFICABLE']['0']['#']);
            $register->offlinecomments = backup_todb($info['MOD']['#']['OFFLINECOMMENTS']['0']['#']);
            $register->mandatoryofflinecomm = backup_todb($info['MOD']['#']['MANDATORYOFFLINECOMMENTS']['0']['#']);
            $register->offlinespecifycourse = backup_todb($info['MOD']['#']['OFFLINESPECIFYCOURSE']['0']['#']);
            $register->mandofflspeccourse = backup_todb($info['MOD']['#']['MANDATORYOFFLINESPECIFYCOURSE']['0']['#']);
            $register->showtolerance = backup_todb($info['MOD']['#']['SHOWTOLERANCE']['0']['#']);

            //The structure is equal to the db, so insert the register
            $newid = insert_record ("register",$register);
            
            if ($newid) {
                //We have the newid, update backup_ids
                backup_putid($restore->backup_unique_code,$mod->modtype,
                             $mod->id, $newid);
                
                 //now restore the answers for this register.
                 if (restore_userdata_selected($restore,'register',$mod->id)) {
                    //Restore register_answers
                    $status = register_sessions_restore_mods($newid,$info,$restore);     
                 }                               
            } else {
                $status = false;
            }

            //Do some output     
            if (!defined('RESTORE_SILENTLY')) {
                echo "<li>".get_string("modulename","register")." \"".format_string(stripslashes($register->name),true)."\"</li>";
            }
            backup_flush(300);

        } else {
            $status = false;
        }
        return $status;
    }

    //This function restores the register_offline sessions
    function register_sessions_restore_mods($registerid,$info,$restore) {

        global $CFG;

        $status = true;

		// In no offline session, returns
		$offlinesessions=$info['MOD']['#']['SESSIONS']['0']['#'];
		if ( !is_array($offlinesessions) || !array_key_exists( 'OFFLINESESSION' ,$offlinesessions) ) 
			return false;
       	 
       	$sessions = $offlinesessions['OFFLINESESSION'];

        //Iterate over answers
        for($i = 0; $i < sizeof($sessions); $i++) {
            $ses_info = $sessions[$i];
            //traverse_xmlize($sub_info);                                                                 //Debug
            //print_object ($GLOBALS['traverse_array']);                                                  //Debug
            //$GLOBALS['traverse_array']="";                                                              //Debug

            //We'll need this later!!
            $oldid = backup_todb($ses_info['#']['ID']['0']['#']);
            $olduserid = backup_todb($ses_info['#']['USERID']['0']['#']);

            //Now, build the register_offline session record structure
            $session->register = $registerid;
            $session->userid = backup_todb($ses_info['#']['USERID']['0']['#']);
            $session->login = backup_todb($ses_info['#']['LOGIN']['0']['#']);
            $session->logout = backup_todb($ses_info['#']['LOGOUT']['0']['#']);
            $session->tolerance = backup_todb($ses_info['#']['TOLERANCE']['0']['#']);
            $session->refcourse = backup_todb($ses_info['#']['REF_COURSE']['0']['#']);
            $session->comments = backup_todb($ses_info['#']['COMMENTS']['0']['#']);
            $session->online = 0;
            

           //We have to recode the refcourse field
            if (!empty($session->refcourse)) {
                $refcourseshortname = backup_todb($ses_info['#']['REF_COURSE_SHORTNAME']['0']['#']);
                $refcoursefullname = backup_todb($ses_info['#']['REF_COURSE_FULLNAME']['0']['#']);
                $succeed = true;
                if (!($course = get_record ('course', 'id', $session->refcourse))) $succeed = false;
                if ($succeed)
                    if (($course-> shortname != $refcourseshortname)&&($course-> fullname != $refcoursefullname)) $succeed = false;
                if (!$succeed) {
                    $succeed = true;
                    if (!($course = get_record ('course', 'shortname', $refcourseshortname))) $succeed = false;
                    if (!$succeed) {
                        $succeed = true;
                        if (!($course = get_record ('course', 'fullname', $refcoursefullname))) $succeed = false;
                        if (!$succeed) {
                            $session->refcourse=0;
                            $session->comments .= " ($refcoursefullname)";
                        } else $session->refcourse=$course->id;
                    } else $session->refcourse=$course->id;
                } else $session->refcourse=$course->id;
            }

            //We have to recode the userid field
            $user = backup_getid($restore->backup_unique_code,"user",$session->userid);
            if ($user) {
                $session->userid = $user->new_id;
            }

            //The structure is equal to the db, so insert the register_answers
            $newid = insert_record ("register_logs",$session);

            //Do some output
            if (($i+1) % 50 == 0) {
                if (!defined('RESTORE_SILENTLY')) {
                    echo ".";
                    if (($i+1) % 1000 == 0) {
                        echo "<br />";
                    }
                }
                backup_flush(300);
            }

            if ($newid) {
                //We have the newid, update backup_ids
                backup_putid($restore->backup_unique_code,"register_logs",$oldid,
                             $newid);
            } else {
                $status = false;
            }
        }

        return $status;
    }

    //Return a content decoded to support interactivities linking. Every module
    //should have its own. They are called automatically from
    //register_decode_content_links_caller() function in each module
    //in the restore process
    function register_decode_content_links ($content,$restore) {
            
        global $CFG;
            
        $result = $content;
                
        //Link to the list of registers
                
        $searchstring='/\$@(registerINDEX)\*([0-9]+)@\$/';
        //We look for it
        preg_match_all($searchstring,$content,$foundset);
        //If found, then we are going to look for its new id (in backup tables)
        if ($foundset[0]) {
            //print_object($foundset);                                     //Debug
            //Iterate over foundset[2]. They are the old_ids
            foreach($foundset[2] as $old_id) {
                //We get the needed variables here (course id)
                $rec = backup_getid($restore->backup_unique_code,"course",$old_id);
                //Personalize the searchstring
                $searchstring='/\$@(registerINDEX)\*('.$old_id.')@\$/';
                //If it is a link to this course, update the link to its new location
                if($rec->new_id) {
                    //Now replace it
                    $result= preg_replace($searchstring,$CFG->wwwroot.'/mod/register/index.php?id='.$rec->new_id,$result);
                } else { 
                    //It's a foreign link so leave it as original
                    $result= preg_replace($searchstring,$restore->original_wwwroot.'/mod/register/index.php?id='.$old_id,$result);
                }
            }
        }

        //Link to register view by moduleid

        $searchstring='/\$@(registerVIEWBYID)\*([0-9]+)@\$/';
        //We look for it
        preg_match_all($searchstring,$result,$foundset);
        //If found, then we are going to look for its new id (in backup tables)
        if ($foundset[0]) {
            //print_object($foundset);                                     //Debug
            //Iterate over foundset[2]. They are the old_ids
            foreach($foundset[2] as $old_id) {
                //We get the needed variables here (course_modules id)
                $rec = backup_getid($restore->backup_unique_code,"course_modules",$old_id);
                //Personalize the searchstring
                $searchstring='/\$@(registerVIEWBYID)\*('.$old_id.')@\$/';
                //If it is a link to this course, update the link to its new location
                if($rec->new_id) {
                    //Now replace it
                    $result= preg_replace($searchstring,$CFG->wwwroot.'/mod/register/view.php?id='.$rec->new_id,$result);
                } else {
                    //It's a foreign link so leave it as original
                    $result= preg_replace($searchstring,$restore->original_wwwroot.'/mod/register/view.php?id='.$old_id,$result);
                }
            }
        }

        return $result;
    }

    //This function makes all the necessary calls to xxxx_decode_content_links()
    //function in each module, passing them the desired contents to be decoded
    //from backup format to destination site/course in order to mantain inter-activities
    //working in the backup/restore process. It's called from restore_decode_content_links()
    //function in restore process
    function register_decode_content_links_caller($restore) {
        global $CFG;
        $status = true;
        
        if ($registers = get_records_sql ("SELECT c.id, c.name
                                   FROM {$CFG->prefix}register c
                                   WHERE c.course = $restore->course_id")) {
                                               //Iterate over each register->text
            $i = 0;   //Counter to send some output to the browser to avoid timeouts
            foreach ($registers as $register) {
                //Increment counter
                $i++;
                $content = $register->text;
                $result = restore_decode_content_links_worker($content,$restore);
                if ($result != $content) {
                    //Update record
                    $register->text = addslashes($result);
                    $status = update_record("register",$register);
                    if ($CFG->debug>7) {
                        if (!defined('RESTORE_SILENTLY')) {
                            echo '<br /><hr />'.s($content).'<br />changed to<br />'.s($result).'<hr /><br />';
                        }
                    }
                }
                //Do some output
                if (($i+1) % 5 == 0) {
                    if (!defined('RESTORE_SILENTLY')) {
                        echo ".";
                        if (($i+1) % 100 == 0) {
                            echo "<br />";
                        }
                    }
                    backup_flush(300);
                }
            }
        }

        return $status;
    }

    //This function converts texts in FORMAT_WIKI to FORMAT_MARKDOWN for
    //some texts in the module
    function register_restore_wiki2markdown ($restore) {
    
        global $CFG;

        $status = true;

        //Convert register->text
        if ($records = get_records_sql ("SELECT c.id, c.name, c.format
                                         FROM {$CFG->prefix}register c,
                                              {$CFG->prefix}backup_ids b
                                         WHERE c.course = $restore->course_id AND
                                               c.format = ".FORMAT_WIKI. " AND
                                               b.backup_code = $restore->backup_unique_code AND
                                               b.table_name = 'register' AND
                                               b.new_id = c.id")) {
            foreach ($records as $record) {
                //Rebuild wiki links
                $record->text = restore_decode_wiki_content($record->text, $restore);
                //Convert to Markdown
                $wtm = new WikiToMarkdown();
                $record->text = $wtm->convert($record->text, $restore->course_id);
                $record->format = FORMAT_MARKDOWN;
                $status = update_record('register', addslashes_object($record));
                //Do some output
                $i++;
                if (($i+1) % 1 == 0) {
                    if (!defined('RESTORE_SILENTLY')) {
                        echo ".";
                        if (($i+1) % 20 == 0) {
                            echo "<br />";
                        }
                    }
                    backup_flush(300);
                }
            }

        }
        return $status;
    }

    //This function returns a log record with all the necessay transformations
    //done. It's used by restore_log_module() to restore modules log.
    function register_restore_logs($restore,$log) {
                    
        $status = false;
                    
        //Depending of the action, we recode different things
        switch ($log->action) {
        case "add":
            if ($log->cmid) {
                //Get the new_id of the module (to recode the info field)
                $mod = backup_getid($restore->backup_unique_code,$log->module,$log->info);
                if ($mod) {
                    $log->url = "view.php?id=".$log->cmid;
                    $log->info = $mod->new_id;
                    $status = true;
                }
            }
            break;
        case "update":
            if ($log->cmid) {
                //Get the new_id of the module (to recode the info field)
                $mod = backup_getid($restore->backup_unique_code,$log->module,$log->info);
                if ($mod) {
                    $log->url = "view.php?id=".$log->cmid;
                    $log->info = $mod->new_id;
                    $status = true;
                }
            }
            break;
        case "view":
            if ($log->cmid) {
                //Get the new_id of the module (to recode the info field)
                $mod = backup_getid($restore->backup_unique_code,$log->module,$log->info);
                if ($mod) {
                    $log->url = "view.php?id=".$log->cmid;
                    $log->info = $mod->new_id;
                    $status = true;
                }
            }
            break;
        case "view all":
            $log->url = "index.php?id=".$log->course;
            $status = true;
            break;
        default:
            if (!defined('RESTORE_SILENTLY')) {
                echo "action (".$log->module."-".$log->action.") unknown. Not restored<br />";                 //Debug
            }
            break;
        }

        if ($status) {
            $status = $log;
        }
        return $status;
    }
?>
