Merge commit 'catalyst/MOODLE_19_STABLE' into mdl19-linuxchix
[moodle-linuxchix.git] / mod / wiki / ewiki / plugins / moodle / moodle_wikidump.php
blob1d9fded5b06d694e7a4689fa4eca2973de86f6ce
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) {
62 die;
65 $url = ewiki_script("", "WikiExport");
66 $ret = ewiki_make_title($id, $id, 2);
67 $ret .= ($cont&&$cont!==true)?$cont."<br /><br />\n":"";
68 $ret .= get_string("wikiexportcomment","wiki");
69 // removing name="form" from the following form as it does not validate
70 // and is not referenced. MDL-7861
71 $ret .= "<br /><br />\n".
72 '<FORM method="post" action="view.php">'."\n".
73 "<div class=\"wikiexportbox\">\n".
74 '<INPUT type="hidden" name="page" value="WikiExport" />'."\n".
75 '<INPUT type="hidden" name="userid" value="'.$userid.'" />'."\n".
76 '<INPUT type="hidden" name="groupid" value="'.$groupid.'" />'."\n".
77 '<INPUT type="hidden" name="id" value="'.$cm->id.'" />'."\n".
78 '<INPUT type="hidden" name="wikipage" value="'.$wikipage.'" />'."\n";
81 // Export binaries too ?
82 if(!$wiki->ewikiacceptbinary) {
83 $ret.='<INPUT type="hidden" name="exportbinaries" value="0" />'.$exportdestinations[0]."\n";
84 } else {
85 $ret.='<INPUT type="hidden" name="exportbinaries" value="0" />'."\n";
87 $ret.="<TABLE cellpadding=\"5\">\n";
88 if($wiki->ewikiacceptbinary) {
89 $ret.=" <TR valign=\"top\">\n".
90 ' <TD align="right">'.get_string("withbinaries","wiki").":</TD>\n".
91 " <TD>\n".
92 ' <input type="checkbox" name="exportbinaries" value="1"'.($_REQUEST["exportbinaries"]==1?" checked":"")." />\n".
93 " </TD>\n".
94 " </TR>\n";
96 $ret.=" <TR valign=\"top\">\n".
97 ' <TD align="right">'.get_string("withvirtualpages","wiki").":</TD>\n".
98 " <TD>\n".
99 ' <input type="checkbox" name="withvirtualpages" value="1"'.($_REQUEST["withvirtualpages"]==1?" checked":"")." />\n".
100 " </TD>\n".
101 " </TR>\n";
102 $exportformats=array( "0" => get_string("plaintext","wiki") , "1" => get_string("html","wiki"));
103 /// Formats
104 $ret.=" <TR valign=\"top\">\n".
105 ' <TD align="right">'.get_string("exportformats","wiki").":</TD>\n".
106 " <TD>\n";
107 if($wiki->htmlmode!=2) {
108 $ret.= choose_from_menu($exportformats, "exportformats", $_REQUEST["exportformats"], "", "", "", true)."\n";
109 } else {
110 $ret.= '<INPUT type="hidden" name="exportformats" value="1" />'.
111 get_string("html","wiki");
113 $ret.=" </TD>\n".
114 " </TR>\n";
115 /// Destination
116 $exportdestinations=array("0" => get_string("downloadaszip","wiki"));
117 if(wiki_is_teacher($wiki)) {
118 // Get Directory List
119 $rawdirs = get_directory_list("$CFG->dataroot/$course->id", 'moddata', true, true, false);
121 foreach ($rawdirs as $rawdir) {
122 $exportdestinations[$rawdir] = get_string("moduledirectory","wiki").": ".$rawdir;
126 $ret.=" <TR valign=\"top\">\n".
127 ' <TD align="right">'.get_string("exportto","wiki").":</TD>\n".
128 " <TD>\n";
129 if(count($exportdestinations)==1) {
130 $ret.='<INPUT type="hidden" name="exportdestinations" value="0" />'.$exportdestinations[0]."\n";
131 } else {
132 $ret.=choose_from_menu($exportdestinations, "exportdestinations", $_REQUEST["exportdestinations"], "", "", "", true)."\n";
134 $ret.=" </TD>\n".
135 " </TR>\n".
136 "</TABLE>\n".
137 ' <input type="submit" name="wikiexport" value= "'.get_string("export","wiki").'" />'."\n".
138 "</div>\n";
139 "</FORM>\n";
140 return $ret;
143 function ewiki_page_wiki_dump_send($exportbinaries=0, $exportformats=0, $withvirtualpages=0, $exportdestinations=0) {
144 global $ewiki_config, $wiki, $ewiki_plugins, $wiki_entry, $course, $CFG, $ewiki_t, $userid, $groupid;
146 $filestozip=array();
147 #-- disable protected email
148 if (is_array($ewiki_plugins["link_url"])) {
149 foreach($ewiki_plugins["link_url"] as $key => $linkplugin){
150 if($linkplugin == "ewiki_email_protect_link"){
151 unset($ewiki_plugins["link_url"][$key]);
156 /// HTML-Export
157 if($exportformats==1) {
158 #-- if exportformats is html
159 $HTML_TEMPLATE = '<html>
160 <head>'.$ewiki_t["c"]["EWIKIDUMPCSS"].'
161 <title>$title</title>
162 </head>
163 <body bgcolor="#ffffff";>
164 <div id="PageText">
165 <h2>$title</h2>
166 $content
167 </div>
168 </body>
169 </html>';
171 #-- reconfigure ewiki_format() to generate offline pages and files
172 $html_ext = ".html";
173 $ewiki_config["script"] = "%s$html_ext";
174 $ewiki_config["script_binary"] = "%s";
177 // Export Virtual pages special
178 $a_virtual = array_keys($ewiki_plugins["page"]);
180 #-- get all pages / binary files
181 $a_validpages = ewiki_valid_pages(1, $withvirtualpages);
182 $a_pagelist = ewiki_sitemap_create($wiki_entry->pagename, $a_validpages, 100, 1);
184 # Add linked binary files to pagelist
185 foreach($a_pagelist as $key => $value) {
186 if(is_array($a_validpages[$value]["refs"])){
187 foreach($a_validpages[$value]["refs"] as $refs){
188 if($a_validpages[$refs]["type"]=="image" || $a_validpages[$refs]["type"]=="file"){
189 $a_pagelist[]=$refs;
195 # Adjust links to binary files
196 foreach($a_pagelist as $key => $value){
197 if($a_validpages[$value]["type"]=="image"){
198 $a_images[]=urlencode($value);
199 $a_rimages[]=urlencode(preg_replace(EWIKI_DUMP_FILENAME_REGEX, "", $value));
200 unset($a_validpages[$value]);
202 if($a_validpages[$value]["type"]=="file") {
203 $a_images[]=urlencode($value);
204 $a_rimages[]=clean_filename(substr($value,strlen(EWIKI_IDF_INTERNAL)));
205 $a_images[]=$value;
206 $a_rimages[]=clean_filename(substr($value,strlen(EWIKI_IDF_INTERNAL)));
207 unset($a_validpages[$value]);
211 # Remove binaries from a_validpages and add to a_pagelist
212 foreach($a_validpages as $key => $value){
213 if($a_validpages[$key]["type"]=="image" || $a_validpages[$key]["type"]=="file"){
214 $a_pagelist[]=$key;
215 unset($a_validpages[$key]);
219 #print "<pre>"; print_r($a_validpages); print "</pre>";
220 #print "<hr /><pre>"; print_r($a_pagelist); print "</pre>";
222 $a_sitemap = ewiki_sitemap_create($wiki_entry->pagename, $a_validpages, 99, 0);
223 if ($a_pagelist) {
224 #-- create new zip file
225 #if($arctype == "ZIP"){
226 # $archivename=EWIKI_WIKIDUMP_ARCNAME."$rootid.zip";
227 # $archive = new ewiki_virtual_zip();
228 #} elseif ($arctype == "TAR") {
229 # $archivename=EWIKI_WIKIDUMP_ARCNAME."$rootid.tar";
230 # $archive = new ewiki_virtual_tarball();
231 #} else {
232 # die();
235 /// Create/Set Directory
236 $wname=clean_filename(strip_tags(format_string($wiki->name,true)));
237 if($exportdestinations) {
238 if(wiki_is_teacher($wiki)) {
239 $exportdir=$CFG->dataroot."/".$course->id."/".$exportdestinations;
240 } else {
241 add_to_log($course->id, "wiki", "hack", "", format_string($wiki->name,true).": Tried to export a wiki as non-teacher into $exportdestinations.");
242 error("You are not a teacher !");
244 } else {
245 $exportbasedir=tempnam("/tmp","WIKIEXPORT");
246 @unlink($exportbasedir);
247 @mkdir($exportbasedir);
248 /// maybe we need to check the name here...?
249 $exportdir=$exportbasedir."/".$wname;
250 @mkdir($exportdir);
251 if(!is_dir($exportdir)) {
252 error("Cannot create temporary directory $exportdir !");
256 $a_pagelist = array_unique($a_pagelist);
259 #-- convert all pages
260 foreach($a_pagelist as $pagename){
261 if ((!in_array($pagename, $a_virtual))) {
262 $id = $pagename;
263 #-- not a virtual page
264 $row = ewiki_database("GET", array("id"=>$pagename));
265 $content = "";
266 } elseif($withvirtualpages) {
267 $id = $pagename;
268 #-- is a virtual page
269 $pf = $ewiki_plugins["page"][$id];
270 $content = $pf($id, $content, "view");
271 if ($exportformats==1) {
272 $content = str_replace('$content', $content, str_replace('$title', $id, $HTML_TEMPLATE));
274 $fn = urlencode($id);
275 $fn = preg_replace(EWIKI_DUMP_FILENAME_REGEX, "", $fn);
276 $fn = $fn.$html_ext;
277 } else {
278 continue;
281 if (empty($content)){
282 switch ($row["flags"] & EWIKI_DB_F_TYPE) {
283 // Text Page
284 case (EWIKI_DB_F_TEXT):
285 #print "<pre>"; print_r($row[content]); print "\n-------------</pre>";
287 if($exportformats==1) {/// HTML-Export
288 $content = ewiki_format($row["content"]);
289 } else {
290 $content = $row["content"];
293 # Binary files link adjustment when html
294 if($exportformats==1) {
295 $content = str_replace($a_images, $a_rimages, $content);
298 $fn = preg_replace(EWIKI_DUMP_FILENAME_REGEX, "", urlencode($id));
299 $fn = $fn.$html_ext;
300 if($exportformats==1) {/// HTML-Export
301 $content = str_replace('$content', $content, str_replace('$title', $id, $HTML_TEMPLATE));
303 break;
304 case (EWIKI_DB_F_BINARY):
305 #print "Binary: $row[id]<br />";
306 if (($row["meta"]["class"]=="image" || $row["meta"]["class"]=="file") && ($exportbinaries)) {
307 # Copy files to the appropriate directory
308 $fn= moodle_binary_get_path($id, $row["meta"], $course, $wiki, $userid, $groupid);
309 $destfn=clean_filename(substr($id,strlen(EWIKI_IDF_INTERNAL)));
310 $dest="$exportdir/".$destfn;
311 if(!copy($fn,$dest)) {
312 notify("Cannot copy $fn to $dest.");
315 #$fn = urlencode(preg_replace(EWIKI_DUMP_FILENAME_REGEX, "", $id));
316 #$content = &$row["content"];
317 $filestozip[]=$exportdir."/".$destfn;
318 continue (2);
320 else {
321 #-- php considers switch statements as loops so continue 2 is needed to
322 #-- hit the end of the for loop
323 continue(2);
325 break;
327 default:
328 # don't want it
329 continue(2);
333 # Do not translate links when wiki already in pure html - mode
334 if($wiki->htmlmode!=2) {
335 $content=preg_replace_callback(
336 '/(<a href=")(.*?)(\.html">)/',
337 create_function(
338 // single quotes are essential here,
339 // or alternative escape all $ as \$
340 '$matches',
341 'return($matches[1].preg_replace(EWIKI_DUMP_FILENAME_REGEX,"",$matches[2]).$matches[3]);'
343 $content
346 #-- add file
347 // Let's make sure the file exists and is writable first.
348 if (!$handle = fopen($exportdir."/".$fn, 'w')) {
349 error("Cannot open file ($exportdir/$fn)");
352 // Write $content to our opened file.
353 if (fwrite($handle, $content) === FALSE) {
354 error("Cannot write to file ($exportdir/$fn)");
357 fclose($handle);
358 $filestozip[]=$exportdir."/".$fn;
359 #$archive->add($content, $fn, array(
360 # "mtime" => $row["lastmodified"],
361 # "uname" => "ewiki",
362 # "mode" => 0664 | (($row["flags"]&EWIKI_DB_F_WRITEABLE)?0002:0000),
363 # ), $complevel);
366 #-- create index page
367 /// HTML-Export
368 if($exportformats==1) {
369 $timer=array();
370 $level=-1;
371 $fordump=1;
372 $str_formatted="<ul>\n<li><a href=\"".($wiki_entry->pagename).$html_ext."\">".($wiki_entry->pagename)."</a></li>";
373 $fin_level=format_sitemap($a_sitemap, ($wiki_entry->pagename), $str_formatted, $level, $timer, $fordump);
374 $str_formatted.="</ul>".str_pad("", $fin_level*6, "</ul>\n");
375 $str_formatted=preg_replace_callback(
376 '/(<a href=")(.*?)(\.html">)/',
377 create_function(
378 // single quotes are essential here,
379 // or alternative escape all $ as \$
380 '$matches',
381 'return($matches[1].preg_replace(EWIKI_DUMP_FILENAME_REGEX,"",$matches[2]).$matches[3]);'
383 $str_formatted
385 $str_formatted = str_replace('$content', $str_formatted, str_replace('$title', get_string("index","wiki"), $HTML_TEMPLATE));
386 #-- add file
387 // Let's make sure the file exists and is writable first.
388 $indexname="index".$html_ext;
389 if (!$handle = fopen($exportdir."/".$indexname, 'w')) {
390 error("Cannot open file ($exportdir/$indexname)");
393 // Write $somecontent to our opened file.
394 if (fwrite($handle, $str_formatted) === FALSE) {
395 error("Cannot write to file ($exportdir/$indexname)");
398 fclose($handle);
399 $filestozip[]=$exportdir."/".$indexname;
401 #-- add index page
402 # $archive->add($str_formatted, "Index_$rootid".$html_ext, array(
403 # "mtime" => $row["lastmodified"],
404 # "uname" => "ewiki",
405 # "mode" => 0664 | (($row["flags"]&EWIKI_DB_F_WRITEABLE)?0002:0000),
406 # ), $complevel);
409 if(!$exportdestinations) {
410 $archivename=$wname.".zip";
411 zip_files($filestozip, "$exportbasedir/$archivename");
413 #-- Headers
414 Header("Content-type: application/zip");
415 Header("Content-disposition: attachment; filename=\"$archivename\"");
416 Header("Cache-control: private");
417 Header("Original-Filename: $archivename");
418 Header("X-Content-Type: application/zip");
419 Header("Content-Location: $archivename");
420 if(!@readfile("$exportbasedir/$archivename")) {
421 error("Cannot read $exportbasedir/$archivename");
423 if(!deldir($exportbasedir)) {
424 error("Cannot delete $exportbasedir");
426 #exit();
427 return false;
428 } else {
429 return get_string("exportsuccessful","wiki")."<br />";
434 function deldir($dir)
436 $handle = opendir($dir);
437 while (false!==($FolderOrFile = readdir($handle)))
439 if($FolderOrFile != "." && $FolderOrFile != "..")
441 if(is_dir("$dir/$FolderOrFile"))
442 { deldir("$dir/$FolderOrFile"); } // recursive
443 else
444 { unlink("$dir/$FolderOrFile"); }
447 closedir($handle);
448 if(rmdir($dir))
449 { $success = true; }
450 return $success;