Project

General

Profile

1
<?php
2
/**
3
 *
4
 * @category        backend
5
 * @package         installation
6
 * @author          WebsiteBaker Project
7
 * @copyright       Website Baker Org. e.V.
8
 * @link            http://wwebsitebaker.org/
9
 * @license         http://www.gnu.org/licenses/gpl.html
10
 * @platform        WebsiteBaker 2.8.3
11
 * @requirements    PHP 5.3.6 and higher
12
 * @version         $Id: upgrade-script.php 2 2017-07-02 15:14:29Z Manuela $
13
 * @filesource      $HeadURL: svn://isteam.dynxs.de/wb/2.10.x/trunk/upgrade-script.php $
14
 * @lastmodified    $Date: 2017-07-02 17:14:29 +0200 (Sun, 02 Jul 2017) $
15
 *
16
 */
17
// Stop execution if PHP version is too old
18
// PHP less then 5.6.0 is prohibited ---
19
if (version_compare(PHP_VERSION, '5.6.0', '<')) {
20
    $sMsg = '<p style="color: #ff0000;">WebsiteBaker is not able to run with PHP-Version less then 5.6.0!!<br />'
21
          . 'Please change your PHP-Version to any kind from 5.6.0 and up!<br />'
22
          . 'If you have problems to solve that, ask your hosting provider for it.<br  />'
23
          . 'The very best solution is the use of PHP-7.0 and up</p>';
24
    die($sMsg);
25
}
26
/* ************************************************************************** */
27
function sanitizeConfigFile($sConfigFile)
28
{
29
    $sFileMarker = '*** auto generated config file for '.getNewVersionString();
30
// check if config is writeable
31
    if (!is_readable($sConfigFile)) {
32
        throw new RuntimeException('sorry, '.basename($sConfigFile).' is not readable or does not exists!');
33
    }
34
    $sCfgContent = file_get_contents($sConfigFile);
35
// check if config is created by WB
36
    if (!preg_match('/'.preg_quote($sFileMarker, '/').'/siU', $sCfgContent)) {
37
        if (!is_writeable($sConfigFile)) {
38
            $sMsg = 'The file ['.basename($sConfigFile).'] is not writeable and can not be corrected!'."\n"
39
                  . 'Please grant neccessary rights to the file and restart this program!';
40
            throw new RuntimeException($sMsg);
41
        }
42
        // clean from includes
43
        $sPattern = '/\n[^;]*(require|include).*framework\/initialize\.php.*$/siU';
44
        $sCfgContent = preg_replace($sPattern, "\n",$sCfgContent);
45
        // create temporary file
46
        $sTmpFilename = tempnam(__DIR__.'/temp', '~config');
47
        // fill it with old content
48
        file_put_contents($sTmpFilename, $sCfgContent);
49
        // include this file
50
        include $sTmpFilename;
51
        // it can be deleted now
52
        unlink($sTmpFilename);
53
        // collect and check available data
54
        $aValues = ['ADMIN_DIRECTORY' => ''];
55
        if (!defined('ADMIN_DIRECTORY')) {
56
            if (defined('ADMIN_URL')) {
57
                $aValues['ADMIN_DIRECTORY'] = trim(str_replace(str_replace('\\', '/', WB_URL), '', str_replace('\\', '/', ADMIN_URL)), '/');
58
            }
59
        } else { $aValues['ADMIN_DIRECTORY'] = ADMIN_DIRECTORY; }
60
        $aValues['WB_URL']       = defined('WB_URL')       ? WB_URL       : '';
61
        $aValues['DB_TYPE']      = defined('DB_TYPE')      ? DB_TYPE      : 'mysqli';
62
        $aValues['DB_HOST']      = defined('DB_HOST')      ? DB_HOST      : '';
63
        $aValues['DB_PORT']      = defined('DB_PORT')      ? DB_PORT      : '3306';
64
        $aValues['DB_NAME']      = defined('DB_NAME')      ? DB_NAME      : '';
65
        $aValues['DB_USERNAME']  = defined('DB_USERNAME')  ? DB_USERNAME  : '';
66
        $aValues['DB_PASSWORD']  = defined('DB_PASSWORD')  ? DB_PASSWORD  : '';
67
        $aValues['DB_CHARSET']   = ((defined('DB_CHARSET') && trim(DB_CHARSET) != '') ? DB_CHARSET : 'utf8');
68
        $aValues['TABLE_PREFIX'] = defined('TABLE_PREFIX') ? TABLE_PREFIX : 'wb_';
69
        // build the new config content
70
        $sConfigContent
71
            = '<?php'."\n"
72
            . '/*'."\n"
73
            . ' '.$sFileMarker."\n"
74
            . ' ****[WebsiteBaker]****'."\n"
75
            . ' *** created at '.date('Y-m-d h:i:s e')."\n"
76
            . ' */'."\n"
77
            . '// define(\'DEBUG\', false);'."\n"
78
            . 'define(\'DB_TYPE\',         \''.$aValues['DB_TYPE'].'\');'."\n"
79
            . 'define(\'DB_HOST\',         \''.$aValues['DB_HOST'].'\');'."\n"
80
            . 'define(\'DB_PORT\',         \''.$aValues['DB_PORT'].'\');'."\n"
81
            . 'define(\'DB_NAME\',         \''.$aValues['DB_NAME'].'\');'."\n"
82
            . 'define(\'DB_USERNAME\',     \''.$aValues['DB_USERNAME'].'\');'."\n"
83
            . 'define(\'DB_PASSWORD\',     \''.$aValues['DB_PASSWORD'].'\');'."\n"
84
            . 'define(\'DB_CHARSET\',      \''.$aValues['DB_CHARSET'].'\');'."\n"
85
            . 'define(\'TABLE_PREFIX\',    \''.$aValues['TABLE_PREFIX'].'\');'."\n"
86
            . "\n"
87
            . 'define(\'WB_URL\',          \''.$aValues['WB_URL'].'\'); '
88
            . '// no trailing slash or backslash!!'."\n"
89
            . 'define(\'ADMIN_DIRECTORY\', \''.$aValues['ADMIN_DIRECTORY'].'\'); '
90
            . '// no leading/trailing slash or backslash!! A simple directory name only!!'."\n"
91
            . "\n"
92
            . 'require_once __DIR__.\'/framework/initialize.php\';'."\n"
93
            . '// --- end of file ----------------------------------'."\n"
94
        ;
95
        if (false === file_put_contents($sConfigFile, $sConfigContent)) {
96
            $sMsg = 'Write file ['.basename($sConfigFile).'] failed!'."\n"
97
                  . 'Please create the file manualy. You ca find an example at '
98
                  . '<a href="http://wiki.websitebaker.org/" title="WB-wiki">WebsiteBaker Wiki</a>';
99
            throw new RuntimeException($sMsg);
100
        }
101
        $sMsg = 'Update file ['.basename($sConfigFile).'] successful done!';
102
        throw new RuntimeException($sMsg);
103
    }
104
}
105
/* ************************************************************************** */
106
function getOldVersionString()
107
{
108
    $sRetval = '';
109
    $sConfigFile = file_get_contents(__DIR__.'/config.php');
110
    $sPattern = '=(\ \*\*\*[^\*]*?WebsiteBaker.*? )(?:[0-9][^ \n]*?)$=ism';
111
    if (preg_match($sPattern, $sConfigFile, $aMatches)) {
112
        $sRetval = $aMatches[0];
113
    }
114
    return $sRetval;
115
}
116
/* ************************************************************************** */
117
function getNewVersionString()
118
{
119
    $sAdminDirectory = searchAdminDir();
120
    $sVersionFile = file_get_contents(__DIR__.'/'.$sAdminDirectory.'/interface/version.php');
121
    $sPattern = '=define\s*\(\'VERSION\'\,\s*\'([^\']*)\'=is';
122
    $sRetval = ((preg_match($sPattern, $sVersionFile, $aMatches)) ? $aMatches[1] : '???');
123
    return $sRetval;
124
}
125
/* ************************************************************************** */
126
function updateConfigPhP($sConfigFile, $sOldVersionString)
127
{
128
    $sNewVersion = getNewVersionString();
129
    $sql = 'SELECT `value` FROM `'.TABLE_PREFIX.'settings` '
130
         . 'WHERE `name`=\'wb_version\'';
131
    $sOldVersion = $GLOBALS['database']->get_one($sql);
132
    if ($sNewVersion != $sOldVersion) {
133
    // new upgrade detected
134
        $sVersionString = ' *** WebsiteBaker upgrade from '.$sOldVersion.' to '.$sNewVersion;
135
    } else {
136
    // modify old string if needed
137
        $sVersionString = ($sOldVersionString ?: ' *** WebsiteBaker '.$sNewVersion);
138
    }
139
    $sCfgContent = file_get_contents($sConfigFile);
140

    
141
    file_put_contents($sConfigFile, str_replace(' ****[WebsiteBaker]****', $sVersionString, $sCfgContent));
142
    $sVersionString = sprintf($sVersionString, $sNewVersion);
143
}
144
/* ************************************************************************** */
145
function searchAdminDir()
146
{
147
    $sBaseDir = __DIR__.'/*';
148
    $sAdminFolder = false;
149
    foreach (glob($sBaseDir, GLOB_MARK|GLOB_ONLYDIR) as $sFolder) {
150
        $sFolder = str_replace('\\', '/', $sFolder);
151
        if (
152
            file_exists($sFolder.'access/') &&
153
            file_exists($sFolder.'interface/') &&
154
            file_exists($sFolder.'groups/')
155
        ) {
156
            $sAdminFolder = trim(basename($sFolder), '/');
157
            break;
158
        }
159
    }
160
    if (!$sAdminFolder) {
161
        throw new RuntimeException('sorry, '.basename($sConfigFile).' is not readable or does not exists!');
162
    }
163
    return $sAdminFolder;
164
}
165

    
166
/* ************************************************************************** */
167
/* *** start script ********************************************************* */
168
/* ************************************************************************** */
169

    
170
$sOldVersionString = getOldVersionString();
171
// exception handling
172
try {
173
    sanitizeConfigFile(__DIR__.'/config.php');
174
} catch(Exception $e) {
175
    $sProtokol   = ((!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == 'off' ) ? 'http' : 'https') . '://';
176
    $sSriptname = trim(isset($_SERVER['SCRIPT_URI'])
177
                   ? $_SERVER['SCRIPT_URI'].'?'.$_SERVER['QUERY_STRING']
178
                   : (isset($_SERVER['REQUEST_URI'])
179
                     ? $_SERVER['REQUEST_URI']
180
                     : $_SERVER['SCRIPT_NAME']),'/');
181
    $sReloadLink = $sProtokol.$_SERVER['HTTP_HOST'].($_SERVER['SERVER_PORT'] == 80 ? '' : $_SERVER['SERVER_PORT'].':').'/'.$sSriptname;
182
    $aTmp = explode('?', $sReloadLink, 2);
183
    $sReloadLink = $aTmp[0].'?ts='.dechex(time());
184
    $sOutput
185
        = '<!DOCTYPE html><html lang="en-US"><head>'
186
        . '<meta name="viewport" content="width=device-width, initial-scale=1.0">'
187
        . '<meta charset="UTF-8"><meta name="robots" content="noindex,nofollow">'
188
        . '<meta http-equiv="expires" content="0">'
189
        . '<title>System Message</title></head>'
190
        . '<body><h1>WebsiteBaker - System Message</h1><hr>'
191
        . '<p>'.nl2br($e->getMessage(), false).'</p>'
192
        . '<form><button style="margin: 5px 50px;" type="submit" formmethod="get" formaction="'.$sReloadLink.'">'
193
        . 'Restart Programm<br>(or press F5)</button></form>'
194
        . '<hr></body></html>';
195
    echo $sOutput;
196
    flush();
197
    die;
198
}
199
/* ************************************************************************** */
200
// include the new config and initialize
201
if (!defined('WB_URL')) { require_once(__DIR__.'/config.php'); }
202

    
203
updateConfigPhP(__DIR__.'/config.php', $sOldVersionString);
204

    
205
if (!function_exists('make_dir'))  {require(__DIR__.'/framework/functions.php');}
206
if (!class_exists('admin', false)) {require(__DIR__.'/framework/class.admin.php');}
207
$admin = new admin('Addons', 'modules', false, false);
208

    
209
/* display a status message on the screen **************************************
210
 * @param string $message: the message to show
211
 * @param string $class:   kind of message as a css-class
212
 * @param string $element: witch HTML-tag use to cover the message
213
 * @return void
214
 */
