Added update_year.sh (still not fully flexible) and updated all years with it.
[mailer.git] / inc / install-functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 10/22/2009 *
4  * ===================                          Last change: 10/22/2009 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : install-functions.php                            *
8  * -------------------------------------------------------------------- *
9  * Short description : Functions for installation procedure             *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Funktionen fuer die Installationsroutine         *
12  * -------------------------------------------------------------------- *
13  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
14  * Copyright (c) 2009 - 2015 by Mailer Developer Team                   *
15  * For more information visit: http://mxchange.org                      *
16  *                                                                      *
17  * This program is free software; you can redistribute it and/or modify *
18  * it under the terms of the GNU General Public License as published by *
19  * the Free Software Foundation; either version 2 of the License, or    *
20  * (at your option) any later version.                                  *
21  *                                                                      *
22  * This program is distributed in the hope that it will be useful,      *
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
25  * GNU General Public License for more details.                         *
26  *                                                                      *
27  * You should have received a copy of the GNU General Public License    *
28  * along with this program; if not, write to the Free Software          *
29  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
30  * MA  02110-1301  USA                                                  *
31  ************************************************************************/
32
33 // Some security stuff...
34 if ((!defined('__SECURITY')) || (!isInstaller())) {
35         die();
36 } // END - if
37
38 // Init installer
39 function initInstaller () {
40         // Initialize installer group array
41         $GLOBALS['installer_groups'] = array(
42                 // base_data
43                 'base_path'       => 'base_data',
44                 'base_url'        => 'base_data',
45                 'main_title'      => 'base_data',
46                 'slogan'          => 'base_data',
47                 'webmaster'       => 'base_data',
48                 // database_config
49                 'mysql_host'      => 'database_config',
50                 'mysql_dbase'     => 'database_config',
51                 'mysql_prefix'    => 'database_config',
52                 'mysql_engine'    => 'database_config',
53                 'mysql_login'     => 'database_config',
54                 'mysql_password1' => 'database_config',
55                 'mysql_password2' => 'database_config',
56                 // smtp_config
57                 'smtp_host'       => 'smtp_config',
58                 'smtp_user'       => 'smtp_config',
59                 'smtp_password1'  => 'smtp_config',
60                 'smtp_password2'  => 'smtp_config',
61                 // other_config
62                 'output_mode'     => 'other_config',
63                 'warn_no_pass'    => 'other_config',
64                 'write_footer'    => 'other_config',
65                 'enable_backlink' => 'other_config',
66                 // first_admin
67                 'admin_login'     => 'first_admin',
68                 'admin_email'     => 'first_admin',
69                 'admin_password1' => 'first_admin',
70                 'admin_password2' => 'first_admin',
71         );
72
73         // Set mininmum password length/score and other config entries
74         setConfigEntry('min_password_length', 5);
75         setConfigEntry('min_password_score' , 3);
76         setConfigEntry('verbose_sql'        , 'N');
77 }
78
79 // Write the local config-local.php file from "template"
80 function doInstallWriteLocalConfigurationFile ($path, $url, $title, $slogan, $email, $noPassword, $writeFooter, $backLink, $databaseHost, $databaseName, $databaseLogin, $databasePassword, $databasePrefix, $tableType, $databaseExtension, $smtpHost, $smtpUser, $smtpPassword) {
81         // Copy the config template and verify it
82         copyFileVerified($path . 'inc/config-local.php.dist', $path . getCachePath() . 'config-local.php', 0644);
83
84         /*
85          * Ok, all done. So we can write the config data to the php files. Do only
86          * write these if they differ from auto-detected values.
87          */
88         if ($path != getPath()) {
89                 changeDataInLocalConfigurationFile('SERVER-PATH', "setConfigEntry('PATH', '", "');", $path, 0);
90         } // END - if
91         if ($url != getUrl()) {
92                 changeDataInLocalConfigurationFile('HOST-URL', "setConfigEntry('URL', '", "');", $url, 0);
93         } // END - if
94
95         // Write more data
96         changeDataInLocalConfigurationFile('MAIN-TITLE', "setConfigEntry('MAIN_TITLE', '", "');", $title, 0);
97         changeDataInLocalConfigurationFile('SLOGAN', "setConfigEntry('SLOGAN', '", "');", $slogan, 0);
98         changeDataInLocalConfigurationFile('WEBMASTER', "setConfigEntry('WEBMASTER', '", "');", $email, 0);
99         changeDataInLocalConfigurationFile('NULLPASS-WARNING', "setConfigEntry('WARN_NO_PASS', '", "');", $noPassword, 0);
100         changeDataInLocalConfigurationFile('WRITE-FOOTER', "setConfigEntry('WRITE_FOOTER', '", "');", $writeFooter, 0);
101         changeDataInLocalConfigurationFile('BACKLINK', "setConfigEntry('ENABLE_BACKLINK', '", "');", $backLink, 0);
102         // @TODO DEACTIVATED: changeDataInLocalConfigurationFile('OUTPUT-MODE', "setConfigEntry('OUTPUT_MODE', '", "');", postRequestElement('omode'), 0);
103         changeDataInLocalConfigurationFile('MYSQL-HOST', "      'host'     => '", "',", $databaseHost, 0);
104         changeDataInLocalConfigurationFile('MYSQL-DBASE', "     'dbase'    => '", "',", $databaseName, 0);
105         changeDataInLocalConfigurationFile('MYSQL-LOGIN', "     'login'    => '", "',", $databaseLogin, 0);
106         changeDataInLocalConfigurationFile('MYSQL-PASSWORD', "  'password' => '", "',", $databasePassword, 0);
107         changeDataInLocalConfigurationFile('MYSQL-PREFIX', "setConfigEntry('_MYSQL_PREFIX', '", "');", $databasePrefix, 0);
108         changeDataInLocalConfigurationFile('TABLE-TYPE', "setConfigEntry('_TABLE_TYPE', '", "');", $tableType, 0);
109         changeDataInLocalConfigurationFile('DATABASE-TYPE', "setConfigEntry('_DB_TYPE', '", "');", $databaseExtension, 0);
110         changeDataInLocalConfigurationFile('SMTP-HOSTNAME', "setConfigEntry('SMTP_HOSTNAME', '", "');", $smtpHost, 0);
111         changeDataInLocalConfigurationFile('SMTP-USER', "setConfigEntry('SMTP_USER', '", "');", $smtpUser, 0);
112         changeDataInLocalConfigurationFile('SMTP-PASSWORD', "setConfigEntry('SMTP_PASSWORD', '", "');", $smtpPassword, 0);
113
114         // Generate a long site-key and write it
115         changeDataInLocalConfigurationFile('SITE-KEY', "setConfigEntry('SITE_KEY', '", "');", generatePassword(50), 0);
116
117         // Script is now installed
118         return changeDataInLocalConfigurationFile('INSTALLED', "setConfigEntry('MAILER_INSTALLED', '", "');", 'Y', 0);
119 }
120
121 // Adds a given template with content to install output stream
122 function addTemplateToInstallContent ($template, $content = array()) {
123         // Load the template
124         $out = loadTemplate($template, TRUE, $content);
125
126         // Add it to output
127         addToInstallContent($out);
128 }
129
130 // Add it to install content
131 function addToInstallContent ($out) {
132         // Set or add it...
133         if (!isset($GLOBALS['install_content'])) {
134                 // Set it
135                 $GLOBALS['install_content'] = $out;
136         } else {
137                 // Add it
138                 $GLOBALS['install_content'] .= $out;
139         } // END - if
140 }
141
142 // Somewhat getter for installer content
143 function getInstallerContent () {
144         // Is it here?
145         if (isset($GLOBALS['install_content'])) {
146                 // Yes, then use it
147                 $content = $GLOBALS['install_content'];
148         } else {
149                 // Nothing found, this needs fixing
150                 $content = returnMessage('{--INSTALLER_CONTENT_404--}');
151         }
152
153         // Return content
154         return $content;
155 }
156
157 // Read a given SQL dump
158 function readSqlDump ($FQFN) {
159         // Load the file
160         $content = readFromFile($FQFN);
161
162         // Remove some unwanted chars
163         $content = str_replace(array(chr(13), PHP_EOL . PHP_EOL), array('', PHP_EOL), $content);
164
165         // Return the content
166         return $content;
167 }
168
169 // Generates the installer menu by simply loading another template
170 function generateInstallerMenu () {
171         // Load installer menu template
172         $OUT = loadTemplate('install_menu', TRUE);
173
174         // Return loaded content
175         return $OUT;
176 }
177
178 // Generate the install footer navigation by simply loading another template
179 function generateInstallerFooterNavigation () {
180         // Load installer menu template
181         $OUT = loadTemplate('install_footer', TRUE);
182
183         // Return loaded content
184         return $OUT;
185 }
186
187 // Generate an option list for database types for given default value
188 function generateInstallerDatabaseTypeOptions () {
189         return generateOptions(
190                 '/ARRAY/',
191                 array(
192                         'MyISAM',
193                         'InnoDB'
194                 ),
195                 array(
196                         '{--INSTALLER_TABLE_TYPE_MYISAM--}',
197                         '{--INSTALLER_TABLE_TYPE_INNODB--}'
198                 ),
199                 getSession('mysql_engine')
200         );
201 }
202
203 // Generate an option list for database extensions for given default value
204 function generateInstallerDatabaseExtensionOptions () {
205         // Init all arrays
206         $keys = array();
207         $values = array();
208         $foundExtensions = array();
209
210         // Scan directory
211         $drivers = getArrayFromDirectory('inc/db/', 'lib-', FALSE, FALSE);
212
213         // Remove prefix + extension
214         foreach ($drivers as $key => $driver) {
215                 // Remove driver
216                 $drivers[$key] = substr($driver, 4, -4);
217
218                 // Is the corresponding extension loaded?
219                 if (isPhpExtensionLoaded($drivers[$key])) {
220                         // Then add it
221                         array_push($foundExtensions, $drivers[$key]);
222                 } // END - if
223         } // END - foreach
224
225         // Generate list for keys/values ("translations")
226         foreach ($foundExtensions as $extension) {
227                 // Use it as direct key
228                 array_push($keys, $extension);
229
230                 // Add "translation" function around it as value
231                 array_push($values, '{%pipe,translatePhpExtension=' . $extension . '%}');
232         } // END - if
233
234         // Get a directory list
235         return generateOptions(
236                 '/ARRAY/',
237                 $keys,
238                 $values,
239                 getSession('database_extension')
240         );
241 }
242
243 // Generate an option list for output mode types for given default value
244 function generateInstallerOutputModeOptions ($defaultValue) {
245         return generateOptions(
246                 '/ARRAY/',
247                 array('render', 'direct'),
248                 array('{--INSTALLER_MODE_RENDER--}', '{--INSTALLER_MODE_DIRECT--}'),
249                 $defaultValue
250         );
251 }
252
253 // Checks whether we have an AJAX-enabled installer which defaults to red pill
254 function isAjaxInstaller () {
255         // Get the session data and compare it against 'ajax'
256         $isAjaxInstaller = (getSession('installer') == 'ajax');
257
258         // Return it
259         return $isAjaxInstaller;
260 }
261
262 // Checks whether we have an plain installer which defaults to red pill
263 function isPlainInstaller () {
264         // Get the session data and compare it against 'plain'
265         $isPlainInstaller = (getSession('installer') == 'plain');
266
267         // Return it
268         return $isPlainInstaller;
269 }
270
271 // Handle all given failed fields
272 function handleInstallerFailedFields ($failedFields) {
273         // Don't do anything with no array or no entries
274         if (!isFilledArray($failedFields)) {
275                 // Abort here
276                 reportBug(__FUNCTION__, __LINE__, 'failedFields[]=' . gettype($failedFields) . ' verification failed');
277         } // END - if
278
279         // Handle all
280         $out = '<ol>';
281         foreach ($failedFields as $key => $field) {
282                 // "Translate" it
283                 $out .= '<li>{--INSTALLER_FIELD_FAILED_' . strtoupper($field) . '--}</li>';
284         } // END - foreach
285         $out .= '</ol>';
286
287         // Return it
288         return $out;
289 }
290
291 // Checks given key/value pair if it is valid by a call-back
292 function isInstallerDataValid (&$saveStatus, $key, $value) {
293         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',value=' . $value . ' - ENTERED!');
294         // Generate call-back function based on given key
295         $callbackName = 'isInstaller' . capitalizeUnderscoreString($key) . 'Valid';
296
297         // Is the function there?
298         if (!function_exists($callbackName)) {
299                 // Not found, which is not bad, but it means this data is always valid
300                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Call-back function ' . $callbackName . ' not found. saveStatus[status]=' . $saveStatus['status'] . ', key=' . $key . ', value=' . $value);
301
302                 // All fine (CAREFULL!)
303                 return TRUE;
304         } // END - if
305
306         // Then call it back
307         $isValid = (bool) call_user_func($callbackName, $value);
308
309         // Is it not valid?
310         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',value=' . $value . ',isValid=' . intval($isValid));
311         if ($isValid === FALSE) {
312                 // Then add it to saveStatus
313                 array_push($saveStatus['failed_fields'], $key);
314         } // END - if
315
316         // Return status
317         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',value=' . $value . ',isValid=' . intval($isValid) . ' - EXIT!');
318         return $isValid;
319 }
320
321 // Post-check on installer data
322 function doInstallerPostCheck ($currentTab, &$saveStatus) {
323         // Debug message
324         //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currentTab=' . $currentTab . ',saveStatus[status]=' . $saveStatus['status'] . ' - ENTERED!');
325
326         // Create the call-back function on 'tab'
327         $callbackName = 'isInstallerPost' . capitalizeUnderscoreString($currentTab) . 'Valid';
328
329         // Is the function there?
330         if (!function_exists($callbackName)) {
331                 // Not found, which is not bad, but it means the post-check won't be run
332                 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Call-back function ' . $callbackName . ' not found. saveStatus[status]=' . $saveStatus['status'] . ', currentTab=' . $currentTab);
333
334                 // Abort here
335                 return FALSE;
336         } // END - if
337
338         // Init 'tab-specific error message'
339         $GLOBALS['installer_post_error'][$currentTab]    = '';
340         $GLOBALS['installer_failed_fields'][$currentTab] = array();
341
342         // Debug message
343         //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Calling function ' . $callbackName . ',currentTab=' . $currentTab . ',saveStatus[status]=' . $saveStatus['status']);
344
345         // Then call it back
346         $isValid = (bool) call_user_func($callbackName, $currentTab);
347
348         // Is it not valid?
349         if (($isValid === FALSE) || (isFilledArray($GLOBALS['installer_failed_fields'][$currentTab]))) {
350                 // Then change status and message
351                 $saveStatus['status']  = 'failed';
352                 $saveStatus['message'] = '{%message,INSTALLER_POST_CHECK_' . strtoupper($currentTab) . '_FAILED=' . $GLOBALS['installer_post_error'][$currentTab] . '%}';
353
354                 // Is there failed fields?
355                 if (isFilledArray($GLOBALS['installer_failed_fields'][$currentTab])) {
356                         // Then merge both
357                         $saveStatus['failed_fields'] = merge_array($saveStatus['failed_fields'], $GLOBALS['installer_failed_fields'][$currentTab]);
358                 } // END - if
359         } // END - if
360
361         // Debug message
362         //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currentTab=' . $currentTab . ',saveStatus[status]=' . $saveStatus['status'] . ' - EXIT!');
363 }
364
365 // Determines an installer group by given key
366 function determineInstallerGroupByKey ($key) {
367         // Try to look it up
368         if (!isset($GLOBALS['installer_groups'][$key])) {
369                 // Log missing entry
370                 logDebugMessage(__FUNCTION__, __LINE__, 'Cannot determine installer group, returning dummy group. key=' . $key);
371
372                 // Return dummy group
373                 return 'dummy';
374         } // END - if
375
376         // Return it
377         return $GLOBALS['installer_groups'][$key];
378 }
379
380 // Adds given key/value pair to an overview group
381 function addKeyValueToInstallerOverviewGroup ($key, $value) {
382         // First determine the group by given key
383         $group = determineInstallerGroupByKey($key);
384
385         // Depending on the group, add it for later usage (to render the overview page)
386         $GLOBALS['installer_overview'][$group][$key] = $value;
387 }
388
389 //-----------------------------------------------------------------------------
390 //                        Template call-back functions
391 //-----------------------------------------------------------------------------
392
393 // ----------------- Extensions -----------------
394
395 // Generates (and returns) a table from all extensions
396 function generateInstallerExtensionTable () {
397         // Generate extension list
398         $extensions = loadAllExtensionsByTemplate();
399
400         // "Walk" through all
401         $OUT = '';
402         foreach ($extensions as $extension) {
403                 // Remove prefix + suffix
404                 $ext_name = substr(basename($extension), 4, -4);
405
406                 // Is the extension not in development and not admintheme* ?
407                 if ((loadExtension($ext_name, 'test', '0.0.0', TRUE)) && (isExtensionProductive($ext_name)) && (substr($ext_name, 0, 10) != 'admintheme')) {
408                         // Default is not disabled
409                         $disabled = '';
410                         if (in_array($ext_name, array('sql_patches', 'timezone'))) {
411                                 // Always keep this enabled
412                                 $disabled = ' disabled="disabled"';
413                         } // END - if
414
415                         // Initialize content array
416                         $content = array(
417                                 'ext_name'    => $ext_name,
418                                 'ext_version' => getExtensionVersion($ext_name),
419                                 'checked'     => getExtensionSelectedFromSession($ext_name, 'extensions'),
420                                 'disabled'    => $disabled,
421                                 'description' => loadTemplate('ext_' . $ext_name, TRUE),
422                         );
423
424                         // Load row template
425                         $OUT .= loadTemplate('install_list_extensions_row', TRUE, $content);
426                 } // END - if
427         } // END - foreach
428
429         // Load main template
430         return loadTemplate('install_list_extensions', TRUE, $OUT);
431 }
432
433 //-----------------------------------------------------------------------------
434 //                   Call-back functions to check validity
435 //-----------------------------------------------------------------------------
436
437 // ----------------- Base data -----------------
438
439 // Call-back function to check validity of 'base_path'
440 function isInstallerBasePathValid ($value) {
441         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' - ENTERED!');
442         // Is it a directory and if some typical files could be found
443         $isValid = (
444                 // Is it a directory?
445                 (isDirectory($value))
446         &&
447                 // Doesn't contain dots
448                 (strpos($value, '..') === FALSE)
449         &&
450                 // Is there a trailing slash?
451                 (substr($value, -1, 1) == '/')
452         &&
453                 // Is mysql-manager.php there?
454                 (isFileReadable($value . 'inc/mysql-manager.php'))
455         &&
456                 // What about gen_sql_patches.php?
457                 (isFileReadable($value . 'inc/gen_sql_patches.php'))
458         &&
459                 // And how about referral-functions.php?
460                 (isFileReadable($value . 'inc/referral-functions.php'))
461         );
462
463         // Return it
464         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ',isValid=' . intval($isValid) . ' - EXIT');
465         return $isValid;
466 }
467
468 // Call-back function to check validity of 'base_url'
469 function isInstallerBaseUrlValid ($value) {
470         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' - ENTERED!');
471         // Is it same as URL
472         $isValid = (
473                 // Same as URL?
474                 ($value == getUrl())
475         || (
476                 // Starts with http:// or https:// ?
477                 ((substr($value, 0, 7) == 'http://') || (substr($value, 0, 8) == 'https://'))
478         &&
479                 // Has no trailing slash?
480                 (substr($value, -1, 1) != '/')
481         &&
482                 // And total length is at least 6+8=14 chars long? (https://foo.ba)
483                 (strlen($value) >= 14)
484         &&
485                 // Is the URL valid?
486                 (isUrlValid($value))
487         ));
488
489         // Return it
490         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ',isValid=' . intval($isValid) . ' - EXIT');
491         return $isValid;
492 }
493
494 // Call-back function to checl validity of 'main_title'
495 function isInstallerMainTitleValid ($value) {
496         // Is it valid?
497         // @TODO Comparing with DEFAULT_MAIN_TITLE doesn't work
498         $isValid = ((strlen($value) >= 4) && ($value != getMessage('DEFAULT_MAIN_TITLE')));
499
500         // Return it
501         return $isValid;
502 }
503
504 // Call-back function to checl validity of 'slogan'
505 function isInstallerSloganValid ($value) {
506         // Is it valid?
507         $isValid = ((strlen($value) >= 4) && ($value != getMessage('DEFAULT_SLOGAN')));
508
509         // Return it
510         return $isValid;
511 }
512
513 // Call-back function to check validity of 'webmaster'
514 function isInstallerWebmasterValid ($value) {
515         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' - ENTERED!');
516         // Is it a valid email address?
517         $isValid = ((
518                 // Is it a valid email address?
519                 (isEmailValid($value))
520         ||
521                 // Or is there 'localhost/127.0.0.1' as hostname? Then don't check email address (e.g. you@localhost)
522                 (isDeveloperSystem())
523         ) && (
524                 // Is not default "email address"
525                 $value != getMessage('DEFAULT_WEBMASTER')
526         ) && (
527                 strlen($value) >= 11
528         ));
529
530         // Return it
531         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ',isValid=' . intval($isValid) . ' - EXIT');
532         return $isValid;
533 }
534
535 // ----------------- Database configuration -----------------
536
537 // Call-back function to check validity of 'mysql_host'
538 function isInstallerMysqlHostValid ($value) {
539         // This value must match a hostname or IP address
540         $isValid = (
541                 // Shall not be empty
542                 (!empty($value)) && (
543                 // Is localhost/127.0.0.1? (mostly the case)
544                 (in_array($value, array('localhost', '127.0.0.1')))
545         ||
546                 // IP number match (this regex was taken from www.regexlib.com)
547                 (preg_match('/((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9]))/', $value))
548         ||
549                 // Host name match
550                 (preg_match('/([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}/', $value))
551         ));
552
553         // Return it
554         return $isValid;
555 }
556
557 // Call-back function to check validity of 'mysql_engine'
558 function isInstallerMysqlEngineValid ($value) {
559         // This value must be 'MyISAM' or 'InnoDB'
560         $isValid = in_array($value, array('MyISAM', 'InnoDB'));
561
562         // Return it
563         return $isValid;
564 }
565
566 // Call-back function to check validity of 'mysql_dbase'
567 function isInstallerMysqlDbaseValid ($value) {
568         // This value must not be empty
569         $isValid = ((!empty($value)) && ($value != 'your_database'));
570
571         // Return it
572         return $isValid;
573 }
574
575 // Call-back function to check validity of 'mysql_login'
576 function isInstallerMysqlLoginValid ($value) {
577         // This value must not be empty
578         $isValid = ((!empty($value)) && ($value != 'your_login'));
579
580         // Return it
581         return $isValid;
582 }
583
584 // Call-back function to check validity of 'mysql_prefix'
585 function isInstallerMysqlPrefixValid ($value) {
586         // This value must not be empty
587         $isValid = !empty($value);
588
589         // Return it
590         return $isValid;
591 }
592
593 // ----------------- SMTP configuration -----------------
594
595 // ----------------- Other configuration -----------------
596
597 // ----------------- First administator -----------------
598
599 // Call-back function to check validity of 'admin_login'
600 function isInstallerAdminLoginValid ($value) {
601         // Length should not be shorter than 4 characters
602         return (strlen($value) >= 4);
603 }
604
605 // Call-back function to check validity of 'admin_email'
606 function isInstallerAdminEmailValid ($value) {
607         // Just call webmaster-check function
608         return isInstallerWebmasterValid($value);
609 }
610
611 // Call-back function to check validity of 'admin_password1'
612 function isInstallerAdminPassword1Valid ($value) {
613         // Check if it is strong
614         return isStrongPassword($value);
615 }
616
617 // Call-back function to check validity of 'admin_password2'
618 function isInstallerAdminPassword2Valid ($value) {
619         // Check if it is strong
620         return isStrongPassword($value);
621 }
622
623 // ----------------- Extensions -----------------
624
625 // Call-back function to check 'sel' (array!)
626 function isInstallerSelValid ($value) {
627         // $value is not an array, is really bad.
628         if (!is_array($value)) {
629                 // Is no array
630                 reportBug(__FUNCTION__, __LINE__, 'sel,value[]=' . gettype($value) . '!=array');
631         } // END - if
632
633         // Add always missing ext-sql_patches
634         $value['sql_patches'] = '1';
635
636         // Default is fine
637         $isValid = TRUE;
638
639         // "Walk" through all extensions
640         foreach ($value as $ext_name => $sel) {
641                 // Is this extension choosen?
642                 if ($sel != '1') {
643                         // Skip this
644                         continue;
645                 } // END - if
646
647                 // Can it be loaded?
648                 $isValid = (($isValid) && (loadExtension($ext_name, 'test', '0.0.0', TRUE)));
649         } // END - foreach
650
651         // Remove 'sel' from POST data as it cannot be saved
652         unsetPostRequestElement('sel');
653
654         // Save it in session (sorry to do that here :( )
655         setSession('extensions', implode(':', array_keys($value)));
656
657         // Return result
658         return $isValid;
659 }
660
661 //-----------------------------------------------------------------------------
662 //                 Call-back functions to post-check validity
663 //-----------------------------------------------------------------------------
664
665 // Call-back function to check if base data is valid
666 function isInstallerPostBaseDataValid ($currentTab) {
667         // By default it is not valid
668         $isValid = FALSE;
669
670         // Is the base path valid?
671         if (!isInstallerBasePathValid(postRequestElement('base_path'))) {
672                 // Then mark it
673                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_BASE_PATH_INVALID--}';
674                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'base_path');
675                 return FALSE;
676         } elseif (!isInstallerBaseUrlValid(postRequestElement('base_url'))) {
677                 // Then mark it
678                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_BASE_URL_INVALID--}';
679                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'base_url');
680                 return FALSE;
681         } elseif (strlen(postRequestElement('main_title')) < 3) {
682                 // To short
683                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_MAIN_TITLE_INVALID--}';
684                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'main_title');
685                 return FALSE;
686         } elseif (strlen(postRequestElement('slogan')) < 3) {
687                 // To short
688                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_SLOGAN_INVALID--}';
689                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'slogan');
690                 return FALSE;
691         } elseif (!isInstallerWebmasterValid(postRequestElement('webmaster'))) {
692                 // Then mark it
693                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_WEBMASTER_INVALID--}';
694                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'webmaster');
695                 return FALSE;
696         } else {
697                 // All fine
698                 $isValid = TRUE;
699
700                 // Remember this tab in session
701                 installTabOkay($currentTab);
702         }
703
704         // Return it
705         return $isValid;
706 }
707
708 // Call-back function to check if database configuration in POST is valid
709 function isInstallerPostDatabaseConfigValid ($currentTab) {
710         // By default nothing is valid
711         $isValid       = FALSE;
712         $engineValid   = FALSE;
713         $missingTables = 0;
714
715         // Do both passwords match?
716         if ((!isPostRequestElementSet('mysql_password1')) && (isPostRequestElementSet('mysql_password2'))) {
717                 // Password 1 not set
718                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_DATABASE_PASSWORD1_EMPTY--}';
719                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'mysql_password1');
720                 return FALSE;
721         } elseif ((isPostRequestElementSet('mysql_password1')) && (!isPostRequestElementSet('mysql_password2'))) {
722                 // Password 2 not set
723                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_DATABASE_PASSWORD2_EMPTY--}';
724                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'mysql_password2');
725                 return FALSE;
726         } elseif (postRequestElement('mysql_password1') != postRequestElement('mysql_password2')) {
727                 // Passwords mismatch
728                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_DATABASE_PASSWORDS_MISMATCH--}';
729                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'mysql_password1', 'mysql_password2');
730                 return FALSE;
731         } // END - if
732
733         // Remove any previous flag
734         unsetSqlLinkUp(__FUNCTION__, __LINE__);
735
736         // Try to connect to the database
737         sqlConnectToDatabase(postRequestElement('mysql_host'), postRequestElement('mysql_login'), postRequestElement('mysql_password1'), __FUNCTION__, __LINE__);
738
739         // Is the link up
740         if (!isSqlLinkUp()) {
741                 // Cannot connect to database
742                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_DATABASE_CONNECT_ERROR--}';
743                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'mysql_login', 'mysql_password1', 'mysql_password2');
744                 return FALSE;
745         } // END - if
746
747         // Then attempt to select the database
748         if (!sqlSelectDatabase(postRequestElement('mysql_dbase'), __FUNCTION__, __LINE__)) {
749                 // Could not find database
750                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_DATABASE_SELECT_FAILED--}';
751                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'mysql_dbase');
752
753                 // Disconnect here, we don't need idle database connections laying around
754                 sqlCloseLink(__FUNCTION__, __LINE__);
755
756                 // Abort here
757                 return FALSE;
758         } // END - if
759
760         // Set database name and prefix
761         setConfigEntry('__DB_NAME'    , postRequestElement('mysql_dbase'));
762         setConfigEntry('_MYSQL_PREFIX', postRequestElement('mysql_prefix'));
763
764         // Get an array of all supported engines
765         $engines = getArrayFromSupportedSqlEngines(postRequestElement('mysql_engine'));
766
767         // Is this an array?
768         if (!is_array($engines)) {
769                 // Something bad happened
770                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_DATABASE_ENGINES_SQL_ERROR--}';
771                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'mysql_engine');
772
773                 // Disconnect here, we don't need idle database connections laying around
774                 sqlCloseLink(__FUNCTION__, __LINE__);
775
776                 // Abort here
777                 return FALSE;
778         } elseif (!isFilledArray($engines)) {
779                 // No engine is active
780                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_DATABASE_NO_ENGINES_ACTIVE--}';
781                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'mysql_engine');
782
783                 // Disconnect here, we don't need idle database connections laying around
784                 sqlCloseLink(__FUNCTION__, __LINE__);
785
786                 // Abort here
787                 return FALSE;
788         }
789
790         // Then check all, if the requested is working
791         foreach ($engines as $engineArray) {
792                 // By default the selected engine is not valid
793                 $engineValid = FALSE;
794
795                 // Is the engine there?
796                 if (strtolower($engineArray['Engine']) == strtolower(postRequestElement('mysql_engine'))) {
797                         // Okay, engine is found
798                         $engineValid = TRUE;
799                         break;
800                 } // END - if
801         } // END - foreach
802
803         // So, is the engine found?
804         if ($engineValid === FALSE) {
805                 // Requested engine is not active
806                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_DATABASE_ENGINE_UNSUPPORTED--}';
807                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'mysql_engine');
808
809                 // Disconnect here, we don't need idle database connections laying around
810                 sqlCloseLink(__FUNCTION__, __LINE__);
811
812                 // Abort here
813                 return FALSE;
814         } // END - if
815
816         // Init some known tables
817         $tables = array(
818                 // Admins
819                 'admins'      => TRUE,
820                 // Admin menu
821                 'admin_menu'  => TRUE,
822                 // Categories
823                 'cats'        => TRUE,
824                 // Configuration
825                 'config'      => TRUE,
826                 // Extensions
827                 'extensions'  => TRUE,
828                 // Guest menu
829                 'guest_menu'  => TRUE,
830                 // Max receive
831                 'max_receive' => TRUE,
832                 // Member menu
833                 'member_menu' => TRUE,
834                 // Module registry
835                 'mod_reg'     => TRUE,
836                 // Payments
837                 'payments'    => TRUE,
838                 // Sending pool
839                 'pool'        => TRUE,
840                 // Referral banner
841                 'refbanner'   => TRUE,
842                 // Referral levels
843                 'refdepths'   => TRUE,
844                 // Referral system
845                 'refsystem'   => TRUE,
846                 // Task system
847                 'task_system' => TRUE,
848         );
849
850         // So check if all tables are not there
851         foreach ($tables as $tableName => $isFound) {
852                 // Check it out
853                 $tables[$tableName] = ifSqlTableExists($tableName);
854
855                 // Is it (hopefully not) there?
856                 if ($tables[$tableName] === FALSE) {
857                         // This does not exist
858                         $missingTables++;
859                 } // END - if
860         } // END - foreach
861
862         // Determine final status (simply compare both counts
863         $isValid = (count($tables) == $missingTables);
864
865         // Disconnect here, we don't need idle database connections laying around
866         sqlCloseLink(__FUNCTION__, __LINE__);
867
868         // If the status is true, disconnect the database
869         if ($isValid === FALSE) {
870                 // Still something bad happened (e.g. tables found)
871                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_DATABASE_IN_USE--}';
872                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'mysql_dbase');
873         } else {
874                 // Remember this tab in session
875                 installTabOkay($currentTab);
876         }
877
878         // Return status
879         return $isValid;
880 }
881
882 // Call-back function to check if first admin data is valid
883 function isInstallerPostFirstAdminValid ($currentTab) {
884         // Is all data valid?
885         if (!isPostRequestElementSet('admin_login')) {
886                 // Login not set
887                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_FIRST_ADMIN_LOGIN_EMPTY--}';
888                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'admin_login');
889                 return FALSE;
890         } elseif (strlen(postRequestElement('admin_login')) < 4) {
891                 // Login to short
892                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_FIRST_ADMIN_LOGIN_SHORT--}';
893                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'admin_login');
894                 return FALSE;
895         } elseif (!isPostRequestElementSet('admin_email')) {
896                 // Email address not set
897                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_FIRST_ADMIN_EMAIL_EMPTY--}';
898                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'admin_email');
899                 return FALSE;
900         } elseif (!isInstallerAdminEmailValid(postRequestElement('admin_email'))) {
901                 // Invalid email address
902                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_FIRST_ADMIN_EMAIL_INVALID--}';
903                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'admin_email');
904                 return FALSE;
905         } elseif ((!isPostRequestElementSet('admin_password1')) && (isPostRequestElementSet('admin_password2'))) {
906                 // Password 1 not set
907                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_FIRST_ADMIN_PASSWORD1_EMPTY--}';
908                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'admin_password1');
909                 return FALSE;
910         } elseif ((isPostRequestElementSet('admin_password1')) && (!isPostRequestElementSet('admin_password2'))) {
911                 // Password 2 not set
912                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_FIRST_ADMIN_PASSWORD2_EMPTY--}';
913                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'admin_password2');
914                 return FALSE;
915         } elseif (postRequestElement('admin_password1') != postRequestElement('admin_password2')) {
916                 // Passwords mismatch
917                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_FIRST_ADMIN_PASSWORDS_MISMATCH--}';
918                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'admin_password1', 'admin_password2');
919                 return FALSE;
920         } elseif (!isStrongPassword(postRequestElement('admin_password1'))) {
921                 // Weak passwords entered
922                 $GLOBALS['installer_post_error'][$currentTab] = '{--INSTALLER_POST_FIRST_ADMIN_PASSWORDS_WEAK--}';
923                 array_push($GLOBALS['installer_failed_fields'][$currentTab], 'admin_password1', 'admin_password2');
924                 return FALSE;
925         } // END - if
926
927         // All tests passed
928         return TRUE;
929 }
930
931 // Store given tab in session
932 function installTabOkay ($currentTab) {
933         // Is it set?
934         if (isSessionVariableSet('installer_okay')) {
935                 // Is this tab already found?
936                 if (strpos(getSession('installer_okay'), $currentTab) === FALSE) {
937                         // Then extend it
938                         setSession('installer_okay', getSession('installer_okay') . ';' . $currentTab);
939                 } // END - if
940         } else {
941                 // Initially set it
942                 setSession('installer_okay', $currentTab);
943         }
944 }
945
946 // Checks whether at least the required tabs are completed
947 function isInstallationDataCompleted () {
948         // Check both
949         $isCompleted = (
950                 (isSessionVariableSet('installer_okay')) &&
951                 (strpos(getSession('installer_okay'), 'base_data') !== FALSE) &&
952                 (strpos(getSession('installer_okay'), 'database_config') !== FALSE)
953         );
954
955         // Return it
956         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isCompleted=' . intval($isCompleted) . ',installer_okay=' . getSession('installer_okay'));
957         return $isCompleted;
958 }
959
960 // Call-back function to check if enable_backlink is Y/N
961 function isInstallerEnableBacklinkValid ($currentTab) {
962         // Check and return it
963         return in_array($currentTab, array('Y', 'N'));
964 }
965
966 // Call-back function to check if warn_no_pass is Y/N
967 function isInstallerWarnNoPassValid ($currentTab) {
968         // Check and return it
969         return in_array($currentTab, array('Y', 'N'));
970 }
971
972 // Call-back function to check if write_footer is Y/N
973 function isInstallerWriteFooterValid ($currentTab) {
974         // Check and return it
975         return in_array($currentTab, array('Y', 'N'));
976 }
977
978 // Call-back function to check if output_mode is Y/N
979 function isInstallerOutputModeValid ($currentTab) {
980         // Check and return it
981         return in_array($currentTab, array('render', 'direct'));
982 }
983
984 // Wrapper to import given installation SQL dump
985 function importInstallSqlDump ($dumpName) {
986         // Import the file
987         importSqlDump('install', $dumpName, 'install');
988 }
989
990 // Wrapper to check if tables.sql and menu-foo.sql are readable
991 function isInstallerSqlsReadable ($path) {
992         // Determine it
993         return ((isFileReadable($path . 'install/tables.sql')) && (isFileReadable($path . 'install/menu-' . getLanguage() . '.sql')));
994 }
995
996 // [EOF]
997 ?>