This repository has been archived on 2020-08-21. You can view files and clone it, but cannot push or open issues or pull requests.
nemubot-askweb/QuestionsFile.class.php

125 lines
2.5 KiB
PHP

<?php
require_once("Question.class.php");
class QuestionsFile
{
private $filename;
private $treeXML;
private $root_node;
private $tmp = array();
public function __construct($filename)
{
$this->filename = $filename;
$this->reload();
}
/**
* Load or reload the questions file.
* Unsave changes will be erased.
*/
private function reload()
{
$this->treeXML = new DOMDocument('1.0', 'UTF-8');
if (@$this->treeXML->load($this->filename))
{
$root_nodes = $this->treeXML->getElementsByTagName("questions");
if ($root_nodes->length > 0)
$this->root_node = $root_nodes->item(0);
else
throw Exception("Not a valid nemubot QuestionsFile.");
}
else
{
$this->root_node = $this->treeXML->createElement("questions");
$this->treeXML->appendChild($this->root_node);
}
}
/**
* Add a new question into the file
* @param $question The question object
*/
public function add_question($question)
{
$this->tmp[$question->getId()] = $question;
}
public function del_question($question)
{
unset($this->tmp[$question->getId()]);
}
/**
* Get a question from its unique identifiant
*/
public function get_question($id)
{
if (isset($this->tmp[$id]))
return $this->tmp[$id];
else
{
$q = $this->treeXML->getElementById($id);
if (isset($q))
{
$this->root_node->removeChild($q);
$this->tmp[$id] = new Question($q);
return $this->tmp[$id];
}
}
return NULL;
}
public function get_ids()
{
$ret = array();
$qs = $this->treeXML->getElementsByTagName("question");
foreach($qs as $q)
$ret[] = $q->getAttribute("xml:id");
return $ret;
}
public function get_questions()
{
$ret = array();
$qs = $this->treeXML->getElementsByTagName("question");
foreach($qs as $q)
$ret[] = new Question($q);
return $ret;
}
/**
* Write changes into the real file
*/
public function save($newfilename = null)
{
foreach ($this->tmp as $question)
{
$qnode = $question->to_xml($this->treeXML);
$this->root_node->appendChild($qnode);
}
if (!empty($newfilename))
$this->filename = $newfilename;
$this->treeXML->formatOutput = true;
$this->treeXML->save($this->filename);
}
}
/*
$file = new QuestionsFile("questions.xml");
foreach ($file->get_ids() as $id)
{
$q = $file->get_question($id);
echo $q->convert()."<br>";
}
$file->save();
//*/
?>