215
    function status_msg($message, $class='check', $element='p')
216
    {
217
        // returns a status message
218
        $msg  = '<'.$element.' class="'.$class.'" style="padding: 0 0 2.00em 0.825em; ">';
219
    #    $msg .= '<h4>'.strtoupper(strtok($class, ' ')).'</h4>';
220
        $msg .= $message.'</'.$element.'>';
221
        echo '<div class="message">'.$msg.'</div>';
222
    }
223

    
224
    if (is_readable(WB_PATH.'/install/ModuleWhiteList')){
225
        $aModuleWhiteList = file(WB_PATH.'/install/ModuleWhiteList', FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
226
    } else {
227
        $aModuleWhiteList =
228
              array (
229
                    'captcha_control',
230
                    'ckeditor',
231
                    'code',
232
                    'droplets',
233
                    'form',
234
                    'jsadmin',
235
                    'menu_link',
236
                    'mod_multilingual',
237
                    'news',
238
                    'output_filter',
239
                    'show_menu2',
240
                    'wrapper',
241
                    'wysiwyg'
242
            );
243
    }
244

    
245
$aDefaultSettings = array (
246
    'app_name' => 'wb-1281',
247
    'confirmed_registration' => '0',
248
    'debug' => 'false',
249
    'default_charset' => 'utf-8',
250
    'default_date_format' => 'M d Y',
251
    'default_language' => 'en',
252
    'default_template' => 'DefaultTemplate',
253
    'default_theme' => 'DefaultTheme',
254
    'default_time_format' => 'g:i A',
255
    'default_timezone' => '',
256
    'er_level' => '',
257
    'frontend_login' => 'false',
258
    'frontend_signup' => 'false',
259
    'home_folders' => 'true',
260
    'homepage_redirection' => 'false',
261
    'intro_page' => 'false',
262
    'manage_sections' => 'true',
263
    'media_directory' => '/media',
264
    'mediasettings' => '',
265
    'multiple_menus' => 'true',
266
    'operating_system' => 'linux',
267
    'page_extension' => '.php',
268
    'page_icon_dir' => '/templates/*/title_images',
269
    'page_languages' => 'true',
270
    'page_level_limit' => '4',
271
    'page_spacer' => '-',
272
    'page_trash' => 'inline',
273
    'pages_directory' => '/pages',
274
    'redirect_timer' => '1000',
275
    'rename_files_on_upload' => 'ph.*?,cgi,pl,pm,exe,com,bat,pif,cmd,src,asp,aspx,js',
276
    'search' => 'public',
277
    'sec_anchor' => 'Sec',
278
    'sec_token_fingerprint' => 'true',
279
    'sec_token_netmask4' => '24',
280
    'sec_token_netmask6' => '64',
281
    'sec_token_life_time' => '1800',
282
    'section_blocks' => 'true',
283
    'server_email' => 'info@example.com',
284
    'smart_login' => 'true',
285
    'string_dir_mode' => '0755',
286
    'string_file_mode' => '0644',
287
    'system_locked' => '0',
288
    'warn_page_leave' => '1',
289
    'wb_revision' => '',
290
    'wb_sp' => '',
291
    'wb_version' => '',
292
    'wbmailer_default_sendername' => 'WB Mailer',
293
    'wbmailer_routine' => 'phpmail',
294
    'wbmailer_smtp_auth' => '',
295
    'wbmailer_smtp_host' => 'localhost',
296
    'wbmailer_smtp_password' => '',
297
    'wbmailer_smtp_port' => '25',
298
    'wbmailer_smtp_secure' => 'TLS',
299
    'wbmailer_smtp_username' => '',
300
    'website_description' => '',
301
    'website_footer' => '',
302
    'website_header' => '',
303
    'website_keywords' => '',
304
    'website_signature' => '',
305
    'website_title' => '',
306
    'wysiwyg_editor' => 'ckeditor',
307
    'wysiwyg_style' => 'font-family: Verdana => Arial => Helvetica => sans-serif; font-size: 12px;',
308
);
309

    
310
// database tables including in WB package
311
$table_list = array ('settings','groups','addons','pages','sections','search','users');
312

    
313
$OK               = ' <span class="ok">OK</span> ';
314
$FAIL             = ' <span class="error">FAILED</span> ';
315
$DEFAULT_THEME    = 'DefaultTheme';
316
$DEFAULT_TEMPLATE = (@DEFAULT_TEMPLATE?:'DefaultTemplate');
317
if (@DEFAULT_THEME != $DEFAULT_THEME) {
318
  db_update_key_value('settings', 'default_theme', $DEFAULT_THEME);
319
  exit();
320
}
321
$sScriptUrl = $_SERVER['SCRIPT_NAME'];
322
$sThemeUrl = WB_URL.'/templates/'.(is_readable(WB_URL.'/templates/'.$DEFAULT_THEME) ? $DEFAULT_THEME:'DefaultTheme');
323
$stepID = 0;
324
$dirRemove = array(
325
            '[INCLUDE]lightbox/',
326
            '[MODULES]SecureFormSwitcher/',
327
            '[MODULES]fckeditor/',
328
            '[INSTALL]sources/'
329
/*
330
            '[TEMPLATE]allcss/',
331
            '[TEMPLATE]blank/',
332
            '[TEMPLATE]round/',
333
            '[TEMPLATE]simple/',
334
*/
335
         );
336

    
337
$filesRemove = array(
338
            '[ROOT]SP5_UPGRADE_DE',
339
            '[ROOT]SP5_UPGRADE_EN',
340
            '[ROOT]SP6_UPGRADE_EN',
341
            '[ROOT]SP7_UPGRADE_EN',
342
            '[ROOT]README-FIX',
343
            '[ROOT]/var/logs/php_error.log',
344

    
345
            '[DOCU]SP7_UPGRADE_EN',
346
            '[DOCU]README-FIX',
347

    
348
            '[ACCOUNT]template.html',
349

    
350
            '[ADMIN]preferences/details.php',
351
            '[ADMIN]preferences/email.php',
352
            '[ADMIN]preferences/password.php',
353
            '[ADMIN]settings/setting.js',
354
            '[ADMIN]settings/array.php',
355

    
356
            '[FRAMEWORK]class.login.php',
357
            '[FRAMEWORK]SecureForm.mtab.php',
358
            '[FRAMEWORK]SecureForm.php',
359
            '[FRAMEWORK]class.wbmailer.php.new',
360

    
361
            '[INCLUDE]idna_convert\ReadMe.txt',
362
            '[INCLUDE]idna_convert\LICENCE',
363
            '[INCLUDE]idna_convert\example.php',
364

    
365
            '[INSTALL]install_struct.sql',
366
            '[INSTALL]install_data.sql',
367
/*  */
368
            '[MODULES]ckeditor/ckeditor/plugins/plugin.js',
369

    
370
            '[MODULES]captcha_control/uninstall.php',
371
            '[MODULES]jsadmin/uninstall.php',
372
            '[MODULES]menu_link/uninstall.php',
373
            '[MODULES]output_filter/uninstall.php',
374
            '[MODULES]output_filter/filters/canonical.php',
375
            '[MODULES]output_filter/filters/filterScript.php',
376
            '[MODULES]output_filter/filters/filterSysvarMedia.php',
377
            '[MODULES]show_menu2/uninstall.php',
378
            '[MODULES]wysiwyg/uninstall.php',
379

    
380
            '[MODULES]droplets/add_droplet.php',
381
            '[MODULES]droplets/backup_droplets.php',
382
            '[MODULES]droplets/delete_droplet.php',
383
            '[MODULES]droplets/modify_droplet.php',
384
            '[MODULES]droplets/save_droplet.php',
385
            '[MODULES]droplets/languages/DA.php',
386

    
387
            '[MODULES]form/save_field.php',
388

    
389
            '[TEMPLATE]wb_theme/uninstall.php',
390
            '[TEMPLATE]wb_theme/templates/access.htt',
391
            '[TEMPLATE]wb_theme/templates/addons.htt',
392
            '[TEMPLATE]wb_theme/templates/admintools.htt',
393
            '[TEMPLATE]wb_theme/templates/error.htt',
394
            '[TEMPLATE]wb_theme/templates/groups.htt',
395
            '[TEMPLATE]wb_theme/templates/groups_form.htt',
396
            '[TEMPLATE]wb_theme/templates/languages.htt',
397
            '[TEMPLATE]wb_theme/templates/languages_details.htt',
398
            '[TEMPLATE]wb_theme/templates/media.htt',
399
            '[TEMPLATE]wb_theme/templates/media_browse.htt',
400
            '[TEMPLATE]wb_theme/templates/media_rename.htt',
401
            '[TEMPLATE]wb_theme/templates/modules.htt',
402
            '[TEMPLATE]wb_theme/templates/modules_details.htt',
403
            '[TEMPLATE]wb_theme/templates/pages.htt',
404
            '[TEMPLATE]wb_theme/templates/pages_modify.htt',
405
            '[TEMPLATE]wb_theme/templates/pages_sections.htt',
406
            '[TEMPLATE]wb_theme/templates/pages_settings.htt',
407
            '[TEMPLATE]wb_theme/templates/preferences.htt',
408
            '[TEMPLATE]wb_theme/templates/setparameter.htt',
409
//            '[TEMPLATE]wb_theme/templates/settings.htt', SP7 replace this
410
            '[TEMPLATE]wb_theme/templates/start.htt',
411
            '[TEMPLATE]wb_theme/templates/success.htt',
412
            '[TEMPLATE]wb_theme/templates/templates.htt',
413
            '[TEMPLATE]wb_theme/templates/templates_details.htt',
414
            '[TEMPLATE]wb_theme/templates/users.htt',
415
            '[TEMPLATE]wb_theme/templates/users_form.htt',
416
            '[ACCOUNT]preferences_form.php.old',
417
            '[ADMIN]themes/templates/admintools.htt.old',
418
            '[INCLUDE]pclzip/Constants.php.old',
419
            '[INCLUDE]pclzip/pclzip.lib.php.old',
420
            '[LANGUAGES]NL.zip',
421
            '[MODULES]droplets/data/archiv/Droplet_ShortUrl_20170111_155201.zip',
422
            '[MODULES]droplets/themes/default/css/backend.css.org',
423
            '[MODULES]form/backend.css.new',
424
            '[MODULES]form/frontend.css.new',
425
            '[MODULES]show_menu2/README.de.txt',
426
            '[MODULES]show_menu2/README.en.txt',
427
            '[MODULES]wrapper/languages/DE.info',
428
            '[TEMPLATE]DefaultTemplate/PLACEHOLDER',
429
            '[TEMPLATE]DefaultTheme/PLACEHOLDER',
430
         );
431

    
432
// analyze/check database tables
433
function mysqlCheckTables( $dbName )
434
{
435
    global $database, $table_list,$FAIL;
436
    $table_prefix = TABLE_PREFIX;
437

    
438
    $sql = 'SHOW TABLES FROM `'.$dbName.'`';
439
    $result = $database->query($sql);
440

    
441
    $data = array();
442
    $retVal = array();
443
    $x = 0;
444

    
445
//    while( ( $row = @mysqli_fetch_array( $result, MYSQLI_NUM ) ) == true )
446
    while (( $row = $result->fetchRow(MYSQLI_NUM)) == true)
447
    {
448
                $sql = "CHECK TABLE `" . $row[0].'`';
449
                $analyze = $database->query($sql);
450
                if( $analyze ) {
451
                    $rowFetch = $analyze->fetchRow(MYSQLI_ASSOC);
452
                    $data[$x]['Op'] = $rowFetch["Op"];
453
                    $data[$x]['Msg_type'] = $rowFetch["Msg_type"];
454
                    $msgColor = '<span class="error">';
455
                    $data[$x]['Table'] = $row[0];
456
                    $retVal[] = $row[0];
457
                   // print  " ";
458
                    $msgColor = ($rowFetch["Msg_text"] == 'OK') ? '<span class="ok">' : '<span class="error">';
459
                    $data[$x]['Msg_text'] = $msgColor.$rowFetch["Msg_text"].'</span>';
460
                   // print  "";
461
                    $x++;
462
                 } else {
463
                    echo '<br /><b>'.$sql.'</b>'.$FAIL.'<br />';
464
                }
465
   }
466
    return $retVal; //$data;
467
}
468

    
469
// check existings tables for upgrade or install
470
function check_wb_tables()
471
{
472
    global $database,$table_list;
473

    
474
 // if prefix inludes '_' or '%'
475
 $search_for = addcslashes ( TABLE_PREFIX, '%_' );
476
 $get_result = $database->query( 'SHOW TABLES LIKE "'.$search_for.'%"');
477

    
478
        // $get_result = $database->query( "SHOW TABLES FROM ".DB_NAME);
479
        $all_tables = array();
480
        if($get_result->numRows() > 0)
481
        {
482
            while ($data = $get_result->fetchRow())
483
            {
484
                $tmp = str_replace(TABLE_PREFIX, '', $data[0]);
485
                if(in_array($tmp,$table_list))
486
                {
487
                    $all_tables[] = $tmp;
488
                }
489
            }
490
        }
491
     return $all_tables;
492
}
493

    
494
// check existing tables
495
$all_tables = check_wb_tables();
496

    
497
?><!DOCTYPE HTML>
498
<html lang="en">
499
<head>
500
<meta charset="utf-8" />
501
<title>Upgrade script</title>
502
<style type="text/css">
503
html { overflow: -moz-scrollbars-vertical; /* Force firefox to always show room for a vertical scrollbar */ }
504

    
505
body {
506
    margin:0;
507
    padding:0;
508
    border:0;
509
    background: #EBF7FC;
510
    color:#000;
511
    font-family: 'Trebuchet MS', Verdana, Arial, Helvetica, Sans-Serif;
512
    font-size: small;
513
    height:101%;
514
}
515

    
516
#container {
517
    width:85%;
518
    background: #A8BCCB url("<?php echo $sThemeUrl;?>/images/background.png") repeat-x;
519
    border:1px solid #000;
520
    color:#000;
521
    margin:2em auto;
522
    padding:0 15px;
523
    min-height: 500px;
524
    text-align:left;
525
}
526

    
527
p { line-height:1.5em; }
528

    
529
form {
530
    display: inline-block;
531
    line-height: 20px;
532
    vertical-align: baseline;
533
}
534
input[type="submit"].restart {
535
    background-color: #FFDBDB;
536
    font-weight: bold;
537
}
538

    
539
h1,h2,h3,h4,h5,h6 {
540
    font-family: Verdana, Arial, Helvetica, sans-serif;
541
    color: #369;
542
    margin-top: 1.0em;
543
    margin-bottom: 0.1em;
544
}
545

    
546
h1 { font-size:150%; }
547
h2 { font-size: 130%; border-bottom: 1px #CCC solid; }
548
h3 { font-size: 120%; }
549

    
550
.ok, .error { font-weight:bold; }
551
.ok { color:green; }
552
.error { color: red; }
553
.check { color:#555; }
554
.content { margin-left: 1.925em; }
555
.warning {
556
    width: 98%;
557
    background:#FCDADA;
558
    padding:0.2em;
559
    margin-top:0.5em;
560
    border: 1px solid black;
561
}
562
.error p { color: #369; }
563

    
564
.info {
565
    width: 98%;
566
    background:#C3E3C3;
567
    padding:0.2em;
568
    margin-top:0.5em;
569
    border: 1px solid black;
570
}
571
.message { padding: 0; }
572

    
573
</style>
574
</head>
575
<body>
576
<div id="container">
577
<img src="<?php echo $sThemeUrl;?>/images/logo.png" alt="WebsiteBaker Project" />
578
<h1>WebsiteBaker Upgrade</h1>
579
<?php
580
    if( version_compare( WB_VERSION, '2.7', '<' )) {
581
        status_msg('It is not possible to upgrade from WebsiteBaker Versions before 2.7.<br />For upgrading to version '.VERSION.' you must upgrade first to v.2.8 at least!!!', 'warning', 'div');
582
        echo '<br />';
583
        echo "
584
        </body>
585
        </html>
586
        ";
587
        exit();
588
    }
589

    
590
$oldVersionOutput  = trim(''.WB_VERSION.'+'.( defined('WB_SP') ? WB_SP : ''), '+').' (r'.WB_REVISION.')';
591
$newVersionOutput  = trim(''.VERSION.'+'.( defined('SP') ? SP : ''), '+').' (r'.REVISION.')';
592
$oldVersion  = trim(''.WB_VERSION.'+'.WB_REVISION.'+'.( defined('WB_SP') ? WB_SP : ''), '+');
593
$newVersion  = trim(''.VERSION.'+'.REVISION.'+'.( defined('SP') ? SP : ''), '+');
594
if ( WB_VERSION != '2.8.4'){
595
    if (version_compare($oldVersion, $newVersion, '>') === true) {
596
        status_msg('It is not possible to upgrade from WebsiteBaker Versions '.WB_VERSION.'!<br />For upgrading to version '.$newVersionOutput.' you have to upgrade first to v.2.8.3 at least!!!', 'warning', 'div');
597
        echo '<br />';
598
        echo "
599
        </body>
600
        </html>
601
        ";
602
        exit();
603
    }
604
}
605
if($admin->get_user_id()!=1){
606
  status_msg('<br /><h3>WebsiteBaker upgrading is not possible!<br />Before upgrading '
607
            .'to Revision '.REVISION.' you have to login as System-Administrator!</h3>',
608
            'warning', 'div');
609
  echo '<br /><br />';
610
// delete remember key of current user from database
611
  //if (isset($_SESSION['USER_ID']) && isset($database)) {
612
  //     $table = TABLE_PREFIX . 'users';
613
  //     $sql = "UPDATE `$table` SET `remember_key` = '' WHERE `user_id` = '" . (int) $_SESSION['USER_ID'] . "'";
614
  //     $database->doQuery($sql);
615
  //}
616
// delete remember key cookie if set
617
  if (isset($_COOKIE['REMEMBER_KEY']) && !headers_sent() ) {
618
    setcookie('REMEMBER_KEY', '', time() - 3600, '/');
619
  }
620
  // delete most critical session variables manually
621
  $_SESSION['USER_ID'] = null;
622
  $_SESSION['GROUP_ID'] = null;
623
  $_SESSION['GROUPS_ID'] = null;
624
  $_SESSION['USERNAME'] = null;
625
  $_SESSION['PAGE_PERMISSIONS'] = null;
626
  $_SESSION['SYSTEM_PERMISSIONS'] = null;
627
  // overwrite session array
628
  $_SESSION = array();
629
  // delete session cookie if set
630
  if (isset($_COOKIE[session_name()]) && !headers_sent()) {
631
    setcookie(session_name(), '', time() - 42000, '/');
632
  }
633
  // delete the session itself
634
  session_destroy();
635
  status_msg('<br /><h3>You have to login as System-Adminstrator start '
636
            .'upgrade-script.php again!</h3>',
637
             'info', 'div');
638
  echo '<br /><br />';
639
  if(defined('ADMIN_URL')) {
640
    echo '<form action="'.ADMIN_URL.'/index.php" method="post">'
641
        .'&nbsp;<input name="backend_send" type="submit" value="Kick me to the Login" />'
642
        .'</form>';
643
  }
644
  echo '<br /><br /></div>'
645
      .'</div>'
646
      .'</div>'
647
      .'</body>'
648
      .'</html>';
649
  exit();
650
}
651

    
652
?>
653
<p>This script upgrades an existing WebsiteBaker <strong> <?php echo $oldVersionOutput; ?></strong> installation to the <strong> <?php echo $newVersionOutput ?> </strong>.<br />The upgrade script alters the existing WB database to reflect the changes introduced with WB 2.8.x</p>
654

    
655
<?php
656
/**
657
 * Check if disclaimer was accepted
658
 */
659
if (!(isset($_POST['backup_confirmed']) && $_POST['backup_confirmed'] == 'confirmed')) { ?>
660
<h2>Step 1: Backup your files</h2>
661
<p>It is highly recommended to <strong>create a manual backup</strong> of the entire <strong>/pages folder</strong> and the <strong>MySQL database</strong> before proceeding.<br /><strong class="error">Note: </strong>The upgrade script alters some settings of your existing database!!! You need to confirm the disclaimer before proceeding.</p>
662

    
663
<form name="send" action="<?php echo $sScriptUrl;?>" method="post">
664
    <textarea cols="80" rows="5">DISCLAIMER: The WebsiteBaker upgrade script is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. One needs to confirm that a manual backup of the /pages folder (including all files and subfolders contained in it) and backup of the entire WebsiteBaker MySQL database was created before you can proceed.</textarea>
665
    <br /><br /><input name="backup_confirmed" type="checkbox" value="confirmed" />&nbsp;I confirm that a manual backup of the /pages folder and the MySQL database was created.
666
    <br /><br /><input name="send" type="submit" value="Start upgrade script" />
667
    </form>
668
    <br />
669
<?php
670
    status_msg('<h4>You need to confirm that you have created a manual backup of the /pages directory and the MySQL database before you can proceed.</h4>', 'warning', 'div');
671
    echo '<br />';
672
    echo "</div>
673
    </body>
674
    </html>
675
    ";
676
    exit();
677
}
678

    
679
// function to add a var/value-pair into settings-table
680
function db_add_key_value($key, $value) {
681
    global $database, $OK, $FAIL;
682
    $table = TABLE_PREFIX.'settings';
683
    $query = $database->query("SELECT value FROM $table WHERE name = '$key' ");
684
    if($query->numRows() > 0) {
685
        echo "$key: already exists. $OK.<br />";
686
        return true;
687
    } else {
688
        $database->query("INSERT INTO $table (name,value) VALUES ('$key', '$value')");
689
        echo ($database->is_error() ? $database->get_error().'<br />' : '');
690
        $query = $database->query("SELECT value FROM $table WHERE name = '$key' ");
691
        if($query->numRows() > 0) {
692
            echo "$key: $OK.<br />";
693
            return true;
694
        } else {
695
            echo "$key: $FAIL!<br />";
696
            return false;
697
        }
698
    }
699
}
700

    
701
// function to add a new field into a table
702
function db_add_field($table, $field, $desc) {
703
    global $database, $OK, $FAIL;
704
    $table = TABLE_PREFIX.$table;
705
    $query = $database->query("DESCRIBE $table '$field'");
706
    if($query->numRows() == 0) { // add field
707
        $query = $database->query("ALTER TABLE $table ADD $field $desc");
708
        echo ($database->is_error() ? $database->get_error().'<br />' : '');
709
        $query = $database->query("DESCRIBE $table '$field'");
710
        echo ($database->is_error() ? $database->get_error().'<br />' : '');
711
        if($query->numRows() > 0) {
712
            echo "'$field' added. $OK.<br />";
713
        } else {
714
            echo "adding '$field' $FAIL!<br />";
715
        }
716
    } else {
717
        echo "'$field' already exists. $OK.<br />";
718
    }
719
}
720
/**
721
 *
722
 * @param object $oDb  current database object
723
 * @param string $sTablePrefix the valid TABLE_PREFIX
724
 * @return an error message or emty string on ok
725
 */
726
    function MigrateSettingsTable($oDb, $sTablePrefix, $aDefaults)
727
    {
728
        $sRetval = '';
729
        $aSettings = [];
730
        $aOldSettings = [];
731
        $sql = 'SELECT * FROM `'.$sTablePrefix.'settings`';
732
        if (($oSettings = $oDb->query($sql))) {
733
            // backup all entries and remove duplicate entries
734
            while (($aEntry = $oSettings->fetchArray(MYSQLI_ASSOC))) {
735
                $aOldSettings[$aEntry ['name']] = $aEntry ['value'];
736
            }
737
            $aSettings = array_merge($aDefaults, $aOldSettings);
738
            // drop the old table
739
            $sql = 'DROP TABLE IF EXISTS `'.$sTablePrefix.'settings`';
740
            if (!($oDb->query($sql))) { $sRetval = 'unable to delete old table `settings`'; goto end;}
741
            // recreate the table with correctet structure
742
            $sql = 'CREATE TABLE IF NOT EXISTS `'.$sTablePrefix.'settings` ('
743
                 .     '`name` VARCHAR(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT \'\', '
744
                 .     '`value` text COLLATE utf8_unicode_ci NOT NULL, '
745
                 .     'PRIMARY KEY (`name`)'
746
                 . ')ENGINE=MyIsam DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci';
747
            if (!($oDb->query($sql))) { $sRetval = 'unable to recreate table `settings`'; goto end; }
748
            // insert backed up entries into the new table
749
            foreach ($aSettings as $sName => $sValue) {
750
                $sql = 'INSERT INTO  `'.$sTablePrefix.'settings`'
751
                     . 'SET `name`=\''.$oDb->escapeString($sName).'\', '
752
                     .     '`value`=\''.$oDb->escapeString($sValue).'\'';
753
                if (!($oDb->query($sql))) { $sRetval = 'unable to insert values into new table `settings`'; goto end;}
754
                @define($sName, $sValue);
755
            }
756
        } else {
757
            $sRetval = 'unable to read old table `settings`';
758
        }
759
end:
760
        return $sRetval;
761
    }
762

    
763
// check again all tables, to get a new array
764
 if(sizeof($all_tables) < sizeof($table_list)) { $all_tables = check_wb_tables(); }
765
/**********************************************************
766
 *  - check tables comin with WebsiteBaker
767
 */
768
    $check_text = 'total ';
769
    // $check_tables = mysqlCheckTables( DB_NAME ) ;
770
    if(sizeof($all_tables) == sizeof($table_list))
771
    {
772
        echo ('<h2>Step '.(++$stepID).' Your database '.DB_NAME.' has '.sizeof($all_tables).' '.$check_text.' tables from '.sizeof($table_list).' included in package '.$OK.'</h2>');
773
    }
774
    else
775
    {
776
        status_msg('can\'t run Upgrade, missing tables', 'warning', 'div');
777
        echo '<h4>Missing required tables. You can install them in backend->addons->modules->advanced. Then again run upgrade-script.php</h4>';
778
        $result = array_diff ( $table_list, $all_tables );
779
        echo '<h4 class="warning"><br />';
780
        while ( list ( $key, $val ) = each ( $result ) )
781
        {
782
            echo TABLE_PREFIX.$val.' '.$FAIL.'<br>';
783
        }
784
        echo '<br /></h4>';
785
        echo '<br /><form action="'. $sScriptUrl .'">';
786
        echo '<input type="submit" value="kick me back" style="float:left;" />';
787
        echo '</form>';
788
        if(defined('ADMIN_URL'))
789
        {
790
            echo '<form action="'.ADMIN_URL.'" target="_self">';
791
            echo '&nbsp;<input type="submit" value="kick me to the Backend" />';
792
            echo '</form>';
793
        }
794
        echo "<br /><br /></div>
795
        </body>
796
        </html>
797
        ";
798
        exit();
799
    }
800
echo '<h2>Step '.(++$stepID).' : clear Translate cache if exists</h2>';
801
//**********************************************************
802
if (is_writable(WB_PATH.'/temp/cache')) {
803
    Translate::getInstance()->clearCache();
804
}
805

    
806
if (defined('DEBUG') && DEBUG){
807
    echo '<h2>Step '.(++$stepID).' : Adding/Updating settings table</h2>';
808
    echo "<br />Set DEBUG Modus to false in settings table<br />";
809
    db_update_key_value('settings', 'debug', 'false');
810
    $msg = '<p> The upgrade-script has be run properly, therefore the property Debug was set to the value false.</p><p>Please restart the upgrade-script!</p>';
811
    status_msg($msg, 'error warning', 'div');
812
    echo '<p style="font-size:120%;"><strong>WARNING: The upgrade script failed ...</strong></p>';
813
    echo '<form action="'.$sScriptUrl.'">';
814
    echo '&nbsp;<input name="send" type="submit" value="Restart upgrade script" />';
815
    echo '</form>';
816
    echo '<br /><br /></div></body></html>';
817
    exit;
818

    
819
}
820

    
821
/**********************************************************/
822

    
823
echo '<h2>Step '.(++$stepID).' : Adding/Updating database tables</h2>';
824
/**********************************************************
825
 *  - Upgrade Core Tables
826
echo "<br />Upgrade Core Tables <br />"; $mysqli->error_list
827
$sql = 'ALTER TABLE `'.TABLE_PREFIX.'addons` ADD UNIQUE `ident` ( `directory` )';
828
 */
829
// try to upgrade table if not exists
830
$sInstallStruct = WB_PATH.'/install/install-struct.sql';
831
if (is_readable($sInstallStruct))
832
{
833
    if (!$database->SqlImport($sInstallStruct, TABLE_PREFIX, true )){
834
        echo '<div class="content">';
835
        echo $database->get_error(). $FAIL.'(Index already exists)<br />';
836
        echo '</div>';
837
    } else {
838
        echo '<div class="content">';
839
        echo 'Upgrade Core Tables '. $OK.'<br />';
840
        echo '</div>';
841
        echo '<h2>Step '.(++$stepID).' Clear default title value in sections table</h2>';
842
        echo '<div class="content">';
843
        $sDescription = 'UPDATE `'.TABLE_PREFIX.'sections` SET `title` = REPLACE(`title`,\'Section-ID 0\',\'\') WHERE `title` LIKE \'%Section-ID%\'';
844
        if (!$database->query($sDescription)){
845
          echo 'Upgrading sections Table (empty title field) '. $FAIL.'<br />';
846
        } else {
847
          echo 'Upgrade sections Table '. $OK.'<br />';
848
        }
849
        echo '</div>';
850
    }
851
} else {
852

    
853
    if (!is_readable(WB_PATH.'/install')) {
854
    $msg = '<p>\'Missing or not readable install folder\' '.$FAIL.'</p>';
855
    } else {
856
    $msg = '<p>\'Missing or not readable file [install-struct.sql]\'</p> '.$FAIL.'';
857
    }
858
/*
859
            $sWbPath = str_replace('\\', '/', WB_PATH );
860
            array_walk($aMsg, function(&$sMsg) use ($sWbPath) { $sMsg = str_replace($sWbPath, '', $sMsg); });
861
            $msg = implode('<br />', $aMsg).'<br />';
862
*/
863
    $msg = $msg.'<p>Check if the install folder exist.<br />Please upload install folder
864
            using FTP and restart upgrade-script!</p>';
865
    status_msg($msg, 'error warning', 'div');
866
    echo '<p style="font-size:120%;">>WARNING: The upgrade script failed ...</p>';
867
    echo '<form action="'.$sScriptUrl.'">';
868
    echo '&nbsp;<input name="send" type="submit" value="Restart upgrade script" />';
869
    echo '</form>';
870
    echo '<br /><br /></div></body></html>';
871
    exit;
872
}
873

    
874
// --- modify table `settings` -----------------------------------------------------------
875
    echo '<h2>Step '.(++$stepID).' : Modify PRIMARY KEY in settings table and add missing entries</h2>';
876
    echo '<div class="content">';
877
    $msg = MigrateSettingsTable($database, TABLE_PREFIX, $aDefaultSettings);
878
    echo ($msg!=''?$msg.' '.$FAIL:'Modify settings table '.$OK).'<br />';
879
    echo '</div>';
880

    
881
    echo '<h2>Step '.(++$stepID).' : Updating default_theme/default_template in settings table</h2>';
882
/**********************************************************
883
 *  - Adding field default_theme to settings table
884
 */
885
    echo '<div class="content">';
886
    echo "Adding default_theme to settings table<br />";
887
    db_update_key_value('settings', 'default_theme', $DEFAULT_THEME);
888
    echo "Adding default_template to settings table<br />";
889
    db_update_key_value('settings', 'default_template', $DEFAULT_TEMPLATE);
890
    echo '</div>';
891

    
892
#echo '<h2>Step '.(++$stepID).' : checking database entries</h2>';
893
    $check_tables = mysqlCheckTables( DB_NAME ) ;
894

    
895
/**********************************************************
896
 *  - install droplets
897
echo '<h2>Step '.(++$stepID).' : checking table droplets</h2>';
898
    echo '<div class="content">';
899
    $drops = (!in_array ( TABLE_PREFIX."mod_droplets", $check_tables)) ? "Install droplets" : "Upgrade droplets";
900
    echo '<b>'.$drops.'</b><br />';
901
     $file_name = (!in_array ( TABLE_PREFIX."mod_droplets", $check_tables) ? "install.php" : "upgrade.php");
902
     require_once (WB_PATH."/modules/droplets/".$file_name);
903
    echo '</div>';
904
 */
905

    
906
/**********************************************************
907
 *  - Adding field sec_anchor to settings table
908
 */
909
    echo '<h2>Step '.(++$stepID).' : Adding/Updating settings table</h2>';
910
    echo '<div class="content">';
911
    echo "<br />Adding string_dir_mode and string_file_mode to settings table<br />";
912
    $cfg = array(
913
        'confirmed_registration' => (defined('CONFIRMED_REGISTRATION')?CONFIRMED_REGISTRATION:'0'),
914
        'groups_updated' => (defined('GROUPS_UPDATED')?GROUPS_UPDATED:''),
915
        'page_icon_dir' => (defined('PAGE_ICON_DIR')?PAGE_ICON_DIR:'/templates/*/title_images'),
916
        'system_locked' => (defined('SYSTEM_LOCKED')?SYSTEM_LOCKED:'0'),
917
        'string_dir_mode' => (defined('STRING_DIR_MODE')?STRING_DIR_MODE:'0755'),
918
        'string_file_mode' => (defined('STRING_FILE_MODE')?STRING_FILE_MODE:'0644')
919
    );
920
    foreach($cfg as $key=>$value) {
921
        db_add_key_value($key, $value);
922
    }
923

    
924
/**********************************************************
925
 *  - Adding field sec_anchor to settings table
926
 */
927
    echo '<h2>Step '.(++$stepID).' : Adding/Updating settings table</h2>';
928
    echo '<div class="content">';
929
    echo "<br />Adding sec_anchor and website_signature to settings table<br />";
930
    $cfg = array(
931
        'sec_anchor' => (defined('SEC_ANCHOR')?SEC_ANCHOR:'wb_'),
932
        'website_signature' => (defined('WEBSITE_SIGNATURE')?WEBSITE_SIGNATURE:'')
933
    );
934
    foreach($cfg as $key=>$value) {
935
        db_add_key_value($key, $value);
936
    }
937

    
938
/**********************************************************
939
 *  - Adding redirect timer to settings table
940
 */
941
echo "<br />Adding redirect timer to settings table<br />";
942
$cfg = array(
943
    'redirect_timer' => (defined('REDIRECT_TIMER')?REDIRECT_TIMER:'1500')
944
);
945
foreach($cfg as $key=>$value) {
946
    db_add_key_value($key, $value);
947
}
948

    
949
/**********************************************************
950
 *  - Adding rename_files_on_upload to settings table
951
 */
952
echo "<br />Updating rename_files_on_upload to settings table<br />";
953
$cfg = array(
954
    'rename_files_on_upload' => (defined(RENAME_FILES_ON_UPLOAD)?RENAME_FILES_ON_UPLOAD:'ph.*?,cgi,pl,pm,exe,com,bat,pif,cmd,src,asp,aspx,js')
955
);
956
db_add_key_value( 'rename_files_on_upload', $cfg['rename_files_on_upload']);
957

    
958
/**********************************************************
959
 *  - Adding mediasettings to settings table
960
 */
961
echo "<br />Adding mediasettings and debug to settings table<br />";
962

    
963
$cfg = array(
964
    'debug' => (defined('DEBUG')?DEBUG:'false'),
965
    'mediasettings' => (defined('MEDIASETTINGS') ?MEDIASETTINGS:''),
966
);
967

    
968
foreach($cfg as $key=>$value) {
969
    db_add_key_value($key, $value);
970
}
971

    
972
/**********************************************************
973
 *  - Set wysiwyg_editor to settings table
974
 */
975
echo "<br />Set wysiwyg_editor to ckeditor<br />";
976
    db_update_key_value('settings', 'wysiwyg_editor', 'ckeditor');
977

    
978
/**********************************************************
979
 *  - Adding fingerprint_with_ip_octets to settings table
980
 */
981
echo "<br />Adding fingerprint_with_ip_octets to settings table<br />";
982
$cfg = array(
983
    'sec_token_fingerprint' => (defined('SEC_TOKEN_FINGERPRINT') ?SEC_TOKEN_FINGERPRINT:'true'),
984
    'sec_token_netmask4'    => (defined('SEC_TOKEN_NETMASK4') ?SEC_TOKEN_NETMASK4:'24'),
985
    'sec_token_netmask6'    => (defined('SEC_TOKEN_NETMASK6') ?SEC_TOKEN_NETMASK6:'64'),
986
    'sec_token_life_time'   => (defined('SEC_TOKEN_LIFE_TIME') ?SEC_TOKEN_LIFE_TIME:'180'),
987
    'wbmailer_smtp_port'    => (defined('WBMAILER_SMTP_PORT') ?WBMAILER_SMTP_PORT:'25'),
988
    'wbmailer_smtp_secure'  => (defined('WBMAILER_SMTP_SECURE') ?WBMAILER_SMTP_SECURE:'TLS')
989
);
990
foreach($cfg as $key=>$value) {
991
    db_add_key_value($key, $value);
992
}
993

    
994
/**********************************************************
995
 *  - Add field "redirect_type" to table "mod_menu_link"
996
 */
997
echo "<br />Adding field redirect_type to mod_menu_link table<br />";
998
db_add_field('mod_menu_link', 'redirect_type', "INT NOT NULL DEFAULT '301' AFTER `target_page_id`");
999
echo '</div>';
1000

    
1001
/**********************************************************
1002
 *  - Update search no results database filed to create
1003
 *  valid XHTML if search is empty
1004
 */
1005
if (version_compare(WB_VERSION, '2.8', '<'))
1006
{
1007
    echo "<br />Updating database field `no_results` of search table: ";
1008
    $search_no_results = addslashes('<tr><td><p>[TEXT_NO_RESULTS]</p></td></tr>');
1009
    $sql  = 'UPDATE `'.TABLE_PREFIX.'search` ';
1010
    $sql .= 'SET `value`=\''.$search_no_results.'\' ';
1011
    $sql .= 'WHERE `name`=\'no_results\'';
1012
    echo ($database->query($sql)) ? ' $OK<br />' : ' $FAIL<br />';
1013
}
1014
/* *****************************************************************************
1015
 * - check for deprecated / never needed files
1016
 */
1017
    if(sizeof($filesRemove)) {
1018
        echo '<h2>Step '.(++$stepID).': Remove deprecated and old files</h2>';
1019
    }
1020
    $searches = array(
1021
        '[ROOT]',
1022
        '[ACCOUNT]',
1023
        '[ADMIN]',
1024
        '[INCLUDE]',
1025
        '[INSTALL]',
1026
        '[FRAMEWORK]',
1027
        '[MEDIA]',
1028
        '[MODULES]',
1029
        '[PAGES]',
1030
        '[TEMP]',
1031
        '[TEMPLATE]',
1032
        '[DOCU]'
1033
    );
1034
    $replacements = array(
1035
        '/',
1036
        '/account/',
1037
        '/'.substr(ADMIN_PATH, strlen(WB_PATH)+1).'/',
1038
        '/include/',
1039
        '/install/',
1040
        '/framework/',
1041
        MEDIA_DIRECTORY.'/',
1042
        '/modules/',
1043
        PAGES_DIRECTORY.'/',
1044
        '/temp/',
1045
        '/templates/',
1046
        '/DOCU/'
1047
    );
1048

    
1049
        $aMsg = array();
1050
        array_walk(
1051
            $filesRemove,
1052
            function (&$sFile) use($searches, $replacements) {
1053
                $sFile = str_replace( '\\', '/', WB_PATH.str_replace($searches, $replacements, $sFile) );
1054
            }
1055
        );
1056
       foreach ( $filesRemove as $sFileToDelete ) {
1057
            if (false !== ($aExistingFiles = glob(dirname($sFileToDelete).'/*', GLOB_MARK)) ) {
1058
                if ( in_array($sFileToDelete, $aExistingFiles) ) {
1059
                    if ( is_writable($sFileToDelete) && unlink($sFileToDelete) ) {
1060
                        print '<strong>Remove  '.$sFileToDelete.'</strong>'." $OK<br />";
1061
                    } else {
1062
                        $aMsg[] = $sFileToDelete;
1063
                    }
1064
                }
1065
            }
1066
        }
1067
        unset($aExistingFiles);
1068
        if( sizeof($aMsg) )
1069
        {
1070
            $sWbPath = str_replace('\\', '/', WB_PATH );
1071
            array_walk($aMsg, function(&$sMsg) use ($sWbPath) { $sMsg = str_replace($sWbPath, '', $sMsg); });
1072
            $msg = implode('<br />', $aMsg).'<br />';
1073
            $msg = '<br /><br />Following files are deprecated, outdated or a security risk and
1074
                    can not be removed automatically.<br /><br />Please delete them
1075
                    using FTP and restart upgrade-script!<br /><br />'.$msg.'<br />';
1076
            status_msg($msg, 'error warning', 'div');
1077
            echo '<p style="font-size:120%;"><strong>WARNING: The upgrade script failed ...</strong></p>';
1078
            echo '<form action="'.$sScriptUrl.'">';
1079
            echo '&nbsp;<input name="send" type="submit" value="Restart upgrade script" />';
1080
            echo '</form>';
1081
            echo '<br /><br /></div></body></html>';
1082
            exit;
1083
        }
1084

    
1085

    
1086
/**********************************************************
1087
 * - check for deprecated / never needed folder
1088
 */
1089
    if(sizeof($dirRemove)) {
1090
        echo '<h2>Step  '.(++$stepID).': Remove deprecated and old folders</h2>';
1091
        $searches = array(
1092
            '[ADMIN]',
1093
            '[INCLUDE]',
1094
            '[MEDIA]',
1095
            '[MODULES]',
1096
            '[PAGES]',
1097
            '[TEMPLATE]',
1098
            '[INSTALL]'
1099
        );
1100
        $replacements = array(
1101
            '/'.substr(ADMIN_PATH, strlen(WB_PATH)+1).'/',
1102
            '/include/',
1103
            MEDIA_DIRECTORY.'/',
1104
            '/modules/',
1105
            PAGES_DIRECTORY.'/',
1106
            '/templates/',
1107
            '/install/'
1108
        );
1109
        $msg = '';
1110
        foreach( $dirRemove as $dir ) {
1111
            $dir = str_replace($searches, $replacements, $dir);
1112
            $dir = WB_PATH.'/'.$dir;
1113
            if( is_dir( $dir )) {
1114
            // try to delete dir
1115
                if(!rm_full_dir($dir)) {
1116
                // save in err-list, if failed
1117
                    $msg .= $dir.'<br />';
1118
                } else {
1119
                        print '<strong>Remove  '.$dir.'</strong>'." $OK<br />";
1120
                }
1121
            }
1122
        }
1123
        if($msg != '') {
1124
            $msg = '<br /><br />Following files are deprecated, outdated or a security risk and
1125
                    can not be removed automatically.<br /><br />Please delete them
1126
                    using FTP and restart upgrade-script!<br /><br />'.$msg.'<br />';
1127
            status_msg($msg, 'error warning', 'div');
1128
            echo '<p style="font-size:120%;"><strong>WARNING: The upgrade script failed ...</strong></p>';
1129
            echo '<form action="'.$sScriptUrl.'">';
1130
            echo '&nbsp;<input name="send" type="submit" value="Restart upgrade script" />';
1131
            echo '</form>';
1132
            echo '<br /><br /></div></body></html>';
1133
            exit;
1134
        }
1135
    }
1136

    
1137
/**********************************************************
1138
 * upgrade modules if newer version is available
1139
    $aModuleList = array_intersect($aModuleDirList, $aModuleWhiteList);
1140
print '<pre  class="mod-pre rounded">function <span>'.__FUNCTION__.'( '.''.' );</span>  filename: <span>'.basename(__FILE__).'</span>  line: '.__LINE__.' -> <br />';
1141
print_r( in_array($sModulName, $aModuleWhiteList).'O) '.$sModulName.'=='.$aModuleWhiteList[$sModulName] ); print '</pre>'; flush (); //  ob_flush();;sleep(10); die();
1142
 */
1143

    
1144
    echo '<h2>Step '.(++$stepID).' : Checking all addons with a newer version (upgrade)</h2>';
1145
    echo '<div class="content">';
1146
    $aModuleDirList = glob(WB_PATH.'/modules/*', GLOB_ONLYDIR|GLOB_ONLYDIR );
1147
    $i = $upgradeID = 0;
1148
#    $aModuleWhiteList = array_flip($aModuleWhiteList);
1149
    foreach($aModuleDirList as $sModul)
1150
    {
1151
        $sModulName = basename($sModul);
1152
        $i++;
1153
        if (in_array($sModulName, $aModuleWhiteList) && file_exists($sModul.'/upgrade.php'))
1154
        {
1155
            $currModulVersion = get_modul_version ($sModulName, false);
1156
            $newModulVersion =  get_modul_version ($sModulName, true);
1157
            if((version_compare($currModulVersion, $newModulVersion, '<' ) )) {
1158
                require($sModul.'/upgrade.php');
1159
                load_module($sModul);
1160
                echo '<h5> '.sprintf("[%2s]", (++$upgradeID)).' : Upgrade module \''.$sModulName.'\' from version '.$currModulVersion.' to version'.$newModulVersion.'</h5>';
1161
            } else {
1162
                echo '<h5 style="color: #16702B"> '.sprintf("[%2s]", (++$upgradeID)).' : Module \''.$sModulName.'\' - Your current version is '.$currModulVersion.'</h5>';
1163
            }
1164
        } else {
1165
            echo '<h5 style="color: #C26106"> '.sprintf("[%2s]", (++$upgradeID)).' : Unchecked Module \''.$sModulName.'\' is not registered in /install/ModuleWhiteList</h5>';
1166

    
1167
        }
1168
    }
1169
    echo '</div>';
1170
/**********************************************************
1171
 *  - Reload all addons
1172
 */
1173

    
1174
    echo '<h2>Step '.(++$stepID).' : Reload all addons database entry (no upgrade)</h2>';
1175
    echo '<div class="content">';
1176
    echo '<br />Modules will be reloaded<br />';
1177
/*
1178
*/
1179
    ////delete modules
1180
    $sql = 'DELETE FROM `'.TABLE_PREFIX.'addons` '
1181
         . 'WHERE `type` = \'module\'';
1182
    $database->query($sql);
1183
    // Load all modules
1184
    if( ($handle = opendir(WB_PATH.'/modules/')) ) {
1185
        while(false !== ($file = readdir($handle))) {
1186
            if($file != '' AND substr($file, 0, 1) != '.' AND $file != 'admin.php' AND $file != 'index.php') {
1187
                load_module(WB_PATH.'/modules/'.$file );
1188
               //     upgrade_module($file, true);
1189
            }
1190
        }
1191
        closedir($handle);
1192
    }
1193
    ////delete templates
1194
    //$database->query("DELETE FROM ".TABLE_PREFIX."addons WHERE type = 'template'");
1195
    // Load all templates
1196
    if( ($handle = opendir(WB_PATH.'/templates/')) ) {
1197
        while(false !== ($file = readdir($handle))) {
1198
            if($file != '' AND substr($file, 0, 1) != '.' AND $file != 'index.php') {
1199
                load_template(WB_PATH.'/templates/'.$file);
1200
            }
1201
        }
1202
        closedir($handle);
1203
    }
1204
    echo '<br />Templates reloaded<br />';
1205

    
1206
    ////delete languages
1207
    //$database->query("DELETE FROM ".TABLE_PREFIX."addons WHERE type = 'language'");
1208
    // Load all languages
1209
    if( ($handle = opendir(WB_PATH.'/languages/')) ) {
1210
        while(false !== ($file = readdir($handle))) {
1211
            if($file != '' AND substr($file, 0, 1) != '.' AND $file != 'index.php') {
1212
                load_language(WB_PATH.'/languages/'.$file);
1213
            }
1214
        }
1215
        closedir($handle);
1216
    }
1217
    echo '<br />Languages reloaded<br />';
1218

    
1219
/**********************************************************
1220
 *  - End of upgrade script
1221
 */
1222

    
1223
// require(WB_PATH.'/framework/initialize.php');
1224

    
1225
    if(!defined('DEFAULT_THEME')) { define('DEFAULT_THEME', $DEFAULT_THEME); }
1226
    if(!defined('THEME_PATH')) { define('THEME_PATH', WB_PATH.'/templates/'.DEFAULT_THEME);}
1227
    if(!defined('THEME_URL')) { define('THEME_URL', WB_URL.'/templates/'.DEFAULT_THEME);}
1228

    
1229
    if(!defined('DEFAULT_TEMPLATE')) { define('DEFAULT_TEMPLATE', $DEFAULT_TEMPLATE); }
1230
    if(!defined('TEMPLATE_PATH')) { define('TEMPLATE_PATH', WB_PATH.'/templates/'.DEFAULT_TEMPLATE);}
1231
    if(!defined('TEMPLATE_DIR')) { define('TEMPLATE_DIR', WB_URL.'/templates/'.DEFAULT_TEMPLATE);}
1232
/**********************************************************
1233
 *  - Set Version to new Version
1234
 */
1235
    echo '<br />Reload all addons database entry (no upgrade)<br />';
1236
    echo '</div>';
1237
    echo '<h2>Step '.(++$stepID).' : Update WebsiteBaker version number to '.VERSION.' '.SP.' '.' Revision ['.REVISION.'] </h2>';
1238
    // echo ($database->query("UPDATE `".TABLE_PREFIX."settings` SET `value`='".VERSION."' WHERE `name` = 'wb_version'")) ? " $OK<br />" : " $FAIL<br />";
1239
    db_update_key_value('settings', 'wb_version', VERSION);
1240
    db_update_key_value('settings', 'wb_revision', REVISION);
1241
    db_update_key_value('settings', 'wb_sp', SP);
1242

    
1243
    status_msg('<h2>Congratulations: The upgrade script is finished ...</h2>', 'info', 'div');
1244

    
1245
    // show buttons to go to the backend or frontend
1246
    echo '<br />';
1247
    if(defined('WB_URL')) {
1248
        echo '<form action="'.WB_URL.'/">';
1249
        echo '&nbsp;<input type="submit" value="kick me to the Frontend" />';
1250
        echo '</form>';
1251
    }
1252
    if(defined('ADMIN_URL')) {
1253
        echo '<form action="'.ADMIN_URL.'/">';
1254
        echo '&nbsp;<input type="submit" value="kick me to the Backend" />';
1255
        echo '</form>';
1256
    }
1257

    
1258
    echo '<br /><br /></div></body></html>';
(5-5/5)