1<?php
2
3	if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../../../').'/');
4	if(!defined('NL')) define('NL',"\n");
5	if(!defined('EPUB_DIR')) define('EPUB_DIR',realpath(dirname(__FILE__).'/../').'/');
6	require_once(DOKU_INC.'inc/init.php');
7	require_once(EPUB_DIR.'scripts/epub_utils.php');
8	global $entities;
9	$entities = unserialize(file_get_contents(EPUB_DIR . 'scripts/epub_ents.ser'));
10
11	class epub_creator {
12		private $_renderer;
13		function create($id, $user_title=false) {
14
15            ob_start();
16            $id = ltrim($id, ':');
17            $id = ":$id";
18            $namespace= getNS($id);
19            epub_save_namespace($namespace);
20            $mode ='epub';
21            $Renderer =& plugin_load('renderer',$mode);
22            $Renderer->set_oebps() ;
23            $Renderer->set_current_page(epub_clean_name(str_replace(':', '_', $id)) . '.html') ;
24            $this->_renderer = $Renderer;
25            if(is_null($Renderer)){
26                msg("No renderer for $mode found",-1);
27                exit;
28            }
29
30
31			global $ID;
32			$oldID = $ID;
33
34			$ID = cleanID($id);
35
36			$wiki_file = wikiFN($id);
37			if(!file_exists($wiki_file)) {
38                 epub_push_spine(array("",""));
39			     echo htmlentities($id) . " not found\n";
40				 return false;
41			}
42            epub_update_progress("reading $id");
43			$instructions = p_cached_instructions($wiki_file, false, $id);
44			if(is_null($instructions)) return '';
45
46
47			$Renderer->notoc();
48			$Renderer->smileys = getSmileys();
49			$Renderer->entities = getEntities();
50			$Renderer->acronyms = array();
51			$Renderer->interwiki = getInterwiki();
52			epub_update_progress("rendering $id,  this could take some time");
53			// Loop through the instructions
54			foreach ( $instructions as $instruction ) {
55				// Execute the callback against the Renderer
56				call_user_func_array(array(&$Renderer, $instruction[0]),$instruction[1]);
57			}
58			$result = "";
59            $result .='<?xml version="1.0" encoding="utf-8"?>
60            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
61            "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">';
62			$result .= '<html xmlns="http://www.w3.org/1999/xhtml">' . "\n";
63			$result .= "\n<head>\n";
64			$result .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>' ."\n";
65			$result .= '<link rel="stylesheet"  type="text/css" href="../Styles/style.css"/>';
66            epub_check_for_mathjax($result);
67			$result .= "\n<title>";
68			$result .= "</title>\n</head><body>\n";
69			$result .= "<div class='dokuwiki'>\n";
70			$info = $Renderer->info;
71			$data = array($mode,& $Renderer->doc);
72			trigger_event('RENDERER_CONTENT_POSTPROCESS',$data);
73
74			$xhtml = $Renderer->doc;
75			$result .= $xhtml;
76            //handle image maps
77            if(strpos($result, 'usemap') !== false) {
78            $R = $Renderer;
79			$result = preg_replace_callback(
80                     '|<img\s+src=\"(.*?)\"(.*?usemap.*?)>|im',
81				   function($matches)  use($R) {
82                   if(strpos( $matches[1],'?') !== false) {
83                       list($pre, $img) = explode('=', $matches[1]);
84                   }
85                   else $img =  basename($matches[1]);
86
87                    $name = '../'. $R->copy_media($img);
88                    echo "Map image name = $name\n";
89                      return '<img src="' . $name . '"' . $matches[2] . '>';
90					},
91					$result
92                   );
93             //Convert internal links to localized epub links
94			$result = preg_replace_callback(
95                     '|<area(.*?)>|im',
96                   function($matches) {
97					   if(strpos($matches[0], 'http') !== false) return $matches[0];  	//External link, no conversioon needed
98					   $matches[0]= preg_replace_callback(
99					      '|href\s*=\s*([\"\'])(.*?)\1|m',     //test $matches[0]
100					      function($m) {
101							  if(stripos($m[0],'javascript:') !== false) {
102							     return $m[0];   // we do no convert javascript links
103							  }
104                            $patterns = array('!^' . preg_quote(DOKU_BASE) . '!', "/^doku.php/","!^\?\s*id\s*=\s*!");
105                            $_REQUEST['epubid'] = preg_replace($patterns,  "", $m[2]);
106                            $id = getID('epubid') . '.html' ;
107                            $id = "../Text/" . str_replace(':','_',$id) ;
108                            echo "revised url: " . htmlentities($id)."\n";
109                            return "href='$id'";
110						  },$matches[0]);
111					   return $matches[0];
112				   }, $result
113
114                  );
115
116            }
117			$result .= "\n</div></body></html>\n";
118			$result =  preg_replace_callback("/&(\w+);/m", "epbub_entity_replace", $result );
119			$result = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/m", "\n", $result);
120			$result = preg_replace("/^\s+/m", "", $result );
121			$result = preg_replace_callback(
122			                          '|<p>([\s\n]*)(.*?<div.*?/div>.*?)([\s\n])*<\/p>|im',
123									   function($matches) {
124											$result = $matches[1] . $matches[2] . $matches[3];
125											//echo "$result\n";
126											return $result;
127										},
128										$result
129                            );
130
131            ob_end_flush();
132            if($user_title) {
133                $id = 'title.html';
134            }
135            else {
136            $id = epub_clean_name(str_replace(':', '_', $id)) . '.html';
137               }
138             io_saveFile(epub_get_oebps() ."Text/$id",$result);
139
140			if($user_title) {
141			    epub_write_zip('Text/title.html');
142                $ID = $oldID;
143				return true;
144			}
145			$item_num=epub_write_item("Text/$id", "application/xhtml+xml");
146			epub_push_spine(array("Text/$id",$item_num));
147            epub_save_namespace();
148
149			$ID = $oldID;
150
151			return true;
152		}
153
154		function get_renderer	() {
155			return $this->_renderer;
156		}
157
158
159	}
160
161           global $INPUT;
162            // $epub_ids = 'ditaa:win_filebrowser;;introduction;;v06;;features;;index:site_inx';
163            if(isset ($_POST['epub_ids'])) $epub_ids = rawurldecode($INPUT->post->str('epub_ids'));
164            if(isset ($_POST['epub_titles'])) $e_titles = rawurldecode($INPUT->post->str('epub_titles'));
165			$epub_pages =  explode(';;',$epub_ids) ;
166            $epub_titles = explode(';;',$e_titles) ;
167            $epub_user_title = strpos($epub_pages[0], 'title') !== false ? true: false;
168	   	    epub_setup_book_skel($epub_user_title) ;
169            epub_opf_header($epub_user_title);
170            if($epub_user_title) {
171                $creator = new epub_creator();
172                $creator->create($epub_pages[0], $epub_user_title);
173                array_shift($epub_pages);
174                echo "processed: title page \n";
175            }
176            else {
177                array_unshift($epub_titles, 'Title Page');
178            }
179            epub_checkfor_ns($epub_pages[0],$epub_pages, $epub_titles);
180            array_push($epub_titles,"Footnotes");
181            epub_titlesStack($epub_titles);
182            $page_num = 0;
183            $creator = false;
184            foreach($epub_pages as $page) {
185                epub_update_progress("processing: $page");
186                $creator = new epub_creator();
187                if($creator->create($page)) {
188                if(isset ($_POST['epub_ids']))
189                    echo rawurlencode("processed: $page \n");
190                        else
191                        echo "processed: $page \n";
192                }
193            }
194
195            if(epub_footnote_handle(true)) {
196				epub_close_footnotes();
197			}
198
199            epub_css($creator);
200            epub_write_item('Styles/style.css',"text/css");
201            epub_opf_write('</manifest>');
202            epub_write_spine();
203            epub_write_footer();
204            epub_write_ncx();
205            epub_finalize_zip() ;
206            epub_update_progress("packing  ebook");
207            epub_pack_book();
208		    epub_update_progress();  // deletes progress file
209
210
211			exit;
212