function wiki_restore_mods($mod, $restore)
{
    global $CFG, $COURSE;
    $status = true;
    $ewiki = false;
    //Get record from backup_ids
    $data = backup_getid($restore->backup_unique_code, $mod->modtype, $mod->id);
    $info = $data->info;
    //Now check if the mod is a ewiki or a newwiki mod, an create the
    //array $data with the info with the same format in both cases.
    if (isset($info["MOD"]["#"]["ENTRIES"])) {
        $data = wiki_read_xml_ewiki($info["MOD"]["#"], $restore);
        $ewiki = true;
        //Use this later.
    } else {
        $data = wiki_read_xml_wiki($info["MOD"]["#"], $restore->course_id);
    }
    if (!isset($data)) {
        $status = false;
    } else {
        $schema = wiki_create_schema();
        $wiki = wiki_validate($data['wiki'], $schema['wiki']);
        $wiki->course = $restore->course_id;
        $id = get_record_sql('SELECT id
					FROM ' . $CFG->prefix . 'wiki WHERE wikicourse=' . addslashes($wiki->course));
        if (empty($id->id) && $wiki->wikicourse != '0') {
            //The course is a wiki format course, then set the correct wikicourse id
            $wiki->wikicourse = $wiki->course;
        } else {
            $wiki->wikicourse = 0;
        }
        //Now insert the wiki record
        $newid = insert_record("wiki", $wiki);
        //Do some output
        echo "<li>" . get_string("modulename", 'wiki') . " \"" . format_string(stripslashes($wiki->name), true) . "\"</li>";
        backup_flush(300);
        if ($newid) {
            //We have the newid, update backup_ids
            backup_putid($restore->backup_unique_code, $mod->modtype, $mod->id, $newid);
            //Now check if want to restore user data and do it.
            if ($restore->mods['wiki']->userinfo) {
                $oldid = backup_todb($info['MOD']['#']['ID']['0']['#']);
                $order = backup_todb($info['MOD']['#']['ORDER']['0']['#']);
                //Now, build the wiki record structure
                $schemapages = $schema['wiki_pages'];
                $datapages = $data['wiki_pages'];
                $numpages = count($datapages);
                for ($i = 0; $i < $numpages; $i++) {
                    //$page=wiki_validate_page($datapages[$i],$schemapages);
                    $page = wiki_validate($datapages[$i], $schemapages);
                    $page->dfwiki = $newid;
                    //We have to recode the userid field
                    $user = backup_getid($restore->backup_unique_code, "user", $page->userid);
                    if ($user) {
                        $page->userid = $user->new_id;
                    }
                    //We have to recode the ownerid field
                    if ($ewiki) {
                        if ($wiki->studentmode != '0') {
                            $page->ownerid = $page->userid;
                        }
                    }
                    $owner = backup_getid($restore->backup_unique_code, "owner", $page->ownerid);
                    if ($owner) {
                        $page->ownerid = $owner->new_id;
                    }
                    //We have to recode the groupid field
                    $group = backup_getid($restore->backup_unique_code, "group", $page->groupid);
                    if ($group) {
                        $page->groupid = $group->new_id;
                    }
                    //The structure is equal to the db
                    $oldpageid = $page->id;
                    $newpageid = insert_record("wiki_pages", $page);
                    $page->id = $oldpageid;
                    //Do some output
                    if (($i + 1) % 50 == 0) {
                        echo ".";
                        if (($i + 1) % 1000 == 0) {
                            echo "<br />";
                        }
                        backup_flush(300);
                    }
                    if ($newpageid) {
                        //We have the newid, update backup_ids
                        //$page->id is now the page old id
                        backup_putid($restore->backup_unique_code, "wiki_pages", $page->id, $newpageid);
                    } else {
                        $status = false;
                    }
                }
                //Restore synonymous for the newwiki mod
                if (!$ewiki && isset($data['wiki_synonymous'])) {
                    $schemasyn = $schema['wiki_synonymous'];
                    $datasyns = $data['wiki_synonymous'];
                    $numsyns = count($datasyns);
                    for ($i = 0; $i < $numsyns; $i++) {
                        $syn = wiki_validate($datasyns[$i], $schemasyn);
                        $syn->dfwiki = $newid;
                        //We have to recode the userid field
                        $owner = backup_getid($restore->backup_unique_code, "owner", $syn->ownerid);
                        if ($owner) {
                            $syn->ownerid = $owner->new_id;
                        }
                        $group = backup_getid($restore->backup_unique_code, "group", $syn->groupid);
                        if ($group) {
                            $syn->groupid = $group->new_id;
                        }
                        //The structure is equal to the db
                        $newsynid = insert_record("wiki_synonymous", $syn);
                        //Do some output
                        if (($i + 1) % 50 == 0) {
                            echo ".";
                            if (($i + 1) % 1000 == 0) {
                                echo "<br />";
                            }
                            backup_flush(300);
                        }
                        if ($newsynid) {
                            //We have the newid, update backup_ids
                            backup_putid($restore->backup_unique_code, "wiki_synonymous", $syn->id, $newsynid);
                        } else {
                            $status = false;
                        }
                    }
                }
                //Now copy moddata associated files
                $e_wiki = $data['wiki_pages'][0];
                wiki_restore_files($oldid, $restore, $order, $e_wiki);
            }
        } else {
            $status = false;
        }
    }
    return $status;
}
function wiki_validate_and_insert_content($wiki_content, &$WS, $id_group_template = 0)
{
    global $CFG, $COURSE, $USER;
    $schemas = wiki_create_schema();
    $data[] = null;
    foreach ($wiki_content as $tablename => $rowstable) {
        $actualTag = strtolower($tablename);
        if ($actualTag === 'synonymous' || $actualTag === 'votes') {
            $actualTag = 'wiki_' . $actualTag;
        }
        if ($actualTag === 'blocks') {
            $actualTag = 'block_instance';
        }
        foreach ($rowstable as $rownumber => $confrows) {
            switch ($actualTag) {
                case 'wiki':
                    break;
                case 'contents':
                    foreach ($schemas['wiki_pages']->fields as $field) {
                        if (array_key_exists($field->name, $confrows)) {
                            $data["wiki_pages"][$rownumber][$field->name] = $confrows[$field->name];
                        } else {
                            if (isset($field->Default)) {
                                $data["wiki_pages"][$rownumber][$field->name] = $field->default;
                            } else {
                                if ($field->notnull == "0") {
                                    $data["wiki_pages"][$rownumber][$field->name] = null;
                                } else {
                                    error("The field:'{$field->Field}' not exist in the xml backup file, and is necesary in the wiki_pages table");
                                }
                            }
                        }
                    }
                    break;
                case 'pages':
                    foreach ($schemas['wiki_' . $actualTag] as $field) {
                        if (array_key_exists($field->name, $confrows)) {
                            $data["wiki_history"][$rownumber][$field->name] = $confrows[$field->name];
                        } else {
                            if (!isset($field->default)) {
                                $data["wiki_history"][$rownumber][$field->name] = $field->default;
                            } else {
                                if ($field->notnull == "0") {
                                    $data["wiki_history"][$rownumber][$field->name] = null;
                                } else {
                                    error("The field:'{$field->Field}' not exist in the xml backup file, and is necesary in the wiki_pages table");
                                }
                            }
                        }
                    }
                    break;
                    //Tratamos las p�ginas en caso de estar importando desde un backup, ya que no se hace distinci�n entre la p�gina principal y las hist�ricas.
                    //Insertamos TODAS las p�ginas
                //Tratamos las p�ginas en caso de estar importando desde un backup, ya que no se hace distinci�n entre la p�gina principal y las hist�ricas.
                //Insertamos TODAS las p�ginas
                case 'importfrombackup':
                    foreach ($schemas["wiki_pages"] as $field) {
                        if (array_key_exists($field->name, $confrows)) {
                            $data["wiki_import"][$rownumber][$field->name] = $confrows[$field->name];
                        } else {
                            if (isset($field->default)) {
                                $data["wiki_import"][$rownumber][$field->name] = $field->default;
                            } else {
                                if ($field->notnull == "0") {
                                    $data["wiki_import"][$rownumber][$field->name] = null;
                                } else {
                                    error("The field:'{$field->Field}' not exist in the import from backup xml file, and is necesary in the wiki_pages table");
                                }
                            }
                        }
                    }
                    break;
                case 'wiki_synonymous' or 'wiki_votes' or 'block_instance':
                    foreach ($schemas[$actualTag] as $field) {
                        if (array_key_exists($field->name, $confrows)) {
                            $data[$actualTag][$rownumber][$field->name] = $confrows[$field->name];
                        } else {
                            if (isset($field->default)) {
                                $data[$actualTag][$rownumber][$field->name] = $field->default;
                            } else {
                                if ($field->notnull == "0") {
                                    $data[$actualTag][$rownumber][$field->Field] = null;
                                } else {
                                    notify("The field:'{$field->Field}' not exist in the xml backup file, and is necesary in the {$actualTag} table");
                                }
                            }
                        }
                    }
                    break;
                default:
                    error("Error in validation for the {$actualtag} content with the DB schema");
            }
        }
    }
    foreach ($data as $bd_table => $table) {
        //tomamos el nombre de la tabla
        if (isset($table)) {
            foreach ($table as $fields) {
                $data_bd = null;
                if (is_array($fields)) {
                    $recordok = true;
                    foreach ($fields as $name => $value) {
                        //Treat special cases
                        if ($WS->dfwiki->wikicourse == 0) {
                            $pageid = $WS->dfwiki->id;
                            $pagetype = 'mod-wiki-view';
                        } else {
                            $pageid = $WS->dfwiki->wikicourse;
                            $pagetype = 'course-view';
                        }
                        if ($name == "dfwiki") {
                            $data_bd->dfwiki = backup_todb($WS->dfwiki->id);
                        } else {
                            if ($name == "editable") {
                                $data_bd->editable = backup_todb($WS->dfwiki->editable);
                            } else {
                                if ($name == "blockid") {
                                    $data_bd->blockid = wiki_blockid(backup_todb($value));
                                } else {
                                    if ($name == "pageid") {
                                        $data_bd->pageid = backup_todb($pageid);
                                    } else {
                                        if ($name == "pagetype") {
                                            $data_bd->pagetype = backup_todb($pagetype);
                                        } else {
                                            if ($name == "weight") {
                                                $weight = get_record_sql('SELECT 1, max(weight) + 1 AS nextfree FROM ' . $CFG->prefix . 'block_instance WHERE pageid = ' . $pageid . ' AND position = \'' . $data_bd->position . '\'');
                                                $data_bd->weight = empty($weight->nextfree) ? 0 : $weight->nextfree;
                                            } else {
                                                if ($name == "author") {
                                                    $userinfo = get_record_sql('SELECT *
                                            FROM ' . $CFG->prefix . 'user
                                            WHERE username=\'' . $value . '\'');
                                                    if ($userinfo) {
                                                        $data_bd->author = $userinfo->username;
                                                        $data_bd->userid = $userinfo->id;
                                                    } else {
                                                        $data_bd->author = $USER->username;
                                                        $data_bd->userid = $USER->id;
                                                        //  	$recordok=false;
                                                        //      notify("The user $value not exists in the system, and is necesary for importing the wiki page.");
                                                    }
                                                } else {
                                                    if ($name == "userid") {
                                                        //Userid is defined by the author.
                                                    } else {
                                                        if ($name == "ownerid") {
                                                            if ($WS->dfwiki->studentmode == 0) {
                                                                if ($value != '0') {
                                                                    //ownerid!=0
                                                                    $recordok = false;
                                                                    notify(" The field ownerid has defined the value:{$value}, and this is incompatible with the wiki on importing, because this wiki is a common student wiki.");
                                                                } else {
                                                                    //ownerid=0
                                                                    $data_bd->ownerid = '0';
                                                                }
                                                            } else {
                                                                if ($value != 0) {
                                                                    $ownerid = wiki_exits_ownerid($value);
                                                                    if (isset($ownerid)) {
                                                                        $data_bd->ownerid = $ownerid;
                                                                    } else {
                                                                        //ownerid not exists in the system
                                                                        $recordok = false;
                                                                        notify(" The ownerid:{$value}, not exists in the system and is necesary for a wiki with students mode defined");
                                                                    }
                                                                } else {
                                                                    //ownerid=0
                                                                    if (isset($data_bd->syn)) {
                                                                        //Case synonimous
                                                                        $data_bd->ownerid = '0';
                                                                    } else {
                                                                        //case pages
                                                                        $data_bd->ownerid = $data_bd->userid;
                                                                    }
                                                                }
                                                            }
                                                        } else {
                                                            if ($name == "groupid") {
                                                                //name is the name of tag of xml, and your value is $value
                                                                if ($value == 0) {
                                                                    //content of xml
                                                                    if (isset($WS->cm->groupmode) && $WS->cm->groupmode == 0) {
                                                                        $data_bd->groupid = 0;
                                                                    } else {
                                                                        //if $value = grupid = 0, No groups on xml
                                                                        //but the course is possible to have groups
                                                                        //only create wiki of current group of wiki or course.
                                                                        if ($id_group_template == 0) {
                                                                            $data_bd->groupid = wiki_groupid_actual();
                                                                        } else {
                                                                            $data_bd->groupid = $id_group_template;
                                                                        }
                                                                    }
                                                                } else {
                                                                    if (isset($WS->cm->groupmode) && $WS->cm->groupmode == 0) {
                                                                        $recordok = false;
                                                                        notify("The field groupid has defined the value:{$value}, and this is incompatible with the wiki on importing, because this wiki is a common group wiki.");
                                                                        //XML for groups
                                                                        //current course without groups
                                                                        //add content of xml only one time, for the current course
                                                                    } else {
                                                                        $groupid = wiki_groupid($value, $COURSE->id);
                                                                        if (isset($groupid)) {
                                                                            $data_bd->groupid = $groupid;
                                                                        } else {
                                                                            //xml with groups
                                                                            //current course with groups
                                                                            //but the number ob groups of xml and current course there are diferent
                                                                            //because the xml there are of any course
                                                                            //is possible that this option there are not necessary
                                                                            $recordok = false;
                                                                            notify("The field groupid has defined the value:{$value}, and this group not exists in the course.");
                                                                        }
                                                                    }
                                                                }
                                                            } else {
                                                                $data_bd->{$name} = backup_todb($value);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if ($recordok) {
                        switch ($bd_table) {
                            case "wiki_pages":
                                if (record_exists('wiki_pages', 'pagename', $data_bd->pagename, 'dfwiki', $WS->dfwiki->id, 'groupid', $data_bd->groupid)) {
                                    $infopages = wiki_treat_page($data_bd, $WS);
                                } else {
                                    $infopages[] = $data_bd->pagename;
                                    if (!insert_record("{$bd_table}", $data_bd)) {
                                        notify("Can\\'t insert {$bd_table} record with name {$data_bd->pagename}");
                                    }
                                    add_to_log($COURSE->id, 'wiki', "save {$data_bd->pagename}", "view.php?id={$WS->cm->id}&amp;page={$data_bd->pagename}", "wiki edited {$WS->dfwiki->name}: {$data_bd->pagename}");
                                }
                                break;
                            case "wiki_history":
                                if (exist_pagename_infopages($infopages, $data_bd->pagename)) {
                                    echo "wiki_history:{$data_bd->pagename} <br>";
                                    if (!insert_record('wiki_pages', $data_bd)) {
                                        notify("Can\\'t insert {$bd_table} record with name {$data_bd->pagename}");
                                    }
                                    add_to_log($COURSE->id, 'wiki', "save {$data_bd->pagename}", "view.php?id={$WS->cm->id}&amp;page={$data_bd->pagename}", "wiki edited {$WS->dfwiki->name}: {$data_bd->pagename}");
                                } else {
                                    if (record_exists('wiki_pages', 'pagename', $data_bd->pagename, 'dfwiki', $WS->dfwiki->id, 'groupid', $data_bd->groupid)) {
                                        $infopages = wiki_treat_page($data_bd, $WS);
                                    } else {
                                        $infopages[] = $data_bd->pagename;
                                        if (!insert_record("{$bd_table}", $data_bd)) {
                                            notify("Can\\'t insert {$bd_table} record with name {$data_bd->pagename}");
                                        }
                                        add_to_log($COURSE->id, 'wiki', "save {$data_bd->pagename}", "view.php?id={$WS->cm->id}&amp;page={$data_bd->pagename}", "wiki edited {$WS->dfwiki->name}: {$data_bd->pagename}");
                                    }
                                }
                                break;
                                //import the synonymous only if not exists
                                //other sinonymous with the same name
                                //in the actual wiki.
                            //import the synonymous only if not exists
                            //other sinonymous with the same name
                            //in the actual wiki.
                            case "wiki_synonymous":
                                if (exist_pagename_infopages($infopages, $data_bd->original)) {
                                    if (!wiki_synonymous_ok($data_bd)) {
                                        if (!insert_record("{$bd_table}", $data_bd)) {
                                            notify("Can\\'t insert {$bd_table} record with name {$data_bd->syn}");
                                        }
                                    }
                                }
                                break;
                            case "block_instance":
                                //look if dfwiki contains this block to not import
                                $fill = get_record_sql('SELECT * FROM ' . $CFG->prefix . 'block_instance WHERE pageid = ' . $data_bd->pageid . ' AND blockid = \'' . $data_bd->blockid . '\'');
                                if (empty($fill)) {
                                    if (!insert_record("{$bd_table}", $data_bd)) {
                                        notify("Can\\'t insert {$bd_table} record for blockid {$data_bd->blockid}");
                                    }
                                }
                                break;
                            case "wiki_votes":
                                if (!wiki_voted($data_bd)) {
                                    if (!insert_record("{$bd_table}", $data_bd)) {
                                        notify("Can\\'t insert {$bd_table} record for the pagename {$data_bd->pagename}");
                                    }
                                }
                                break;
                            case "wiki_import":
                                if (record_exists('wiki_pages', 'dfwiki', $WS->dfwiki->id, 'pagename', $data_bd->pagename, 'version', $data_bd->version, 'groupid', $data_bd->groupid)) {
                                    $infopages = wiki_treat_page($data_bd, $WS);
                                    add_to_log($COURSE->id, 'wiki', "save {$data_bd->pagename}", "view.php?id={$WS->cm->id}&amp;page={$data_bd->pagename}", "wiki edited {$WS->dfwiki->name}: {$data_bd->pagename}");
                                } else {
                                    $infopages[] = $data_bd->pagename;
                                    if (!insert_record('wiki_pages', $data_bd)) {
                                        notify("Can\\'t insert {$bd_table} record with name {$data_bd->pagename}");
                                    }
                                    add_to_log($COURSE->id, 'wiki', "save {$data_bd->pagename}", "view.php?id={$WS->cm->id}&amp;page={$data_bd->pagename}", "wiki edited {$WS->dfwiki->name}: {$data_bd->pagename}");
                                }
                                break;
                            default:
                                error("Can\\'t insert {$bd_table} record");
                        }
                    } else {
                        notify($recordok);
                    }
                }
            }
        }
    }
}