source: extras/auto-install/trunk/piwigo-loader.php @ 2860

Last change on this file since 2860 was 2860, checked in by laurent_duretz, 15 years ago

Replace backslashes for Windows servers

File size: 11.2 KB
Line 
1<?php
2# -- BEGIN LICENSE BLOCK ----------------------------------
3#
4# This file is part of Piwigo.
5#
6# Copyright (c) 2003-2008 Olivier Meunier and contributors
7# Licensed under the GPL version 2.0 license.
8# See LICENSE file or
9# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
10#
11# -- END LICENSE BLOCK ------------------------------------
12
13error_reporting(E_ALL & ~E_NOTICE);
14
15if (function_exists('date_default_timezone_set')) {
16        date_default_timezone_set('UTC');
17} elseif (!ini_get('safe_mode') && function_exists('putenv')) {
18        putenv('TZ=UTC');
19}
20
21define('DC_LOADER_VERSION','0.8');
22define('DC_LOADER_SERVICE','http://piwigo.duretz.net/');
23define('DC_LOADER_ARCHIVE','http://piwigo.duretz.net/latest.zip');
24define('DC_LOADER_DIRECTORY','phpwebgallery-1.7.3');
25define('DC_LOADER_LANG', getLanguage());
26
27$can_write = is_writable(dirname(__FILE__));
28$can_fetch = false;
29if ((boolean)ini_get('allow_url_fopen')) {
30        $can_fetch = true;
31}
32if (function_exists('curl_init')) {
33        $can_fetch = true;
34        define('DC_LOADER_CURL',true);
35}
36
37$step = !empty($_REQUEST['step']) ? (integer)$_REQUEST['step'] : 1;
38$got_php5  = (strpos(PHP_VERSION,'5') === 0);
39if (!$got_php5 && $step != 2) {
40        $step = 1;
41}
42
43function __($str)
44{
45        return $str;
46}
47
48function fetchRemote($src,&$dest,$step=0) # Rudimentary HTTP client
49{
50        if ($step > 3) {
51                return false;
52        }
53       
54        $src = parse_url($src);
55        $host = $src['host'];
56        $path = $src['path'];
57       
58        if (($s = @fsockopen($host,80,$errno,$errstr,5)) === false) {
59                return false;
60        }
61       
62        fwrite($s,
63                'GET '.$path." HTTP/1.0\r\n"
64                .'Host: '.$host."\r\n"
65                ."User-Agent: Piwigo Net Install\r\n"
66                ."Accept: text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*\r\n"
67                ."\r\n"
68        );
69       
70        $i = 0;
71        $in_content = false;
72        while (!feof($s))
73        {
74                $line = fgets($s,4096);
75               
76                if (rtrim($line,"\r\n") == '' && !$in_content) {
77                        $in_content = true;
78                        $i++;
79                        continue;
80                }
81               
82                if ($i == 0) {
83                        if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/',rtrim($line,"\r\n"), $m)) {
84                                fclose($s);
85                                return false;
86                        }
87                        $status = (integer) $m[2];
88                        if ($status < 200 || $status >= 400) {
89                                fclose($s);
90                                return false;
91                        }
92                }
93               
94                if (!$in_content)
95                {
96                        if (preg_match('/Location:\s+?(.+)$/',rtrim($line,"\r\n"),$m)) {
97                                fclose($s);
98                                return fetchRemote(trim($m[1]),$dest,$step+1);
99                        }
100                        $i++;
101                        continue;
102                }
103               
104                if (is_resource($dest)) {
105                        fwrite($dest,$line);
106                } else {
107                        $dest .= $line;
108                }
109               
110                $i++;
111        }
112       
113        fclose($s);
114        return true;
115}
116
117function getLanguage($default = 'en')
118{
119        $supported = array('fr','en');
120        if (!empty($_REQUEST['lang']) && in_array($_REQUEST['lang'],$supported)) {
121                return $_REQUEST['lang'];
122        }
123        if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
124                $languages = explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
125                $l = explode(';',$languages[0]);
126                $dlang = substr(trim($l[0]),0,2);
127                if (in_array($dlang, $supported)) {
128                        return $dlang;
129                }
130        }
131        return $default;
132}
133
134function getLocation()
135{
136        $server_name = explode(':',$_SERVER['HTTP_HOST']);
137        $server_name = $server_name[0];
138        if ($_SERVER['SERVER_PORT'] == '443')
139        {
140                $scheme = 'https';
141                $port = '';
142        }
143        elseif (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')
144        {
145                $scheme = 'https';
146                $port = ($_SERVER['SERVER_PORT'] != '443') ? ':'.$_SERVER['SERVER_PORT'] : '';
147        }
148        else
149        {
150                $scheme = 'http';
151                $port = ($_SERVER['SERVER_PORT'] != '80') ? ':'.$_SERVER['SERVER_PORT'] : '';
152        }
153       
154        $loc = preg_replace('#/$#','',str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])));
155       
156        return $scheme.'://'.$server_name.$port.$loc.'/';
157}
158
159function openPage()
160{
161        header('Content-Type: text/html; charset=UTF-8');
162        echo
163        '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" '.
164        ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'."\n".
165        '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'.DC_LOADER_LANG.'" lang="'.DC_LOADER_LANG.'">'."\n".
166        "<head>\n".
167        '  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />'."\n".
168        '  <title>'.__('Piwigo NetInstall').'</title>'."\n".
169        '  <meta name="ROBOTS" content="NOARCHIVE,NOINDEX,NOFOLLOW" />'."\n".
170        '  <link rel="stylesheet" type="text/css" media="screen" href="'.DC_LOADER_SERVICE.'loader.css" />'."\n".
171        '</head>'."\n".
172        '<body>'."\n".
173        '<div id="page">'."\n".
174        '<h1>'.__('Piwigo NetInstall').'</h1>'."\n".
175        '<div id="main">'."\n";
176}
177
178function closePage()
179{
180        echo
181        '</div>'."\n".
182        '</div>'."\n".
183        '<div id="footer">'."\n".
184    '<p>This loader was initialy coded for <a href="http://www.dotclear.net" title="Dotclear">Dotclear</a>. Thanks !</p>'.
185        '</div>'."\n".
186        '</body>'."\n".
187        '</html>';
188}
189
190function initPHP5()
191{
192        $htaccess = dirname(__FILE__).'/.htaccess';
193        if (file_exists($htaccess)) {
194                if (!is_readable($htaccess) || !is_writable($htaccess)) {
195                        return false;
196                }
197        }
198        $rawdatas = '';
199        if (!fetchRemote(DC_LOADER_SERVICE.'hosting.txt',$rawdatas)) {
200                return false;
201        }
202        $rawdatas = explode("\n",$rawdatas);
203        if (!($my_hostname = @gethostbyaddr($_SERVER['SERVER_ADDR']))) {
204                return false;
205        }
206        $found = false;
207        foreach ($rawdatas as $line) {
208                list($name,$hostname,$rule) = explode('|',trim($line));
209                if (preg_match('!'.preg_quote($hostname).'$!',$my_hostname)) {
210                        $found = $rule;
211                        break;
212                }
213        }
214        if ($found) {
215                if (false !== ($fh = @fopen($htaccess,"ab"))) {
216                        fwrite($fh,"\n".$found);
217                        fclose($fh);
218                        return true;
219                }
220        }
221        return false;
222}
223
224function cleanFiles()
225{
226        unlink(dirname(__FILE__).'/pwg_files.php');
227        unlink(dirname(__FILE__).'/pwg_unzip.php');
228        unlink(dirname(__FILE__).'/piwigo-install.zip');
229}
230
231function grabFiles()
232{
233        $failed = true;
234        $lib_files = @fopen(dirname(__FILE__).'/pwg_files.php','wb');
235        $lib_unzip = @fopen(dirname(__FILE__).'/pwg_unzip.php','wb');
236        $dc_zip    = @fopen(dirname(__FILE__).'/piwigo-install.zip','wb');
237       
238        if (!$lib_files || !$lib_unzip || !$dc_zip) {
239                return false;
240        }
241       
242        if (fetchRemote(DC_LOADER_SERVICE.'lib.files.php.txt',$lib_files)) {
243                if (fetchRemote(DC_LOADER_SERVICE.'class.unzip.php.txt',$lib_unzip)) {
244                        if (fetchRemote(DC_LOADER_ARCHIVE.'',$dc_zip)) {
245                                $failed = false;
246                        }
247                }
248        }
249       
250        fclose($lib_files);
251        fclose($lib_unzip);
252        fclose($dc_zip);
253       
254        if ($failed) {
255                cleanFiles();
256                return false;
257        }
258        return true;
259}
260
261function writeMessage($level,$title,$lines)
262{
263        if (empty($lines)) {
264                return;
265        }
266       
267        echo
268        '<div class="msg '.$level.'">'.
269        '<h3>'.$title.'</h3>';
270        foreach ($lines as $line) {
271                echo '<p>'.$line.'</p>';
272        }
273        echo '</div>';
274}
275
276function nextAction($label,$step,$more='')
277{
278        echo
279        '<form action="'.$_SERVER['SCRIPT_NAME'].'" method="post">'.
280        $more.
281        '<p><input type="hidden" name="step" value="'.$step.'" />'.
282        '<input type="hidden" name="lang" value="'.DC_LOADER_LANG.'" />'.
283        '<input type="submit" name="submit" value="'.$label.'" />'.
284        '</p></form>';
285}
286
287if (!$can_fetch) {
288        openPage();
289        echo
290        '<h2>'.__('NetInstall').'</h2>'."\n";
291        writeMessage('warning',__('Damnit !'), array(
292                __('Due to restrictions in your PHP configuration, NetInstall cannot get its job done.'),
293                __('Please see Piwigo documentation to perform a normal installation.'),
294                __('Really sorry for the inconvenience.')
295        ));
296        closePage();
297        exit;
298}
299
300switch ($step) {
301        case 1 : {
302                openPage();
303                echo
304                '<h2>'.__('Welcome to NetInstall').'</h2>'."\n".
305                '<p>'.__('This tool is meant to retrieve the latest Piwigo archive and unzip it in your webspace.').'</p>'.
306                '<p>'.__('Right after then, you will be redirect to the Piwigo Setup Wizard.').'</p>';
307               
308                if (!$can_write) {
309                        writeMessage('warning',__('Write access is needed'), array(
310                                __('It looks like NetInstall wont be able to write in the current directory, and this is required to follow on.'),
311                                __('Please try to change the permissions to allow write access, then reload this page by hitting the Refresh button.')
312                        ));
313                        nextAction(__('Refresh'),1);
314                }
315                elseif (!$got_php5) {
316                        writeMessage('notice',__('PHP 5 is required'), array(
317                                sprintf(__('It appears your webhost is currently running PHP %s.'), PHP_VERSION),
318                                __('NetInstall may try to switch your configuration to PHP 5 by creating or modifying a .htaccess file.'),
319                                __('Note you can change your configuration by yourself and restart NetInstall after that.')
320                        ));
321                        nextAction(__('Try to configure PHP 5'),2);
322                }
323                else {
324                        nextAction(__('Retrieve and unzip Piwigo'),3,
325                                '<p><label for="destination">'.__('Destination:').'</label> '.
326                                getLocation().
327                                '<input type="text" id="destination" name="destination" '.
328                                'value="piwigo" size="15" maxlength="100" /></p>'
329                        );
330                }
331                closePage();
332                break;
333        }
334        case 2 : {
335                if (!empty($_POST['submit']) && !$got_php5) {
336                        if (($got_php5 = initPHP5())) {
337                                header('Location: '.$_SERVER['SCRIPT_NAME'].'?step=1');
338                        }
339                }
340                elseif ($got_php5) {
341                        header('Location: '.$_SERVER['SCRIPT_NAME'].'?step=1');
342                }
343                else {
344                        openPage();
345                        writeMessage('warning',__('OMG !'),array(
346                                __('NetInstall was not able to configure PHP 5.'),
347                                __("You may referer to your hosting provider's support and see how you could switch to PHP 5 by yourself."),
348                                __('Hope to see you back soon.')
349                        ));
350                        closePage();
351                }
352                break;
353        }
354        case 3 : {
355                $msg = array(__('WTF are you doing here that way ?!'));
356                $text = '';
357                if (!empty($_POST['submit']) && isset($_POST['destination']))
358                {
359                        $msg = array();
360                        $dest = preg_replace('/[^A-Za-z0-9_\/-]/','',$_POST['destination']);
361                        $dest = preg_replace('#/+#','/',$dest);
362                       
363                        if (file_exists(dirname(__FILE__).'/./'.$dest.'/include/mysql.inc.php') || file_exists(dirname(__FILE__).'/./'.$dest.'/iclude/default_config.inc.php'))
364                        {
365                                $msg[] = __('It seems like a previous Piwigo installation is still sitting in that space.');
366                                $msg[] = __('You need to rename or remove it before we can go further...');
367                        }
368                        elseif (grabFiles())
369                        {
370                                $lib_files = dirname(__FILE__).'/pwg_files.php';
371                                $lib_unzip = dirname(__FILE__).'/pwg_unzip.php';
372                                $dc_zip    = dirname(__FILE__).'/piwigo-install.zip';
373                                if (!file_exists($lib_files) || !file_exists($lib_unzip) || !file_exists($dc_zip)) {
374                                        $msg[] = __('Needed files are not present.');
375                                }
376                               
377                                require $lib_files;
378                                require $lib_unzip;
379                                $uz = new fileUnzip($dc_zip);
380                                $files = $uz->getList();
381                                if (count($files) == 0) {
382                                        $msg[] = __('Invalid zip file.');
383                                }
384                               
385                                foreach ($files as $k => $v)
386                                {
387                                        if ($v['is_dir']) {
388                                                continue;
389                                        }
390                                        $t = preg_replace('#^'.DC_LOADER_DIRECTORY.'/#','./'.$dest.'/',$k);
391                                        $uz->unzip($k,$t);
392                                }
393                $uz->close;
394                unset($uz);
395                               
396                                if (!is_dir(dirname(__FILE__).'/./'.$dest))
397                                {
398                                        $msg[] = __('It seems that the zip file was not extracted.');
399                                }
400                                else
401                                {
402                                        # Remove files, create public directory, and self-destruction
403                                        files::makeDir('./'.$dest.'/public');
404                                        cleanFiles();
405                                        unlink(__FILE__);
406                                       
407                                        $redir = preg_replace('#/+#','/',str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])).'/'.$dest.'/install.php');
408                                       
409                                        $text = '<h2>'.__('Congratulations!').'</h2>'
410                                        .'<p>'.__('Everything went fine. You are now ready to start the installation procedure.').'</p>'
411                                        .'<form action="'.$redir.'" method="get">'
412                                        .'<p><input type="submit" value="'.__('Install now').'" /></p>'
413                                        .'</form>';
414                                }
415                        }
416                        else
417                        {
418                                $msg[] = __('An error occurred while grabbing the necessary files to go on.');
419                        }
420                }
421                openPage();
422                writeMessage('warning',__('Something went wrong ...'),$msg);
423                echo $text;
424                closePage();
425                break;
426        }
427}
428?>
Note: See TracBrowser for help on using the repository browser.