function wiki_read_xml_wiki($info, $courseid)
{
    foreach ($info as $name => $value) {
        if ($name != "PAGES" and $name != "SYNONYMOUS") {
            //Tratamos la wiki
            $data['wiki'][strtolower($name)] = $value['0']['#'];
        } elseif ($name == "PAGES") {
            //Tratamos las paginas
            $pages = $value['0']['#']['PAGE'];
            $numpages = count($pages);
            for ($i = 0; $i < $numpages; $i++) {
                foreach ($pages[$i]['#'] as $name => $page) {
                    //search the groupid using the groupname
                    if ($name == "GROUPNAME") {
                        $groupname = $page['0']['#'];
                        if (!empty($groupname)) {
                            $data['wiki_pages'][$i]['groupid'] = wiki_groupid($groupname, $courseid);
                        } else {
                            $data['wiki_pages'][$i]['groupid'] = 0;
                        }
                    } else {
                        $data['wiki_pages'][$i][strtolower($name)] = $page['0']['#'];
                    }
                }
            }
        } elseif ($name == "SYNONYMOUS") {
            //tratamos ls sinonimos
            $syns = $value['0']['#']['SYNONYM'];
            $numsyns = count($syns);
            for ($i = 0; $i < $numsyns; $i++) {
                foreach ($syns[$i]['#'] as $name => $syn) {
                    //search the groupid using the groupname
                    if ($name == "GROUPNAME") {
                        $groupname = $syn['0']['#'];
                        if (!empty($groupname)) {
                            $data['wiki_synonymous'][$i]['groupid'] = wiki_groupid($groupname, $courseid);
                        } else {
                            $data['wiki_synonymous'][$i]['groupid'] = 0;
                        }
                    } else {
                        $data['wiki_synonymous'][$i][strtolower($name)] = $syn['0']['#'];
                    }
                }
            }
        }
    }
    return $data;
}
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);
                    }
                }
            }
        }
    }
}