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

Last change on this file since 22589 was 22589, checked in by ddtddt, 11 years ago

[netinstall] direction

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