source: extensions/netinstall/trunk/piwigo-netinstall.php @ 9780

Last change on this file since 9780 was 9780, checked in by plg, 13 years ago

new color scheme (clear background) and new logo for NetInstall, just like install.php in Piwigo 2.2

File size: 13.8 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
13// +-----------------------------------------------------------------------+
14// |                              Configuration                            |
15// +-----------------------------------------------------------------------+
16
17define('DC_LOADER_SERVICE','http://piwigo.org/download/netinstall/');
18define('DC_LOADER_ARCHIVE','http://piwigo.org/download/dlcounter.php?code=latest');
19
20$available_languages = array(
21  'en_UK' => 'English [UK]',
22  'fr_FR' => 'Français [FR]',
23  'es_ES' => 'Español [ES]',
24  'it_IT' => 'Italiano [IT]',
25  'de_DE' => 'Deutch [DE]',
26  'pl_PL' => 'Polski [PL]',
27  'zh_CN' => '简体中文 [CN]',
28  'cs_CZ' => 'Česky [CZ]',
29  'hu_HU' => 'Magyar [HU]',
30  'tr_TR' => 'Türkçe [TR]',
31  'ru_RU' => 'Русский [RU]',
32  'lv_LV' => 'Latviešu [LV]',
33);
34
35$url_subdomain_for_language = array(
36  'fr_FR' => 'fr',
37  'es_ES' => 'es',
38  'it_IT' => 'it',
39  'de_DE' => 'de',
40  'pl_PL' => 'pl',
41  'zh_CN' => 'cn',
42  'hu_HU' => 'hu',
43  'ru_RU' => 'ru',
44  );
45
46// +-----------------------------------------------------------------------+
47
48error_reporting(E_ALL & ~E_NOTICE);
49
50getLanguage();
51
52$step = !empty($_REQUEST['step']) ? (integer)$_REQUEST['step'] : 1;
53$got_php5       = version_compare(PHP_VERSION, '5', '>=');
54if (!$got_php5 && $step != 2)
55{
56        $step = 1;
57}
58
59function l10n($str)
60{
61        global $lang;
62
63        return isset($lang[$str]) ? $lang[$str] : $str;
64}
65
66function fetchRemote($src,&$dest,$step=0)
67{
68        if ($step > 3)
69        {
70                return false;
71        }
72
73        // Try curl to read remote file
74        if (function_exists('curl_init'))
75        {
76                $ch = @curl_init(); 
77                @curl_setopt($ch, CURLOPT_URL, $src); 
78                @curl_setopt($ch, CURLOPT_HEADER, 0); 
79                @curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
80                @curl_setopt($ch, CURLOPT_USERAGENT, 'Piwigo Net Install'); 
81                $content = @curl_exec($ch);
82                @curl_close($ch);
83                if ($content !== false)
84                {
85                        write_dest($content, $dest);
86                        return true;
87                }
88        }
89
90        // Try file_get_contents to read remote file
91        if ((boolean)ini_get('allow_url_fopen'))
92        {
93                $content = @file_get_contents($src);
94                if ($content !== false)
95                {
96                        write_dest($content, $dest);
97                        return true;
98                }
99        }
100
101        // Try fsockopen to read remote file
102        $src = parse_url($src);
103        $host = $src['host'];
104        $path = $src['path'];
105       
106        if (($s = @fsockopen($host,80,$errno,$errstr,5)) === false)
107        {
108                return false;
109        }
110
111        fwrite($s,
112                'GET '.$path." HTTP/1.0\r\n"
113                .'Host: '.$host."\r\n"
114                ."User-Agent: Piwigo Net Install\r\n"
115                ."Accept: text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*\r\n"
116                ."\r\n"
117        );
118
119        $i = 0;
120        $in_content = false;
121        while (!feof($s))
122        {
123                $line = fgets($s,4096);
124
125                if (rtrim($line,"\r\n") == '' && !$in_content)
126                {
127                        $in_content = true;
128                        $i++;
129                        continue;
130                }
131                if ($i == 0)
132                {
133                        if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/',rtrim($line,"\r\n"), $m))
134                        {
135                                fclose($s);
136                                return false;
137                        }
138                        $status = (integer) $m[2];
139                        if ($status < 200 || $status >= 400)
140                        {
141                                fclose($s);
142                                return false;
143                        }
144                }
145                if (!$in_content)
146                {
147                        if (preg_match('/Location:\s+?(.+)$/',rtrim($line,"\r\n"),$m))
148                        {
149                                fclose($s);
150                                return fetchRemote(trim($m[1]),$dest,$step+1);
151                        }
152                        $i++;
153                        continue;
154                }
155                write_dest($line, $dest);
156                $i++;
157        }
158        fclose($s);
159        return true;
160}
161
162function write_dest($str, &$dest)
163{
164  if (is_resource($dest))
165        {
166                fwrite($dest, $str);
167        }
168        else
169        {
170                $dest .= $str;
171        }
172}
173
174function getLanguage()
175{
176        global $lang, $available_languages;
177
178        if (isset($_GET['language']) and isset($available_languages[$_GET['language']]))
179        {
180                $language = $_GET['language'];
181        }
182        else
183        {
184                $language = 'en_UK';
185                // Try to get browser language
186                foreach ($available_languages as $language_code => $language_name)
187                {
188                        if (substr($language_code,0,2) == @substr($_SERVER["HTTP_ACCEPT_LANGUAGE"],0,2))
189                        {
190                                $language = $language_code;
191                                break;
192                        }
193                }
194        }
195        // Retrieve traductions
196        $lang = array();
197        if (fetchRemote(DC_LOADER_SERVICE.'language/'.$language.'/loader.lang.txt', $code))
198        {
199                @eval($code);
200                define('DC_LOADER_LANG', $language);
201        }
202}
203
204function getLocation()
205{
206        $server_name = explode(':',$_SERVER['HTTP_HOST']);
207        $server_name = $server_name[0];
208        if ($_SERVER['SERVER_PORT'] == '443')
209        {
210                $scheme = 'https';
211                $port = '';
212        }
213        elseif (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')
214        {
215                $scheme = 'https';
216                $port = ($_SERVER['SERVER_PORT'] != '443') ? ':'.$_SERVER['SERVER_PORT'] : '';
217        }
218        else
219        {
220                $scheme = 'http';
221                $port = ($_SERVER['SERVER_PORT'] != '80') ? ':'.$_SERVER['SERVER_PORT'] : '';
222        }
223        $loc = preg_replace('#/$#','',str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])));
224
225        return $scheme.'://'.$server_name.$port.$loc.'/';
226}
227
228function openPage()
229{
230        header('Content-Type: text/html; charset=UTF-8');
231        echo
232        '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" '.
233        ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'."\n".
234        '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'.substr(DC_LOADER_LANG,0,2).'" lang="'.substr(DC_LOADER_LANG,0,2).'">'."\n".
235        "<head>\n".
236        ' <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />'."\n".
237        ' <title>'.l10n('Piwigo NetInstall').'</title>'."\n".
238        ' <meta name="ROBOTS" content="NOARCHIVE,NOINDEX,NOFOLLOW" />'."\n".
239        ' <link rel="stylesheet" type="text/css" media="screen" href="'.DC_LOADER_SERVICE.'loader.css" />'."\n".
240        '</head>'."\n".
241        '<body>'."\n".
242        '<div id="theHeader"></div>'."\n".
243        '<div id="content">'."\n".
244        '<h2>'.l10n('Piwigo NetInstall').'</h2>'."\n";
245}
246
247function closePage()
248{
249  global $url_subdomain_for_language;
250
251  $prefix = '';
252  if (isset($url_subdomain_for_language[DC_LOADER_LANG]))
253  {
254    $prefix = $url_subdomain_for_language[DC_LOADER_LANG].'.';
255  }
256 
257        echo
258        '<div style="text-align:center">'.
259          sprintf(l10n('Need help ? Ask your question on <a href="%s">Piwigo message board</a>.'), 'http://'.$prefix.'piwigo.org/forum').
260        "</div>\n".
261        '</div>'."\n".
262        '</body>'."\n".
263        '</html>';
264}
265
266function initPHP5()
267{
268        $htaccess = dirname(__FILE__).'/.htaccess';
269        if (file_exists($htaccess)) {
270                if (!is_readable($htaccess) || !is_writable($htaccess))
271                {
272                        return false;
273                }
274        }
275        $rawdatas = '';
276        if (!fetchRemote(DC_LOADER_SERVICE.'hosting.txt',$rawdatas))
277        {
278                return false;
279        }
280        $rawdatas = explode("\n",$rawdatas);
281        if (!($my_hostname = @gethostbyaddr($_SERVER['SERVER_ADDR'])))
282        {
283                return false;
284        }
285        $found = false;
286        foreach ($rawdatas as $line) {
287                list($name,$hostname,$rule) = explode('|',trim($line));
288                if (preg_match('!'.preg_quote($hostname).'$!',$my_hostname))
289                {
290                        $found = $rule;
291                        break;
292                }
293        }
294        if ($found) {
295                if (false !== ($fh = @fopen($htaccess,"ab")))
296                {
297                        fwrite($fh,"\n".$found);
298                        fclose($fh);
299                        return true;
300                }
301        }
302        return false;
303}
304
305function cleanFiles()
306{
307        @unlink(dirname(__FILE__).'/pwg_files.php');
308        @unlink(dirname(__FILE__).'/pwg_unzip.php');
309        @unlink(dirname(__FILE__).'/piwigo-install.zip');
310}
311
312function grabFiles()
313{
314        $failed = true;
315        $lib_files = @fopen(dirname(__FILE__).'/pwg_files.php','wb');
316        $lib_unzip = @fopen(dirname(__FILE__).'/pwg_unzip.php','wb');
317        $dc_zip    = @fopen(dirname(__FILE__).'/piwigo-install.zip','wb');
318
319        if (!$lib_files || !$lib_unzip || !$dc_zip)
320        {
321                return false;
322        }
323
324        if (fetchRemote(DC_LOADER_SERVICE.'lib.files.txt',$lib_files))
325        {
326                if (fetchRemote(DC_LOADER_SERVICE.'class.unzip.txt',$lib_unzip))
327                {
328                        if (fetchRemote(DC_LOADER_ARCHIVE.'',$dc_zip))
329                        {
330                                $failed = false;
331                        }
332                }
333        }
334
335        fclose($lib_files);
336        fclose($lib_unzip);
337        fclose($dc_zip);
338
339        if ($failed)
340        {
341                cleanFiles();
342                return false;
343        }
344        return true;
345}
346
347function writeMessage($level,$title,$lines)
348{
349        if (empty($lines))
350        {
351                return;
352        }
353
354        echo 
355        '<div class="msg '.$level.'">'."\n".
356        '<h3>'.$title.'</h3>'."\n".
357        '<p>'."\n";
358        foreach ($lines as $line)
359        {
360                echo $line.'<br />'."\n";
361        }
362        echo '</p></div>'."\n";
363}
364
365function nextAction($label,$step,$more='')
366{
367        echo
368        '<form action="'.$_SERVER['SCRIPT_NAME'].'?language='.DC_LOADER_LANG.'" method="post">'."\n".
369        $more."\n".
370        '<p class="button"><input type="hidden" name="step" value="'.$step.'" />'."\n".
371        '<input type="hidden" name="lang" value="'.DC_LOADER_LANG.'" />'."\n".
372        '<input type="submit" name="submit" value="'.$label.'"/>'."\n".
373        '</p></form>'."\n";
374}
375
376
377if (!defined('DC_LOADER_LANG'))
378{
379        // No traduction for this part because can't fetch!
380        openPage();
381        echo
382        '<h2>Piwigo NetInstall</h2>'."\n";
383        writeMessage('warning','Damnit!', array(
384                'Due to restrictions in your PHP configuration, NetInstall cannot get its job done.',
385                'Please see Piwigo documentation to perform a normal installation.',
386                'Really sorry for the inconvenience.'
387        ));
388        closePage();
389        exit;
390}
391
392switch ($step)
393{
394        case 1 :
395        {
396                openPage();
397                echo '<fieldset><legend>'.l10n('Welcome to NetInstall!').'</legend>'."\n";
398
399                // Show available languages
400                asort($available_languages);
401                echo
402                '<p class="language">'.l10n('Language').' &nbsp;'."\n".
403                '<select name="language" onchange="document.location = \''.basename(__FILE__).'?language=\'+this.options[this.selectedIndex].value;">'."\n";
404                foreach ($available_languages as $language_code => $language_name)
405                {
406                        echo '<option label="'.$language_name.'" value="'.$language_code.'" '.($language_code == DC_LOADER_LANG ? 'selected="selected"' : '').'>'.$language_name.'</option>'."\n";
407                }
408                echo '</select>'."\n".'</p>'."\n";
409
410                echo
411                '<p>'.l10n('This tool is meant to retrieve the latest Piwigo archive and unzip it in your webspace.').'<br />'."\n".
412                l10n('Right after then, you will be redirect to the Piwigo Setup Wizard.').'</p>'."\n";
413
414                if (!is_writable(dirname(__FILE__)))
415                {
416                        writeMessage('warning',l10n('Write access is needed'), array(
417                                l10n('It looks like NetInstall wont be able to write in the current directory, and this is required to follow on.'),
418                                l10n('Please try to change the permissions to allow write access, then reload this page by hitting the Refresh button.')
419                        ));
420                        nextAction(l10n('Refresh'),1);
421                }
422                elseif (!$got_php5)
423                {
424                        writeMessage('notice',l10n('PHP 5 is required'), array(
425                                sprintf(l10n('It appears your webhost is currently running PHP %s.'), PHP_VERSION),
426                                l10n('NetInstall may try to switch your configuration to PHP 5 by creating or modifying a .htaccess file.'),
427                                l10n('Note you can change your configuration by yourself and restart NetInstall after that.')
428                        ));
429                        nextAction(l10n('Try to configure PHP 5'),2);
430                }
431                else
432                {
433                        nextAction(l10n('Retrieve and unzip Piwigo'),3,
434                                '<p class="destination"><label for="destination">'.l10n('Destination:').'</label> '.
435                                getLocation().
436                                ' <input type="text" id="destination" name="destination" '.
437                                'value="piwigo" size="15" maxlength="100" /></p>'
438                        );
439                }
440                echo '</fieldset>';
441                closePage();
442                break;
443        }
444
445        case 2 :
446        {
447                if (!empty($_POST['submit']) && !$got_php5)
448                {
449                        $got_php5 = initPHP5();
450                }
451                if ($got_php5)
452                {
453                        header('Location: '.$_SERVER['SCRIPT_NAME'].'?step=1&language='.DC_LOADER_LANG);
454                }
455                else
456                {
457                        openPage();
458                        writeMessage('warning',l10n('Sorry!'),array(
459                                l10n('NetInstall was not able to configure PHP 5.'),
460                                l10n("You may referer to your hosting provider's support and see how you could switch to PHP 5 by yourself."),
461                                l10n('Hope to see you back soon.')
462                        ));
463                        closePage();
464                }
465                break;
466        }
467
468        case 3 :
469        {
470                $msg = array(l10n('What are you doing here that way ?!'));
471                $text = '';
472                if (!empty($_POST['submit']) && isset($_POST['destination']))
473                {
474                        $msg = array();
475                        $dest = preg_replace('/[^A-Za-z0-9_\/-]/','',$_POST['destination']);
476                        $dest = preg_replace('#/+#','/',$dest);
477                       
478                        if (file_exists(dirname(__FILE__).'/./'.$dest.'/include/mysql.inc.php') || file_exists(dirname(__FILE__).'/./'.$dest.'/include/default_config.inc.php'))
479                        {
480                                $msg[] = l10n('It seems like a previous Piwigo installation is still sitting in that space.');
481                                $msg[] = l10n('You need to rename or remove it before we can go further...');
482                        }
483                        elseif (grabFiles())
484                        {
485                                $lib_files = dirname(__FILE__).'/pwg_files.php';
486                                $lib_unzip = dirname(__FILE__).'/pwg_unzip.php';
487                                $dc_zip         = dirname(__FILE__).'/piwigo-install.zip';
488                                if (!file_exists($lib_files) || !file_exists($lib_unzip) || !file_exists($dc_zip))
489                                {
490                                        $msg[] = l10n('Needed files are not present.');
491                                }
492
493                                require $lib_files;
494                                require $lib_unzip;
495                                $uz = new fileUnzip($dc_zip);
496                                $files = $uz->getList();
497                                if (!is_array($files) or count($files) == 0)
498                                {
499                                        $msg[] = l10n('Invalid zip file.');
500                                }
501                                else
502                                {
503                                        foreach ($files as $k => $v)
504                                        {
505                                                if ($v['is_dir'])
506                                                {
507                                                        continue;
508                                                }
509                                        if (preg_match('#^[^/]*/_data#', $k))
510                                        {
511                                                continue;
512                                        }
513                                                $t = preg_replace('#^[^/]*/#','./'.$dest.'/',$k);
514                                                $uz->unzip($k,$t);
515                                        }
516                                }
517                                $uz->close;
518                                unset($uz);
519
520                                if (!is_dir(dirname(__FILE__).'/'.$dest))
521                                {
522                                        $msg[] = l10n('It seems that the zip file was not extracted.');
523                                }
524                                else
525                                {
526                                        # Remove files and self-destruction
527                                        cleanFiles();
528                                        unlink(__FILE__);
529
530                                        $redir = preg_replace('#/+#','/',str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])).'/'.$dest.'/install.php');
531
532                                        $text = '<fieldset><legend>'.l10n('Congratulations!').'</legend>'
533                                        .'<p>'.l10n('Everything went fine. You are now ready to start the installation procedure.').'</p>'
534                                        .'<form action="'.$redir.'" method="get"><p class="button">'
535                                        . '<input type="hidden" name="language" value="'.DC_LOADER_LANG.'">'
536                                        . '<input type="submit" value="'.l10n('Install Piwigo now').'" />'
537                                        . '</p></form>';
538
539                                        $text.= '</fieldset>';
540                                }
541                        }
542                        else
543                        {
544                                $msg[] = l10n('An error occurred while grabbing the necessary files to go on.');
545                        }
546                }
547                openPage();
548                writeMessage('warning',l10n('Something went wrong...'),$msg);
549                echo $text;
550                closePage();
551                break;
552        }
553}
554?>
Note: See TracBrowser for help on using the repository browser.