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									   create_function(
124											'$matches',
125											'$result = $matches[1] . $matches[2] . $matches[3];
126											//echo "$result\n";
127											return $result;'
128										),
129										$result
130                            );
131
132            ob_end_flush();
133            if($user_title) {
134                $id = 'title.html';
135            }
136            else {
137            $id = epub_clean_name(str_replace(':', '_', $id)) . '.html';
138               }
139             io_saveFile(epub_get_oebps() ."Text/$id",$result);
140
141			if($user_title) {
142			    epub_write_zip('Text/title.html');
143                $ID = $oldID;
144				return true;
145			}
146			$item_num=epub_write_item("Text/$id", "application/xhtml+xml");
147			epub_push_spine(array("Text/$id",$item_num));
148            epub_save_namespace();
149
150			$ID = $oldID;
151
152			return true;
153		}
154
155		function get_renderer	() {
156			return $this->_renderer;
157		}
158
159
160	}
161
162           global $INPUT;
163            // $epub_ids = 'ditaa:win_filebrowser;;introduction;;v06;;features;;index:site_inx';
164            if(isset ($_POST['epub_ids'])) $epub_ids = rawurldecode($INPUT->post->str('epub_ids'));
165            if(isset ($_POST['epub_titles'])) $e_titles = rawurldecode($INPUT->post->str('epub_titles'));
166			$epub_pages =  explode(';;',$epub_ids) ;
167            $epub_titles = explode(';;',$e_titles) ;
168            $epub_user_title = strpos($epub_pages[0], 'title') !== false ? true: false;
169	   	    epub_setup_book_skel($epub_user_title) ;
170            epub_opf_header($epub_user_title);
171            if($epub_user_title) {
172                $creator = new epub_creator();
173                $creator->create($epub_pages[0], $epub_user_title);
174                array_shift($epub_pages);
175                echo "processed: title page \n";
176            }
177            else {
178                array_unshift($epub_titles, 'Title Page');
179            }
180            epub_checkfor_ns($epub_pages[0],$epub_pages, $epub_titles);
181            array_push($epub_titles,"Footnotes");
182            epub_titlesStack($epub_titles);
183            $page_num = 0;
184            $creator = false;
185            foreach($epub_pages as $page) {
186                epub_update_progress("processing: $page");
187                $creator = new epub_creator();
188                if($creator->create($page)) {
189                if(isset ($_POST['epub_ids']))
190                    echo rawurlencode("processed: $page \n");
191                        else
192                        echo "processed: $page \n";
193                }
194            }
195
196            if(epub_footnote_handle(true)) {
197				epub_close_footnotes();
198			}
199
200            epub_css($creator);
201            epub_write_item('Styles/style.css',"text/css");
202            epub_opf_write('</manifest>');
203            epub_write_spine();
204            epub_write_footer();
205            epub_write_ncx();
206            epub_finalize_zip() ;
207            epub_update_progress("packing  ebook");
208            epub_pack_book();
209		    epub_update_progress();  // deletes progress file
210
211
212			exit;
213