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