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

Last change on this file since 28589 was 28589, checked in by mistic100, 10 years ago

indent with spaces

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