MDL-11517 reserved word MOD used in table alias in questions backup code
[moodle-pu.git] / mod / wiki / ewiki / plugins / moodle / moodle_wikidump.php
blob460cabc06b079240af60b2cc12b9725e60d21ceb
1 <?php // $Id$
2 # ToDo: Binary Content
3 # Binary Linking
4 /*
5 Allows to download a tarball including all WikiPages and images that
6 currently are in the database.
7 */
10 #-- text
11 $ewiki_t["en"]["WIKIEXPORTCOMMENT"] = "Here you can tailor your WikiDump to your needs. When you are ready, click the \"Download\" button.";
12 $ewiki_t["en"]["DOWNLOAD_ARCHIVE"] = "Download";
14 #define("EWIKI_WIKIDUMP_ARCNAME", "WikiDump_");
15 #define("EWIKI_WIKIDUMP_DEFAULTTYPE", "TAR");
16 #define("EWIKI_WIKIDUMP_MAXLEVEL", 1);
17 define('EWIKI_DUMP_FILENAME_REGEX',"/\W\+/");
19 #-- glue
20 #if((function_exists(gzcompress) && EWIKI_WIKIDUMP_DEFAULTTYPE=="ZIP") || EWIKI_WIKIDUMP_DEFAULTTYPE=="TAR"){
21 $ewiki_plugins["page"]["WikiExport"] = "moodle_ewiki_page_wiki_dump";
22 #$ewiki_plugins["action"]['wikidump'] = "moodle_ewiki_page_wiki_dump";
25 $ewiki_t["c"]["EWIKIDUMPCSS"] = '
26 <style TYPE="text/css">
27 <!--
28 body {
29 background-color:#eeeeff;
30 padding:2px;
33 H2 {
34 background:#000000;
35 color:#ffffff;
36 border:1px solid #000000;
38 -->
39 </style>
40 ';
43 function moodle_ewiki_page_wiki_dump($id=0, $data=0, $action=0) {
44 global $userid, $groupid, $cm, $wikipage, $wiki, $course, $CFG;
45 #-- return legacy page
46 $cont = true;
47 if (!empty($_REQUEST["wikiexport"])) {
48 $binaries=$_REQUEST["exportbinaries"];
49 if(!$wiki->ewikiacceptbinary) {
50 $binaries=0;
52 $exportformats=$_REQUEST["exportformats"];
53 if($wiki->htmlmode==2) {
54 $exportformats=1;
56 $cont=ewiki_page_wiki_dump_send($binaries,
57 $exportformats,
58 $_REQUEST["withvirtualpages"],
59 $_REQUEST["exportdestinations"]);
61 if($cont===false) return;
63 $url = ewiki_script("", "WikiExport");
64 $ret = ewiki_make_title($id, $id, 2);
65 $ret .= ($cont&&$cont!==true)?$cont."<br /><br />\n":"";
66 $ret .= get_string("wikiexportcomment","wiki");
67 // removing name="form" from the following form as it does not validate
68 // and is not referenced. MDL-7861
69 $ret .= "<br /><br />\n".
70 '<FORM method="post" action="'.$url.'">'."\n".
71 "<div class=\"wikiexportbox\">\n".
72 '<INPUT type="hidden" name="userid" value="'.$userid.'" />'."\n".
73 '<INPUT type="hidden" name="groupid" value="'.$groupid.'" />'."\n".
74 '<INPUT type="hidden" name="id" value="'.$cm->id.'" />'."\n".
75 '<INPUT type="hidden" name="wikipage" value="'.$wikipage.'" />'."\n";
78 // Export binaries too ?
79 if(!$wiki->ewikiacceptbinary) {
80 $ret.='<INPUT type="hidden" name="exportbinaries" value="0" />'.$exportdestinations[0]."\n";
81 } else {
82 $ret.='<INPUT type="hidden" name="exportbinaries" value="0" />'."\n";
84 $ret.="<TABLE cellpadding=\"5\">\n";
85 if($wiki->ewikiacceptbinary) {
86 $ret.=" <TR valign=\"top\">\n".
87 ' <TD align="right">'.get_string("withbinaries","wiki").":</TD>\n".
88 " <TD>\n".
89 ' <input type="checkbox" name="exportbinaries" value="1"'.($_REQUEST["exportbinaries"]==1?" checked":"")." />\n".
90 " </TD>\n".
91 " </TR>\n";
93 $ret.=" <TR valign=\"top\">\n".
94 ' <TD align="right">'.get_string("withvirtualpages","wiki").":</TD>\n".
95 " <TD>\n".
96 ' <input type="checkbox" name="withvirtualpages" value="1"'.($_REQUEST["withvirtualpages"]==1?" checked":"")." />\n".
97 " </TD>\n".
98 " </TR>\n";
99 $exportformats=array( "0" => get_string("plaintext","wiki") , "1" => get_string("html","wiki"));
100 /// Formats
101 $ret.=" <TR valign=\"top\">\n".
102 ' <TD align="right">'.get_string("exportformats","wiki").":</TD>\n".
103 " <TD>\n";
104 if($wiki->htmlmode!=2) {
105 $ret.= choose_from_menu($exportformats, "exportformats", $_REQUEST["exportformats"], "", "", "", true)."\n";
106 } else {
107 $ret.= '<INPUT type="hidden" name="exportformats" value="1" />'.
108 get_string("html","wiki");
110 $ret.=" </TD>\n".
111 " </TR>\n";
112 /// Destination
113 $exportdestinations=array("0" => get_string("downloadaszip","wiki"));
114 if(wiki_is_teacher($wiki)) {
115 // Get Directory List
116 $rawdirs = get_directory_list("$CFG->dataroot/$course->id", 'moddata', true, true, false);
118 foreach ($rawdirs as $rawdir) {
119 $exportdestinations[$rawdir] = get_string("moduledirectory","wiki").": ".$rawdir;
123 $ret.=" <TR valign=\"top\">\n".
124 ' <TD align="right">'.get_string("exportto","wiki").":</TD>\n".
125 " <TD>\n";
126 if(count($exportdestinations)==1) {
127 $ret.='<INPUT type="hidden" name="exportdestinations" value="0" />'.$exportdestinations[0]."\n";
128 } else {
129 $ret.=choose_from_menu($exportdestinations, "exportdestinations", $_REQUEST["exportdestinations"], "", "", "", true)."\n";
131 $ret.=" </TD>\n".
132 " </TR>\n".
133 "</TABLE>\n".
134 ' <input type="submit" name="wikiexport" value= "'.get_string("export","wiki").'" />'."\n".
135 "</div>\n";
136 "</FORM>\n";
137 return $ret;
140 function ewiki_page_wiki_dump_send($exportbinaries=0, $exportformats=0, $withvirtualpages=0, $exportdestinations=0) {
141 global $ewiki_config, $wiki, $ewiki_plugins, $wiki_entry, $course, $CFG, $ewiki_t, $userid, $groupid;
143 $filestozip=array();
144 #-- disable protected email
145 if (is_array($ewiki_plugins["link_url"])) {
146 foreach($ewiki_plugins["link_url"] as $key => $linkplugin){
147 if($linkplugin == "ewiki_email_protect_link"){
148 unset($ewiki_plugins["link_url"][$key]);
153 /// HTML-Export
154 if($exportformats==1) {
155 #-- if exportformats is html
156 $HTML_TEMPLATE = '<html>
157 <head>'.$ewiki_t["c"]["EWIKIDUMPCSS"].'
158 <title>$title</title>
159 </head>
160 <body bgcolor="#ffffff";>
161 <div id="PageText">
162 <h2>$title</h2>
163 $content
164 </div>
165 </body>
166 </html>';
168 #-- reconfigure ewiki_format() to generate offline pages and files
169 $html_ext = ".html";
170 $ewiki_config["script"] = "%s$html_ext";
171 $ewiki_config["script_binary"] = "%s";
174 // Export Virtual pages special
175 $a_virtual = array_keys($ewiki_plugins["page"]);
177 #-- get all pages / binary files
178 $a_validpages = ewiki_valid_pages(1, $withvirtualpages);
179 $a_pagelist = ewiki_sitemap_create($wiki_entry->pagename, $a_validpages, 100, 1);
181 # Add linked binary files to pagelist
182 foreach($a_pagelist as $key => $value) {
183 if(is_array($a_validpages[$value]["refs"])){
184 foreach($a_validpages[$value]["refs"] as $refs){
185 if($a_validpages[$refs]["type"]=="image" || $a_validpages[$refs]["type"]=="file"){
186 $a_pagelist[]=$refs;
192 # Adjust links to binary files
193 foreach($a_pagelist as $key => $value){
194 if($a_validpages[$value]["type"]=="image"){
195 $a_images[]=urlencode($value);
196 $a_rimages[]=urlencode(preg_replace(EWIKI_DUMP_FILENAME_REGEX, "", $value));
197 unset($a_validpages[$value]);
199 if($a_validpages[$value]["type"]=="file") {
200 $a_images[]=urlencode($value);
201 $a_rimages[]=clean_filename(substr($value,strlen(EWIKI_IDF_INTERNAL)));
202 $a_images[]=$value;
203 $a_rimages[]=clean_filename(substr($value,strlen(EWIKI_IDF_INTERNAL)));
204 unset($a_validpages[$value]);
208 # Remove binaries from a_validpages and add to a_pagelist
209 foreach($a_validpages as $key => $value){
210 if($a_validpages[$key]["type"]=="image" || $a_validpages[$key]["type"]=="file"){
211 $a_pagelist[]=$key;
212 unset($a_validpages[$key]);
216 #print "<pre>"; print_r($a_validpages); print "</pre>";
217 #print "<hr /><pre>"; print_r($a_pagelist); print "</pre>";
219 $a_sitemap = ewiki_sitemap_create($wiki_entry->pagename, $a_validpages, 99, 0);
220 if ($a_pagelist) {
221 #-- create new zip file
222 #if($arctype == "ZIP"){
223 # $archivename=EWIKI_WIKIDUMP_ARCNAME."$rootid.zip";
224 # $archive = new ewiki_virtual_zip();
225 #} elseif ($arctype == "TAR") {
226 # $archivename=EWIKI_WIKIDUMP_ARCNAME."$rootid.tar";
227 # $archive = new ewiki_virtual_tarball();
228 #} else {
229 # die();
232 /// Create/Set Directory
233 $wname=clean_filename(strip_tags(format_string($wiki->name,true)));
234 if($exportdestinations) {
235 if(wiki_is_teacher($wiki)) {
236 $exportdir=$CFG->dataroot."/".$course->id."/".$exportdestinations;
237 } else {
238 add_to_log($course->id, "wiki", "hack", "", format_string($wiki->name,true).": Tried to export a wiki as non-teacher into $exportdestinations.");
239 error("You are not a teacher !");
241 } else {
242 $exportbasedir=tempnam("/tmp","WIKIEXPORT");
243 @unlink($exportbasedir);
244 @mkdir($exportbasedir);
245 /// maybe we need to check the name here...?
246 $exportdir=$exportbasedir."/".$wname;
247 @mkdir($exportdir);
248 if(!is_dir($exportdir)) {
249 error("Cannot create temporary directory $exportdir !");
253 $a_pagelist = array_unique($a_pagelist);
256 #-- convert all pages
257 foreach($a_pagelist as $pagename){
258 if ((!in_array($pagename, $a_virtual))) {
259 $id = $pagename;
260 #-- not a virtual page
261 $row = ewiki_database("GET", array("id"=>$pagename));
262 $content = "";
263 } elseif($withvirtualpages) {
264 $id = $pagename;
265 #-- is a virtual page
266 $pf = $ewiki_plugins["page"][$id];
267 $content = $pf($id, $content, "view");
268 if ($exportformats==1) {
269 $content = str_replace('$content', $content, str_replace('$title', $id, $HTML_TEMPLATE));
271 $fn = urlencode($id);
272 $fn = preg_replace(EWIKI_DUMP_FILENAME_REGEX, "", $fn);
273 $fn = $fn.$html_ext;
274 } else {
275 continue;
278 if (empty($content)){
279 switch ($row["flags"] & EWIKI_DB_F_TYPE) {
280 // Text Page
281 case (EWIKI_DB_F_TEXT):
282 #print "<pre>"; print_r($row[content]); print "\n-------------</pre>";
284 if($exportformats==1) {/// HTML-Export
285 $content = ewiki_format($row["content"]);
286 } else {
287 $content = $row["content"];
290 # Binary files link adjustment when html
291 if($exportformats==1) {
292 $content = str_replace($a_images, $a_rimages, $content);
295 $fn = preg_replace(EWIKI_DUMP_FILENAME_REGEX, "", urlencode($id));
296 $fn = $fn.$html_ext;
297 if($exportformats==1) {/// HTML-Export
298 $content = str_replace('$content', $content, str_replace('$title', $id, $HTML_TEMPLATE));
300 break;
301 case (EWIKI_DB_F_BINARY):
302 #print "Binary: $row[id]<br />";
303 if (($row["meta"]["class"]=="image" || $row["meta"]["class"]=="file") && ($exportbinaries)) {
304 # Copy files to the appropriate directory
305 $fn= moodle_binary_get_path($id, $row["meta"], $course, $wiki, $userid, $groupid);
306 $destfn=clean_filename(substr($id,strlen(EWIKI_IDF_INTERNAL)));
307 $dest="$exportdir/".$destfn;
308 if(!copy($fn,$dest)) {
309 notify("Cannot copy $fn to $dest.");
312 #$fn = urlencode(preg_replace(EWIKI_DUMP_FILENAME_REGEX, "", $id));
313 #$content = &$row["content"];
314 $filestozip[]=$exportdir."/".$destfn;
315 continue (2);
317 else {
318 #-- php considers switch statements as loops so continue 2 is needed to
319 #-- hit the end of the for loop
320 continue(2);
322 break;
324 default:
325 # don't want it
326 continue(2);
330 # Do not translate links when wiki already in pure html - mode
331 if($wiki->htmlmode!=2) {
332 $content=preg_replace_callback(
333 '/(<a href=")(.*?)(\.html">)/',
334 create_function(
335 // single quotes are essential here,
336 // or alternative escape all $ as \$
337 '$matches',
338 'return($matches[1].preg_replace(EWIKI_DUMP_FILENAME_REGEX,"",$matches[2]).$matches[3]);'
340 $content
343 #-- add file
344 // Let's make sure the file exists and is writable first.
345 if (!$handle = fopen($exportdir."/".$fn, 'w')) {
346 error("Cannot open file ($exportdir/$fn)");
349 // Write $content to our opened file.
350 if (fwrite($handle, $content) === FALSE) {
351 error("Cannot write to file ($exportdir/$fn)");
354 fclose($handle);
355 $filestozip[]=$exportdir."/".$fn;
356 #$archive->add($content, $fn, array(
357 # "mtime" => $row["lastmodified"],
358 # "uname" => "ewiki",
359 # "mode" => 0664 | (($row["flags"]&EWIKI_DB_F_WRITEABLE)?0002:0000),
360 # ), $complevel);
363 #-- create index page
364 /// HTML-Export
365 if($exportformats==1) {
366 $timer=array();
367 $level=-1;
368 $fordump=1;
369 $str_formatted="<ul>\n<li><a href=\"".($wiki_entry->pagename).$html_ext."\">".($wiki_entry->pagename)."</a></li>";
370 $fin_level=format_sitemap($a_sitemap, ($wiki_entry->pagename), $str_formatted, $level, $timer, $fordump);
371 $str_formatted.="</ul>".str_pad("", $fin_level*6, "</ul>\n");
372 $str_formatted=preg_replace_callback(
373 '/(<a href=")(.*?)(\.html">)/',
374 create_function(
375 // single quotes are essential here,
376 // or alternative escape all $ as \$
377 '$matches',
378 'return($matches[1].preg_replace(EWIKI_DUMP_FILENAME_REGEX,"",$matches[2]).$matches[3]);'
380 $str_formatted
382 $str_formatted = str_replace('$content', $str_formatted, str_replace('$title', get_string("index","wiki"), $HTML_TEMPLATE));
383 #-- add file
384 // Let's make sure the file exists and is writable first.
385 $indexname="index".$html_ext;
386 if (!$handle = fopen($exportdir."/".$indexname, 'w')) {
387 error("Cannot open file ($exportdir/$indexname)");
390 // Write $somecontent to our opened file.
391 if (fwrite($handle, $str_formatted) === FALSE) {
392 error("Cannot write to file ($exportdir/$indexname)");
395 fclose($handle);
396 $filestozip[]=$exportdir."/".$indexname;
398 #-- add index page
399 # $archive->add($str_formatted, "Index_$rootid".$html_ext, array(
400 # "mtime" => $row["lastmodified"],
401 # "uname" => "ewiki",
402 # "mode" => 0664 | (($row["flags"]&EWIKI_DB_F_WRITEABLE)?0002:0000),
403 # ), $complevel);
406 if(!$exportdestinations) {
407 $archivename=$wname.".zip";
408 zip_files($filestozip, "$exportbasedir/$archivename");
410 #-- Headers
411 Header("Content-type: application/zip");
412 Header("Content-disposition: attachment; filename=\"$archivename\"");
413 Header("Cache-control: private");
414 Header("Original-Filename: $archivename");
415 Header("X-Content-Type: application/zip");
416 Header("Content-Location: $archivename");
417 if(!@readfile("$exportbasedir/$archivename")) {
418 error("Cannot read $exportbasedir/$archivename");
420 if(!deldir($exportbasedir)) {
421 error("Cannot delete $exportbasedir");
423 #exit();
424 return false;
425 } else {
426 return get_string("exportsuccessful","wiki")."<br />";
431 function deldir($dir)
433 $handle = opendir($dir);
434 while (false!==($FolderOrFile = readdir($handle)))
436 if($FolderOrFile != "." && $FolderOrFile != "..")
438 if(is_dir("$dir/$FolderOrFile"))
439 { deldir("$dir/$FolderOrFile"); } // recursive
440 else
441 { unlink("$dir/$FolderOrFile"); }
444 closedir($handle);
445 if(rmdir($dir))
446 { $success = true; }
447 return $success;