xref: /plugin/siteexport/inc/filewriter.php (revision 82618ac8ab56a7f512fa69d40e531cc34cb40578)
1<?php
2
3if(!defined('DOKU_PLUGIN')) die('meh');
4require_once(DOKU_PLUGIN.'siteexport/inc/pdfgenerator.php');
5
6class siteexport_zipfilewriter
7{
8    /**
9     * further classes
10     */
11    private $pdfGenerator = false;
12    private $functions = null;
13
14    public function siteexport_zipfilewriter( $functions = null )
15    {
16        $this->functions = $functions;
17        if ( class_exists( 'siteexport_pdfgenerator' ) )
18        {
19            $this->pdfGenerator = new siteexport_pdfgenerator($functions);
20        }
21    }
22
23    public function canDoPDF()
24    {
25        return $this->pdfGenerator !== false;
26    }
27
28
29    /**
30     * Wrapper for fetching the Context or the TOC for Eclipse Documentation
31     * This also puts the file into the zip package
32     **/
33    public function __moveDataToZip($DATA, $FILENAME='toc.xml') {
34
35        if ( empty($DATA) ) { return false; }
36
37        $tmpFile = tempnam($this->functions->settings->tmpDir , 'siteexport__');
38
39        $fp = fopen( $tmpFile, "w");
40        if(!$fp) return false;
41
42        fwrite($fp,$DATA);
43        fclose($fp);
44
45        // Add to zip
46        $status = $this->__addFileToZip($tmpFile, $FILENAME);
47        @unlink($tmpFile);
48
49        return true;
50    }
51
52    /**
53     * Adds a file to the zip file
54     * @param $FILE file-name of the zip
55     * @param $NAME name of the file that is being added
56     * @param $ZIP name of the zip file to which we add
57     */
58    function __addFileToZip($FILE, $NAME, $ZIP=null) {
59
60        if ( $NAME[0] === "/" ) {
61            $this->functions->debug->message("Weird, the NAME for the ZIP started with a '/'. This may result in wrong links!", null, 3);
62            $NAME = substr($NAME, 1);
63        }
64
65        // check for mpdf
66        if ( $this->canDoPDF() ) {
67            $this->functions->debug->message("Trying to create PDF from File '$FILE' with name '$NAME' for ZIP '$ZIP'", null, 2);
68
69            if ( $this->functions->debug->debugLevel() <= 1 ) { // 2011-01-12 Write HTML to ZIP for Debug purpose
70                $this->__writeFileToZip($FILE, "_debug/$NAME.html", $ZIP);
71            }
72
73            if ( !$this->pdfGenerator->createPDFFromFile($FILE, $NAME) ) {
74                $this->functions->debug->runtimeException("Create PDF from File '$FILE' with name '$NAME' went wrong and is not being added!");
75                return false;
76            }
77        }
78
79        return $this->__writeFileToZip($FILE, $NAME, $ZIP);
80    }
81
82    /**
83     * This really writes a file to a zip-file
84     * @param $FILE file-name of the zip
85     * @param $NAME name of the file that is being added
86     * @param $ZIP name of the zip file to which we add
87     */
88    private function __writeFileToZip($FILE, $NAME, $ZIP) {
89        if ( empty( $ZIP ) ) $ZIP = $this->functions->settings->zipFile;
90
91        if ( !class_exists('ZipArchive') ) {
92            $this->functions->debug->runtimeException("PHP class 'ZipArchive' does not exist. Please make sure that you have the ziplib extension for PHP installed.");
93            return false;
94        }
95
96        $zip = new ZipArchive();
97        if ( !$zip ) {
98            $this->functions->debug->runtimeException("Can't create new instance of 'ZipArchive'. Please make sure that you have the ziplib extension for PHP installed.");
99            return false;
100        }
101
102        $code = $zip->open($ZIP, ZipArchive::CREATE);
103        if ($code === TRUE) {
104
105            $this->functions->debug->message("Adding file '$NAME' to ZIP $ZIP", null, 2);
106
107            $zip->addFile($FILE, $NAME);
108            $zip->close();
109
110            // If this has worked out, we may put this version into the cache ... ?
111
112            // ALibi Touching - 2011-09-13 wird nicht gebraucht nach Umstellung
113            // io_saveFile(mediaFN($this->origZipFile), "alibi file");
114
115            return true;
116        }
117
118        $this->functions->debug->runtimeException("Zip Error #$code");
119        return false;
120    }
121
122    /**
123     * check if a file exists allready
124     * @param $NAME name of the file in the zip
125     */
126    function fileExistsInZip($NAME)
127    {
128        $zip = new ZipArchive();
129        $code = $zip->open($this->functions->settings->zipFile, ZipArchive::CREATE);
130        if ($code === TRUE) {
131            return !($zip->statName($NAME) === FALSE);
132        }
133
134        return false;
135    }
136
137    /**
138     * Checks if a valid cache file exists for the given request parameters
139     * @param $requestData
140     */
141    function hasValidCacheFile($requestData, $depends=array())
142    {
143        $pattern = $this->functions->requestParametersToCacheHash($requestData);
144        return $this->hasValidCacheFileForPattern($pattern, $depends);
145    }
146
147    private function hasValidCacheFileForPattern($pattern, $depends=array())
148    {
149        $this->functions->debug->message("HASH-Pattern for CacheFile: ", $pattern, 2);
150        $this->functions->settings->hasValidCacheFile = false; // reset the cache settings
151        $cacheFile = $this->functions->getCacheFileNameForPattern($pattern);
152
153        $mtime = @filemtime($cacheFile); // 0 if not exists
154
155        // Check if the file is expired - if so, just create a new one.
156        if ( $mtime == 0 || $mtime < time()-$this->functions->settings->cachetime )
157        {
158            @unlink($cacheFile);
159            @unlink($this->functions->settings->zipFile);
160            $this->functions->debug->message("New CacheFile because the file was over the cachetime: ", $cacheFile, 2);
161            return false;
162        }
163
164        // Check for dependencies
165        if ( !empty($depends) )
166        {
167            foreach ($depends as $site) {
168
169                if ( !page_exists($site['id']) )
170                {
171                    continue;
172                }
173
174                if ($mtime < @filemtime(wikiFN($site['id']))) {
175                    @unlink($cacheFile);
176                    @unlink($this->functions->settings->zipFile);
177                    $this->functions->debug->message("New CacheFile, because a page changed: ", $cacheFile, 2);
178                    return false;         // cache older than files it depends on?
179                }
180            }
181        }
182
183        $this->functions->debug->message("CacheFile exists: ", $cacheFile, 2);
184        return $this->functions->settings->hasValidCacheFile = true;
185    }
186
187    public function getOnlyFileInZip(&$data = null) {
188
189    	if ( is_null($data['file']) ) $data['file'] = $this->functions->settings->zipFile;
190
191	    $zip = new ZipArchive();
192	    $code = $zip->open($data['file']);
193	    if ( $code !== TRUE ) {
194            $this->functions->debug->message("Can't open the zip-file.", $data['file'], 2);
195		    return false;
196	    }
197
198		if ( $zip->numFiles != 1 ) {
199            $this->functions->debug->message("More than one ({$zip->numFiles}) file in zip.", $data['file'], 2);
200			return false;
201		}
202
203		$stat = $zip->statIndex( 0 );
204		$this->functions->debug->message("Stat.", $stat, 3);
205		if ( substr($stat['name'], -3) != 'pdf' ) {
206            $this->functions->debug->message("The file was not a PDF ({$stat['name']}).", $stat['name'], 2);
207			return false;
208		}
209
210		$data['mime'] = 'application/pdf';
211		$data['download'] = $this->functions->settings->download ? 1 : 0;
212
213		// Extract single file.
214		$folder = dirname($data['file']);
215
216		$data['orig'] = utf8_basename($stat['name']);
217		$zip->extractTo($folder, $stat['name']);
218		$zip->close();
219
220		sleep(1);
221		$data['file'] .= '.' . cleanID($data['orig']); // Wee need the other file for cache reasons.
222		@rename($folder.'/'.$data['orig'], $data['file']);
223	    return true;
224    }
225}
226
227?>