Platform  3.1
PHP API documentation
 All Data Structures Namespaces Files Functions Variables Pages
freedom_import_xml.php
Go to the documentation of this file.
1 <?php
2 /*
3  * @author Anakeen
4  * @license http://creativecommons.org/licenses/by-nc-sa/2.0/fr/ Anakeen - licence CC
5  * @package FDL
6 */
7 /**
8  * Import directory with document descriptions
9  *
10  * @author Anakeen 2000
11  * @version $Id: freedom_import_dir.php,v 1.5 2007/01/19 16:23:32 eric Exp $
12  * @license http://creativecommons.org/licenses/by-nc-sa/2.0/fr/ Anakeen - licence CC
13  * @package FDL
14  * @subpackage GED
15  */
16 /**
17  */
18 
19 include_once ("FDL/import_tar.php");
20 /**
21  * export global xml file
22  * @param Action $action main action
23  * @param string $filename xml filename to import
24  */
26 {
27 
28  $opt["analyze"] = (substr(strtolower(getHttpVars("analyze", "N")) , 0, 1) == "y");
29  $opt["policy"] = getHttpVars("policy", "update");
30  $dbaccess = $action->getParam("FREEDOM_DB");
31  global $_FILES;
32  if (intval(ini_get("max_execution_time")) < 300) ini_set("max_execution_time", 300);
33  if ($filename == "") {
34  if (isset($_FILES["file"])) {
35  $filename = $_FILES["file"]['name'];
36  $xmlfiles = $_FILES["file"]['tmp_name'];
37  $ext = substr($filename, strrpos($filename, '.') + 1);
38  rename($xmlfiles, $xmlfiles . ".$ext");
39  $xmlfile.= ".$ext";
40  } else {
41  $filename = GetHttpVars("file");
42  $xmlfiles = $filename;
43  }
44  } else {
45  $xmlfiles = $filename;
46  }
47  $splitdir = uniqid(getTmpDir() . "/xmlsplit");
48  @mkdir($splitdir);
49  if (!is_dir($splitdir)) $action->exitError(_("Cannot create directory %s for xml import") , $splitdir);
50  $err = splitXmlDocument($xmlfiles, $splitdir);
51  if ($err) $action->exiterror($err);
52  //print "Split OK in $splitdir";
54  if ($err) $action->exiterror($err);
55 
56  $log = importXmlDirectory($dbaccess, $splitdir, $opt);
57  system(sprintf("/bin/rm -fr %s ", $splitdir));
58  // print "look : $splitdir\n";
59  return $log;
60 }
61 /**
62  * export global xml file
63  * @param Action $action main action
64  * @param string $filename xml filename to import
65  */
67 {
68 
69  $opt["analyze"] = (substr(strtolower(getHttpVars("analyze", "Y")) , 0, 1) == "y");
70  $opt["policy"] = getHttpVars("policy", "update");
71  $dbaccess = $action->getParam("FREEDOM_DB");
72  global $_FILES;
73  if (intval(ini_get("max_execution_time")) < 300) ini_set("max_execution_time", 300);
74  if ($filename == "") {
75  if (isset($_FILES["file"])) {
76  $filename = $_FILES["file"]['name'];
77  $zipfiles = $_FILES["file"]['tmp_name'];
78  $ext = substr($filename, strrpos($filename, '.') + 1);
79  rename($zipfiles, $zipfiles . ".$ext");
80  $zipfile.= ".$ext";
81  } else {
82  $filename = GetHttpVars("file");
83  $zipfiles = $filename;
84  }
85  } else {
86  $zipfiles = $filename;
87  }
88  $splitdir = uniqid(getTmpDir() . "/xmlsplit");
89  @mkdir($splitdir);
90  if (!is_dir($splitdir)) $action->exitError(_("Cannot create directory %s for xml import") , $splitdir);
91  $err = splitZipXmlDocument($zipfiles, $splitdir);
92  if ($err) $action->exiterror($err);
93  //print "Split OK in $splitdir";
95  if ($err) $action->exiterror($err);
96 
97  $log = importXmlDirectory($dbaccess, $splitdir, $opt);
98  system(sprintf("/bin/rm -fr %s ", $splitdir));
99  //print "look : $splitdir\n";
100  return $log;
101 }
102 /**
103  * read a directory to import all xml files
104  * @param string $splitdir
105  * @param array options analyze (boolean) , policy (string)
106  */
107 function importXmlDirectory($dbaccess, $splitdir, $opt)
108 {
109  $tlog = array();
110  if ($handle = opendir($splitdir)) {
111  while (false !== ($file = readdir($handle))) {
112  if ($file[0] != "." && is_file("$splitdir/$file")) {
113  $ext = substr($file, strrpos($file, '.') + 1);
114  if ($ext == "xml") {
115  $err = importXmlDocument($dbaccess, "$splitdir/$file", $log, $opt);
116  $tlog[] = $log;
117  }
118  }
119  }
120  }
121  return $tlog;
122 }
123 /**
124  * read a directory to extract all encoded files
125  * @param $splitdir
126  */
127 function extractFilesFromXmlDirectory($splitdir)
128 {
129  $err = '';
130  if ($handle = opendir($splitdir)) {
131  while (false !== ($file = readdir($handle))) {
132  if ($file[0] != ".") {
133  $err.= extractFileFromXmlDocument("$splitdir/$file");
134  }
135  }
136  }
137  return $err;
138 }
139 /**
140  * extract encoded base 64 file from xml and put it in local media directory
141  * the file is rewrite without encoded data and replace by href attribute
142  * @param $file
143  * @return string error message empty if no errors
144  */
146 {
147  static $mediaindex = 0;
148  $err = '';
149  $dir = dirname($file);
150  if (!file_exists($file)) return sprintf(_("import Xml extract : file %s not found") , $file);
151  $mediadir = "media";
152  if (!is_dir("$dir/$mediadir")) mkdir("$dir/$mediadir");
153  $f = fopen($file, "r");
154  $nf = fopen($file . ".new", "w");
155  while (!feof($f)) {
156  $buffer = fgets($f, 4096);
157  $mediaindex++;
158  if (preg_match("/<([a-z_0-9-]+)[^>]*mime=\"[^\"]+\"(.*)>(.*)/", $buffer, $reg)) {
159  if (substr($reg[2], -1) != "/") { // not empty tag
160  $tag = $reg[1];
161  if (preg_match("/<([a-z_0-9-]+)[^>]*title=\"([^\"]+)\"/", $buffer, $regtitle)) {
162  $title = $regtitle[2];
163  } else if (preg_match("/<([a-z_0-9-]+)[^>]*title='([^']+)'/", $buffer, $regtitle)) {
164  $title = $regtitle[2];
165  } else $title = "noname";
166  mkdir(sprintf("%s/%s/%d", $dir, $mediadir, $mediaindex));
167  $rfin = sprintf("%s/%d/%s", $mediadir, $mediaindex, $title);
168  $fin = sprintf("%s/%s", $dir, $rfin);
169  $fi = fopen($fin, "w");
170 
171  if (preg_match("/(.*)(<$tag [^>]*)>/", $buffer, $regend)) {
172  fputs($nf, $regend[1] . $regend[2] . ' href="' . $rfin . '">');
173  }
174  if (preg_match("/>([^<]*)<\/$tag>(.*)/", $buffer, $regend)) {
175  // end of file
176  fputs($fi, $regend[1]);
177  fputs($nf, "</$tag>");
178  fputs($nf, $regend[2]);
179  } else {
180  // find end of file
181  fputs($fi, $reg[3]);
182  $findtheend = false;
183  while (!feof($f) && (!$findtheend)) {
184  $buffer = fgets($f, 4096);
185  if (preg_match("/(.*)<\/$tag>(.*)/", $buffer, $regend)) {
186  fputs($fi, $regend[1]);
187  fputs($nf, "</$tag>");
188  fputs($nf, $regend[2]);
189  $findtheend = true;
190  } else {
191  fputs($fi, $buffer);
192  }
193  }
194  }
195  fclose($fi);
196  base64_decodefile($fin);
197  } else {
198  fputs($nf, $buffer);
199  }
200  } else {
201  fputs($nf, $buffer);
202  }
203  }
204  fclose($f);
205  fclose($nf);
206  rename($file . ".new", $file);
207  return $err;
208 }
209 
210 function importXmlDocument($dbaccess, $xmlfile, &$log, $opt)
211 {
212  static $families = array();
213  $log = array(
214  "err" => "",
215  "msg" => "",
216  "specmsg" => "",
217  "folderid" => 0,
218  "foldername" => "",
219  "filename" => "",
220  "title" => "",
221  "id" => "",
222  "values" => array() ,
223  "familyid" => 0,
224  "familyname" => "",
225  "action" => "-"
226  );
227 
228  if (!is_file($xmlfile)) {
229  $err = sprintf(_("Xml import file %s not found") , $xmlfile);
230  $log["err"] = $err;
231  return $err;
232  }
233  $importdirid = 0;
234  $analyze = true;
235  $policy = "update";
236  if ($opt["policy"]) $policy = $opt["policy"];
237  if ($opt["analyze"] !== null) $analyze = $opt["analyze"];
238  $splitdir = dirname($xmlfile);
239  $tkey = array(
240  "title"
241  );
242  $prevalues = array();
243  $dom = new DOMDocument();
244  try {
245  $ok = @$dom->load($xmlfile);
246 
247  if (!$ok) {
248  throw new XMLParseErrorException($xmlfile);
249  }
250  }
251  catch(Exception $e) {
252  $log["action"] = 'ignored';
253  $log["err"] = $e->userInfo;
254  return $e->userInfo;
255  }
256  // print $doc->saveXML();
257  $root = $dom->documentElement;
258  $id = $root->getAttribute("id");
259  $name = $root->getAttribute("name");
260  $key = $root->getAttribute("key");
261  if ($key) {
262  $tkey = explode(',', $key);
263  foreach ($tkey as & $v) {
264  $v = trim($v);
265  }
266  }
267 
268  $family = $root->tagName;
270  if (!isset($families[$famid])) {
271  $families[$famid] = new_doc($dbaccess, $famid);
272  }
273  //print("family : $family $id $name $famid\n");
274  $la = $families[$famid]->getNormalAttributes();
275  $tord = array();
276  $tdoc = array(
277  "DOC",
278  $famid,
279  ($id) ? $id : $name,
280  '-'
281  );
282  foreach ($la as $k => & $v) {
283  $n = $dom->getElementsByTagName($v->id);
284  $val = array();
285  foreach ($n as $item) {
286  switch ($v->type) {
287  case 'array':
288  break;
289 
290  case 'docid':
291  $id = $item->getAttribute("id");
292  if (!$id) {
293  $name = $item->getAttribute("name");
294  if ($name) $id = getIdFromName($dbaccess, $name);
295  if (!$id) {
296  // search from title
297  if ($item->nodeValue) {
298  $afamid = $v->format;
299  $id = getIdFromTitle($dbaccess, $item->nodeValue, $afamid);
300  if (!$id) $msg.= sprintf(_("No identificator found for relation %s") . "\n", $v->id);
301  }
302  }
303  }
304  if ($v->getOption("multiple") == "yes") {
305  $id = str_replace(',', '\n', $id);
306  if ($v->inArray()) $id = str_replace(array(
307  '\\n',
308  "\n",
309  ) , "<BR>", $id);
310  }
311  $val[] = $id;
312  break;
313 
314  case 'image':
315  case 'file':
316  $href = $item->getAttribute("href");
317  if ($href) {
318  $val[] = $href;
319  } else {
320  $vid = $item->getAttribute("vid");
321  $mime = $item->getAttribute("mime");
322  $title = $item->getAttribute("title");
323  if ($vid) {
324  $val[] = "$mime|$vid|$title";
325  } else $val[] = '';
326  }
327  break;
328 
329  case 'htmltext':
330  $val[] = str_replace("\n", " ", str_replace(">\n", ">", $item->nodeValue));
331  break;
332 
333  default:
334  $val[] = $item->nodeValue;
335  }
336  // print $v->id.":".$item->nodeValue."\n";
337 
338  }
339  $tord[] = $v->id;
340  $tdoc[] = implode("\n", $val);
341  }
342  $log = csvAddDoc($dbaccess, $tdoc, $importdirid, $analyze, $splitdir, $policy, $tkey, $prevalues, $tord);
343  if ($msg) $log["err"].= "\n" . $msg;
344  }
345 
346  function splitZipXmlDocument($zipfiles, $splitdir)
347  {
348  $err = "";
349  $ll = exec(sprintf("cd %s && unzip %s", $splitdir, $zipfiles) , $out, $retval);
350  if ($retval != 0) $err = sprintf(_("export Xml : cannot unzip %s : %s") , $zipfiles, $ll);
351  return $err;
352  }
353  function splitXmlDocument($xmlfiles, $splitdir)
354  {
355  $f = fopen($xmlfiles, "r");
356  if (!$f) return sprintf(_("Xml import : Cannot open file %s") , $xmlfiles);
357  // find first document
358  $findfirst = false;
359  while ((!feof($f)) && (!$findfirst)) {
360  $buffer = fgets($f, 4096);
361  if (strpos($buffer, "<documents") !== false) {
362  $findfirst = true;
363  }
364  }
365  while (!feof($f)) {
366  $buffer = fgets($f, 4096);
367  if (preg_match("/<([a-z-_0-9]+)/", $buffer, $reg)) {
368  //print_r2($reg);
369  $top = $reg[1];
370  if (preg_match("/name=[\"|']([a-z-_0-9]+)[\"|']/", $buffer, $reg)) {
371  $fname = $reg[1];
372  } else if (preg_match("/id=[\"|']([0-9]+)[\"|']/", $buffer, $reg)) {
373  $fname = $reg[1];
374  } else {
375  $fname = uniqid("new");
376  }
377  $fxo = $splitdir . '/' . $fname . ".xml";
378  $xo = fopen($fxo, "w");
379  if (!$xo) return sprintf(_("Xml import : Cannot create file %s") , $fxo);
380  fputs($xo, '<?xml version="1.0" encoding="UTF-8"?>' . "\n");
381  fputs($xo, $buffer);
382  $theend = false;
383  while (!feof($f) && (!$theend)) {
384  $buffer = fgets($f, 4096);
385  if (strpos($buffer, '</' . $top . '>') !== false) {
386  $theend = true;
387  }
388  fputs($xo, $buffer);
389  }
390  fclose($xo);
391  }
392  if (strpos($buffer, "<documents") !== false) {
393  $findfirst = true;
394  }
395  }
396  fclose($f);
397  }
398 
400  {
401  $dir = dirname($filename);
402  $tmpdest = uniqid(getTmpDir() . "/fdlbin");
403  $chunkSize = 1024 * 30;
404  $src = fopen($filename, 'rb');
405  $dst = fopen($tmpdest, 'wb');
406  while (!feof($src)) {
407  fwrite($dst, base64_decode(fread($src, $chunkSize)));
408  }
409  fclose($dst);
410  fclose($src);
411  rename($tmpdest, $filename);
412  }
413 
414  class XMLParseErrorException extends Exception
415  {
416 
417  public function __construct($filename)
418  {
419  set_error_handler(array(
420  $this,
421  "errorHandler"
422  ));
423  $dom = new DomDocument();
424  $dom->load($filename);
425  restore_error_handler();
426  $this->message = "XML Parse Error in $filename";
427  parent::__construct();
428  }
429 
430  public function errorHandler($errno, $errstr, $errfile, $errline)
431  {
432  $pos = strpos($errstr, "]:");
433  if ($pos) {
434  $errstr = substr($errstr, $pos + 2);
435  }
436  $this->userInfo.= "$errstr";
437  }
438  }
439 ?>
← centre documentaire © anakeen - published under CC License - Dynacase