PageRenderTime 66ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/setup.php

https://github.com/paulheaney/sitracker
PHP | 1516 lines | 1217 code | 120 blank | 179 comment | 195 complexity | 59aebe696f0a7c71c63d1104b0b8b744 MD5 | raw file
Possible License(s): LGPL-2.1, LGPL-2.0, BSD-3-Clause, GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. // setup.php - Install/Upgrade and set up plugins
  3. //
  4. // SiT (Support Incident Tracker) - Support call tracking system
  5. // Copyright (C) 2000-2009 Salford Software Ltd. and Contributors
  6. //
  7. // This software may be used and distributed according to the terms
  8. // of the GNU General Public License, incorporated herein by reference.
  9. //
  10. // Author: Ivan Lucas <ivanlucas[at]users.sourceforge.net>
  11. // Define path constants, we don't include core.php so we do this here
  12. define ('APPLICATION_FSPATH', realpath(dirname( __FILE__ ) . DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR);
  13. define ('APPLICATION_LIBPATH', realpath(dirname( __FILE__ ).DIRECTORY_SEPARATOR . 'lib') . DIRECTORY_SEPARATOR);
  14. define ('APPLICATION_HELPPATH', realpath(dirname( __FILE__ ).DIRECTORY_SEPARATOR . 'help') . DIRECTORY_SEPARATOR);
  15. define ('APPLICATION_INCPATH', realpath(dirname( __FILE__ ).DIRECTORY_SEPARATOR . 'inc') . DIRECTORY_SEPARATOR);
  16. define ('APPLICATION_I18NPATH', realpath(dirname( __FILE__ ).DIRECTORY_SEPARATOR . 'i18n') . DIRECTORY_SEPARATOR);
  17. define ('APPLICATION_PORTALPATH', realpath(dirname( __FILE__ ).DIRECTORY_SEPARATOR . 'portal') . DIRECTORY_SEPARATOR);
  18. define ('APPLICATION_PLUGINPATH', realpath(dirname( __FILE__ ).DIRECTORY_SEPARATOR . 'plugins') . DIRECTORY_SEPARATOR);
  19. // Load config defaults
  20. @include (APPLICATION_LIBPATH . 'defaults.inc.php');
  21. // Keep the defaults as a seperate array
  22. $DEFAULTS = $CONFIG;
  23. // Load config file with customisations
  24. // @include ("config.inc-dist.php");
  25. if (file_exists(APPLICATION_FSPATH . "config.inc.php")
  26. AND !include (APPLICATION_FSPATH . "config.inc.php"))
  27. {
  28. die('Could not read config file config.inc.php');
  29. }
  30. // Server Configuration
  31. // for legacy systems
  32. if (file_exists('/etc/webtrack.conf')
  33. AND !include ('/etc/webtrack.conf'))
  34. {
  35. die('Could not read config file webtrack.conf');
  36. }
  37. if (file_exists('/etc/sit.conf')
  38. AND !include ('/etc/sit.conf'))
  39. {
  40. die('Cound not read config file sit.conf');
  41. }
  42. // // Some actions require authentication
  43. // if ($_REQUEST['action'] == 'reconfigure')
  44. // {
  45. // $permission = 22;
  46. // $_REQUEST['config'] = 'advanced'; // set advanced mode
  47. // require (APPLICATION_LIBPATH . 'functions.inc.php');
  48. // require (APPLICATION_LIBPATH . 'auth.inc.php');
  49. // }
  50. // These are the required variables we want to configure during installation
  51. $SETUP = array('db_hostname','db_database','db_username','db_password', 'db_tableprefix','application_webpath');
  52. require(APPLICATION_LIBPATH . 'configvars.inc.php');
  53. $upgradeok = FALSE;
  54. $config_filename = APPLICATION_FSPATH . 'config.inc.php';
  55. $configfiles = get_included_files();
  56. $systemhash = md5(date('Y-m-d') . $_SERVER['REMOTE_ADDR']
  57. . $_SERVER['SCRIPT_FILENAME'] . $_SERVER['HTTP_USER_AGENT']
  58. . $CONFIG['attachment_fspath'] . $_SERVER['SERVER_SIGNATURE'] );
  59. /**
  60. * Array filter callback to check to see if a config file is a recognised file
  61. * @author Ivan Lucas
  62. * @param string $var. Filename to check
  63. * @retval bool TRUE : recognised
  64. * @retval bool FALSE : unrecognised
  65. */
  66. function filterconfigfiles($var)
  67. {
  68. $poss_config_files = array('config.inc.php', 'sit.conf', 'webtrack.conf');
  69. $recognised = FALSE;
  70. foreach ($poss_config_files AS $poss)
  71. {
  72. if (substr($var, strlen($var)-strlen($poss)) == $poss) $recognised = TRUE;
  73. }
  74. return $recognised;
  75. }
  76. $configfiles = array_filter($configfiles, 'filterconfigfiles');
  77. $configfiles = array_values($configfiles);
  78. $numconfigfiles = count($configfiles);
  79. if ($numconfigfiles == 1)
  80. {
  81. $config_filename = $configfiles[0];
  82. }
  83. elseif ($numconfigfiles < 1)
  84. {
  85. $configfiles[] = './config.inc.php';
  86. }
  87. $cfg_file_exists = FALSE;
  88. $cfg_file_writable = FALSE;
  89. foreach ($configfiles AS $conf_filename)
  90. {
  91. if (file_exists($conf_filename)) $cfg_file_exists = TRUE;
  92. if (is_writable($conf_filename)) $cfg_file_writable = TRUE;
  93. }
  94. // Detect whether an array is associative
  95. // From http://uk.php.net/manual/en/function.is-array.php#77744
  96. //function is_assoc($array)
  97. //{
  98. // return is_array($array) && count($array) !== array_reduce(array_keys($array), 'is_assoc_callback', 0);
  99. //}
  100. //function is_assoc_callback($a, $b)
  101. //{
  102. // return $a === $b ? $a + 1 : 0;
  103. //}
  104. /**
  105. * Setup configuration form
  106. * @author Ivan Lucas
  107. * @retval string HTML
  108. */
  109. function setup_configure()
  110. {
  111. global $SETUP, $CFGVAR, $CONFIG, $configfiles, $config_filename, $cfg_file_exists;
  112. global $cfg_file_writable, $numconfigfiles;
  113. $html = '';
  114. if ($cfg_file_exists AND $_REQUEST['configfile'] != 'new')
  115. {
  116. if ($_SESSION['new'])
  117. {
  118. if ($numconfigfiles < 2)
  119. {
  120. $html .= "<h4>Found an existing config file <var>{$config_filename}</var></h4>";
  121. }
  122. else
  123. {
  124. $html .= "<p class='error'>Found more than one existing config file</p>";
  125. if ($cfg_file_writable)
  126. {
  127. $html .= "<ul>";
  128. foreach ($configfiles AS $conf_filename)
  129. {
  130. $html .= "<li><var>{$conf_filename}</var></li>";
  131. }
  132. $html .= "</ul>";
  133. }
  134. }
  135. }
  136. //$html .= "<p>Since you already have a config file we assume you are upgrading or reconfiguring, if this is not the case please delete the existing config file.</p>";
  137. if ($cfg_file_writable)
  138. {
  139. $html .= "<p class='error'>Important: The file permissions on the configuration file ";
  140. $html .= "allow it to be modified, we recommend you make this file read-only once SiT! is configured.";
  141. $html .= "</p>";
  142. }
  143. else
  144. {
  145. $html .= "<p><a href='setup.php?action=reconfigure&amp;configfile=new' >Create a new config file</a>.</p>";
  146. }
  147. }
  148. else $html .= "<h2>New Configuration</h2><p>Please complete this form to create a new configuration file for SiT!</p>";
  149. if ($cfg_file_writable OR $_SESSION['new'] === 1 OR $cfg_file_exists == FALSE OR $_REQUEST['configfile'] == 'new')
  150. {
  151. $html .= "\n<form action='setup.php' method='post'>\n";
  152. if ($_REQUEST['config'] == 'advanced')
  153. {
  154. $html .= "<input type='hidden' name='config' value='advanced' />\n";
  155. foreach ($CFGVAR AS $setupvar => $setupval)
  156. {
  157. $SETUP[] = $setupvar;
  158. }
  159. }
  160. $c=1;
  161. foreach ($SETUP AS $setupvar)
  162. {
  163. $html .= "<div class='configvar{$c}'>";
  164. if ($CFGVAR[$setupvar]['title']!='') $title = $CFGVAR[$setupvar]['title'];
  165. else $title = $setupvar;
  166. $html .= "<h4>{$title}</h4>";
  167. if ($CFGVAR[$setupvar]['help']!='') $html .= "<p class='helptip'>{$CFGVAR[$setupvar]['help']}</p>\n";
  168. $html .= "<var>\$CONFIG['$setupvar']</var> = ";
  169. $value = '';
  170. if (!$cfg_file_exists OR ($cfg_file_exists AND $cfg_file_writable))
  171. {
  172. $value = $CONFIG[$setupvar];
  173. if (is_bool($value))
  174. {
  175. if ($value==TRUE) $value='TRUE';
  176. else $value='FALSE';
  177. }
  178. elseif (is_array($value))
  179. {
  180. if (is_assoc($value))
  181. {
  182. $value = "array(".implode_assoc('=>',',',$value).")";
  183. }
  184. else
  185. {
  186. $value="array(".implode(',',$value).")";
  187. }
  188. }
  189. if ($setupvar=='db_password' AND $_REQUEST['action']!='reconfigure') $value='';
  190. }
  191. if (!$cfg_file_exists OR $_REQUEST['configfile'] == 'new')
  192. {
  193. // Dynamic defaults
  194. // application_fspath was removed, leaving this code just-in-case
  195. // DEPRECATED - remove for >= 3.50
  196. if ($setupvar == 'application_fspath')
  197. {
  198. $value = str_replace('htdocs' . DIRECTORY_SEPARATOR, '', dirname( __FILE__ ) . DIRECTORY_SEPARATOR);
  199. }
  200. if ($setupvar == 'application_webpath')
  201. {
  202. $value = dirname( strip_tags( $_SERVER['PHP_SELF'] ) );
  203. if ($value == '/' OR $value == '\\') $value = '/';
  204. else $value = $value . '/';
  205. }
  206. }
  207. switch ($CFGVAR[$setupvar]['type'])
  208. {
  209. case 'select':
  210. $html .= "<select name='$setupvar'>";
  211. if (empty($CFGVAR[$setupvar]['options'])) $CFGVAR[$setupvar]['options'] = "TRUE|FALSE";
  212. $options = explode('|', $CFGVAR[$setupvar]['options']);
  213. foreach ($options AS $option)
  214. {
  215. $html .= "<option value=\"{$option}\"";
  216. if ($option == $value) $html .= " selected='selected'";
  217. $html .= ">{$option}</option>\n";
  218. }
  219. $html .= "</select>";
  220. break;
  221. case 'percent':
  222. $html .= "<select name='$setupvar'>";
  223. for($i = 0; $i <= 100; $i++)
  224. {
  225. $html .= "<option value=\"{$i}\"";
  226. if ($i == $value) $html .= " selected='selected'";
  227. $html .= ">{$i}</option>\n";
  228. }
  229. $html .= "</select>";
  230. break;
  231. case 'text':
  232. default:
  233. if (strlen($CONFIG[$setupvar]) < 65)
  234. {
  235. $html .= "<input type='text' name='$setupvar' size='60' value=\"{$value}\" />";
  236. }
  237. else
  238. {
  239. $html .= "<textarea name='$setupvar' cols='60' rows='10'>{$value}</textarea>";
  240. }
  241. }
  242. if ($setupvar=='db_password' AND $_REQUEST['action']!='reconfigure' AND $value != '') $html .= "<p class='info'>The current password setting is not shown</p>";
  243. $html .= "</div>";
  244. $html .= "<br />\n";
  245. if ($c==1) $c==2; else $c=1;
  246. }
  247. $html .= "<input type='hidden' name='action' value='save_config' />";
  248. $html .= "<br /><input type='submit' name='submit' value='Save Configuration' />";
  249. $html .= "</form>\n";
  250. }
  251. return $html;
  252. }
  253. /**
  254. * Execute a list of SQL queries
  255. * @author Ivan Lucas
  256. * @note Attempts to be clever and print helpful messages in the case
  257. * of an error
  258. */
  259. function setup_exec_sql($sqlquerylist)
  260. {
  261. global $CONFIG, $dbSystem, $installed_schema, $application_version;
  262. if (!empty($sqlquerylist))
  263. {
  264. if (!is_array($sqlquerylist)) $sqlquerylist = array($sqlquerylist);
  265. // echo "<pre>".print_r($sqlquerylist,true)."</pre>";
  266. // Loop around the queries
  267. foreach ($sqlquerylist AS $schemaversion => $queryelement)
  268. {
  269. if ($schemaversion != '0') $schemaversion = substr($schemaversion, 1);
  270. // echo "<p>Schema version $schemaversion, installed schema $installed_schema, query $queryelement</p>";
  271. if ($schemaversion == 0 OR $installed_schema < $schemaversion)
  272. {
  273. $sqlqueries = explode( ';', $queryelement);
  274. // We don't need the last entry it's blank, as we end with a ;
  275. array_pop($sqlqueries);
  276. $errors = 0;
  277. foreach ($sqlqueries AS $sql)
  278. {
  279. if (!empty($sql))
  280. {
  281. mysql_query($sql);
  282. if (mysql_error())
  283. {
  284. $errno = mysql_errno();
  285. $errstr = '';
  286. // See http://dev.mysql.com/doc/refman/5.0/en/error-messages-server.html
  287. // For list of mysql error numbers
  288. switch ($errno)
  289. {
  290. case 1022:
  291. case 1050:
  292. case 1060:
  293. case 1061:
  294. case 1062:
  295. $severity = 'info';
  296. $errstr = "This could be because this part of the database schema is already up to date.";
  297. break;
  298. case 1058:
  299. $severity = 'error';
  300. $errstr = "This looks suspiciously like a bug, if you think this is the case please report it.";
  301. break;
  302. // case 1054:
  303. // if (preg_match("/ALTER TABLE/", $sql) >= 1)
  304. // {
  305. // $severity = 'info';
  306. // $errstr = "This could be because this part of the database schema is already up to date.";
  307. // }
  308. // break;
  309. case 1051:
  310. case 1091:
  311. if (preg_match("/DROP/", $sql) >= 1)
  312. {
  313. $severity = 'info';
  314. $errstr = "We expected to find something in order to remove it but it doesn't exist. This could be because this part of the database schema is already up to date..";
  315. }
  316. break;
  317. case 1044:
  318. case 1045:
  319. case 1142:
  320. case 1143:
  321. case 1227:
  322. $severity = 'error';
  323. $errstr = "This could be because the MySQL user '{$CONFIG['db_username']}' does not have appropriate permission to modify the database schema.<br />";
  324. $errstr .= "<strong>Check your MySQL permissions allow the schema to be modified</strong>.";
  325. default:
  326. $severity = 'error';
  327. $errstr = "You may have found a bug, if you think this is the case please report it.";
  328. }
  329. $html .= "<p class='$severity'>";
  330. if ($severity == 'info')
  331. {
  332. $html .= "<strong>Information:</strong>";
  333. }
  334. else
  335. {
  336. $html .= "<strong>A MySQL error occurred:</strong>";
  337. $errors ++;
  338. }
  339. $html .= " [".mysql_errno()."] ".mysql_error()."<br />";
  340. if (!empty($errstr)) $html .= $errstr."<br />";
  341. $html .= "Raw SQL: <code class='small'>".htmlspecialchars($sql)."</code>";
  342. }
  343. }
  344. }
  345. }
  346. }
  347. }
  348. echo $html;
  349. return $errors;
  350. }
  351. /**
  352. * Create a blank SiT database
  353. * @author Ivan Lucas
  354. * @retval bool TRUE database created OK
  355. * @retval bool FALSE database not created, error.
  356. */
  357. function setup_createdb()
  358. {
  359. global $CONFIG;
  360. $res = FALSE;
  361. $sql = "CREATE DATABASE `{$CONFIG['db_database']}` DEFAULT CHARSET utf8";
  362. $db = @mysql_connect($CONFIG['db_hostname'], $CONFIG['db_username'], $CONFIG['db_password']);
  363. if (!@mysql_error())
  364. {
  365. // See Mantis 506 for sql_mode discussion
  366. @mysql_query("SET SESSION sql_mode = '';");
  367. // Connected to database
  368. echo "<h2>Creating empty database...</h2>";
  369. $result = mysql_query($sql);
  370. if ($result)
  371. {
  372. $res = TRUE;
  373. echo "<p><strong>OK</strong> Database '{$CONFIG['db_database']}' created.</p>";
  374. echo setup_button('', 'Next');
  375. }
  376. else $res = FALSE;
  377. }
  378. else
  379. {
  380. $res = FALSE;
  381. }
  382. if ($res == FALSE)
  383. {
  384. echo "<p class='error'>";
  385. if (mysql_error())
  386. {
  387. echo mysql_error()."<br />";
  388. }
  389. echo "The database could not be created automatically, ";
  390. echo "you can create it manually by executing the SQL statement <br /><code>{$sql};</code></p>";
  391. echo setup_button('', 'Next');
  392. }
  393. return $res;
  394. }
  395. /**
  396. * Check to see whether an admin user exists
  397. * @author Ivan Lucas
  398. * @retval bool TRUE : an admin account exists
  399. * @retval bool FALSE : an admin account doesn't exist
  400. */
  401. function setup_check_adminuser()
  402. {
  403. global $dbUsers;
  404. $sql = "SELECT id FROM `{$dbUsers}` WHERE id=1 OR username='admin' OR roleid='1'";
  405. $result = @mysql_query($sql);
  406. if (mysql_num_rows($result) >= 1) return TRUE;
  407. else FALSE;
  408. }
  409. /**
  410. * An HTML action button, i.e. a form with a single button
  411. * @author Ivan Lucas
  412. * @param string $action. Value for the hidden 'action' field
  413. * @param string $label. Label for the submit button
  414. * @param string $extrahtml. Extra HTML to display on the form
  415. * @returns A form with a button
  416. * @retval string HTML form
  417. */
  418. function setup_button($action, $label, $extrahtml='')
  419. {
  420. $html = "\n<form action='{$_SERVER['PHP_SELF']}' method='post'>";
  421. if (!empty($action))
  422. {
  423. $html .= "<input type='hidden' name='action' value=\"{$action}\" />";
  424. }
  425. $html .= "<input type='submit' value=\"{$label}\" />";
  426. if (!empty($extrahtml)) $html .= $extrahtml;
  427. $html .= "</form>\n";
  428. return $html;
  429. }
  430. session_name($CONFIG['session_name']);
  431. session_start();
  432. // Force logout
  433. $_SESSION['auth'] = FALSE;
  434. $_SESSION['portalauth'] = FALSE;
  435. echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n";
  436. echo " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";
  437. echo "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n";
  438. echo "<head>\n";
  439. echo "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\" />\n";
  440. echo "<style type=\"text/css\">\n";
  441. echo "body { background-color: #FFF; font-family: Tahoma, Helvetica, sans-serif; font-size: 10pt;}\n";
  442. echo "h1,h2,h3,h4,h5 { color: #203894; padding: 0.1em; border: 1px solid #4D485B; }\n";
  443. if (file_exists('./images/sitlogo_270x100.png')) echo "body {background-image: url('images/sitlogo_270x100.png'); background-attachment:fixed; background-position: 98% 98%; background-repeat: no-repeat;}\n";
  444. echo "h4 {background-color: transparent; color: #000; border: 0px; margin: 2px 0px 3px 0px; }\n";
  445. echo "div.configvar1 {background-color: #F7FAFF; border: 1px solid #4D485B; margin-bottom: 10px; padding: 0px 5px 10px 5px; filter:alpha(opacity=75); opacity: 0.75; -moz-opacity:0.75; -moz-border-radius: 3px;} ";
  446. echo "div.configvar2 {background-color: green; border: 1px solid #4D485B; margin-bottom: 10px;} ";
  447. echo ".error {background-position: 3px 2px;
  448. background-repeat: no-repeat;
  449. padding: 3px 3px 3px 22px;
  450. min-height: 16px;
  451. -moz-border-radius: 5px;
  452. /* display: inline; */
  453. border: 1px solid #000;
  454. margin-left: 2em;
  455. margin-right: 2em;
  456. width: auto;
  457. text-align: left;
  458. background-image: url('images/icons/sit/16x16/warning.png');
  459. color: #5A3612;
  460. border: 1px solid #A26120;
  461. background-color: #FFECD7;
  462. }
  463. .info {
  464. background-position: 3px 2px;
  465. background-repeat: no-repeat;
  466. padding: 3px 3px 3px 22px;
  467. min-height: 16px;
  468. -moz-border-radius: 5px;
  469. /* display: inline; */
  470. border: 1px solid #000;
  471. margin-left: 2em;
  472. margin-right: 2em;
  473. width: auto;
  474. text-align: left;
  475. }
  476. p.info {
  477. background-image: url('images/icons/sit/16x16/info.png');
  478. color: #17446B;
  479. border: 1px solid #17446B;
  480. background-color: #F4F6FF;
  481. }
  482. a.button:link, a.button:visited
  483. {
  484. float: left;
  485. margin: 2px 5px 2px 5px;
  486. padding: 2px;
  487. width: 100px;
  488. border-top: 1px solid #ccc;
  489. border-bottom: 1px solid black;
  490. border-left: 1px solid #ccc;
  491. border-right: 1px solid black;
  492. background: #ccc;
  493. text-align: center;
  494. text-decoration: none;
  495. font: normal 10px Verdana;
  496. color: black;
  497. }
  498. a.button:hover
  499. {
  500. background: #eee;
  501. }
  502. a.button:active
  503. {
  504. border-bottom: 1px solid #eee;
  505. border-top: 1px solid black;
  506. border-right: 1px solid #eee;
  507. border-left: 1px solid black;
  508. }
  509. var { font-family: Andale Mono, monospace; font-style: normal; }
  510. code.small { font-size: 75%; color: #555; }
  511. }
  512. ";
  513. echo ".help {background: #F7FAFF; border: 1px solid #3165CD; color: #203894; padding: 2px;}\n";
  514. echo ".helptip { color: #203894; }\n";
  515. echo ".warning {background: #FFFFE6; border: 2px solid #FFFF31; color: red; padding: 2px;}\n";
  516. echo "pre {background:#FFF; border:#999; padding: 1em;}\n";
  517. echo "a.button { border: 1px outset #000; padding: 2px; background-color: #EFEFEF;} ";
  518. echo "a:link,a:visited { color: #000099; }\n";
  519. echo "a:hover { background: #99CCFF; }\n";
  520. echo "hr { background-color: #4D485B; margin-top: 3em; }\n";
  521. echo "</style>\n";
  522. echo "<title>Support Incident Tracker Setup</title>\n";
  523. echo "</head>\n<body>\n";
  524. echo "<h1>Support Incident Tracker - Installation &amp; Setup</h1>";
  525. //
  526. // Pre-flight Checks
  527. //
  528. if (!empty($_REQUEST['msg']))
  529. {
  530. $msg = strip_tags(base64_decode(urldecode($_REQUEST['msg'])));
  531. if ($cfg_file_exists === FALSE)
  532. {
  533. echo "<p class='info'><strong>It looks like you are setting up SiT! for the first time</strong> because we could not find a configuration file.<br />";
  534. echo "Please proceed with creating a new configuration file.</p>";
  535. }
  536. else
  537. {
  538. echo "<p class='error'><strong>Configuration Problem</strong>: {$msg}</p>";
  539. }
  540. }
  541. // Check that includes worked and that we have some config variables set, these two should always be set
  542. if ($CONFIG['application_name'] == '' AND $CONFIG['application_shortname'] == '')
  543. {
  544. echo "<p class='error'>SiT! Setup couldn't find configuration defaults (defaults.inc.php). Is your lib/ directory missing?</p>";
  545. }
  546. // Check we have the mysql extension
  547. if (!extension_loaded('mysql'))
  548. {
  549. echo "<p class='error'>Error: Could not find the mysql extension, SiT! requires MySQL to be able to run, you should install and enable the MySQL PHP Extension then run setup again.</p>";
  550. }
  551. if (version_compare(PHP_VERSION, "5.0.0", "<"))
  552. {
  553. echo "<p class='error'>You are running an older PHP version (< PHP 5), SiT v3.35 and later require PHP 5.0.0 or newer, some features may not work properly.</p>";
  554. }
  555. echo "\n\n<!-- A:".strip_tags($_REQUEST['action'])." -->\n\n";
  556. switch ($_REQUEST['action'])
  557. {
  558. case 'save_config':
  559. $newcfgfile = "<";
  560. $newcfgfile .= "?php\n";
  561. $newcfgfile .= "# config.inc.php - SiT! Config file generated automatically by setup.php on ".date('r')."\n\n";
  562. if ($_REQUEST['config'] == 'advanced')
  563. {
  564. foreach ($CFGVAR AS $setupvar => $setupval)
  565. {
  566. $SETUP[] = $setupvar;
  567. }
  568. }
  569. // Keep the posted setup
  570. foreach ($SETUP AS $setupvar)
  571. {
  572. if ($_POST[$setupvar]==='TRUE') $_POST[$setupvar] = TRUE;
  573. if ($_POST[$setupvar]==='FALSE') $_POST[$setupvar] = FALSE;
  574. $CONFIG[$setupvar]=$_POST[$setupvar];
  575. }
  576. // Set up a hard to find attachment path
  577. if ($CONFIG['attachment_fspath'] == '')
  578. {
  579. // We generate a path based on some semi-static values so that it's hard to guess,
  580. // but will still probably be the same if setup is run again the same day
  581. $CONFIG['attachment_fspath'] = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . "attachments-" . $systemhash . DIRECTORY_SEPARATOR;
  582. }
  583. // Extract the differences between the defaults and the newly configured items
  584. $CFGDIFF = array_diff_assoc($CONFIG, $DEFAULTS);
  585. if (count($CFGDIFF) > 0)
  586. {
  587. foreach ($CFGDIFF AS $setupvar => $setupval)
  588. {
  589. if ($CFGVAR[$setupvar]['title'] != '')
  590. {
  591. $newcfgfile .= "# {$CFGVAR[$setupvar]['title']}\n";
  592. }
  593. if ($CFGVAR[$setupvar]['help']!='')
  594. {
  595. $newcfgfile .= "# {$CFGVAR[$setupvar]['help']}\n";
  596. }
  597. $newcfgfile .= "\$CONFIG['$setupvar'] = ";
  598. if (is_numeric($setupval))
  599. {
  600. $newcfgfile .= "{$setupval}";
  601. }
  602. elseif (is_bool($setupval))
  603. {
  604. $newcfgfile .= $setupval == TRUE ? "TRUE" : "FALSE";
  605. }
  606. elseif (substr($setupval, 0, 6)=='array(')
  607. {
  608. $newcfgfile .= stripslashes("{$setupval}");
  609. }
  610. else
  611. {
  612. $newcfgfile .= "'".addslashes($setupval)."'";
  613. }
  614. $newcfgfile .= ";\n\n";
  615. }
  616. }
  617. else
  618. {
  619. $newcfgfile .= "# Nothing configured. This will mean the defaults are used.\n\n";
  620. }
  621. // INL if we leave off the php closing tag it saves people having trouble
  622. // with whitespace
  623. //$newcfgfile .= "?";
  624. //$newcfgfile .= ">";
  625. $fp = @fopen($config_filename, 'w');
  626. if (!$fp)
  627. {
  628. echo "<p class='error'>Could not write {$config_filename}</p>";
  629. echo "<p class='help'>Copy this text and paste it into a <var>config.inc.php</var> file in the SiT root directory (the folder than contains setup.php for example)<br />";
  630. // or <var>sit.conf</var> in the <var>/etc</var> directory
  631. echo "Or change the permissions on the folder so that it is writable and <a href=\"javascript:location.reload(true)\">refresh</a> this page to try again (if you do this remember to make it ";
  632. echo "read-only again afterwards)</p>";
  633. echo "<script type='text/javascript'>\n
  634. function selectText(divid)
  635. {
  636. if (document.selection)
  637. {
  638. var div = document.body.createTextRange();
  639. div.moveToElementText(document.getElementById(divid));
  640. div.select();
  641. }
  642. else
  643. {
  644. var div = document.createRange();
  645. div.setStartBefore(document.getElementById(divid));
  646. div.setEndAfter(document.getElementById(divid)) ;
  647. window.getSelection().addRange(div);
  648. }
  649. }
  650. </script>";
  651. echo "<div id='configfile' onclick=\"selectText('configfile');\" style='margin-left: 5%; margin-right: 5%; background-color: #F7FAFF; padding: 1em; border: 1px dashed #ccc;filter:alpha(opacity=75); opacity: 0.75; -moz-opacity:0.75; -moz-border-radius: 3px; '>";
  652. highlight_string($newcfgfile);
  653. echo "</div>";
  654. echo "<p>After creating your config file click the 'Next' button below.</p>";
  655. }
  656. else
  657. {
  658. echo "<p>Writing to {$config_filename}</p>";
  659. fwrite($fp, $newcfgfile);
  660. fclose($fp);
  661. echo "<p>Config file modified</p>";
  662. if (!@chmod($config_filename, 0640))
  663. {
  664. echo "<p class='error'>Important: The file permissions on the file <var>{$config_filename}</var> ";
  665. echo "allow the file to be modified, we recommend you now make this file read-only.";
  666. if (DIRECTORY_SEPARATOR == '/')
  667. {
  668. $html .= "<br />You can run the command <code>chmod 444</code> to make it read-only.";
  669. }
  670. echo "</p>";
  671. }
  672. }
  673. echo setup_button('checkdbstate', 'Next');
  674. break;
  675. case 'reconfigure':
  676. echo "<h2>Reconfigure</h2>";
  677. echo "<p>Amend your existing SiT! configuration. Please take care or you may break your SiT! installation.</p>";
  678. echo setup_configure();
  679. break;
  680. case 'checkdbstate':
  681. // Connect to Database server
  682. $db = @mysql_connect($CONFIG['db_hostname'], $CONFIG['db_username'], $CONFIG['db_password']);
  683. if (@mysql_error())
  684. {
  685. echo "<p class='error'>Setup could not connect to the database server '{$CONFIG['db_hostname']}'. MySQL Said: ".mysql_error()."</p>";
  686. echo setup_configure();
  687. }
  688. else
  689. {
  690. // Connected to database
  691. // Select database
  692. mysql_select_db($CONFIG['db_database'], $db);
  693. if (mysql_error())
  694. {
  695. if (!empty($CONFIG['db_username']))
  696. {
  697. if ($cfg_file_exists)
  698. {
  699. echo "<p class='error'>".mysql_error()."<br />Could not select database";
  700. if ($CONFIG['db_database']!='')
  701. {
  702. echo " '{$CONFIG['db_database']}', check the database name you have configured matches the database in MySQL";
  703. }
  704. else
  705. {
  706. echo ", the database name was not configured, please set the <code>\$CONFIG['db_database'] config variable";
  707. $CONFIG['db_database'] = 'sit';
  708. }
  709. echo "</p>";
  710. if ($_SESSION['new'] == 1)
  711. {
  712. echo "<p class='info'>If this is a new installation of SiT and you would like to use the database name '{$CONFIG['db_database']}', you should proceed and create a database</p>";
  713. }
  714. echo setup_button('reconfigure', 'Reconfigure SiT!');
  715. echo "<br />or<br /><br />";
  716. }
  717. else
  718. {
  719. echo "<p class='info'>You can now go ahead and create a database called '{$CONFIG['db_database']}' for SiT! to use.</p>";
  720. }
  721. echo setup_button('createdb', 'Create a database', "<br /><label><input type='checkbox' name='sampledata' value='yes' checked='checked' /> With sample data</label>");
  722. //echo "<p><a href='{$_SERVER['PHP_SELF']}?action=reconfigure'>Reconfigure</a> SiT!</p>";
  723. }
  724. else
  725. {
  726. // Username and Password are set, but the db could not be selected
  727. }
  728. // FIMXE INL temp removed
  729. // else
  730. // {
  731. // echo "<p class='help'>If this is the first time you have used SiT! you may need to create the database, ";
  732. // echo "if you have the necessary MySQL permissions you can create the database automatically.<br />";
  733. // echo "Alternatively you can create it manually by executing the SQL statement <br /><code>{$sql};</code></p";
  734. // echo "<p><a href='setup.php?action=createdatabase' class='button'>Create Database</a></p>";
  735. // }
  736. // //echo "<p>After creating the database run <a href='setup.php' class='button'>setup</a> again to create the database schema</p>";
  737. if (empty($CONFIG['db_database']) OR empty($CONFIG['db_username']))
  738. {
  739. echo "<p>You need to configure SiT to be able access the MySQL database.</p>";
  740. echo setup_configure();
  741. }
  742. }
  743. else
  744. {
  745. echo "<p class='info'>Sucessfully connected to your database.</p>";
  746. echo setup_button('checkatttdir', 'Next');
  747. }
  748. }
  749. break;
  750. case 'createdb':
  751. if ($_REQUEST['sampledata'] == 'yes' ) $_SESSION['sampledata'] = TRUE;
  752. else $_SESSION['sampledata'] = FALSE;
  753. setup_createdb();
  754. break;
  755. case 'checkatttdiragain':
  756. $again = TRUE;
  757. case 'checkatttdir':
  758. if (file_exists($CONFIG['attachment_fspath']) == FALSE)
  759. {
  760. echo "<h2>Attachments Directory</h2>";
  761. echo "<p>SiT! requires a directory to store attachments.</p>";
  762. echo setup_button('createattdir', "Create attachments directory");
  763. echo "<br />";
  764. if ($again)
  765. {
  766. echo setup_button('checkatttdiragain', 'Next');
  767. echo "<p class='error'>The directory <code>{$CONFIG['attachment_fspath']}</code> must be created before setup can continue.</p>";
  768. }
  769. }
  770. elseif (is_writable($CONFIG['attachment_fspath']) == FALSE)
  771. {
  772. echo "<h2>Attachments Directory</h2>";
  773. echo "<p>SiT! requires that the attachments directory is writable by the web server.</p>";
  774. if (DIRECTORY_SEPARATOR == '/')
  775. {
  776. echo "<br />You can run the following shell command to make it writable.<br /><br /><var>chmod ugo+w {$CONFIG['attachment_fspath']}</var>";
  777. }
  778. else
  779. {
  780. echo "<br />You may need to set windows file permissions to set the folder <var>{$CONFIG['attachment_fspath']}</var> writable.";
  781. }
  782. echo "</p>";
  783. echo setup_button('checkatttdiragain', 'Next');
  784. }
  785. else
  786. {
  787. $sql = "SHOW TABLES LIKE '{$dbUsers}'";
  788. $result = @mysql_query($sql);
  789. if (mysql_error() OR mysql_num_rows($result) < 1)
  790. {
  791. echo "<p>Next we will create a database schema</p>";
  792. echo setup_button('', 'Next');
  793. }
  794. else
  795. {
  796. echo "<p class='info'>You can now go ahead and run SiT!.</p>";
  797. echo "<form action='index.php' method='get'>";
  798. echo "<input type='submit' value=\"Run SiT!\" />";
  799. echo "</form>\n";
  800. }
  801. }
  802. break;
  803. case 'createattdir':
  804. // Note this creates a directory with 777 permissions!
  805. $dir = @mkdir($CONFIG['attachment_fspath'], '0777');
  806. if ($dir)
  807. {
  808. echo setup_button('checkatttdir', 'Next');
  809. }
  810. else
  811. {
  812. echo "<p class='error'>Sorry, the attachment directory could not be created for you.</p>"; // FIXME more help
  813. echo "<p>Please manually create a directory named <code>{$CONFIG['attachment_fspath']}</code></p>";
  814. if (substr($CONFIG['attachment_fspath'], 0, 14) == './attachments-')
  815. {
  816. echo "<p class='info'>Setup has chosen this random looking directory name on purpose, ";
  817. echo "please create the directory named exactly as shown above.</p>";
  818. }
  819. echo setup_button('checkatttdiragain', 'Next');
  820. }
  821. break;
  822. default:
  823. require (APPLICATION_LIBPATH . 'tablenames.inc.php');
  824. // Connect to Database server
  825. $db = @mysql_connect($CONFIG['db_hostname'], $CONFIG['db_username'], $CONFIG['db_password']);
  826. if (@mysql_error())
  827. {
  828. echo setup_configure();
  829. }
  830. else
  831. {
  832. // Connected to database
  833. // Select database
  834. mysql_select_db($CONFIG['db_database'], $db);
  835. if (mysql_error())
  836. {
  837. if (!empty($CONFIG['db_username']))
  838. {
  839. echo "<p class='error'>".mysql_error()."<br />Could not select database";
  840. if ($CONFIG['db_database']!='')
  841. {
  842. echo " '{$CONFIG['db_database']}', check the database name you have configured matches the database in MySQL";
  843. }
  844. else
  845. {
  846. echo ", the database name was not configured, please set the <code>\$CONFIG['db_database'] config variable";
  847. $CONFIG['db_database'] = 'sit';
  848. }
  849. echo "</p>";
  850. echo setup_button('reconfigure', 'Reconfigure SiT!');
  851. echo "<p>or</p>";
  852. echo setup_button('createdb', 'Create a database', "<br /><label><input type='checkbox' name='sampledata' value='yes' checked='checked' /> With sample data</label>");
  853. //echo "<p><a href='{$_SERVER['PHP_SELF']}?action=reconfigure'>Reconfigure</a> SiT!</p>";
  854. }
  855. else
  856. {
  857. // Username and Password are set, but the db could not be selected
  858. }
  859. // FIMXE INL temp removed
  860. // else
  861. // {
  862. // echo "<p class='help'>If this is the first time you have used SiT! you may need to create the database, ";
  863. // echo "if you have the necessary MySQL permissions you can create the database automatically.<br />";
  864. // echo "Alternatively you can create it manually by executing the SQL statement <br /><code>{$sql};</code></p";
  865. // echo "<p><a href='setup.php?action=createdatabase' class='button'>Create Database</a></p>";
  866. // }
  867. // //echo "<p>After creating the database run <a href='setup.php' class='button'>setup</a> again to create the database schema</p>";
  868. if (empty($CONFIG['db_database']) OR empty($CONFIG['db_username']))
  869. {
  870. echo "<p>You need to configure SiT to be able access the MySQL database.</p>";
  871. echo setup_configure();
  872. }
  873. }
  874. else
  875. {
  876. require (APPLICATION_LIBPATH . 'functions.inc.php');
  877. // Load the empty schema
  878. require ('setup-schema.php');
  879. // Connected to database and db selected
  880. echo "<p>Connected to database - ok</p>";
  881. // Check to see if we're already installed
  882. $sql = "SHOW TABLES LIKE '{$dbUsers}'";
  883. $result = mysql_query($sql);
  884. if (mysql_error())
  885. {
  886. echo "<p class='error'>Could not find a users table, an error occurred ".mysql_error()."</p>";
  887. exit;
  888. }
  889. if (mysql_num_rows($result) < 1)
  890. {
  891. echo "<h2>Creating new database schema...</h2>";
  892. // No users table or empty users table, proceed to install
  893. // $installed_schema = 0;
  894. // $installed_schema = substr(end(array_keys($upgrade_schema[$application_version*100])),1);
  895. $errors = setup_exec_sql($schema);
  896. if ($_SESSION['sampledata'] == TRUE)
  897. {
  898. // Install sample data
  899. echo "<p>Installing sample data...</p>";
  900. $errors = $errors + setup_exec_sql($sampledata_sql);
  901. }
  902. // Update the system version
  903. if ($errors < 1)
  904. {
  905. $vsql = "REPLACE INTO `{$dbSystem}` ( `id`, `version`) VALUES (0, $application_version)";
  906. mysql_query($vsql);
  907. if (mysql_error())
  908. {
  909. $html .= "<p class='error'>Could not store new schema version number '{$application_version}'. ".mysql_error()."</p>";
  910. }
  911. else
  912. {
  913. $html .= "<p>Schema successfully created as version {$application_version}</p>";
  914. }
  915. }
  916. else
  917. {
  918. $html .= "<p class='error'><strong>Summary</strong>: {$errors} Error(s) occurred while creating the schema, ";
  919. $html .= "please resolve the problems reported and then try running setup again.</p>";
  920. }
  921. echo $html;
  922. /* // Set the system version number
  923. $sql = "REPLACE INTO `{$dbSystem}` ( id, version) VALUES (0, $application_version)";
  924. mysql_query($sql);
  925. if (mysql_error()) trigger_error(mysql_error(),E_USER_ERROR);*/
  926. $installed_version = $application_version;
  927. echo "<h2>Database schema created</h2>";
  928. if ($errors > 0)
  929. {
  930. echo "<p>If these errors do not appear to be caused by your configuration or setup, ";
  931. echo "please log a bug <a href='http://sitracker.org/wiki/Bugs'>here</a>";
  932. echo ", with the full error message.</p>";
  933. }
  934. else
  935. {
  936. echo "<p>You can now proceed with the next step.</p>";
  937. }
  938. echo setup_button('checkinstallcomplete', 'Next');
  939. }
  940. else
  941. {
  942. // users table exists and has at least one record, must be already installed
  943. // Do upgrade
  944. // Have a look what version is installed
  945. // First look to see if the system table exists
  946. $exists = mysql_query("SELECT 1 FROM `{$dbSystem}` LIMIT 0");
  947. if (!$exists)
  948. {
  949. echo "<p class='error'>Could not find a 'system' table which probably means you have a version prior to v3.21</p>";
  950. $installed_version = 3.00;
  951. }
  952. else
  953. {
  954. $sql = "SELECT `version` FROM `{$dbSystem}` WHERE id = 0";
  955. $result = mysql_query($sql);
  956. if (mysql_error()) trigger_error(mysql_error(),E_USER_WARNING);
  957. list($installed_version) = mysql_fetch_row($result);
  958. /* if ($installed_version >= 3.35)
  959. {
  960. $sql = "SELECT `schemaversion` FROM `{$dbSystem}` WHERE id = 0";
  961. $result = mysql_query($sql);
  962. if (mysql_error()) trigger_error(mysql_error(),E_USER_WARNING);
  963. list($installed_schema) = mysql_fetch_row($result);
  964. }
  965. else
  966. {
  967. $installed_schema = 334;
  968. $sql = "SHOW COLUMNS FROM `{$dbSystem}` WHERE Field='schema'";
  969. $result = mysql_query($sql);
  970. if (mysql_num_rows($result) < 1)
  971. {
  972. $sql = "ALTER TABLE `{$dbSystem}` ADD `schemaversion` BIGINT UNSIGNED NOT NULL COMMENT 'DateTime in YYYYMMDDHHMM format'";
  973. $result = mysql_query($sql);
  974. if (mysql_error()) trigger_error(mysql_error(),E_USER_WARNING);
  975. }
  976. }*/
  977. }
  978. if (empty($installed_version))
  979. {
  980. echo "<p class='error'>Fatal setup error - Could not determine version of installed software. Try wiping your installation and installing from clean. (sorry)</p>";
  981. echo setup_button('', 'Restart setup');
  982. exit;
  983. }
  984. echo "<h2>Installed OK</h2>";
  985. if ($_REQUEST['action'] == 'upgrade')
  986. {
  987. /*****************************
  988. * Do pre-upgrade tasks here *
  989. *****************************/
  990. if ($installed_version < 3.35)
  991. {
  992. //Get anyone with var_notify_on_reassign on so we can add them a trigger later
  993. $sql = "SELECT * FROM `{$dbUsers}` WHERE var_notify_on_reassign='true'";
  994. if ($result = @mysql_query($sql))
  995. {
  996. while ($row = mysql_fetch_object($result))
  997. {
  998. $assign_notify_users[] = $row->id;
  999. }
  1000. }
  1001. //any kbarticles with private content, change whole type
  1002. $sql = "SELECT docid, distribution FROM `{$dbKBContent} WHERE distribution!='public'";
  1003. if ($result = @mysql_query($sql))
  1004. {
  1005. while ($row = @mysql_fetch_object($result))
  1006. {
  1007. if ($row->distribution == 'private')
  1008. {
  1009. $kbprivate[] = $row->docid;
  1010. }
  1011. elseif (!in_array($row->docid, $kbprivate))
  1012. {
  1013. $kbrestricted[] = $row->docid;
  1014. }
  1015. }
  1016. }
  1017. }
  1018. if ($installed_version < 3.45)
  1019. {
  1020. $sql = "SELECT i.id FROM `{$GLOBALS['dbIncidents']}` AS i, `{$GLOBALS['dbContacts']}` AS c, `{$dbServiceLevels}` AS sl ";
  1021. $sql .= "WHERE c.id = i.contact ";
  1022. $sql .= "AND sl.tag = i.servicelevel AND sl.priority = i.priority AND sl.timed = 'yes' ";
  1023. $sql .= "AND i.status = 2 "; // Only want closed incidents, dont want awaiting closure as they could be reactivated
  1024. $result = mysql_query($sql);
  1025. if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_WARNING);
  1026. if (mysql_num_rows($result) > 0)
  1027. {
  1028. while ($obj = mysql_fetch_object($result))
  1029. {
  1030. $asql = "SELECT DISTINCT origcolref, linkcolref ";
  1031. $asql .= "FROM `{$dbLinks}` AS l, `{$dbLinkTypes}` AS lt ";
  1032. $asql .= "WHERE l.linktype = 6 ";
  1033. $asql .= "AND linkcolref = {$obj->id} ";
  1034. $asql .= "AND direction = 'left'";
  1035. $aresult = mysql_query($asql);
  1036. if (mysql_error()) trigger_error(mysql_error(),E_USER_WARNING);
  1037. if (mysql_num_rows($aresult) == 0)
  1038. {
  1039. $billing_upgrade[] = $obj->id;
  1040. }
  1041. }
  1042. }
  1043. }
  1044. /*****************************
  1045. * UPGRADE THE SCHEMA *
  1046. *****************************/
  1047. for ($v=(($installed_version*100)+1); $v<=($application_version*100); $v++)
  1048. {
  1049. $html = '';
  1050. if (!empty($upgrade_schema[$v]))
  1051. {
  1052. $newversion = number_format(($v/100),2);
  1053. echo "<p>Updating schema from {$installed_version} to v{$newversion}&hellip;</p>";
  1054. $errors = setup_exec_sql($upgrade_schema[$v]);
  1055. // Update the system version
  1056. if ($errors < 1)
  1057. {
  1058. $vsql = "REPLACE INTO `{$dbSystem}` ( `id`, `version`) VALUES (0, $newversion)";
  1059. mysql_query($vsql);
  1060. if (mysql_error())
  1061. {
  1062. $html .= "<p class='error'>Could not store new schema version number '{$newversion}'. ".mysql_error()."</p>";
  1063. }
  1064. else
  1065. {
  1066. $html .= "<p>Schema successfully updated to version {$newversion}.</p>";
  1067. }
  1068. $installed_version = $newversion;
  1069. $upgradeok = TRUE;
  1070. }
  1071. else
  1072. {
  1073. $html .= "<p class='error'><strong>Summary</strong>: {$errors} Error(s) occurred while updating t…

Large files files are truncated, but you can click here to view the full file