3 * This script tries to find the temp folder and unzip all setup files into.
6 * @copyright 2001-2013 WoltLab GmbH
7 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
10 define('INSTALL_SCRIPT', __FILE__
);
11 define('INSTALL_SCRIPT_DIR', dirname(__FILE__
).'/');
12 define('SETUP_FILE', INSTALL_SCRIPT_DIR
. 'WCFSetup.tar.gz');
13 define('NO_IMPORTS', 1);
15 // set exception handler
16 set_exception_handler('handleException');
17 // set php error handler
18 set_error_handler('handleError', E_ALL
);
20 // define list of needed file
21 $neededFilesPattern = array(
23 '!^install/files/acp/images/wcfLogo.*!',
24 '!^install/files/acp/style/setup/.*!',
25 '!^install/files/lib/data/.*!',
26 '!^install/files/icon/.*!',
27 '!^install/files/font/.*!',
28 '!^install/files/lib/system/.*!',
29 '!^install/files/lib/util/.*!',
31 '!^install/packages/.*!');
33 // define needed functions and classes
35 * WCF::handleException() calls the show method on exceptions that implement this interface.
37 * @package com.woltlab.wcf.system.exception
40 interface IPrintableException
{
41 public function show();
44 // define needed classes
46 // SystemException, PrintableException, BasicFileUtil, Tar, File, ZipFile
48 * A SystemException is thrown when an unexpected error occurs.
50 * @package com.woltlab.wcf.system.exception
53 class SystemException
extends \Exception
implements IPrintableException
{
54 protected $description;
55 protected $information = '';
56 protected $functions = '';
59 * Creates a new SystemException.
61 * @param message string error message
62 * @param code integer error code
63 * @param description string description of the error
65 public function __construct($message = '', $code = 0, $description = '') {
66 parent
::__construct($message, $code);
67 $this->description
= $description;
71 * Returns the description of this exception.
75 public function getDescription() {
76 return $this->description
;
80 * Prints this exception.
81 * This method is called by WCF::handleException().
83 public function show() {
87 <title
>Fatal error
: <?php
echo htmlspecialchars($this->getMessage()); ?
></title
>
89 <style type
="text/css">
91 font
-family
: Verdana
, Helvetica
, sans
-serif
;
95 border
: 1px outset lightgrey
;
97 background
-color
: lightgrey
;
101 border
: 1px inset lightgrey
;
106 background
-color
: #154268;
125 <h1
>Fatal error
: <?php
echo htmlspecialchars($this->getMessage()); ?
></h1
>
128 <p
><?php
echo $this->getDescription(); ?
></p
>
129 <?php
if ($this->getCode()) { ?
><p
>You get more information about the problem in our knowledge base
: <a href
="http://www.woltlab.com/help/?code=<?php echo intval($this->getCode()); ?>">http
://www.woltlab.com/help/?code=<?php echo intval($this->getCode()); ?></a></p><?php } ?>
131 <h2
>Information
:</h2
>
133 <b
>error message
:</b
> <?php
echo htmlspecialchars($this->getMessage()); ?
><br
/>
134 <b
>error code
:</b
> <?php
echo intval($this->getCode()); ?
><br
/>
135 <?php
echo $this->information
; ?
>
136 <b
>file
:</b
> <?php
echo htmlspecialchars($this->getFile()); ?
> (<?php
echo $this->getLine(); ?
>)<br
/>
137 <b
>php version
:</b
> <?php
echo htmlspecialchars(phpversion()); ?
><br
/>
138 <b
>wcf version
:</b
> <?php
if (defined('WCF_VERSION')) echo WCF_VERSION
; ?
><br
/>
139 <b
>date
:</b
> <?php
echo gmdate('r'); ?
><br
/>
140 <b
>request
:</b
> <?php
if (isset($_SERVER['REQUEST_URI'])) echo htmlspecialchars($_SERVER['REQUEST_URI']); ?
><br
/>
141 <b
>referer
:</b
> <?php
if (isset($_SERVER['HTTP_REFERER'])) echo htmlspecialchars($_SERVER['HTTP_REFERER']); ?
><br
/>
145 <pre
><?php
echo htmlspecialchars($this->getTraceAsString()); ?
></pre
>
148 <?php
echo $this->functions
; ?
>
159 * Loads the required classes automatically.
161 function __autoload($className) {
162 $namespaces = explode('\\', $className);
163 if (count($namespaces) > 1) {
164 // remove 'wcf' component
165 array_shift($namespaces);
167 $className = implode('/', $namespaces);
168 $classPath = TMP_DIR
. 'install/files/lib/' . $className . '.class.php';
169 if (file_exists($classPath)) {
170 require_once($classPath);
176 * Escapes strings for execution in sql queries.
178 function escapeString($string) {
179 return \wcf\system\WCF
::getDB()->escapeString($string);
183 * Calls the show method on the given exception.
185 * @param Exception $e
187 function handleException(\Exception
$e) {
188 if ($e instanceof IPrintableException ||
$e instanceof \wcf\system\exception\IPrintableException
) {
197 * Catches php errors and throws instead a system exception.
199 * @param integer $errorNo
200 * @param string $message
201 * @param string $filename
202 * @param integer $lineNo
204 function handleError($errorNo, $message, $filename, $lineNo) {
205 if (error_reporting() != 0) {
208 case 2: $type = 'warning';
210 case 8: $type = 'notice';
214 throw new SystemException('PHP '.$type.' in file '.$filename.' ('.$lineNo.'): '.$message, 0);
219 * BasicFileUtil contains file-related functions.
221 * @package com.woltlab.wcf.util
222 * @author Marcel Werk
224 class BasicFileUtil
{
229 protected static $mode = null;
232 * Tries to find the temp folder.
236 public static function getTempFolder() {
237 // use tmp folder in document root by default
238 if (!empty($_SERVER['DOCUMENT_ROOT'])) {
239 if (strpos($_SERVER['DOCUMENT_ROOT'], 'strato') !== false) {
241 // create tmp folder in document root automatically
242 if (!@file_exists
($_SERVER['DOCUMENT_ROOT'].'/tmp')) {
243 @mkdir
($_SERVER['DOCUMENT_ROOT'].'/tmp/', 0777);
245 self
::makeWritable($_SERVER['DOCUMENT_ROOT'].'/tmp/');
247 catch (SystemException
$e) {}
250 if (@file_exists
($_SERVER['DOCUMENT_ROOT'].'/tmp') && @is_writable
($_SERVER['DOCUMENT_ROOT'].'/tmp')) {
251 return $_SERVER['DOCUMENT_ROOT'].'/tmp/';
255 if (isset($_ENV['TMP']) && @is_writable
($_ENV['TMP'])) {
256 return $_ENV['TMP'] . '/';
258 if (isset($_ENV['TEMP']) && @is_writable
($_ENV['TEMP'])) {
259 return $_ENV['TEMP'] . '/';
261 if (isset($_ENV['TMPDIR']) && @is_writable
($_ENV['TMPDIR'])) {
262 return $_ENV['TMPDIR'] . '/';
265 if (($path = ini_get('upload_tmp_dir')) && @is_writable
($path)) {
268 if (@file_exists
('/tmp/') && @is_writable
('/tmp/')) {
271 if (function_exists('session_save_path') && ($path = session_save_path()) && @is_writable
($path)) {
275 $path = INSTALL_SCRIPT_DIR
.'tmp/';
276 if (@file_exists
($path) && @is_writable
($path)) {
280 throw new SystemException('There is no access to the system temporary folder due to an unknown reason and no user specific temporary folder exists in '.INSTALL_SCRIPT_DIR
.'! This is a misconfiguration of your webserver software! Please create a folder called '.$path.' using your favorite ftp program, make it writable and then retry this installation.');
285 * Returns the temp folder for the installation.
289 public static function getInstallTempFolder() {
290 $dir = self
::getTempFolder() . TMP_FILE_PREFIX
. '/';
292 self
::makeWritable($dir);
298 * Tries to make a file or directory writable. It starts of with the least
299 * permissions and goes up until 0666 for files and 0777 for directories.
301 * @param string $filename
303 public static function makeWritable($filename) {
304 if (!file_exists($filename)) {
309 if (self
::$mode === null) {
310 // do not use PHP_OS here, as this represents the system it was built on != running on
311 if (strpos(php_uname(), 'Windows') !== false) {
317 $tmpFilename = '__permissions_'.sha1(time()).'.txt';
318 @touch
($tmpFilename);
320 // create a new file and check the file owner, if it is the same
321 // as this file (uploaded through FTP), we can safely grant write
322 // permissions exclusively to the owner rather than everyone
323 if (file_exists($tmpFilename)) {
324 $scriptOwner = fileowner(__FILE__
);
325 $fileOwner = fileowner($tmpFilename);
327 if ($scriptOwner === $fileOwner) {
331 @unlink
($tmpFilename);
337 if (is_dir($filename)) {
338 if (self
::$mode == 0644) {
339 @chmod
($filename, 0755);
342 @chmod
($filename, 0777);
346 @chmod
($filename, self
::$mode);
349 if (!is_writable($filename)) {
350 throw new SystemException("Unable to make '".$filename."' writable. This is a misconfiguration of your server, please contact your system administrator or hosting provider.");
356 * Opens tar or tar.gz archives.
360 * $tar = new Tar('archive.tar');
361 * $contentList = $tar->getContentList();
362 * foreach ($contentList as $key => $val) {
363 * $tar->extract($key, DESTINATION);
367 protected $archiveName = '';
368 protected $contentList = array();
369 protected $opened = false;
370 protected $read = false;
371 protected $file = null;
372 protected $isZipped = false;
373 protected $mode = 'rb';
376 * Creates a new Tar object.
377 * archiveName must be tarball or gzipped tarball
379 * @param string $archiveName
381 public function __construct($archiveName) {
382 if (!is_file($archiveName)) {
383 throw new SystemException("unable to find tar archive '".$archiveName."'");
386 $this->archiveName
= $archiveName;
388 $this->readContent();
392 * Destructor of this class, closes tar archive.
394 public function __destruct() {
399 * Opens the tar archive and stores filehandle.
401 public function open() {
402 if (!$this->opened
) {
403 if ($this->isZipped
) $this->file
= new ZipFile($this->archiveName
, $this->mode
);
406 $this->file
= new File($this->archiveName
, $this->mode
);
407 if ($this->file
->read(2) == "\37\213") {
408 $this->file
->close();
409 $this->isZipped
= true;
410 $this->file
= new ZipFile($this->archiveName
, $this->mode
);
413 $this->file
->seek(0);
416 $this->opened
= true;
421 * Closes the opened file.
423 public function close() {
425 $this->file
->close();
426 $this->opened
= false;
431 * Returns the table of contents (TOC) list for this tar archive.
433 * @return array list of content
435 public function getContentList() {
438 $this->readContent();
440 return $this->contentList
;
444 * Returns an associative array with information
445 * about a specific file in the archive.
447 * @param mixed $fileindex index or name of the requested file
448 * @return array $fileInfo
450 public function getFileInfo($fileIndex) {
451 if (!is_int($fileIndex)) {
452 $fileIndex = $this->getIndexByFilename($fileIndex);
455 if (!isset($this->contentList
[$fileIndex])) {
456 throw new SystemException("Tar: could find file '".$fileIndex."' in archive");
458 return $this->contentList
[$fileIndex];
462 * Searchs a file in the tar archive
463 * and returns the numeric fileindex.
464 * Returns false if not found.
466 * @param string $filename
467 * @return integer index of the requested file
469 public function getIndexByFilename($filename) {
470 foreach ($this->contentList
as $index => $file) {
471 if ($file['filename'] == $filename) {
479 * Extracts a specific file and returns the content as string.
480 * Returns false if extraction failed.
482 * @param mixed $index index or name of the requested file
483 * @return string content of the requested file
485 public function extractToString($index) {
488 $this->readContent();
490 $header = $this->getFileInfo($index);
492 // can not extract a folder
493 if ($header['type'] != 'file') {
498 $this->file
->seek($header['offset']);
502 $n = floor($header['size'] / 512);
503 for($i = 0; $i < $n; $i++
) {
504 $content .= $this->file
->read(512);
506 if(($header['size'] %
512) != 0) {
507 $buffer = $this->file
->read(512);
508 $content .= substr($buffer, 0, ($header['size'] %
512));
515 * Extracts a specific file and writes it's content
516 * to the file specified with $destination.
518 * @param mixed $index index or name of the requested file
519 * @param string $destination
520 * @return boolean $success
522 public function extract($index, $destination) {
525 $this->readContent();
527 $header = $this->getFileInfo($index);
529 // can not extract a folder
530 if ($header['type'] != 'file') {
535 $this->file
->seek($header['offset']);
537 $targetFile = new File($destination);
540 $n = floor($header['size'] / 512);
541 for ($i = 0; $i < $n; $i++
) {
542 $content = $this->file
->read(512);
543 $targetFile->write($content, 512);
545 if (($header['size'] %
512) != 0) {
546 $content = $this->file
->read(512);
547 $targetFile->write($content, ($header['size'] %
512));
550 $targetFile->close();
551 BasicFileUtil
::makeWritable($destination);
553 if ($header['mtime']) {
554 @$targetFile->touch($header['mtime']);
558 if (filesize($destination) != $header['size']) {
559 throw new SystemException("Could not untar file '".$header['filename']."' to '".$destination."'. Maybe disk quota exceeded in folder '".dirname($destination)."'.");
566 * Reads table of contents (TOC) from tar archive.
567 * This does not get the entire to memory but only parts of it.
569 protected function readContent() {
570 $this->contentList
= array();
574 // Read the 512 bytes header
575 while (strlen($binaryData = $this->file
->read(512)) != 0) {
577 $header = $this->readHeader($binaryData);
578 if ($header === false) {
581 $this->contentList
[$i] = $header;
582 $this->contentList
[$i]['index'] = $i;
585 $this->file
->seek($this->file
->tell() +
(512 * ceil(($header['size'] / 512))));
590 * Unpacks file header for one file entry.
592 * @param string $binaryData
593 * @return array $fileheader
595 protected function readHeader($binaryData) {
596 if (strlen($binaryData) != 512) {
602 // First part of the header
603 for ($i = 0; $i < 148; $i++
) {
604 $checksum +
= ord(substr($binaryData, $i, 1));
606 // Calculate the checksum
607 // Ignore the checksum value and replace it by ' ' (space)
608 for ($i = 148; $i < 156; $i++
) {
609 $checksum +
= ord(' ');
611 // Last part of the header
612 for ($i = 156; $i < 512; $i++
) {
613 $checksum +
= ord(substr($binaryData, $i, 1));
616 // Extract the values
617 //$data = unpack("a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1typeflag/a100link/a6magic/a2version/a32uname/a32gname/a8devmajor/a8devminor", $binaryData);
618 $data = unpack("a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1typeflag/a100link/a6magic/a2version/a32uname/a32gname/a8devmajor/a8devminor/a155prefix", $binaryData);
620 // Extract the properties
621 $header['checksum'] = octDec(trim($data['checksum']));
622 if ($header['checksum'] == $checksum) {
623 $header['filename'] = trim($data['filename']);
624 $header['mode'] = octDec(trim($data['mode']));
625 $header['uid'] = octDec(trim($data['uid']));
626 $header['gid'] = octDec(trim($data['gid']));
627 $header['size'] = octDec(trim($data['size']));
628 $header['mtime'] = octDec(trim($data['mtime']));
629 $header['prefix'] = trim($data['prefix']);
630 if ($header['prefix']) {
631 $header['filename'] = $header['prefix'].'/'.$header['filename'];
633 if (($header['typeflag'] = $data['typeflag']) == '5') {
635 $header['type'] = 'folder';
638 $header['type'] = 'file';
640 $header['offset'] = $this->file
->tell();
651 * The File class handles all file operations.
654 * using php functions:
655 * $fp = fopen('filename', 'wb');
656 * fwrite($fp, '...');
660 * $file = new File('filename');
661 * $file->write('...');
664 * @author Marcel Werk
667 protected $resource = null;
673 * @param string $filename
674 * @param string $mode
676 public function __construct($filename, $mode = 'wb') {
677 $this->filename
= $filename;
678 $this->resource = fopen($filename, $mode);
679 if ($this->resource === false) {
680 throw new SystemException('Can not open file ' . $filename);
685 * Calls the specified function on the open file.
686 * Do not call this function directly. Use $file->write('') instead.
688 * @param string $function
689 * @param array $arguments
691 public function __call($function, $arguments) {
692 if (function_exists('f' . $function)) {
693 array_unshift($arguments, $this->resource);
694 return call_user_func_array('f' . $function, $arguments);
696 else if (function_exists($function)) {
697 array_unshift($arguments, $this->filename
);
698 return call_user_func_array($function, $arguments);
701 throw new SystemException('Can not call file method ' . $function);
707 * The File class handles all file operations on a zipped file.
709 * @author Marcel Werk
711 class ZipFile
extends File
{
713 * Opens a new zipped file.
715 * @param string $filename
716 * @param string $mode
718 public function __construct($filename, $mode = 'wb') {
719 $this->filename
= $filename;
720 if (!function_exists('gzopen')) {
721 throw new SystemException('Can not find functions of the zlib extension');
723 $this->resource = @gzopen
($filename, $mode);
724 if ($this->resource === false) {
725 throw new SystemException('Can not open file ' . $filename);
730 * Calls the specified function on the open file.
732 * @param string $function
733 * @param array $arguments
735 public function __call($function, $arguments) {
736 if (function_exists('gz' . $function)) {
737 array_unshift($arguments, $this->resource);
738 return call_user_func_array('gz' . $function, $arguments);
740 else if (function_exists($function)) {
741 array_unshift($arguments, $this->filename
);
742 return call_user_func_array($function, $arguments);
745 throw new SystemException('Can not call method ' . $function);
750 * Returns the filesize of the unzipped file
752 public function getFileSize() {
756 // the correction is for zip files that are too small
757 // to get in the first while loop
759 while ($this->seek($eof) == 0) {
764 while ($byteBlock > 1) {
766 $eof +
= $byteBlock * ($this->seek($eof) ?
-1 : 1);
769 if ($this->seek($eof) == -1) $eof -= 1;
772 return $eof - $correction;
777 // get temp file prefix
778 if (isset($_REQUEST['tmpFilePrefix'])) {
779 $prefix = preg_replace('/[^a-f0-9_]+/', '', $_REQUEST['tmpFilePrefix']);
782 $prefix = substr(sha1(uniqid(microtime())), 0, 8);
784 define('TMP_FILE_PREFIX', $prefix);
786 // try to find the temp folder
787 define('TMP_DIR', BasicFileUtil
::getInstallTempFolder());
790 * Reads a file resource from temp folder.
793 * @param string $directory
795 function readFileResource($key, $directory) {
796 if (preg_match('~[\w\-]+\.(css|jpg|png|svg|eot|woff|ttf)~', $_GET[$key], $match)) {
799 header('Content-Type: text/css');
803 header('Content-Type: image/jpg');
807 header('Content-Type: image/png');
811 header('Content-Type: image/svg+xml');
815 header('Content-Type: application/vnd.ms-fontobject');
819 header('Content-Type: application/font-woff');
823 header('Content-Type: application/octet-stream');
827 header('Expires: '.gmdate('D, d M Y H:i:s', time() +
3600).' GMT');
828 header('Last-Modified: Mon, 26 Jul 1997 05:00:00 GMT');
829 header('Cache-Control: public, max-age=3600');
831 readfile($directory . $_GET[$key]);
836 // show image from temp folder
837 if (isset($_GET['showImage'])) {
838 readFileResource('showImage', TMP_DIR
. 'install/files/acp/images/');
840 // show icon from temp folder
841 if (isset($_GET['showIcon'])) {
842 readFileResource('showIcon', TMP_DIR
. 'install/files/icon/');
844 // show css from temp folder
845 if (isset($_GET['showCSS'])) {
846 readFileResource('showCSS', TMP_DIR
. 'install/files/acp/style/setup/');
848 // show fonts from temp folder
849 if (isset($_GET['showFont'])) {
850 readFileResource('showFont', TMP_DIR
. 'install/files/font/');
853 // check whether setup files are already unzipped
854 if (!file_exists(TMP_DIR
. 'install/files/lib/system/WCFSetup.class.php')) {
855 // try to unzip all setup files into temp folder
856 $tar = new Tar(SETUP_FILE
);
857 $contentList = $tar->getContentList();
858 if (empty($contentList)) {
859 throw new SystemException("Can not unpack 'WCFSetup.tar.gz'. File is probably broken.");
862 foreach ($contentList as $file) {
863 foreach ($neededFilesPattern as $pattern) {
864 if (preg_match($pattern, $file['filename'])) {
865 // create directory if not exists
866 $dir = TMP_DIR
. dirname($file['filename']);
867 if (!@is_dir
($dir)) {
868 @mkdir
($dir, 0777, true);
869 BasicFileUtil
::makeWritable($dir);
872 $tar->extract($file['index'], TMP_DIR
. $file['filename']);
878 // create cache folders
879 @mkdir
(TMP_DIR
. 'setup/lang/cache/', 0777);
880 BasicFileUtil
::makeWritable(TMP_DIR
. 'setup/lang/cache/');
882 @mkdir
(TMP_DIR
. 'setup/template/compiled/', 0777);
883 BasicFileUtil
::makeWritable(TMP_DIR
. 'setup/template/compiled/');
886 if (!class_exists('wcf\system\WCFSetup')) {
887 throw new SystemException("Can not find class 'WCFSetup'");
891 new \wcf\system\
WCFSetup();