Xataface  2.0alpha2
Xataface Application Framework
 All Data Structures Namespaces Files Functions Variables Groups Pages
installer.php
Go to the documentation of this file.
1 <?php
2 require_once('PEAR.php');
3 if ( !defined('FILE_APPEND') ){
4  define('FILE_APPEND', 1);
5 }
6 if ( !function_exists('file_put_contents') ) {
7 
8  function file_put_contents($n, $d, $flag = false) {
9  $mode = ($flag == FILE_APPEND || strtoupper($flag) == 'FILE_APPEND') ? 'a' : 'w';
10  $f = @fopen($n, $mode);
11  if ($f === false) {
12  return 0;
13  } else {
14  if (is_array($d)) $d = implode($d);
15  $bytes_written = fwrite($f, $d);
16  fclose($f);
17  return $bytes_written;
18  }
19  }
20 }
21 
22 define('DB_HOST', 'localhost'); // This is the host of your mysql dbms
23 ini_set('include_path','.'.PATH_SEPARATOR.'lib');
24 set_time_limit(1500);
25 class Dataface_Installer {
26 
27  function createApplicationArchive($conf, $path=null){}
30  function authenticate(){
31  header('WWW-Authenticate: Basic realm="Dataface Installer"');
32  header('HTTP/1.0 401 Unauthorized');
33  setcookie('logged_in',1);
34  echo 'Please enter your MySQL Username and password to access this page';
35 
36  exit;
37 
38  }
39 
40 
41  function logout(){
42  //echo "here";
43  setcookie("logged_in", "", time() - 3600);
44  header('Location: '.$_SERVER['PHP_SELF']);
45  exit;
46  }
47 
48  function mainMenu(){
49  include('install'.DIRECTORY_SEPARATOR.'mainMenu.inc.php');
50  }
51 
52 
53  function infoLink($id){
54  return '<img src="images/info.gif" onclick="fieldInfo(\''.$id.'\');" />';
55 
56  }
57 
58  function archive2app(){
59 
60  require_once 'HTML/QuickForm.php';
61  $form = new HTML_QuickForm('fromarchive');
62 
63  $form->addElement('hidden', '-action', 'archive2app');
64 
65  $form->addElement('file','archive', 'Installation Archive'.$this->infoLink('archive2app.archive'));
66  $form->addElement('text','database_name','Database Name '.$this->infoLink('archive2app.database_name'));
67 
68 
69  $form->addElement('text','mysql_user', 'MySQL Username '.$this->infoLink('archive2app.mysql_user'));
70  $form->addElement('password', 'mysql_password', 'MySQL Password');
71  $form->addElement('checkbox', 'create_user', 'Create user '.$this->infoLink('archive2app.create_user'));
72 
73  $form->addElement('select','install_type', 'Installation type '.$this->infoLink('archive2app.install_type'), array(
74  '' => 'Please select ...',
75  'download_tarball' => 'Download Tarball',
76  'ftp_install' => 'Install on server (using FTP)'
77  ),
78  array('onchange'=>"listeners.install_type.onchange(this);")
79  );
80 
81  $form->addElement('header', 'ftp_info', 'FTP Connection Info');
82  $form->addElement('text', 'ftp_host', 'FTP Host');
83  $form->addElement('checkbox', 'ftp_ssl', 'Use SSL');
84  $form->addElement('text', 'ftp_path', 'FTP Path');
85  $form->addElement('text', 'ftp_username', 'FTP Username');
86  $form->addElement('password', 'ftp_password', 'FTP Password');
87 
88  $form->addElement('submit','submit','Submit');
89 
90 
91  $form->addRule('database_name','Please select a database', 'required', null,'client');
92  $form->addRule('mysql_user', 'Please enter a mysql username that the application can connect as.', 'required',null,'client');
93  $form->addRule('install_type', 'Please select an installation type and then click submit.', 'required', null, 'client');
94  $form->addRule('archive', 'Please choose the application tar.gz file to upload', 'uploadedfile',null,'client');
95 
96  $form->setDefaults(array(
97  'mysql_user'=>$_SERVER['PHP_AUTH_USER'],
98  'mysql_password'=>$_SERVER['PHP_AUTH_PW']
99  )
100  );
101 
102  if ( $form->validate() ){
103  $res = $form->process(array(&$this,'archive2app__process'), true);
104  if ( PEAR::isError($res) ){
105  die($res->getMessage());
106  }
107  }
108  require_once 'HTML/QuickForm/Renderer/Array.php';
109  $renderer = new HTML_QuickForm_Renderer_Array(true,true,true);
110  $form->accept($renderer);
111 
112  $context = $renderer->toArray();
113 
114  ob_start();
115  $form->display();
116  $out = ob_get_contents();
117  ob_end_clean();
118  include 'install'.DIRECTORY_SEPARATOR.'archive2app.inc.php';
119  }
120 
121  function archive2app__process($values){
122  require_once 'Archive/Tar.php';
123 
124  if ( preg_match('/\.gz$/', $_FILES['archive']['name']) ){
125  $compression = 'gz';
126  } else {
127  $compression = null;
128  }
129  $archive = new Archive_Tar($_FILES['archive']['tmp_name'], $compression);
130  $files = $archive->listContent();
131  foreach ( $files as $file ){
132  if ( !preg_match('/(\.ini)|(\.php)$/', $file['filename']) ){
133  continue;
134  }
135  $content = $archive->extractInString($file['filename']);
136  $content = str_replace(
137  array(
138  '%%DATAFACE_URL%%',
139  '%%DATAFACE_PATH%%',
140  '%%MYSQL_USER%%',
141  '%%MYSQL_PASSWORD%%',
142  '%%MYSQL_HOST%%',
143  '%%MYSQL_DATABASE_NAME%%'
144  ),
145  array(
146  addslashes(dirname($_SERVER['PHP_SELF'])),
147  addslashes(dirname(__FILE__)),
148  addslashes($values['mysql_user']),
149  addslashes($values['mysql_password']),
150  addslashes(DB_HOST),
151  addslashes($values['database_name'])
152  ),
153  $content
154  );
155  $archive->addString($file['filename'], $content);
156 
157  }
158  $root = $files[0]['filename'];
159 
160  $install = $archive->extractInString($root.'install/install.sql');
161  $res = mysql_select_db($values['database_name'], db());
162  if ( !$res ){
163  $dbname = str_replace('`','',$values['database_name']);
164  $res = mysql_query("create database `".addslashes($dbname)."`", db());
165  if ( !$res ){
166  return PEAR::raiseError("Failed to create database '$dbname'");
167  }
168  $res = mysql_select_db($dbname);
169  if ( !$res ){
170  return PEAR::raiseError("Problem selecting database $dbname.");
171  }
172  }
173 
174  if ( $install ){
175  $installFile = tempnam(null, 'install.sql');
176  file_put_contents($installFile, $install);
177 
178 
179  $file = file($installFile);
180  $queries = array();
181  $ctr = 0;
182  foreach ($file as $line){
183 
184  if ( isComment($line) ) continue;
185  $queries[$ctr] .= $line;
186  $trimmed = trim($line);
187  if ( $trimmed{strlen($trimmed)-1} == ';' ) $ctr++;
188 
189  }
190 
191  //$file = implode("",$out);
192  foreach ($queries as $query){
193 
194  $res = @mysql_query($query, $db);
195  if ( !$res ){
196  $my_errs[] = mysql_error($db);
197  }
198  }
199  }
200 
201 
202 
203  switch ($values['install_type'] ){
204  case 'ftp_install':
205  //echo 'here';
206  require_once 'install/FTPExtractor.class.php';
207  $extractor = new FTPExtractor($archive);
208  $res = $extractor->connect($values['ftp_host'], $values['ftp_username'], $values['ftp_password']);
209 
210  if ( PEAR::isError($res) ){
211  die($res->getMessage());
212  }
213  $res = $extractor->extract($values['ftp_path'],'/');
214  //if ( PEAR::isError($res) ){
215  // die($res->getMessage());
216  //}
217  $context = array();
218  if ( PEAR::isError($res) ){
219  $context['result'] = 'Error: '.$res->getMessage();
220  } else {
221  $context = $res;
222  }
223  include 'install'.DIRECTORY_SEPARATOR.'archive2app-results.inc.php';
224  exit;
225 
226  default: // download_tarball
227  $tarpath = $_FILES['archive']['tmp_name'];
228  if ( $compression == 'gz' ){
229  $mimetype = 'application/x-gzip';
230  } else {
231  $mimetype = 'application/x-tar';
232  }
233  header('Content-type: '.$mimetype);
234  header('Content-Disposition: attachment; filename="'.basename($_FILES['archive']['name']).'.tar.gz"');
235  echo file_get_contents($tarpath);
236  exit;
237 
238  }
239 
240 
241 
242 
243  }
244 
245  function db2app(){
246  require_once 'HTML/QuickForm.php';
247  $form = new HTML_QuickForm('db2app');
248  $res = mysql_list_dbs(db());
249  if ( !$res ) trigger_error(mysql_error(db()), E_USER_ERROR);
250  $options = array('' => 'Please Select Database ...');
251  while ( $row = mysql_fetch_row($res) ) $options[$row[0]] = $row[0];
252  $form->addElement('hidden','-action','db2app');
253  $form->addElement('select', 'database_name','Select Database'.$this->infoLink('archive2app.database_name'), $options, array('onchange'=>'listeners.database_name.onchange(this)'));
254  $form->addElement('header','db_info','Database connection details');
255  //$form->addElement('html', 'this is a test');
256  $form->addElement('text', 'mysql_user', 'MySQL Username '.$this->infoLink('archive2app.mysql_user'));
257  $form->addElement('password', 'mysql_password', 'MySQL Password');
258  //$form->addElement('radio','output_format','Output options','Download as tar.gz archive','download');
259  //$form->addElement('radio','output_format','','Install on webserver in apps directory','install');
260 
261  $form->addElement('select','install_type', 'Installation type '.$this->infoLink('archive2app.install_type'), array(
262  '' => 'Please select ...',
263  'download_tarball' => 'Download Tarball',
264  'ftp_install' => 'Install on server (using FTP)'
265  ),
266 
267  array('onchange'=>"listeners.install_type.onchange(this);")
268  );
269 
270  $form->addElement('header', 'ftp_info', 'FTP Connection Info');
271  $form->addElement('text', 'ftp_host', 'FTP Host');
272  $form->addElement('checkbox', 'ftp_ssl', 'Use SSL');
273  $form->setDefaults(array('ftp_host'=>DB_HOST));
274  $form->addElement('text', 'ftp_path', 'FTP Path',array('size'=>50));
275  $form->setDefaults(array('ftp_path'=>$_SERVER['DOCUMENT_ROOT']));
276  $form->addElement('text', 'ftp_username', 'FTP Username');
277  $form->addElement('password', 'ftp_password', 'FTP Password');
278 
279 
280  $form->addElement('submit','submit','Submit');
281 
282 
283  $form->addRule('database_name','Please select a database', 'required', null,'client');
284  $form->addRule('mysql_user', 'Please enter a mysql username that the application can connect as.', 'required',null,'client');
285  $form->addRule('install_type', 'Please select an installation type and then click submit.', 'required', null, 'client');
286  $form->setDefaults(array(
287  'mysql_user'=>$_SERVER['PHP_AUTH_USER'],
288  'mysql_password'=>$_SERVER['PHP_AUTH_PW']
289  )
290  );
291 
292  if ( $form->validate() ){
293  $tarpath = $form->process(array(&$this,'db2app__process'), true);
294  header('Content-type: application/x-gzip');
295  header('Content-Disposition: attachment; filename="'.basename($tarpath).'.tar.gz"');
296  echo file_get_contents($tarpath);
297  exit;
298  }
299 
300  require_once 'HTML/QuickForm/Renderer/Array.php';
301  $renderer = new HTML_QuickForm_Renderer_Array(true,true,true);
302  $form->accept($renderer);
303 
304  $context = $renderer->toArray();
305  //print_r($context);
306 
307  ob_start();
308  $form->display();
309  $out = ob_get_contents();
310  ob_end_clean();
311  include 'install'.DIRECTORY_SEPARATOR.'db2app.inc.php';
312  }
313 
314  function db2app__process($values){
315  require_once 'Archive/Tar.php';
316  $tarpath = tempnam('/tmp',strval($values['database_name']));
317  //echo $tarpath;
318  $compression='gz';
319  $archive = new Archive_Tar($tarpath,$compression);
320  $path = strval($values['database_name']);
321  $archive->addString($path.'/.htaccess', '<FilesMatch "\.ini$">
322 Deny from all
323 </FilesMatch>');
324  $archive->addString($path.'/Web.config', file_get_contents(dirname(__FILE__).DIRECTORY_SEPARATOR.'site_skeleton'.DIRECTORY_SEPARATOR.'Web.config'));
325 
326 
327 
328 
329  mysql_select_db($values['database_name'], db());
330  $res = mysql_query('show tables', db());
331  if ( !$res ) trigger_error(mysql_error(db()), E_USER_ERROR);
332  $tables = array();
333  while ( $row = mysql_fetch_row($res) ){
334  if ( $row[0]{0} == '_' ) continue;
335  if ( strpos($row[0], 'dataface_') === 0 ) continue;
336  if ( preg_match('/__history$/', $row[0]) ) continue;
337  $tables[] = $row[0].' = "'.ucwords(str_replace('_',' ', $row[0])).'"';
338  }
339 
340  $archive->addString($path.'/conf.ini',';;Configuration settings for application
341 title="'.addslashes($values['database_name']).'"
342 
343 [_database]
344  host="'.DB_HOST.'"
345  name="'.addslashes($values['database_name']).'"
346  user="'.addslashes($values['mysql_user']).'"
347  password="'.addslashes($values['mysql_password']).'"
348 
349 [_tables]
350 '.implode("\n",$tables).'
351 '
352  );
353 
354  $archive->addString($path.'/index.php','<?php //Main Application access point
355 require_once "'.addslashes(dirname(__FILE__).DIRECTORY_SEPARATOR.'public-api.php').'";
356 df_init(__FILE__, "'.addslashes(dirname($_SERVER['PHP_SELF'])).'")->display();
357 '
358  );
359 
360 
361  switch ($values['install_type'] ){
362  case 'ftp_install':
363  //echo 'here';
364  require_once 'install/FTPExtractor.class.php';
365  $extractor = new FTPExtractor($archive);
366  $res = $extractor->connect($values['ftp_host'], $values['ftp_username'], $values['ftp_password']);
367 
368  if ( PEAR::isError($res) ){
369  die($res->getMessage());
370  }
371 
372 
373  $res = $extractor->extract($values['ftp_path'],'/');
374  //if ( PEAR::isError($res) ){
375  // die($res->getMessage());
376  //}
377  $context = array();
378  if ( PEAR::isError($res) ){
379  $context['result'] = 'Error: '.$res->getMessage();
380  } else {
381  $context = $res;
382 
383 
384  }
385  include 'install'.DIRECTORY_SEPARATOR.'archive2app-results.inc.php';
386  exit;
387 
388  default: // download_tarball
389  //$tarpath = $_FILES['archive']['tmp_name'];
390  if ( $compression == 'gz' ){
391  $mimetype = 'application/x-gzip';
392  } else {
393  $mimetype = 'application/x-tar';
394  }
395  header('Content-type: '.$mimetype);
396  header('Content-Disposition: attachment; filename="'.basename($tarpath).'.tar.gz"');
397  echo file_get_contents($tarpath);
398  exit;
399 
400  }
401 
402  //return $tarpath;
403 
404  }
405 
406  function test_db_access($dbname, $username, $password){
407  $db = @mysql_connect(DB_HOST, $username, $password);
408  if ( !$db ){
409  return PEAR::raiseError("Could not connect to the MySQL server with username $username.");
410  }
411 
412  $res = mysql_select_db($dbname, $db);
413  if ( !$res ) return PEAR::raiseError("Could not access the database $dbname as user $username.");
414 
415  return true;
416  }
417 
418  function test_ftp_access($host, $path, $user, $password, $ssl=false){
419  require_once 'install/ftp.api.php';
420  require_once 'install/ftp.class.php';
421  if ( $ssl ){
422  $conn = ftp_ssl_connect($host);
423  } else {
424  $conn = ftp_connect($host);
425  }
426  if ( !$conn ) return PEAR::raiseError("Could not connect to FTP server");
427 
428  $res = @ftp_login($conn, $user, $password);
429  if ( !$res ) return PEAR::raiseError("Failed to login to FTP server with the provided username ($user) and password");
430 
431  $res = @ftp_chdir($conn, $path);
432  if ( !$res ){
433  return PEAR::raiseError("Failed: The directory $path on the server $host does not exist.");
434 
435  }
436 
437  return true;
438 
439  }
440 
441  function testdb(){
442  if ( !@$_REQUEST['-dbname'] || !$_REQUEST['-dbuser'] || !isset($_REQUEST['-dbpass']) ){
443  trigger_error("Please provide all of -dbname, -dbuser, and -dbpass parameters in the POST variables.", E_USER_ERROR);
444 
445  }
446 
447  $res = $this->test_db_access($_REQUEST['-dbname'], $_REQUEST['-dbuser'], $_REQUEST['-dbpass']);
448  if ( PEAR::isError($res) ){
449  $msg = array(
450  'success' => false,
451  'message' => $res->getMessage()
452  );
453 
454 
455  } else {
456  $msg = array(
457  'success' => true,
458  'message' => 'Connected to database successfully'
459  );
460  }
461 
462  header('Content-type: text/json');
463  require_once 'Services/JSON.php';
464  $json = new Services_JSON;
465  echo $json->encode($msg);
466  exit;
467  }
468 
469  function testftp(){
470  if ( !@$_REQUEST['-ftphost'] || !$_REQUEST['-ftpuser'] || !isset($_REQUEST['-ftppass']) ){
471  trigger_error("Please provide all of -ftphost, -ftpuser, and -ftppass parameters in the POST variables.", E_USER_ERROR);
472 
473  }
474 
475  $res = $this->test_ftp_access($_REQUEST['-ftphost'], @$_REQUEST['-ftppath'], $_REQUEST['-ftpuser'], $_REQUEST['-ftppass'], @$_REQUEST['-ftpssl']);
476  if ( PEAR::isError($res) ){
477  $msg = array(
478  'success' => false,
479  'message' => $res->getMessage()
480  );
481 
482 
483  } else {
484  $msg = array(
485  'success' => true,
486  'message' => 'Connected to FTP server successfully'
487  );
488  }
489 
490  header('Content-type: text/json');
491  require_once 'Services/JSON.php';
492  $json = new Services_JSON;
493  echo $json->encode($msg);
494  exit;
495  }
496 
497 }
498 //print_r($_SERVER);
499 function db(){
500  static $db=-1;
501  if ( $db == -1 ){
503  if (!@$_SERVER['PHP_AUTH_USER'] || !$_COOKIE['logged_in'] ){
504  $installer->authenticate();
505  }
506  $db = @mysql_connect(DB_HOST,@$_SERVER['PHP_AUTH_USER'], @$_SERVER['PHP_AUTH_PW']);
507  if ( !$db ){
508  $installer->authenticate();
509  }
510  }
511  return $db;
512 }
513 
514 function isComment($line){
515  $line = trim($line);
516  if ( strlen($line) > 1 and $line{0} == '-' and $line{1} == '-') return true;
517  return false;
518 }
519 
520 
521 db();
522 
523 
525 switch (@$_REQUEST['-action']){
526  case 'testdb':
527  $installer->testdb();
528  break;
529 
530  case 'testftp':
531  $installer->testftp();
532  break;
533 
534  case 'logout':
535  $installer->logout();
536  break;
537 
538  case 'db2app':
539  $installer->db2app();
540  break;
541 
542  case 'archive2app':
543  $installer->archive2app();
544  break;
545 
546  default:
547  $installer->mainMenu();
548 
549 }