root/trunk/wifidog-auth/wifidog/install.php @ 690

Revision 690, 60.4 KB (checked in by plec_, 8 years ago)

Initial commit

  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
Line 
1<?php
2
3  /********************************************************************\
4   * This program is free software; you can redistribute it and/or    *
5   * modify it under the terms of the GNU General Public License as   *
6   * published by the Free Software Foundation; either version 2 of   *
7   * the License, or (at your option) any later version.              *
8   *                                                                  *
9   * This program is distributed in the hope that it will be useful,  *
10   * but WITHOUT ANY WARRANTY; without even the implied warranty of   *
11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the    *
12   * GNU General Public License for more details.                     *
13   *                                                                  *
14   * You should have received a copy of the GNU General Public License*
15   * along with this program; if not, contact:                        *
16   *                                                                  *
17   * Free Software Foundation           Voice:  +1-617-542-5942       *
18   * 59 Temple Place - Suite 330        Fax:    +1-617-542-2652       *
19   * Boston, MA  02111-1307,  USA       gnu@gnu.org                   *
20   *                                                                  *
21   \********************************************************************/
22
23  /**@file install.php
24   * Authserver installation and configuration
25   * @author Copyright (C) 2005 Pascal Leclerc
26   */
27
28empty($_REQUEST['page'])   ? $page    = 'Welcome' : $page    = $_REQUEST['page'];   # The page to be loaded
29empty($_REQUEST['action']) ? $action  = ''        : $action  = $_REQUEST['action']; # The action to be done (in page)
30empty($_REQUEST['debug'])  ? $debug   = 0         : $debug   = $_REQUEST['debug'];  # Use for MySQL debugging
31empty($_REQUEST['config']) ? $config  = ''        : $config  = $_REQUEST['config']; # Store data to be saved in config.php
32
33$exploded_path = explode("/", $_SERVER['SCRIPT_FILENAME']); # Split directories in token
34array_pop($exploded_path);                                  # Remove install.php from the list
35$basepath = implode("/", $exploded_path);                   # Build the basepath for this script
36
37$exploded_path = explode("/", $_SERVER['SCRIPT_NAME']);     # Split directories in token
38array_pop($exploded_path);                                  # Remove install.php from the list
39$system_path = implode("/", $exploded_path);                # Build the system_path for the auth-server
40
41# Security : Minimal access validation is use by asking user to type the wifidog directory field date
42# It's dummy, easy to implement and better than nothing
43$password = exec("ls -ld $basepath | awk '{print \$6\$7\$8}'", $output_array, $return); 
44$auth = false;
45
46if ($page != 'Welcome') {
47  if (isset($_SERVER['PHP_AUTH_PW'])) {
48    #echo "PHP_AUTH_USER=(" . $_SERVER['PHP_AUTH_USER'] . ") PHP_AUTH_PW=(" . $_SERVER['PHP_AUTH_PW'] . ")"; # DEBUG
49    if ($password == $_SERVER['PHP_AUTH_PW'])
50      $auth = true;
51  }
52}
53else
54  $auth = true;
55
56if (!$auth) { # Ask user for the passorwd
57  header('WWW-Authenticate: Basic realm="Private"');
58  header('HTTP/1.0 401 Unauthorized');
59  echo "Authorization Required !";
60  exit;
61}
62# End of Security validation
63
64print <<<EndHTML
65<HTML>
66<HEAD>
67  <TITLE>$page - Wifidog Auth-server configuration</TITLE>
68
69  <SCRIPT type="text/javascript">
70    // This function add new configuration value to the "config" hidden input
71    // On submit, config will be parsed and value saved to config.php file   
72    function newConfig(dataAdd) {
73      // TODO : Validate input data
74      if (document.myform.config.value == '') {
75        document.myform.config.value = dataAdd;
76      }
77      else {
78        document.myform.config.value = document.myform.config.value + '|' + dataAdd;
79      }
80      //alert(document.myform.config.value);  // DEBUG
81    }
82  </SCRIPT>
83
84</HEAD>
85<BODY text="black" bgcolor="#CFCFCF">
86
87<style type="text/css">
88<!--
89.button /* Homemade button */
90{
91  font-size: 12pt;
92  font-weight: bold;
93  color: black;
94  background: #D4D0C8;
95  text-decoration: none;
96  border-top: 1px solid white;
97  border-right: 2px solid gray;
98  border-bottom: 2px solid gray;
99  border-left: 1px solid white;
100  padding: 1px 4px 1px 4px;
101}
102
103td
104{
105  padding: 1px 4px 1px 4px;
106}
107//-->
108</style>
109
110<FORM NAME="myform" METHOD="post">
111<INPUT TYPE="HIDDEN" NAME="page">
112<INPUT TYPE="HIDDEN" NAME="action">
113<INPUT TYPE="HIDDEN" NAME="debug">
114<INPUT TYPE="HIDDEN" NAME="config">
115
116EndHTML;
117
118#print "<PRE>";      # DEBUG
119#print_r($_SERVER);  # DEBUG
120#print_r($_REQUEST); # DEBUG
121#print "</PRE>";     # DEBUG
122#exit();
123
124# Minimal version needed
125$requiredPHPVersion       = '5.0.0';
126$requiredMySQLVersion     = '0.0.0'; // Todo
127$requiredPostgeSQLVersion = '0.0.0'; // Todo
128
129# Needed files/directories with write access
130$dir_array = array('tmp', 'portal/cache', 'lib/smarty', 'tmp/smarty/templates_c', 'lib/magpie', 'lib/Phlickr', 'config.php'); #, 'lib/jpgraph');
131
132$smarty_full_url    = 'http://smarty.php.net/do_download.php?download_file=Smarty-2.6.7.tar.gz';
133$magpierss_full_url = 'http://easynews.dl.sourceforge.net/sourceforge/magpierss/magpierss-0.71.1.tar.gz';
134$phlickr_full_url   = 'http://easynews.dl.sourceforge.net/sourceforge/phlickr/Phlickr-0.2.2.tgz';
135$jpgraph_full_url   = 'http://members.chello.se/jpgraph/jpgdownloads/jpgraph-2.0beta.tar.gz';
136
137$neededPackages = array(
138  'smarty'    => array('needed' => 1, 'available' => 0, 'message' => '', 'file' => 'lib/smarty/Smarty.class.php'),
139  'magpierss' => array('needed' => 0, 'available' => 0, 'message' => '', 'file' => 'lib/magpie/rss_fetch.inc'),
140  'phlickr'   => array('needed' => 0, 'available' => 0, 'message' => '', 'file' => 'lib/Phlickr/Photo.php'),
141  'jpgraph'   => array('needed' => 0, 'available' => 0, 'message' => '', 'file' => 'lib/jpgraph/jpgraph.php'),
142);
143
144$neededExtentions = array(   
145  'xml'      => array('needed'    => 0,
146                      'available' => 0,
147                      'message'   => '<B>xml</B> extention is missing',
148                      'note'      => 'Required for RSS support'),
149  'pgsql'    => array('needed'    => 1,
150                      'available' => 0,
151                      'message'   => '<B>Posgresql</B> extention is missing',
152                      'note'      => 'Required to connect to Postgresql database'),
153  'mysql'    => array('needed'    => 0,
154                      'available' => 0,
155                      'message'   => '<B>MySQL</B> extention is missing',
156                      'note'      => 'Required to connect to MySQL database (experimental and not working)'),
157  'dom'      => array('needed'    => 1,
158                      'available' => 0,
159                      'message'   => '<B>DOM</B> extention is missing',
160                      'note'      => 'Required if you want to export the list of HotSpots as a RSS feed'), 
161  'gettext'  => array('needed'    => 0,
162                      'available' => 0,
163                      'message'   => 'Gettext is unavailable, the auth-server will work, but you will loose internationalization',
164                      'note'      => 'Internationalization support'),
165  'mbstring' => array('needed'    => 1,
166                      'available' => 0,
167                      'message'   => '<B>mbstring</B> extention is missing',
168                      'note'      => 'Required for core auth-server and RSS support'), 
169  'mcrypt'   => array('needed'    => 0,
170                      'available' => 0,
171                      'message'   => '<B>mcrypt</B> extention is missing',
172                      'note'      => 'Required for RADIUS support'), 
173  'mhash'    => array('needed'    => 0,
174                      'available' => 0,
175                      'message'   => '<B>mhash</B> extention is missing',
176                      'note'      => 'Required for RADIUS support'), 
177  'xmlrpc'   => array('needed'    => 0,
178                      'available' => 0,
179                      'message'   => '<B>xmlrpc</B> extention is missing',
180                      'note'      => 'Required for RADIUS support')
181);
182
183$loadedExtensions = array_flip(get_loaded_extensions()); # Debug : An empty array for $loadedExtensions will show needed dependencies
184
185$neededPEARPackages = array(
186  'radius'      => array('needed' => 0, 'available' => 0, 'command' => "return dl('radius.so');",                'message' => 'Try in command line : pear install radius'),
187  'Auth_RADIUS' => array('needed' => 0, 'available' => 0, 'command' => "return include_once 'Auth/RADIUS.php';", 'message' => 'Try in command line : pear install Auth_RADIUS'),
188  'Crypt_CHAP'  => array('needed' => 0, 'available' => 0, 'command' => "return include_once 'Crypt/CHAP.php';",  'message' => 'Try in command line : pear install Crypt_CHAP')
189);
190
191$optionsInfo = array(
192  'SSL_AVAILABLE'                => array('title'   => 'SSL Support',
193                                          'depend'  => 'return 1;',
194                                          'message' => '&nbsp;'),
195  'RSS_SUPPORT'                  => array('title'   => 'RSS Support',
196                                          'depend'  => 'return ($neededExtentions[\'xml\'][\'available\'] && $neededPackages[\'magpierss\'][\'available\']);',
197                                          'message' => 'Missing <B>xml</B> extentions or <B>MagpieRSS</B>'),
198  'PHLICKR_SUPPORT'              => array('title'   => 'Flickr Photostream content support',
199                                          'depend'  => 'return $neededPackages[\'phlickr\'][\'available\'];',
200                                          'message' => '<B>Phlickr</B> library not installed'),
201  'CONF_USE_CRON_FOR_DB_CLEANUP' => array('title'   => 'Use cron for DB cleanup',
202                                          'depend'  => 'return 1;',
203                                          'message' => '&nbsp;'),
204  'XSLT_SUPPORT'                 => array('title'   => 'XSLT Support',
205                                          'depend'  => 'return 1;',
206                                          'message' => '&nbsp;'),
207  'GMAPS_HOTSPOTS_MAP_ENABLED'   => array('title'   => 'Google Maps Support',
208                                          'depend'  => 'return 1;',
209                                          'message' => '&nbsp;')
210);
211
212foreach($neededExtentions as $key => $value) {   # Detect availables extentions
213  if (array_key_exists($key, $loadedExtensions))
214    $neededExtentions[$key]['available'] = 1;
215}
216
217foreach($neededPEARPackages as $key => $value) { # Detect availables PEAR Packages
218  if (@eval($neededPEARPackages[$key]['command']))
219    $neededPEARPackages[$key]['available'] = 1;
220}
221
222foreach($neededPackages as $key => $value) {     # Detect installed libraries (smarty, ...)
223  if (file_exists($basepath . '/' . $neededPackages[$key]['file']))
224    $neededPackages[$key]['available'] = 1;
225}
226
227$CONFIG_FILE       = 'config.php';
228$LOCAL_CONFIG_FILE = 'local.config.php';
229
230if (!empty($config))  # If not empty, save javascript 'config' variable to config.php file
231  saveConfig($config); 
232
233### Read Configuration file. Keys and Values => define('FOO', 'BRAK');
234# Use config.php if local.config.php does not exist
235//if(!file_exists("$basepath/$LOCAL_CONFIG_FILE"))
236  $contentArray = file("$basepath/$CONFIG_FILE");
237//else
238//  $contentArray = file("$basepath/$LOCAL_CONFIG_FILE");
239
240$configArray = array();
241
242foreach($contentArray as $line) {
243  #print "$line<BR>"; # Debug
244  if(preg_match("/^define\((.+)\);/", $line, $matchesArray)) {
245    list($key, $value) = explode(',', $matchesArray[1]);
246    $pattern = array("/^'/", "/'$/");
247    $replacement = array('', '');
248    $key = preg_replace($pattern, $replacement, trim($key));
249    $value = preg_replace($pattern, $replacement, trim($value));
250    $configArray[$key] = $value;
251  }   
252}
253
254# Database connections variables
255$CONF_DBMS              = $configArray['CONF_DBMS'];
256$CONF_DATABASE_HOST     = $configArray['CONF_DATABASE_HOST'];
257$CONF_DATABASE_NAME     = $configArray['CONF_DATABASE_NAME'];
258$CONF_DATABASE_USER     = $configArray['CONF_DATABASE_USER'];
259$CONF_DATABASE_PASSWORD = $configArray['CONF_DATABASE_PASSWORD'];
260
261# Update SYSTEM_PATH if $system_path (value detected be this script) is not the same as the config.php value
262# Don't update SYSTEM_PATH before $page=='permissions' in case of no write access to config.php
263if ($configArray['SYSTEM_PATH'] != $system_path and $page == 'smarty') {
264  print <<<EndHTML
265<script type="text/javascript">
266    newConfig("SYSTEM_PATH='$system_path/'");
267</script>
268EndHTML;
269}
270
271//foreach($configArray as $key => $value) { print "K=$key V=$value<BR>"; } exit(); # DEBUG
272
273###################################
274# array (array1(name1, page1), array2(name2, page2), ..., arrayN(nameN, pageN));
275# Todo : Supporter HTTP_REFERER (j'me comprends)
276function navigation($dataArray) {
277  $SERVER = $_SERVER['HTTP_HOST'];
278  $SCRIPT = $_SERVER['SCRIPT_NAME'];
279  print "\n<P>";
280  foreach($dataArray as $num => $navArray) {
281    $title  = $navArray['title'];
282    $page   = $navArray['page'];
283    empty($navArray['action']) ? $action = '' : $action = $navArray['action'];
284    print <<<EndHTML
285<A HREF="javascript: document.myform.page.value = '$page'; document.myform.action.value = '$action'; document.myform.submit();" CLASS="button">$title</A>
286
287EndHTML;
288    if (array_key_exists($num+1, $dataArray))
289      print "&nbsp;-&nbsp;";
290  }
291  print "</P>\n";
292}
293
294###################################
295#
296function refreshButton() {
297  print <<<EndHTML
298
299<P><A HREF="javascript: window.location.reload(true);" CLASS="button">Refresh</A></P>
300EndHTML;
301}
302
303###################################
304#
305/*function debugButton() {
306  print <<<EndHTML
307<P><INPUT TYPE="button" VALUE="Debug" ONCLICK="javascript: window.location.reload(true);"></P>
308EndHTML;
309} */
310
311###################################
312# In development
313/*function installPackage($pkg_name, $full_url, $copy) {
314    print "<H1>$pkg_name installation</H1>\n";
315    chdir("$basepath/tmp");
316    list($url, $filename) = split ("=", $full_url);
317
318    print "Download source code ($filename) : ";
319    if (!file_exists($filename))
320      exec("wget \"$url\"", $output, $return);
321    if (!file_exists($filename)) // wget success if file exists
322      exec("wget \"$full_url\" 2>&1", $output_array, $return);
323    if (!file_exists($filename)) {
324      print "<B STYLE=\"color:red\">Error</B><P>Current working directory : <B>$basepath/tmp/smarty</B>";
325      $output = implode("\n", $output_array);
326      print "<PRE><B>wget \"$full_url\"</B>\n$output</PRE>";
327      exit();
328    } else {
329      print "OK<BR>";
330    }
331
332    print "Uncompressing : ";
333    $dirname = array_shift(split(".tar.gz", $filename));
334
335    if (!file_exists($dirname))
336      exec("tar -xzf $dirname.tar.gz &>/tmp/tar.output", $output, $return);
337    print "OK<BR>";
338
339    exec("pwd", $output, $return);
340    print "Copying : ";
341    if (!file_exists('../../lib/smarty/Smarty.class.php'));
342      exec("cp -r $dirname/libs/* ../../lib/smarty &>/tmp/cp.output", $output, $return);
343      exec("cp -r $dirname/libs/* ../../lib/smarty &>/tmp/cp.output", $output, $return);
344      $copy
345    print "OK<BR>";
346}*/
347
348###################################
349#
350function saveConfig($data) {
351  print "<!-- saveConfig DATA=($data) -->\n"; # DEBUG
352
353  global $basepath;
354  global $CONFIG_FILE;
355
356  $contentArray = file("$basepath/$CONFIG_FILE");
357  $fd = fopen("$basepath/$CONFIG_FILE", 'w');
358
359  $defineArrayToken = array();
360  $defineArrayToken = explode('|', $data);
361
362  foreach($defineArrayToken as $nameValue) {
363    list($name, $value) = explode('=', $nameValue);
364    $defineArray[$name] = $value;  # New define value ($name and value)
365    #print "K=$name V=$value<BR>"; # DEBUG
366  }
367
368  foreach($contentArray as $line) {
369    #print "L=$line<BR>\n";
370    if(preg_match("/^define\((.+)\);/", $line, $matchesArray)) {
371      list($key, $value) = explode(',', $matchesArray[1]);
372      $pattern     = array("/^'/", "/'$/");
373      $replacement = array('', '');
374      $key   = preg_replace($pattern, $replacement, trim($key));
375      //$value = preg_replace($pattern, $replacement, trim($value));
376
377      if (array_key_exists($key, $defineArray)) { // A new value is defined
378        #print "$key EXISTS<BR>";
379        #print "define => (" . $defineArray[$key] . ")<BR>";
380        $pattern     = array("/^\\\'/", "/\\\'$/");
381        $replacement = array("'", "'");
382        $value = preg_replace($pattern, $replacement, trim($defineArray[$key]));
383        #print "(define('$key', $value);)<BR>";
384                fwrite($fd, "define('$key', $value);\n"); # Write the new define($name, $value)
385          }
386          else { // The key does not exist (no new value to be saved)
387        fwrite($fd, $line); # Write the same line in config.php
388          }
389    }
390    else {
391      fwrite($fd, $line);   # Write the line (not a define line). Ex: Commented text
392    }
393  }
394}
395
396###################################
397# MAIN
398switch ($page) {
399  case 'version':
400/*  TODO : Valider qu'au moins une extention de DB est existante (pgsql, mysql, etc) 
401           Definir les versions minimales de Posgres et MySQL */
402
403    print "<H1>Version validation</H1>";
404    print "<TABLE BORDER=\"1\">";
405
406    $phpVersion = phpversion();
407    $okMsg      = '<TD ALIGN="CENTER" STYLE="background:lime;">OK</TD>';
408    $errorMsg   = '<TD ALIGN="CENTER" STYLE="background:red;">ERROR</TD>';
409    $warningMsg = '<TD ALIGN="CENTER" STYLE="background:yellow;">Warning</TD>';
410    $error = 0;
411
412    print "<TR><TD>PHP</TD>";
413    if (version_compare($phpVersion, $requiredPHPVersion, ">=")) {
414      print "$okMsg<TD>$phpVersion</TD>";  // Version 5.0.0 or later
415    } else {
416      print "$errorMsg<TD>Version $requiredPHPVersion needed</TD>"; // Version < 5.0.0
417      $error = 1;
418    }
419    print "</TR></TABLE><BR>";
420   
421    print "<TABLE BORDER=\"1\"><TR><TD><B>Extention</B></TD><TD><B>Status</B></TD><TD><B>Note</B></TD><TD><B>Message</B></TD></TR>";
422    foreach($neededExtentions as $key => $value) {
423      print  "<TR><TD><A HREF=\"http://www.php.net/$key\">$key</A></TD>";
424      $note = $neededExtentions[$key]['note'];
425      if ($neededExtentions[$key]['available']) {
426        print  "$okMsg<TD>$note</TD><TD>&nbsp;</TD></TR>";
427      } else {
428        $message = $neededExtentions[$key]['message'];
429        if ($neededExtentions[$key]['needed'] == 1) {
430          print  "$errorMsg<TD>$note</TD><TD>$message</TD></TR>";
431          $error = 1;
432        } else {         
433          print  "$warningMsg<TD>$note</TD><TD>$message</TD></TR>";
434        }
435      }     
436    }
437    print "</TABLE><BR>";
438
439    /************************************
440    * PEAR Components
441    *************************************/
442    print "<TABLE BORDER=\"1\"><TR><TD COLSPAN=\"3\"><CENTER><B>PEAR</B></CENTER></TD></TR>";
443    print "<TR><TD><B>Component</B></TD><TD><B>Status</B></TD><TD><B>Note</B></TD></TR>";
444
445    foreach($neededPEARPackages as $key => $value) {
446      $return = 0;
447      print  "<TR><TD><A HREF=\"http://pear.php.net/package/$key\">$key</A></TD>";
448      if ($neededPEARPackages[$key]['available']) {
449        print  "$okMsg<TD>&nbsp;</TD></TR>";
450      } else {
451        $message = $neededPEARPackages[$key]['message'];
452        if ($neededPEARPackages[$key]['needed'] == 1) {
453          print  "$errorMsg<TD>$message</TD></TR>";
454          $error = 1;
455        } else {         
456          print  "$warningMsg<TD>$message</TD></TR>";
457        }
458      } 
459    } 
460    print "</TABLE><BR>";
461
462    /************************************
463    * GD with PNG and JPEG support (will be needed by stats and graphics)
464    *************************************/
465/*  $gdInfo = @gd_info();
466    print "<TABLE BORDER=\"1\"><TR><TD><PRE>";
467    print_r($gdInfo);
468    print "</PRE></TD></TR></TABLE>";
469*/
470
471#    if (!($neededExtentions['pgsql']['available'] && $neededExtentions['mysql']['available']))
472#      print "At least one DB extentions is nedded<BR>";
473
474    print "<B>Todo</B> : PostgreSLQ and MySQL version are not validated";
475
476    refreshButton();
477    if ($error != 1) {
478      navigation(array(array("title" => "Next", "page" => "permission")));
479    }
480
481  break;
482  ###################################
483  case 'permission':
484    print "<H1>Permissions</H1>";
485   
486    $process_info_user_id  = posix_getpwuid(posix_getuid());
487    $process_info_group_id = posix_getgrgid(posix_getegid());
488    $process_username      = $process_info_user_id['name'];
489    $process_group         = $process_info_group_id['name'];
490    $cmd_mkdir = '';
491    $cmd_chown = '';
492    $error     = 0;
493
494    print "<P><B>Home</B>: $basepath</P>";
495    print "<P><B>HTTPD username</B>: $process_username</P>";
496    print "<P><TABLE BORDER=\"1\"><TR><TD><B>Directory</B></TD></TD><TD><B>Owner</B></TD><TD><B>Writable</B></TD></TR>\n";
497
498    foreach($dir_array as $dir) {
499      print "<TR><TD>$dir</TD>";
500      if (!file_exists("$basepath/$dir")) {
501        print "<TD COLSPAN=\"2\" STYLE=\"text-align:center;\">Missing</TD></TR>\n";
502        $cmd_mkdir .= "$dir ";
503        $cmd_chown .= "$dir ";
504        $error = 1;
505        continue;
506      }
507
508      $dir_info = posix_getpwuid(fileowner("$basepath/$dir"));
509      $dir_owner_username = $dir_info['name'];
510      print "<TD>$dir_owner_username</TD>";
511
512      if (is_writable("$basepath/$dir")) {
513        print "<TD>YES</TD>";
514      }
515      else {
516        print "<TD>NO</TD>";
517        $cmd_chown .= "$dir ";
518        $error = 1;
519      }
520      print "</TR>\n";
521    }
522    print "</TABLE>\n";
523
524    if ($error != 1) {
525      navigation(array(array("title" => "Back", "page" => ""), array("title" => "Next", "page" => "smarty")));
526    }
527    else {
528      refreshButton();
529      print "<P>Please allow <B>$process_username</B> to write to these directories (mkdir, chown or chmod)</P>";
530      if(!empty($cmd_mkdir))
531        print "<P><B>Tips</B> : mkdir $cmd_mkdir";
532      if(!empty($cmd_chown))
533        print "<P><B>Tips</B> : chown -R $process_username:$process_group $cmd_chown";
534    }
535  break;
536  ###################################
537  case 'smarty': // Download, uncompress and install Smarty
538    print <<< EndHTML
539    <H1>Smarty installation</H1>
540    <P><A HREF="http://smarty.php.net/">Smarty</A> is known as a "Template Engine". Wifidog's internal fonctionnality needs it.</P>
541EndHTML;
542    if ($neededPackages['smarty']['available']) {
543      print "Already installed !<BR>";
544    }
545    else {
546      chdir("$basepath/tmp");
547      list($url, $filename) = split ("=", $smarty_full_url);
548
549      print "Download source code ($filename) : ";
550      if (!file_exists($filename))
551        exec("wget \"$smarty_full_url\" 2>&1", $output, $return);
552      if (!file_exists($filename)) {
553        print "<B STYLE=\"color:red\">Error</B><P>Current working directory : <B>$basepath/tmp/smarty</B>";
554        $output = implode("\n", $output);
555        print "<PRE><B>wget \"$smarty_full_url\"</B>\n$output</PRE>";
556        exit();
557      } else {
558        print "OK<BR>";
559      }
560
561      print "Uncompressing : ";
562      $dirname = array_shift(split(".tar.gz", $filename));
563
564      if (!file_exists($dirname))
565        exec("tar -xzf $dirname.tar.gz &>/tmp/tar.output", $output, $return);
566      print "OK<BR>";
567
568      exec("pwd", $output, $return);
569      print "Copying : ";
570      if (!file_exists("$basepath/lib/smarty"));
571        exec("cp -r $dirname/libs/* $basepath/lib/smarty &>/tmp/cp.output", $output, $return); # TODO : Utiliser SMARTY_REL_PATH
572      print "OK<BR>";
573
574      refreshButton();
575    }
576    navigation(array(array("title" => "Back", "page" => "permission"), array("title" => "Next", "page" => "magpierss")));
577  break;
578  ###################################
579  case 'magpierss': // Download, uncompress and install MagpieRSS
580    print "<H1>MagpieRSS installation</H1>\n";
581   
582    if ( $neededPackages['magpierss']['available']) {
583      print "Already installed !<BR>";
584      navigation(array(array("title" => "Back", "page" => "smarty"), array("title" => "Next", "page" => "phlickr")));
585    }
586    elseif ($action == 'install') {
587      chdir("$basepath/tmp");
588      $filename = array_pop(preg_split("/\//", $magpierss_full_url));
589     
590      print "Download source code ($filename) : ";
591      if (!file_exists($filename))
592        exec("wget \"$magpierss_full_url\" 2>&1", $output, $return);
593      if (!file_exists($filename)) {
594        print "<B STYLE=\"color:red\">Error</B><P>Current working directory : <B>$basepath/tmp/smarty</B>";
595        $output = implode("\n", $output);
596        print "<PRE><B>wget \"$magpierss_full_url\"</B>\n$output</PRE>";
597        exit();
598      } else {
599        print "OK<BR>";
600      }
601
602      print "Uncompressing : ";
603      $dirname = array_shift(split(".tar.gz", $filename));
604      if (!file_exists($dirname))
605        exec("tar -xzf $dirname.tar.gz &>/tmp/tar.output", $output, $return);
606      print "OK<BR>";
607
608      print "Copying : ";
609      exec("cp -r $dirname/* ../lib/magpie &>/tmp/cp.output", $output, $return); # TODO : Utiliser MAGPIE_REL_PATH
610      print "OK<BR>";
611
612      refreshButton();
613      navigation(array(array("title" => "Back", "page" => "smarty"), array("title" => "Next", "page" => "phlickr")));
614    }
615    else {
616      print <<< EndHTML
617<P><A HREF="http://magpierss.sourceforge.net/">MagpieRSS</A> provides an XML-based (expat) RSS parser in PHP. MagpieRSS is needed by Wifidog for RSS feeds. It's is recommended to install MagpieRSS, if you don't, RSS feeds options will be disable.
618
619<P>Do you want to install MagpieRSS ?
620EndHTML;
621      navigation(array(array("title" => "Back", "page" => "smarty"), array("title" => "Install", "page" => "magpierss", "action" => "install"), array("title" => "Next", "page" => "phlickr")));
622    }
623  break;
624  ###################################
625  case 'phlickr': // Download, uncompress and install phlickr library
626    print "<H1>Phlickr installation</H1>\n";
627
628    if ( $neededPackages['phlickr']['available']) {
629      print "Already installed !<BR>";
630      navigation(array(array("title" => "Back", "page" => "magpierss"), array("title" => "Next", "page" => "jpgraph")));
631    }
632    elseif ($action == 'install') {
633      chdir("$basepath/tmp");
634      $filename = array_pop(preg_split("/\//", $phlickr_full_url));
635
636      print "Download source code ($filename) : ";
637      if (!file_exists($filename))
638        exec("wget \"$phlickr_full_url\" 2>&1", $output, $return);
639      if (!file_exists($filename)) { # Error occured, print output of wget
640        print "<B STYLE=\"color:red\">Error</B><P>Current working directory : <B>$basepath/tmp/smarty</B>";
641        $output = implode("\n", $output);
642        print "<PRE><B>wget \"$phlickr_full_url\"</B>\n$output</PRE>";
643        exit();
644      } else {
645        print "OK<BR>";
646      }
647
648      print "Uncompressing : ";
649      $dirname = array_shift(split(".tgz", $filename));
650      if (!file_exists($dirname))
651        exec("tar -xzf $dirname.tgz &>/tmp/tar.output", $output, $return);
652      print "OK<BR>";
653
654      print "Copying : ";
655      if (!file_exists('../../lib/Phlickr/Photo.php'))
656        exec("cp -r $dirname/* ../lib/Phlickr &>/tmp/cp.output", $output, $return); # TODO : Utiliser PHLICKR_REL_PATH
657      print "OK<BR>";
658
659      refreshButton();
660      navigation(array(array("title" => "Back", "page" => "magpierss"), array("title" => "Next", "page" => "jpgraph")));
661    }
662    else {
663      print <<< EndHTML
664<P><A HREF="http://phlickr.sourceforge.net/">Phlickr</A> is an opensource PHP5 based API kit used to access the Flickr API. <A HREF="http://flickr.com/">Phlick</A> help people make their photos available to the people who matter to them. Phlick allows Wifidog to share common hotspot pictures. It's is recommended to install Phlickr, if you don't, Phlickr options will be disable.
665
666<P>Do you want to install Phlickr ?
667EndHTML;
668      navigation(array(array("title" => "Back", "page" => "magpierss"), array("title" => "Install", "page" => "phlickr", "action" => "install"), array("title" => "Next", "page" => "jpgraph")));
669    }
670  break;
671  ###################################
672  case 'jpgraph': // Download, uncompress and install phlickr library
673    print "<H1>JpGraph installation</H1>\n";
674
675    if ( $neededPackages['jpgraph']['available']) {
676      print "Already installed !<BR>";
677      navigation(array(array("title" => "Back", "page" => "phlickr"), array("title" => "Next", "page" => "database")));
678    }
679    elseif ($action == 'install') {
680      chdir("$basepath/tmp");
681      $filename = array_pop(preg_split("/\//", $jpgraph_full_url));
682
683      print "Download source code ($filename) : ";
684      if (!file_exists($filename))
685        exec("wget \"$jpgraph_full_url\" 2>&1", $output, $return);
686      if (!file_exists($filename)) { # Error occured, print output of wget
687        print "<B STYLE=\"color:red\">Error</B><P>Current working directory : <B>$basepath/tmp</B>";
688        $output = implode("\n", $output);
689        print "<PRE><B>wget \"$jpgraph_full_url\"</B>\n$output</PRE>";
690        exit();
691      } else {
692        print "OK<BR>";
693      }
694
695      print "Uncompressing : ";
696      $dirname = array_shift(split(".tar.gz", $filename));
697      if (!file_exists($dirname))
698        exec("tar -xzf $dirname.tar.gz &>/tmp/tar.output", $output, $return);
699      print "OK<BR>";
700
701      print "Copying : ";
702      if (!file_exists('../../lib/jpgraph/jpgraph.php'))
703        exec("cp $dirname/src/* ../lib/jpgraph &>/tmp/cp.output", $output, $return); # TODO : Utiliser JPGRAPH_REL_PATH
704
705      print "OK<BR>";
706
707      refreshButton();
708      navigation(array(array("title" => "Back", "page" => "phlickr"), array("title" => "Next", "page" => "database")));
709    }
710    else {
711      print <<< EndHTML
712<P><A HREF="http://www.aditus.nu/jpgraph/">JpGraph</A> is a Object-Oriented Graph creating library for PHP.
713JpGraph is not currently use by Wifidog (will be use for statistique graph in a later version). You can skip this installation if your not a developper.
714
715<P>Do you want to install JpGraph ?
716EndHTML;
717      navigation(array(array("title" => "Back", "page" => "phlickr"), array("title" => "Install", "page" => "jpgraph", "action" => "install"), array("title" => "Next", "page" => "database")));
718    }
719  break;
720  ###################################
721  case 'database':
722    ### TODO : Valider en javascript que les champs soumit ne sont pas vide
723    #          Pouvoir choisir le port de la DB ???
724    print <<< EndHTML
725<H1>Database access configuration</H1>
726<BR>
727<TABLE border="1">
728  <TR><TD>DB</TD><TD><SELECT name="CONF_DBMS">
729
730EndHTML;
731
732    foreach($configArray as $key => $value) {  # In config.php, find all DBMS_* define
733          if (preg_match("/^(DBMS_)(.*)/", $key, $matchesArray)) {
734        $dbname_lower = strtolower($matchesArray[2]);
735        if ($dbname_lower == 'postgres') # config.php use postgres and PHP use pgsql
736          $dbname_lower = 'pgsql';
737        if ($neededExtentions[$dbname_lower]['available'] == 0) # Validate dependencie
738          continue;
739        if ($CONF_DBMS == $key)
740          print "    <OPTION value=\"$key\" SELECTED>" . $matchesArray[2] . "</OPTION>\n";
741        else
742          print "    <OPTION value=\"$key\">" . $matchesArray[2] . "</OPTION>\n";
743      }
744        }   
745
746    print <<< EndHTML
747  </TD></TR>
748  <TR><TD>Host</TD><TD><INPUT type="text" name="CONF_DATABASE_HOST" value="$CONF_DATABASE_HOST"></TD></TR>
749  <TR><TD>DB Name</TD><TD><INPUT type="text" name="CONF_DATABASE_NAME" value="$CONF_DATABASE_NAME"></TD></TR>
750  <TR><TD>Username</TD><TD><INPUT type="text" name="CONF_DATABASE_USER" value="$CONF_DATABASE_USER"></TD></TR>
751  <TR><TD>Password</TD><TD><INPUT type="text" name="CONF_DATABASE_PASSWORD" value="$CONF_DATABASE_PASSWORD"></TD></TR>
752</TABLE>
753
754<P>By clicking Next, your configuration will be automaticaly saved
755
756<script type="text/javascript">
757  function submitDatabaseValue() {
758    newConfig("CONF_DBMS=" + document.myform.CONF_DBMS.value);
759    newConfig("CONF_DATABASE_HOST='" + document.myform.CONF_DATABASE_HOST.value + "'");
760    newConfig("CONF_DATABASE_NAME='" + document.myform.CONF_DATABASE_NAME.value + "'");
761    newConfig("CONF_DATABASE_USER='" + document.myform.CONF_DATABASE_USER.value + "'");
762    newConfig("CONF_DATABASE_PASSWORD='" + document.myform.CONF_DATABASE_PASSWORD.value + "'");
763  }
764</script>
765
766<P><B>Note</B> : MySQL support is presently experimental and not working</P>
767
768EndHTML;
769
770    navigation(array(array("title" => "Back", "page" => "magpierss"))); #, array("title" => "Next", "page" => "testdatabase")));
771    print <<< EndHTML
772<P><A HREF="javascript: document.myform.page.value='testdatabase'; submitDatabaseValue(); document.myform.submit();" CLASS="button">Next</A></P>
773
774EndHTML;
775
776  break;
777  ###################################
778  case 'testdatabase':
779    print "<H1>Database connection</H1>";
780    /* TODO : Tester la version minimale requise de MySQL et Postgresql
781              Tester si MySQL supporte InnoDB                           */
782
783    switch ($CONF_DBMS) {
784      case 'DBMS_POSTGRES':
785        print "<UL><LI>Postgresql database connection : ";
786
787        $conn_string = "host=$CONF_DATABASE_HOST dbname=$CONF_DATABASE_NAME user=$CONF_DATABASE_USER password=$CONF_DATABASE_PASSWORD";
788        $ptr_connexion = pg_connect($conn_string) or die(); # or die("Couldn't Connect ==".pg_last_error()."==<BR>");
789
790        #if ($ptr_connexion == TRUE) {
791          print "Success<BR>";
792        #}
793#        } else {
794#          print "Unable to connect to database on $CONF_DATABASE_HOST<BR>The database must be online to continue.<BR>Please go back and retry with correct values";
795#          navigation(array(array("title" => "Back", "page" => "database")));
796#        }
797
798        $postgresql_info = pg_version();
799#        $postgresql_info['server'];
800#        if ($postgresql_info['server'] > $requiredPostgeSQLVersion) { Todo : Do something }
801
802        print "</UL>";
803        refreshButton();
804        navigation(array(array("title" => "Back", "page" => "database"), array("title" => "Next", "page" => "dbinit")));
805      break;
806      ###################################
807      case 'DBMS_MYSQL':
808        $ptr_connexion = @mysql_connect($CONF_DATABASE_HOST, $CONF_DATABASE_USER, $CONF_DATABASE_PASSWORD);
809        print "<UL>\n";
810
811        if ($ptr_connexion == TRUE) {
812          print "<LI>MySQL database connection : Success";
813
814          $mysql_server_version = mysql_get_server_info();
815            print("<LI>MySQL server version: $mysql_server_version");
816
817          #if ($mysql_server_version > $requiredMySQLVersion) { Todo : Do something }
818
819          #printf("<LI>MySQL host info: %s\n", mysql_get_host_info());
820
821          print "<LI>Select DB $CONF_DATABASE_NAME : ";
822          $select_db = mysql_select_db($CONF_DATABASE_NAME);
823
824          if($select_db == TRUE) {
825            print "Success</UL>";
826              navigation(array(array("title" => "Back", "page" => "database"), array("title" => "Next", "page" => "dbinit")));
827          } else {
828            print "</UL>ERROR (Unable to select the database)<BR>";
829            refreshButton();
830            navigation(array(array("title" => "Back", "page" => "database")));
831          }
832        } else {
833          print "Unable to connect to database on <B>$CONF_DATABASE_HOST</B><BR>The database must be online to continue.<P>Please go back and retry with correct values";
834          refreshButton();
835          navigation(array(array("title" => "Back", "page" => "database")));
836        }
837      break;
838      default:
839        print <<<EndHTML
840          The CONF_DBMS value <B>$CONF_DBMS</B> is not currently suported by this install script.
841EndHTML;
842        navigation(array(array("title" => "Back", "page" => "database")));
843    }
844  break;
845  ###################################
846  case 'dbinit':
847    print "<H1>Database initialisation</H1>";
848
849    # SQL are executed with PHP, some lignes need to be commented
850    $file_db_version = 'UNKNOW';
851    $patterns[0]     = '/CREATE DATABASE wifidog/';
852    $patterns[1]     = '/\\\connect/';
853    $patterns[2]     = '/COMMENT/';
854    $patterns[3]     = '/SET default_tablespace/';
855    $patterns[4]     = '/SET default_with_oids/';
856    $replacements[0] = '-- ';
857    $replacements[1] = '-- ';
858    $replacements[2] = '-- ';
859    $replacements[3] = '-- ';
860    $replacements[4] = '-- ';
861
862    $content_schema_array = file("$basepath/../sql/wifidog-postgres-schema.sql");       # Read SQL schema file
863    $content_schema       = implode("", $content_schema_array);
864    $content_data_array   = file("$basepath/../sql/wifidog-postgres-initial-data.sql"); # Read SQL initial data file
865    $content_data         = implode("", $content_data_array);
866
867    $db_schema_version   = ''; # Schema version query from database
868    $file_schema_version = ''; # Schema version from define(REQUIRED_SCHEMA_VERSION) in schema_validate.php
869
870    switch ($CONF_DBMS) {
871      case 'DBMS_POSTGRES':
872        $conn_string = "host=$CONF_DATABASE_HOST dbname=$CONF_DATABASE_NAME user=$CONF_DATABASE_USER password=$CONF_DATABASE_PASSWORD";
873        $connection = pg_connect($conn_string) or die(); # or die("Couldn't Connect ==".pg_last_error()."==<BR>");
874
875        if (preg_match("/\('schema_version', '(\d+)'\);/", $content_data, $matchesArray)) # Get schema_version from initial data file
876          $file_db_version = $matchesArray[1];
877
878        $contentArray = file("$basepath/include/schema_validate.php");
879        foreach($contentArray as $line) {
880          #print "$line<BR>"; # Debug
881          if(preg_match("/^define\('REQUIRED_SCHEMA_VERSION', (\d+)\);/", $line, $matchesArray)) {
882            #print "REQUIRED_SCHEMA_VERSION = " . $matchesArray[1] . "<BR>";
883            $file_schema_version = $matchesArray[1];
884          }   
885        }
886       
887        # Get current database schema version (if defined)
888        $sql = "SELECT * FROM schema_info WHERE tag='schema_version'";
889        if ($result = @pg_query($connection, $sql)) { # The @ remove warning display
890          $result_array = pg_fetch_all($result);
891          $db_shema_version = $result_array[0]['value'];
892
893          print "<P>On <B>$CONF_DATABASE_HOST</B>, Database <B>$CONF_DATABASE_NAME</B> exists and is ";
894          if ($db_shema_version == $file_schema_version) {
895            print "up to date (shema version <B>$db_shema_version</B>).";
896            navigation(array(array("title" => "Back", "page" => "database"), array("title" => "Next", "page" => "options")));
897          } elseif ($db_shema_version < $file_schema_version) {
898            print "at schema version <B>$db_shema_version</B>. The required schema version is <B>$file_schema_version</B><P>Please upgrade the database";
899            navigation(array(array("title" => "Back", "page" => "database"), array("title" => "Upgrade", "page" => "schema_validate"), array("title" => "Next", "page" => "options")));
900          }
901          else { print "Error : Unexpected result"; }
902          exit();
903        }
904
905        print "<UL><LI>Creating wifidog database schema : ";
906        $content_schema = preg_replace($patterns, $replacements, $content_schema); # Comment bad SQL lines
907
908        $result = pg_query($connection, $content_schema) or die("<B>".pg_last_error()."</B> <=<BR>");
909        print "OK";
910
911        print "<LI>Creating wifidog database initial data : ";
912        $content_data = preg_replace($patterns, $replacements, $content_data); # Comment bad SQL lines
913
914        $result = pg_query($connection, $content_data) or die("<B>".pg_last_error()."</B> <=<BR>");
915        print "OK</UL>";
916
917        navigation(array(array("title" => "Back", "page" => "database"), array("title" => "Next", "page" => "options")));
918      break;
919      ###################################
920      case 'DBMS_MYSQL':
921        print "MYSQL ... (Not working)<BR>\n";
922        $ptr_connexion = @mysql_connect($CONF_DATABASE_HOST, $CONF_DATABASE_USER, $CONF_DATABASE_PASSWORD);
923        $select_db = mysql_select_db($CONF_DATABASE_NAME);
924
925        $previous_line = ''; # Used to remove "," on the line before CONSTRAINT removed line.
926
927        if ($debug) print "<PRE>";
928
929        $inTable = 0;
930        foreach ($content_schema_array as $lineNum => $line) {         
931#          if (preg_match("/^--/", $line)) continue; # Remove commented lines
932#          if (preg_match("/^$/", $line))  continue; # Remove empty lines
933          if ($debug) print "<B>ORI</B> $line";
934          if (preg_match("/^CREATE TABLE/", $line, $matchesArray))
935            $inTable = 1;
936          if ($inTable) {
937            if ($inTable && preg_match("/^\);$/", $line, $matchesArray)) {
938              #print "<B STYLE=\"color:#FF0000;\">OUT</B>\n";
939
940              # PG    => );
941              # MySQL => ) TYPE=InnoDB;
942              $line = preg_replace("/^\);$/", ") TYPE=InnoDB;", $line);
943              $inTable = 0;
944            }
945            else {
946              #print "<B>IN  \n</B>"; # The line is in CREATE TABLE
947
948              if(preg_match("/\s*CONSTRAINT.*\n$/", $line)) { # Remove CONSTRAINT. TODO : support constraint
949                $line = preg_replace("/\s*CONSTRAINT.*\n$/", "", $line);
950                $previous_line = preg_replace("/,$/", "", $previous_line);
951                #print "<B STYLE=\"color:#FF0000;\">ICI : L=$line PL=$previous_line</B>";
952              }
953              # Mettre TYPE=InnoDB uniquement pour table avec CONSTRAINT ???
954
955              # PG    =>  token_status character varying(10) NOT NULL
956              # MySQL => `token_status` character varying(10) NOT NULL
957              $line = preg_replace("/^(\s+)(\w+)/", "\${1}`\${2}`", $line);
958
959              $line = preg_replace("/DEFAULT ('.*')::character varying NOT NULL/", "NOT NULL default \${1}", $line);
960
961              $line = preg_replace("/text DEFAULT [\w':]+/", "text DEFAULT ''", $line); # MySQL does not support "text" default value
962              #??? Erreur : 1101 - BLOB/TEXT column 'venue_type' can't have a default value. Solution : Changer 'text' pour varchar ???
963
964              # PG    =>  token_status character varying(10) NOT NULL
965              # MySQL =>  token_status VARCHAR(10) NOT NULL
966              $line = preg_replace("/character varying\(/", "VARCHAR(", $line);
967
968              $line = preg_replace("/::character varying/", "", $line); # Remove string "::character varying"
969
970              # PG    => account_status integer,
971              # MySQL => account_status int,
972              $line = preg_replace("/integer/", "int", $line);
973
974              # TODO : Comprendre : Le timestamp de postgres est sous le format '2005-04-07 16:33:49.917127'
975              #                     datetime de MySQL est '0000-00-00 00:00:00'
976              $line = preg_replace("/timestamp without time zone/", "datetime", $line);
977
978              $line = preg_replace("/now\(\)/", "'NOW()'", $line);
979
980              #$line = preg_replace("/::text/", "", $line);
981
982              $line = preg_replace("/false/", "0", $line); # Change "false" strings for 0 (zero)
983              $line = preg_replace("/true/", "1", $line);  # Change "true" strings for 1 (one)
984              $line = preg_replace("/WITHOUT OIDS/", "", $line); # Remove "WITHOUT OIDS"
985
986              # PG    => binary_data bytea,
987              # MySQL => binary_data MEDIUMBLOB
988              # Uploading, Saving and Downloading Binary Data in a MySQL Database http://www.onlamp.com/lpt/a/370
989              $line = preg_replace("/bytea/", "MEDIUMBLOB", $line); # maximum 16777215 (2^24 - 1) bytes
990            } ### End of else. Regex in CREATE TABLE {};
991          } ### End of if ($inTable).
992
993          # PG    => CREATE INDEX idx_token ON connections USING btree (token);
994          # MySQL => CREATE INDEX idx_token USING btree ON connections (token);
995          $line = preg_replace("/(ON \w+) USING btree/", "USING btree \${1}", $line);
996
997          # SQL-query : CREATE UNIQUE INDEX idx_unique_username_and_account_origin USING btree ON users(username,account_origin)
998          # MySQL said: #1170 - BLOB/TEXT column 'username' used in key specification without a key length
999          # Solution : http://www.dbforums.com/t1100992.html
1000          $line = preg_replace("/CREATE UNIQUE INDEX idx_unique_username_and_account_origin USING btree ON users \(username, account_origin\);/", "CREATE UNIQUE INDEX idx_unique_username_and_account_origin USING btree ON users (username(100), account_origin(100));", $line);
1001
1002          $line = preg_replace("/CREATE INDEX idx_content_group_element_content_group_id USING btree ON content_group_element \(content_group_id\);/", "CREATE INDEX idx_content_group_element_content_group_id USING btree ON content_group_element (content_group_id(100));", $line);
1003
1004          if ($debug) print "NEW $line";
1005            $content_mysql .= $previous_line
1006          $previous_line = $line;
1007        } ### End of foreach ($content_schema_array as $lineNum => $line)
1008
1009        $content_mysql .= $previous_line; # TODO: verif save the last line ?
1010        if ($debug) print "<B STYLE=\"color:#FF0000;\">####################################################################</B>\n\n$content_mysql"; # Debug
1011        if ($debug) print "</PRE>";
1012
1013#        $content_data = implode("", $content_mysql);
1014
1015        $patterns[3]     = '/SET client_encoding/';
1016        $patterns[4]     = '/SET check_function_bodies/';
1017        $patterns[5]     = '/SET search_path/';
1018        $replacements[3] = '-- ';
1019        $replacements[4] = '-- ';
1020        $replacements[5] = '-- ';
1021
1022        $content_mysql = preg_replace($patterns, $replacements, $content_mysql);
1023
1024        print "<PRE>$content_mysql</PRE>"; # Debug
1025
1026        exit();
1027
1028        $result = mysql_query($content_mysql);
1029        if (!$result) {
1030          die('Invalid query: ' . mysql_error());
1031        }
1032
1033        navigation(array(array("title" => "Back", "page" => "database"), array("title" => "Next", "page" => "dbinit")));
1034      break;
1035      default:
1036        print <<<EndHTML
1037          The CONF_DBMS value <B>$CONF_DBMS</B> is not currently suported by this install script.
1038EndHTML;
1039        navigation(array(array("title" => "Back", "page" => "database")));
1040    }
1041  break;
1042
1043  ###################################
1044  case 'schema_validate':
1045    print "<H1>Database schema upgrade</H1>\n";
1046    define('BASEPATH', './');
1047    require_once BASEPATH.'include/common.php';
1048    require_once BASEPATH.'config.php';
1049    require_once BASEPATH.'classes/AbstractDb.php';
1050    require_once BASEPATH.'classes/Session.php';
1051    require_once BASEPATH.'include/schema_validate.php';
1052    validate_schema();
1053
1054    navigation(array(array("title" => "Back", "page" => "dbinit"), array("title" => "Next", "page" => "options")));
1055   
1056    //navigation(array(array("title" => "Back", "page" => "dbinit")));
1057  break;
1058
1059  ###################################
1060  case 'options':
1061    # TODO : Tester que la connection SSL est fonctionnelle
1062    #        Options avancees : Supporter les define de [SMARTY|MAGPIE|PHLICKR|JPGRAPH]_REL_PATH
1063    print <<< EndHTML
1064<H1>Options</H1>
1065<P>Not yet finished ... (dependencies autodetection and few other options)</P>
1066  <TABLE border="1">
1067
1068EndHTML;
1069
1070    #$neededPackages['phlickr']['available'] = 0;
1071    #$neededExtentions['xml']['available'] = 0;
1072    foreach ($optionsInfo as $name => $foo) {         # Foreach generate all <TABLE> fields
1073      $value  = $configArray[$name];                  # Value of option in config.php
1074      $title  = $optionsInfo[$name]['title'];         # Field Title
1075      $message = $optionsInfo[$name]['message'];      # Message why option is disable
1076      $depend = @eval($optionsInfo[$name]['depend']); # Evaluate the dependencie
1077      $selectedTrue = ''; $selectedFalse = '';        # Initialize value
1078      $value  == 'true' ? $selectedTrue = 'SELECTED' : $selectedFalse = 'SELECTED';           # Use to select the previous saved option
1079      $depend == 1      ? $disabled     = ''         : $disabled = 'DISABLED';                # Disable <SELECT> if dependencie is not satisfied
1080      $jscript = "<script type=\"text/javascript\"> newConfig(\"$name=false\"); </script>\n"; # Use to save a failed dependencie (option=false)
1081      if ($disabled == '') # Dependencie ok, erase $jscript value
1082        $jscript = '';
1083
1084      print <<< EndHTML
1085  <TR>
1086    <TD>$title</TD>
1087    <TD><SELECT name="$name" $disabled>
1088          <OPTION value="true" $selectedTrue>true</OPTION>
1089          <OPTION value="false" $selectedFalse>false</OPTION>
1090        </SELECT>
1091    </TD>
1092    <TD>$message</TD>
1093  </TR>
1094  $jscript
1095EndHTML;
1096    } # End or foreach
1097    print <<< EndHTML
1098    </TABLE>
1099
1100<script type="text/javascript">
1101  function submitOptionsValue() {
1102
1103EndHTML;
1104
1105    foreach ($optionsInfo as $name => $foo) { # Generate the javascript to save value on submit
1106    print <<< EndHTML
1107    if (!document.myform.$name.disabled)
1108      newConfig("$name=" + document.myform.$name.value);
1109
1110EndHTML;
1111    } # End Foreach
1112
1113    print <<< EndHTML
1114  }
1115</script>
1116
1117EndHTML;
1118    navigation(array(array("title" => "Back", "page" => "dbinit")));
1119
1120    print <<< EndHTML
1121<P><A HREF="javascript: document.myform.page.value='languages'; submitOptionsValue(); document.myform.submit();" CLASS="button">Next</A></P>
1122EndHTML;
1123
1124  break;
1125
1126  ###################################
1127  case 'languages':
1128    print "<H1>Languages configuration</H1>";
1129    print <<< EndHTML
1130      <P>Not yet implemented ...</P>
1131      <P>Will allow wich language can be use and correct error from unknown locale information</P>
1132<B>Errror message example</B> : <BR>
1133<DIV style="border:solid black;">Warning: language.php: Unable to setlocale() to fr, return value: , current locale: LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C; [...]</DIV>
1134EndHTML;
1135//    exec("locale -a 2>&1", $output, $return);
1136   
1137    navigation(array(array("title" => "Back", "page" => "options"), array("title" => "Next", "page" => "radius")));
1138  break;
1139
1140  ###################################
1141  case 'radius':
1142    print "<H1>Radius configuration</H1>";
1143    print "<P>Not yet implemented ...";
1144
1145    # Dependencies
1146    #$neededExtentions['mcrypt']['available'];
1147    #$neededExtentions['mhash']['available'];
1148    #$neededExtentions['xmlrpc']['available'];
1149    #$neededPEARPackages['radius']['available'];   
1150    #$neededPEARPackages['Auth_RADIUS']['available'];
1151    #$neededPEARPackages['Crypt_CHAP']['available'];     
1152
1153    navigation(array(array("title" => "Back", "page" => "languages"), array("title" => "Next", "page" => "admin")));
1154  break;
1155
1156  ###################################
1157  case 'admin':
1158    print "<H1>Administration account</H1>";
1159    # TODO : Allow to create more than one admin account and list the current admin users
1160    #        Allow admin to choose to show or not is username
1161    empty($_REQUEST['username'])  ? $username   = 'admin'                  : $username   = $_REQUEST['username'];
1162    empty($_REQUEST['password'])  ? $password   = ''                       : $password   = $_REQUEST['password'];
1163    empty($_REQUEST['password2']) ? $password2  = ''                       : $password2  = $_REQUEST['password2'];
1164    empty($_REQUEST['email'])     ? $email      = $_SERVER['SERVER_ADMIN'] : $email      = $_REQUEST['email'];
1165
1166    $conn_string = "host=$CONF_DATABASE_HOST dbname=$CONF_DATABASE_NAME user=$CONF_DATABASE_USER password=$CONF_DATABASE_PASSWORD";
1167    $connection = pg_connect($conn_string) or die();
1168
1169    if ($action == 'create') {
1170      define('BASEPATH', './');
1171      require_once BASEPATH.'classes/User.php';
1172
1173      $created_user = User :: CreateUser(get_guid(), $username, 'LOCAL_USER', $email, $password);
1174      $user_id = $created_user->getId();
1175
1176      # Add user to admin table, hide his username and set his account status to 1 (allowed)
1177      $sql = "INSERT INTO administrators (user_id) VALUES ('" . $created_user->getId() . "'); UPDATE users SET  account_status='1', never_show_username=true WHERE user_id='$user_id'";
1178      $result = pg_query($connection, $sql);
1179    }
1180
1181    $sql = "SELECT * FROM users NATURAL JOIN administrators WHERE account_origin = 'LOCAL_USER'";
1182    $result = pg_query($connection, $sql);
1183    $result_array = pg_fetch_all($result);
1184    $username_db = $result_array[0]['username'];
1185
1186    if (!empty($username_db)) {
1187      print "<P>Your administrator user account is <B>$username_db</B>";
1188      navigation(array(array("title" => "Back", "page" => "radius"), array("title" => "Next", "page" => "network")));
1189    }
1190    else {
1191      print<<<EndHTML
1192        <P>
1193        <TABLE BORDER="1">
1194        <TR>
1195          <TD>Username</TD><TD><INPUT type="text" name="username" value="$username"></TD>
1196        </TR>
1197        <TR>
1198          <TD>Password</TD><TD><INPUT type="password" name="password"></TD>
1199        </TR>
1200        <TR>
1201          <TD>Password again</TD><TD><INPUT type="password" name="password2"></TD>
1202        </TR>
1203        <TR>
1204          <TD>Email</TD><TD><INPUT type="text" name="email" value="$email"></TD>
1205        </TR>
1206        </TABLE>
1207
1208        <script type="text/javascript">
1209          function submitValue() {
1210            if (document.myform.password.value != document.myform.password2.value) {
1211              alert('Password mismatch, Please retry');
1212              exit();
1213            }
1214            if (document.myform.password.value == '') {
1215              alert('You need to type a password');
1216              exit();
1217            }
1218            if (document.myform.email.value == '') {
1219              alert('You need to type a email');
1220              exit();
1221            }
1222            document.myform.page.value='admin';
1223            document.myform.action.value='create';
1224            document.myform.submit();
1225          }
1226        </script>
1227
1228EndHTML;
1229    navigation(array(array("title" => "Back", "page" => "radius")));
1230    print "<P><A HREF=\"javascript: submitValue();\" CLASS=\"button\">Next</A></P>\n";
1231    }
1232  break;
1233
1234  ###################################
1235  case 'network':
1236    print "<H1>Network</H1>";
1237
1238    $HOTSPOT_NETWORK_NAME          = $configArray['HOTSPOT_NETWORK_NAME'];
1239    $HOTSPOT_NETWORK_URL           = $configArray['HOTSPOT_NETWORK_URL'];
1240    $TECH_SUPPORT_EMAIL            = $configArray['TECH_SUPPORT_EMAIL'];
1241    //$UNKNOWN_HOSTPOT_NAME          = $configArray['UNKNOWN_HOSTPOT_NAME'];
1242    $VALIDATION_GRACE_TIME         = $configArray['VALIDATION_GRACE_TIME'];
1243    $VALIDATION_EMAIL_FROM_ADDRESS = $configArray['VALIDATION_EMAIL_FROM_ADDRESS'];   
1244
1245    print <<< EndHTML
1246  <P>
1247  <TABLE border="1">
1248  <TR>
1249    <TD>Network Name</TD><TD><INPUT type="text" name="HOTSPOT_NETWORK_NAME" value="$HOTSPOT_NETWORK_NAME" size="30"></TD>
1250  </TR>
1251  <TR>
1252    <TD>Network URL</TD><TD><INPUT type="text" name="HOTSPOT_NETWORK_URL" value="$HOTSPOT_NETWORK_URL" size="30"></TD>
1253  </TR>
1254  <TR>
1255    <TD>Tech Support Email</TD><TD><INPUT type="text" name="TECH_SUPPORT_EMAIL" value="$TECH_SUPPORT_EMAIL" size="30"></TD>
1256  </TR>
1257  <TR>
1258    <TD>Validation Grace Time (min)</TD><TD><INPUT type="text" name="VALIDATION_GRACE_TIME" value="$VALIDATION_GRACE_TIME" size="30"></TD>
1259  </TR>
1260  <TR>
1261    <TD>Validation Email (send from)</TD><TD><INPUT type="text" name="VALIDATION_EMAIL_FROM_ADDRESS" value="$VALIDATION_EMAIL_FROM_ADDRESS" size="30"></TD>
1262  </TR>
1263  </TABLE>
1264
1265<script type="text/javascript">
1266  function submitOptionsValue() {
1267    newConfig("HOTSPOT_NETWORK_NAME='" + document.myform.HOTSPOT_NETWORK_NAME.value + "'");
1268    newConfig("HOTSPOT_NETWORK_URL='" + document.myform.HOTSPOT_NETWORK_URL.value + "'");
1269    newConfig("TECH_SUPPORT_EMAIL='" + document.myform.TECH_SUPPORT_EMAIL.value + "'");
1270   /* newConfig("UNKNOWN_HOSTPOT_NAME='" + document.myform.UNKNOWN_HOSTPOT_NAME.value + "'"); */
1271    newConfig("VALIDATION_GRACE_TIME=" + document.myform.VALIDATION_GRACE_TIME.value);
1272    newConfig("VALIDATION_EMAIL_FROM_ADDRESS='" + document.myform.VALIDATION_EMAIL_FROM_ADDRESS.value + "'");
1273  }
1274</script>
1275
1276    <P><B>Note</B>: One Wifidog Authentification Server instance will support many network soon. Waiting for new Network implementation/abstraction to become more sophisticated.
1277
1278EndHTML;
1279    navigation(array(array("title" => "Back", "page" => "admin")));
1280
1281    print <<< EndHTML
1282<P><A HREF="javascript: document.myform.page.value='hotspot'; submitOptionsValue(); document.myform.submit();" CLASS="button">Next</A></P>
1283EndHTML;
1284    #navigation(array(array("title" => "Back", "page" => "admin"), array("title" => "Next", "page" => "hotspot")));
1285  break;
1286
1287  ###################################
1288  case 'hotspot':
1289    print "<H1>Hotspot</H1>";
1290    print "<P>Not yet implemented and maybe not needed<P>Default hotstop already created<P>Use administration interface to add new one";
1291    navigation(array(array("title" => "Back", "page" => "network"), array("title" => "Next", "page" => "end")));
1292  break;
1293
1294  ###################################
1295  case 'delete':
1296    print<<<EndHTML
1297  <H1>Delete temporary files</H1>
1298  ...
1299EndHTML;
1300    #navigation(array(array("title" => "Back", "page" => "hotspot")));
1301  break;
1302
1303  ###################################
1304  case 'end':
1305    $url = 'http://' . $_SERVER['HTTP_HOST'] . $system_path;
1306    print<<<EndHTML
1307  <H1>Thanks for using Wifidog</H1>
1308  Redirection to your new Wifidog Authentification Server in few secondes
1309  <meta http-equiv="REFRESH" content="3;url=$url">
1310  <PRE>
1311
1312               |\   /|              _
1313               |A\_/A|            z   z
1314            ___|     |           ( (o) )
1315           o    6     \           z _ z
1316           |___        \           /|
1317               |        \         / |
1318                \        \_______/  |
1319                |                   |
1320                |      WIFIDOG      |
1321                |   Captive Portal  |
1322                |   _____________   |
1323                |  /             \  |
1324                |  |             |  |
1325                |  |             |  |
1326              _/   |           _/   |
1327             ?_____|          ?_____|
1328</PRE>
1329EndHTML;
1330    #navigation(array(array("title" => "Back", "page" => "hotspot")));
1331  break;
1332
1333  ###################################
1334  case 'toc':
1335    print "<H1>Table of content</H1>";
1336    $contentArray = file(__file__); # Read myself
1337    print "<UL>\n";
1338    foreach($contentArray as $line) {
1339      if(preg_match("/^  case '(\w+)':/", $line, $matchesArray)) { # Parse for "case" regex
1340        if ($matchesArray[1] == 'toc')
1341          continue;
1342        print "<LI><A HREF=\"" . $_SERVER['SCRIPT_NAME'] . "?page=" . $matchesArray[1] . "\">" . $matchesArray[1] . "</A>\n";  # Display a Table of Content
1343      }   
1344    }
1345    print "</UL>\n";
1346  break;
1347  ###################################
1348  case 'notes':
1349    print <<<EndHTML
1350<!-- /* Editor highlighting trick -->
1351<PRE>
1352<B>TODO</B>
1353  -Support des define de Google Maps dans config.php
1354  -Faire une fonction d'execution avec gestion de retour d'erreur et d'affichage de l'exection pour chaque "exec"
1355  -Ajouter une veritable validation (user/password admin provenant de la DB)
1356     Pour une meilleur securite du script d'installation.
1357       Au chargement, valider que la connection DB est fonctionnel, que la DB existe et que l'usager admin existe
1358         Si oui, on demande l'authentification
1359             Si non, on creer l'usager admin
1360  -Faire un vrai menu pour acceder directement aux pages desirees (pas une TOC poche)
1361  -Ameliorer le javascript et arreter de faire des document.myform.submit();
1362  -Generate valid HTML code
1363  -Integrate this script with the portal skin
1364  -Tester que les donnees de AVAIL_LOCALE_ARRAY dans config.php sont valides (fonctionnelles)
1365     Regarder le code dans include/language.php
1366  -Support pour l'option CUSTOM_SIGNUP_URL
1367  -Effacer repertoires/fichiers temporaires des installations
1368
1369  -Nice2Have : Si test d'integrite et de fonctionnement existent, les integrer pour assurer le bon fonctionnement
1370  -Nice2Have : Si donnees de tests exitent (pour les developpeurs) Permettre d'en ajouter a la DB
1371  -Nice2Have : Creer un wifidog.conf (client) selon config + questions si necessaires
1372
1373<B>Change Log</B>
1374  15-08-2005 : Bugs correction + comments added
1375  11-08-2005 : Options rewrite with foreach and dependencies
1376  09-08-2005 : Admin user creation + network configuration
1377  27-07-2005 : Added jpgraph install
1378  26-07-2005 : Added minimal security password validation
1379  14-07-2005 : saveConfig and all javascript code
1380  09-07-2005 : Added Phlickr installation
1381  05-07-2005 : Better PHP extention validation process
1382  17-06-2005 : MySQL schema and data submission
1383  17-06-2005 : Postgresql schema and data submission
1384  24-04-2005 : CSS button
1385
1386</PRE>
1387<!-- Editor highlighting trick */ -->
1388EndHTML;
1389  break;
1390  ###################################
1391/*  case 'phpinfo': // Use for debugging, to be removed
1392    print "<PRE>";
1393    print_r(get_loaded_extensions());
1394    print "</PRE><BR><BR>";
1395    phpinfo();
1396  break;*/
1397
1398  default:
1399    $WIFIDOG_VERSION = $configArray['WIFIDOG_VERSION'];
1400    # TODO : Add links to auth-server web documents
1401    print <<<EndHTML
1402<P>Welcome to Wifidog Auth-Server installation and configuration script.</P>
1403<P>This is a work in progress, so please report bugs to the mailing list for better support.
1404Many work needed to be done : validation, error handling, integration, security, etc.
1405The current auth-server version is <B>$WIFIDOG_VERSION</B>. The installation is only available in english.</P>
1406
1407<P>Before going further with this installation you need to have/create a valid user and database.
1408<P>Here is a command line example for PostgreSQL (or use the way you like) :</P>
1409
1410<B>Create the wifidog DB user</B> (createuser and createdb need to be in you PATH) :
1411<PRE>  <I>postgres@yourserver $></I> createuser wifidog --pwprompt
1412  Enter password for new user:
1413  Enter it again:
1414  Shall the new user be allowed to create databases? (y/n) n
1415  Shall the new user be allowed to create more new users? (y/n) n
1416  CREATE USER
1417</PRE>
1418
1419<B>Create the wifidog database</B>
1420<PRE>  <I>postgres@yourserver $></I> createdb -O wifidog wifidog
1421  CREATE DATABASE
1422</PRE>
1423
1424<B>Security</B> : For now, a really simple password protection is in place. To find the password type this in command line :<PRE>  <B>ls -ld $basepath | awk '{print \$6\$7\$8}'</B>
1425
1426  (No username needed)
1427</PRE>
1428
1429<P>When you are ready click next</P>
1430
1431EndHTML;
1432 
1433    navigation(array(array("title" => "Next", "page" => "version")));
1434}
1435
1436
1437?>
1438
1439</form>
1440</body>
1441</html>
Note: See TracBrowser for help on using the browser.