1<?php
2/*
3 * e107 website system
4 *
5 * Copyright (C) 2008-2009 e107 Inc (e107.org)
6 * Released under the terms and conditions of the
7 * GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
8 *
9 */
10
11/**
12 *
13 *	Update routines from older e107 versions to current.
14 *
15 *	Also links to plugin update routines.
16 *
17 *	2-stage process - routines identify whether update is required, and then execute as instructed.
18 */
19
20// [debug=8] shows the operations on major table update
21
22require_once('../class2.php');
23require_once(e_HANDLER.'db_table_admin_class.php');
24e107::includeLan(e_LANGUAGEDIR.e_LANGUAGE.'/admin/lan_e107_update.php');
25// Modified update routine - combines checking and update code into one block per function
26//		- reduces code size typically 30%.
27//		- keeping check and update code together should improve clarity/reduce mis-types etc
28
29
30// @todo: how do we handle update of multi-language tables?
31
32// If following line uncommented, enables a test routine
33// define('TEST_UPDATE',TRUE);
34$update_debug = TRUE;			// TRUE gives extra messages in places
35//$update_debug = TRUE;			// TRUE gives extra messages in places
36if (defined('TEST_UPDATE')) $update_debug = TRUE;
37
38
39//if (!defined('LAN_UPDATE_8')) { define('LAN_UPDATE_8', ''); }
40//if (!defined('LAN_UPDATE_9')) { define('LAN_UPDATE_9', ''); }
41
42
43// Determine which installed plugins have an update file - save the path and the installed version in an array
44$dbupdateplugs = array();		// Array of paths to installed plugins which have a checking routine
45$dbupdatep = array();			// Array of plugin upgrade actions (similar to $dbupdate)
46$dbupdate = array();			// Array of core upgrade actions
47
48global $e107cache;
49
50if(is_readable(e_ADMIN.'ver.php'))
51{
52  include(e_ADMIN.'ver.php');
53}
54
55$mes = e107::getMessage();
56/*
57// If $dont_check_update is both defined and TRUE on entry, a check for update is done only once per 24 hours.
58$dont_check_update = varset($dont_check_update, FALSE);
59
60
61if ($dont_check_update === TRUE)
62{
63	$dont_check_update = FALSE;
64	if ($tempData = $e107cache->retrieve_sys('nq_admin_updatecheck',3600, TRUE))
65	{	// See when we last checked for an admin update
66		list($last_time, $dont_check_update, $last_ver) = explode(',',$tempData);
67		if ($last_ver != $e107info['e107_version'])
68		{
69			$dont_check_update = FALSE;		// Do proper check on version change
70		}
71	}
72}
73*/
74
75$dont_check_update = false;
76
77if (!$dont_check_update)
78{
79	/*
80	if ($sql->db_Select('plugin', 'plugin_id, plugin_version, plugin_path', 'plugin_installflag=1'))
81	{
82		while ($row = $sql->db_Fetch())
83		{  // Mark plugins for update which have a specific update file, or a plugin.php file to check
84			if(is_readable(e_PLUGIN.$row['plugin_path'].'/'.$row['plugin_path'].'_update_check.php') || is_readable(e_PLUGIN.$row['plugin_path'].'/plugin.php') || is_readable(e_PLUGIN.$row['plugin_path'].'/'.$row['plugin_path'].'_setup.php'))
85			{
86				$dbupdateplugs[$row['plugin_path']] = $row['plugin_version'];
87				//TODO - Add support for {plugins}_setup.php upgrade check and routine.
88			}
89		}
90	}
91	*/
92
93	if($dbupdateplugs = e107::getConfig('core')->get('plug_installed'))
94	{
95		// Read in each update file - this will add an entry to the $dbupdatep array if a potential update exists
96		foreach ($dbupdateplugs as $path => $ver)
97		{
98			if(!is_file(e_PLUGIN.$path."/plugin.xml"))
99			{
100				$fname = e_PLUGIN.$path.'/'.$path.'_update_check.php';  // DEPRECATED - left for BC only.
101				if (is_readable($fname)) include_once($fname);
102			}
103
104			$fname = e_PLUGIN.$path.'/'.$path.'_setup.php';
105			if (is_readable($fname))
106			{
107				$dbupdatep[$path] =  $path ; // ' 0.7.x forums '.LAN_UPDATE_9.' 0.8 forums';
108				include_once($fname);
109			}
110		}
111	}
112
113
114	// List of potential updates
115	if (defined('TEST_UPDATE'))
116	{
117		$dbupdate['test_code'] = 'Test update routine';
118	}
119
120	// set 'master' to true to prevent other upgrades from running before it is complete.
121
122	$LAN_UPDATE_4 = deftrue('LAN_UPDATE_4',"Update from [x] to [y]"); // in case language-pack hasn't been upgraded.
123	$LAN_UPDATE_5 = deftrue('LAN_UPDATE_5', "Core database structure");
124
125//	$dbupdate['218_to_219'] = array('master'=>false, 'title'=> e107::getParser()->lanVars($LAN_UPDATE_4, array('2.1.8','2.1.9')), 'message'=> null, 'hide_when_complete'=>true);
126
127//	$dbupdate['217_to_218'] = array('master'=>false, 'title'=> e107::getParser()->lanVars($LAN_UPDATE_4, array('2.1.7','2.1.8')), 'message'=> null, 'hide_when_complete'=>true);
128	$dbupdate['706_to_800'] = array('master'=>true, 'title'=> e107::getParser()->lanVars($LAN_UPDATE_4, array('1.x','2.0')), 'message'=> LAN_UPDATE_29, 'hide_when_complete'=>true);
129
130	$dbupdate['20x_to_220'] = array('master'=>true, 'title'=> e107::getParser()->lanVars($LAN_UPDATE_4, array('2.x','2.2.0')), 'message'=> null, 'hide_when_complete'=>false);
131
132
133
134	// always run these last.
135	$dbupdate['core_database'] = array('master'=>false, 'title'=> $LAN_UPDATE_5);
136	$dbupdate['core_prefs'] = array('master'=>true, 'title'=> LAN_UPDATE_13);						// Prefs check
137
138
139
140//	$dbupdate['70x_to_706'] = LAN_UPDATE_8.' .70x '.LAN_UPDATE_9.' .706';
141}		// End if (!$dont_check_update)
142
143
144
145// New in v2.x  ------------------------------------------------
146
147class e107Update
148{
149	var $core = array();
150	var $updates = 0;
151	var $disabled = 0;
152
153
154	function __construct($core=null)
155	{
156		$mes = e107::getMessage();
157
158		$this->core = $core;
159
160		if(varset($_POST['update_core']) && is_array($_POST['update_core']))
161		{
162			$func = key($_POST['update_core']);
163			$this->updateCore($func);
164		}
165
166		if(varset($_POST['update']) && is_array($_POST['update'])) // Do plugin updates
167		{
168			$func = key($_POST['update']);
169			$this->updatePlugin($func);
170		}
171
172			//	$dbv =  e107::getSingleton('db_verify', e_HANDLER."db_verify_class.php");
173
174	//	$dbv->clearCache();
175
176
177		$this->renderForm();
178	}
179
180
181
182
183	function updateCore($func='')
184	{
185		$mes = e107::getMessage();
186		$tp = e107::getParser();
187		$sql = e107::getDb();
188
189			if(function_exists('update_'.$func)) // Legacy Method.
190			{
191				$installed = call_user_func("update_".$func);
192				//?! (LAN_UPDATE == $_POST[$func])
193				if(vartrue($_POST['update_core'][$func]) && !$installed)
194				{
195					if(function_exists("update_".$func))
196					{
197						// $message = LAN_UPDATE_7." ".$func;
198						$message = $tp->lanVars(LAN_UPDATE_7, $this->core[$func]['title']);
199						$error = call_user_func("update_".$func, "do");
200
201						if($error != '')
202						{
203							$mes->add($message, E_MESSAGE_ERROR);
204							$mes->add($error, E_MESSAGE_ERROR);
205						}
206						else
207						{
208							 $mes->add($message, E_MESSAGE_SUCCESS);
209							 e107::getCache()->clear_sys('Update_core');
210							 $search = ['[',']'];
211							 $replace = ["<a class='alert-link' href='".e_ADMIN."fileinspector.php'>", "</a>"];
212							 $fileInspectorMessage = LAN_UPDATE_58; // running file-inspector is recommended..
213							 $mes->addInfo(str_replace($search,$replace, $fileInspectorMessage));
214						}
215					}
216				}
217			}
218			else
219			{
220				$mes->addDebug("could not run 'update_".$func);
221			}
222
223
224
225	}
226
227
228
229	function updatePlugin($path)
230	{
231		e107::getPlugin()->install_plugin_xml($path, 'upgrade');
232		// e107::getPlugin()->save_addon_prefs(); // Rebuild addon prefs.
233		e107::getMessage()->reset(E_MESSAGE_INFO);
234		e107::getMessage()->addSuccess(LAN_UPDATED." : ".$path);
235
236	}
237
238
239
240	function plugins()
241	{
242		if(!$list = e107::getPlugin()->updateRequired())
243		{
244			return false;
245		}
246
247		$frm = e107::getForm();
248
249		$tp = e107::getParser();
250
251		$text = "";
252
253		uksort($list, "strnatcasecmp");
254
255		foreach($list as $path=>$val)
256		{
257			$name = !empty($val['@attributes']['lan']) ? $tp->toHTML($val['@attributes']['lan'],false,'TITLE') : $val['@attributes']['name'];
258
259			$text .= "<tr>
260					<td>".$name."</td>
261					<td>".$frm->admin_button('update['.$path.']', LAN_UPDATE, 'warning', '', 'disabled='.$this->disabled)."</td>
262					</tr>";
263		}
264
265		return $text;
266	}
267
268
269
270
271	function core()
272	{
273		$frm = e107::getForm();
274		$mes = e107::getMessage();
275		$sql = e107::getDb();
276
277		$text = "";
278
279
280
281		foreach($this->core as $func => $data)
282		{
283			$text2 = '';
284
285			if(function_exists("update_".$func))
286			{
287
288				if(call_user_func("update_".$func))
289				{
290					if(empty($data['hide_when_complete']))
291					{
292						$text2 .= "<td>".$data['title']."</td>";
293						$text2 .= "<td>".ADMIN_TRUE_ICON."</td>";
294					}
295				}
296				else
297				{
298					$text2 .= "<td>".$data['title']."</td>";
299
300					if(vartrue($data['message']))
301					{
302						$mes->addInfo($data['message']);
303					}
304
305					$this->updates ++;
306
307					$text2 .= "<td>".$frm->admin_button('update_core['.$func.']', LAN_UPDATE, 'warning', '', "id=e-{$func}&disabled=".$this->disabled)."</td>";
308
309					if($data['master'] == true)
310					{
311						$this->disabled = 1;
312					}
313				}
314
315				if(!empty($text2))
316				{
317					$text .= "<tr>".$text2."</tr>\n";
318				}
319
320			}
321		}
322
323		return $text;
324	}
325
326
327
328	function renderForm()
329	{
330		$ns = e107::getRender();
331		$mes = e107::getMessage();
332
333		$caption = LAN_UPDATE;
334		$text = "
335		<form method='post' action='".e_ADMIN."e107_update.php'>
336			<fieldset id='core-e107-update'>
337			<legend>{$caption}</legend>
338				<table class='table adminlist'>
339					<colgroup>
340						<col style='width: 60%' />
341						<col style='width: 40%' />
342					</colgroup>
343					<thead>
344						<tr>
345							<th>".LAN_UPDATE_55."</th>
346							<th class='last'>".LAN_UPDATE_2."</th>
347						</tr>
348					</thead>
349					<tbody>
350		";
351
352		$text .= $this->core();
353		$text .= $this->plugins();
354
355		$text .= "
356					</tbody>
357				</table>
358			</fieldset>
359		</form>
360			";
361
362
363		$ns->tablerender(LAN_UPDATES,$mes->render() . $text);
364
365	}
366
367
368}
369
370/**
371 *	Master routine to call to check for updates
372 */
373function update_check()
374{
375
376	$ns = e107::getRender();
377	$e107cache = e107::getCache();
378	$sql = e107::getDb();
379	$mes = e107::getMessage();
380
381	global $dont_check_update, $e107info;
382	global $dbupdate, $dbupdatep, $e107cache;
383
384	$update_needed = FALSE;
385
386
387
388	if ($dont_check_update === FALSE)
389	{
390		$dbUpdatesPref = array();
391
392		$skip = e107::getPref('db_updates');
393
394		foreach($dbupdate as $func => $rmks) // See which core functions need update
395		{
396
397			if(!empty($skip[$func]) && (!deftrue('e_DEBUG') || E107_DBG_TIMEDETAILS)) // skip version checking when debug is off and check already done.
398			{
399				continue;
400			}
401
402			if(function_exists('update_' . $func))
403			{
404
405				e107::getDebug()->logTime('Check Core Update_' . $func . ' ');
406				if(!call_user_func('update_' . $func, false))
407				{
408					$dbUpdatesPref[$func] = 0;
409					$update_needed = true;
410					break;
411				}
412				elseif(strpos($func, 'core_') !==0) // skip the pref and table check.
413				{
414					$dbUpdatesPref[$func] = 1;
415
416				}
417			}
418
419		}
420
421		e107::getConfig()->set('db_updates', $dbUpdatesPref)->save(false,true,false);
422
423
424		// Now check plugins - XXX DEPRECATED
425		foreach($dbupdatep as $func => $rmks)
426		{
427			if(function_exists('update_' . $func))
428			{
429				//	$sql->db_Mark_Time('Check Core Update_'.$func.' ');
430				if(!call_user_func('update_' . $func, false))
431				{
432					$update_needed = true;
433					break;
434				}
435			}
436		}
437
438		// New in v2.x
439		if(e107::getPlugin()->updateRequired('boolean'))
440		{
441			 $update_needed = TRUE;
442		}
443
444
445	//	$e107cache->set_sys('nq_admin_updatecheck', time().','.($update_needed ? '2,' : '1,').$e107info['e107_version'], TRUE);
446	}
447	else
448	{
449		$update_needed = ($dont_check_update == '2');
450	}
451
452	return $update_needed;
453}
454
455
456//XXX to be reworked eventually - for checking remote 'new versions' of plugins and installed theme.
457// require_once(e_HANDLER.'e_upgrade_class.php');
458//	$upg = new e_upgrade;
459
460//	$upg->checkSiteTheme();
461//	$upg->checkAllPlugins();
462
463
464
465//--------------------------------------------
466//	Check current prefs against latest list
467//--------------------------------------------
468function update_core_prefs($type='')
469{
470	global $e107info; // $pref,  $pref must be kept as global
471
472	$pref = e107::getConfig('core', true, true)->getPref();
473	$admin_log = e107::getAdminLog();
474	$do_save = FALSE;
475	$should = get_default_prefs();
476
477	$just_check = $type == 'do' ? FALSE : TRUE;		// TRUE if we're just seeing if an update is needed
478
479	foreach ($should as $k => $v)
480	{
481		if ($k && !array_key_exists($k,$pref))
482		{
483			if ($just_check) return update_needed('Missing pref: '.$k);
484		//	$pref[$k] = $v;
485			e107::getConfig()->set($k,$v);
486			$admin_log->logMessage($k.' => '.$v, E_MESSAGE_NODISPLAY, E_MESSAGE_INFO);
487			$do_save = TRUE;
488		}
489	}
490	if ($do_save)
491	{
492		//save_prefs();
493		e107::getConfig('core')->save(false,true);
494		$admin_log->logMessage(LAN_UPDATE_14.$e107info['e107_version'], E_MESSAGE_NODISPLAY, E_MESSAGE_INFO);
495		$admin_log->flushMessages('UPDATE_03',E_LOG_INFORMATIVE);
496		//e107::getLog()->add('UPDATE_03',LAN_UPDATE_14.$e107info['e107_version'].'[!br!]'.implode(', ',$accum),E_LOG_INFORMATIVE,'');	// Log result of actual update
497	}
498	return $just_check;
499}
500
501
502
503if (defined('TEST_UPDATE'))
504{
505//--------------------------------------------
506//	Test routine - to activate, define TEST_UPDATE
507//--------------------------------------------
508	function update_test_code($type='')
509	{
510		global $sql,$ns, $pref;
511		$just_check = $type == 'do' ? FALSE : TRUE;		// TRUE if we're just seeing whether an update is needed
512		//--------------**************---------------
513		// Add your test code in here
514		//--------------**************---------------
515
516		//--------------**************---------------
517		// End of test code
518		//--------------**************---------------
519		return $just_check;
520	}
521}  // End of test routine
522
523// generic database structure update.
524function update_core_database($type = '')
525{
526	$just_check = ($type == 'do') ? FALSE : TRUE;
527//	require_once(e_HANDLER."db_verify_class.php");
528//	$dbv = new db_verify;
529
530	/** @var db_verify $dbv */
531	$dbv =  e107::getSingleton('db_verify', e_HANDLER."db_verify_class.php");
532
533	$log = e107::getAdminLog();
534
535	if($plugUpgradeReq = e107::getPlugin()->updateRequired())
536	{
537		$exclude =  array_keys($plugUpgradeReq); // search xxxxx_setup.php and check for 'upgrade_required()' == true.
538		asort($exclude);
539	}
540	else
541	{
542		$exclude = false;
543	}
544
545	$dbv->compareAll($exclude); // core & plugins, but not plugins calling for an update with xxxxx_setup.php
546
547
548	if($dbv->errors())
549	{
550		if ($just_check)
551		{
552			$mes = e107::getMessage();
553		//	$mes->addDebug(print_a($dbv->errors,true));
554			$log->addDebug(print_a($dbv->errors,true));
555			$tables = implode(", ", array_keys($dbv->errors));
556			return update_needed("Database Tables require updating: <b>".$tables."</b>");
557		}
558
559		$dbv->compileResults();
560		$dbv->runFix(); // Fix entire core database structure and plugins too.
561
562
563	}
564
565
566	return $just_check;
567}
568
569/*
570	function update_218_to_219($type='')
571	{
572		$sql = e107::getDb();
573		$just_check = ($type == 'do') ? false : true;
574
575		// add common video and audio media categories if missing.
576		$count = $sql->select("core_media_cat","*","media_cat_category = '_common_video' LIMIT 1 ");
577
578		if(!$count)
579		{
580			if ($just_check) return update_needed('Media-Manager is missing the video and audio categories and needs to be updated.');
581
582			$sql->gen("INSERT INTO `".MPREFIX."core_media_cat` VALUES(0, '_common', '_common_video', '(Common Videos)', '', 'Media in this category will be available in all areas of admin. ', 253, '', 0);");
583			$sql->gen("INSERT INTO `".MPREFIX."core_media_cat` VALUES(0, '_common', '_common_audio', '(Common Audio)', '', 'Media in this category will be available in all areas of admin. ', 253, '', 0);");
584		}
585
586
587
588		return $just_check;
589	}*/
590
591
592
593
594	/**
595	 * @param string $type
596	 * @return bool true = no update required, and false if update required.
597	 */
598/*	 function update_217_to_218($type='')
599	{
600		$just_check = ($type == 'do') ? false : true;
601
602		$e_user_list = e107::getPref('e_user_list');
603
604			e107::getPlug()->clearCache()->buildAddonPrefLists();
605			if(empty($e_user_list['user'])) // check e107_plugins/user/e_user.php is registered.
606			{
607				if($just_check)
608				{
609					return update_needed("user/e_user.php need to be registered"); // NO LAN.
610				}
611
612			}
613
614
615		// Make sure, that the pref "post_script" contains one of the allowed userclasses
616		// Close possible security hole
617		if (!array_key_exists(e107::getPref('post_script'), e107::getUserClass()->uc_required_class_list('nobody,admin,main,classes,no-excludes', true)))
618		{
619			if ($just_check)
620			{
621				return update_needed("Pref 'Class which can post < script > and similar tags' contains an invalid value"); // NO LAN.
622			}
623			else
624			{
625				e107::getConfig()->setPref('post_script', 255)->save(false, true);
626			}
627		}
628
629
630		return $just_check;
631
632
633
634	}*/
635
636
637
638	/**
639	 * @param string $type
640	 * @return bool true = no update required, and false if update required.
641	 */
642	 function update_20x_to_230($type='')
643	{
644
645		$sql = e107::getDb();
646		$log = e107::getLog();
647		$just_check = ($type == 'do') ? false : true;
648		$pref = e107::getPref();
649
650
651		if(!$sql->select('core_media_cat', 'media_cat_id', "media_cat_category = '_icon_svg' LIMIT 1"))
652		{
653			if($just_check)
654			{
655				return update_needed("Missing Media-category for SVG");
656			}
657
658			$query = "INSERT INTO `#core_media_cat` (media_cat_id, media_cat_owner, media_cat_category, media_cat_title, media_cat_sef, media_cat_diz, media_cat_class, media_cat_image, media_cat_order) VALUES (NULL, '_icon', '_icon_svg', 'Icons SVG', '', 'Available where icons are used in admin.', '253', '', '0');";
659
660			$sql->gen($query);
661
662		}
663
664
665
666		if(isset($pref['e_header_list']['social']))
667		{
668			if($just_check)
669			{
670				return update_needed("Social Plugin Needs to be refreshed. ");
671			}
672
673			e107::getPlugin()->refresh('social');
674		}
675
676
677		if(empty($pref['themecss'])) // FIX
678		{
679			if($just_check)
680			{
681				return update_needed("Theme CSS pref value is blank.");
682			}
683
684			e107::getConfig()->set('themecss','style.css')->save(false,true,false);
685		}
686
687
688		if(isset($pref['flood_protect']))
689		{
690			if ($just_check)
691			{
692		        return update_needed("Old flood protection pref needs to be removed.");
693			}
694
695			e107::getConfig()->remove('flood_protect')->save(false,true,false);
696		}
697
698
699		// User is marked as not installed.
700		if($sql->select('plugin', 'plugin_id', "plugin_path = 'user' AND plugin_installflag != 1 LIMIT 1"))
701		{
702			if($just_check)
703			{
704				return update_needed("Plugin table 'user' value needs to be reset.");
705			}
706
707			$sql->delete('plugin', "plugin_path = 'user'");
708
709			//e107::getPlug()->clearCache();
710		}
711
712
713		// Make sure, that the pref "post_script" contains one of the allowed userclasses
714		// Close possible security hole
715		if (!array_key_exists(e107::getPref('post_script'), e107::getUserClass()->uc_required_class_list('nobody,admin,main,classes,no-excludes', true)))
716		{
717			if ($just_check)
718			{
719				return update_needed("Pref 'Class which can post < script > and similar tags' contains an invalid value"); // NO LAN.
720			}
721			else
722			{
723				e107::getConfig()->setPref('post_script', 255)->save(false, true);
724			}
725		}
726
727
728		// add common video and audio media categories if missing.
729		$count = $sql->select("core_media_cat","*","media_cat_category = '_common_video' LIMIT 1 ");
730
731		if(!$count)
732		{
733			if ($just_check) return update_needed('Media-Manager is missing the video and audio categories and needs to be updated.');
734
735			$sql->gen("INSERT INTO `".MPREFIX."core_media_cat` VALUES(0, '_common', '_common_video', '(Common Videos)', '', 'Media in this category will be available in all areas of admin. ', 253, '', 0);");
736			$sql->gen("INSERT INTO `".MPREFIX."core_media_cat` VALUES(0, '_common', '_common_audio', '(Common Audio)', '', 'Media in this category will be available in all areas of admin. ', 253, '', 0);");
737		}
738
739
740
741		return $just_check;
742
743
744
745
746
747	}
748
749
750//--------------------------------------------
751//	Upgrade later versions of 0.7.x to 0.8
752//--------------------------------------------
753function update_706_to_800($type='')
754{
755
756	global $pref, $e107info;
757	global $sysprefs, $eArrayStorage;
758
759	//$mes = new messageLog;		// Combined logging and message displaying handler
760	//$mes = e107::getMessage();
761	$log 	= e107::getAdminLog();		// Used for combined logging and message displaying
762	$sql 	= e107::getDb();
763	$sql2 	= e107::getDb('sql2');
764	$tp 	= e107::getParser();
765	$ns 	= e107::getRender();
766
767	e107::getCache()->clearAll('db');
768	e107::getCache()->clear_sys('Config');
769
770	e107::getMessage()->setUnique();
771
772	// List of unwanted $pref values which can go
773	$obs_prefs = array('frontpage_type','rss_feeds', 'log_lvcount', 'zone', 'upload_allowedfiletype', 'real', 'forum_user_customtitle',
774						'utf-compatmode','frontpage_method','standards_mode','image_owner','im_quality', 'signup_option_timezone',
775						'modules', 'plug_sc', 'plug_bb', 'plug_status', 'plug_latest', 'subnews_hide_news', 'upload_storagetype',
776						'signup_remote_emailcheck'
777
778				);
779
780	// List of DB tables not required (includes a few from 0.6xx)
781	$obs_tables = array('flood',  'stat_info', 'stat_counter', 'stat_last',  'preset', 'tinymce');
782
783
784	// List of DB tables newly required  (defined in core_sql.php) (The existing dblog table gets renamed)
785	// No Longer required. - automatically checked against core_sql.php.
786//	$new_tables = array('audit_log', 'dblog', 'news_rewrite', 'core_media', 'core_media_cat','cron', 'mail_recipients', 'mail_content');
787
788	// List of core prefs that need to be converted from serialized to e107ArrayStorage.
789	$serialized_prefs = array("'emote'", "'menu_pref'", "'search_prefs'", "'emote_default'", "'pm_prefs'");
790
791
792
793
794	// List of changed DB tables (defined in core_sql.php)
795	// No Longer required. - automatically checked against core_sql.php.
796	// (primarily those which have changed significantly; for the odd field write some explicit code - it'll run faster)
797	// $changed_tables = array('user', 'dblog', 'admin_log', 'userclass_classes', 'banlist', 'menus',
798							 // 'plugin', 'news', 'news_category', 'online', 'page', 'links', 'comments');
799
800
801	// List of changed DB tables from core plugins (defined in pluginname_sql.php file)
802	// key = plugin directory name. Data = comma-separated list of tables to check
803	// (primarily those which have changed significantly; for the odd field write some explicit code - it'll run faster)
804	// No Longer required. - automatically checked by db-verify
805	/* $pluginChangedTables = array('linkwords' => 'linkwords',
806								'featurebox' => 'featurebox',
807								'links_page' => 'links_page',
808								'poll' => 'polls',
809								'content' => 'pcontent'
810								);
811
812	 */
813/*
814	$setCorePrefs = array( //modified prefs during upgrade.
815		'adminstyle' 		=> 'infopanel',
816		'admintheme' 		=> 'bootstrap',
817		'admincss'			=> 'admin_style.css',
818		'resize_dimensions' => array(
819			'news-image' 	=> array('w' => 250, 'h' => 250),
820			'news-bbcode' 	=> array('w' => 250, 'h' => 250),
821			'page-bbcode' 	=> array('w' => 250, 'h' => 250)
822		)
823	);
824*/
825
826
827
828
829	$do_save = TRUE;
830
831
832	// List of changed menu locations.
833	$changeMenuPaths = array(
834		array('oldpath'	=> 'siteinfo_menu',		'newpath' => 'siteinfo',	'menu' => 'sitebutton_menu'),
835		array('oldpath'	=> 'siteinfo_menu',		'newpath' => 'siteinfo',	'menu' => 'compliance_menu'),
836		array('oldpath'	=> 'siteinfo_menu',		'newpath' => 'siteinfo',	'menu' => 'powered_by_menu'),
837		array('oldpath'	=> 'siteinfo_menu',		'newpath' => 'siteinfo',	'menu' => 'sitebutton_menu'),
838		array('oldpath'	=> 'siteinfo_menu',		'newpath' => 'siteinfo',	'menu' => 'counter_menu'),
839		array('oldpath'	=> 'siteinfo_menu',		'newpath' => 'siteinfo',	'menu' => 'latestnews_menu'),
840		array('oldpath'	=> 'compliance_menu',	'newpath' => 'siteinfo',	'menu' => 'compliance_menu'),
841		array('oldpath'	=> 'powered_by_menu',	'newpath' => 'siteinfo',	'menu' => 'powered_by_menu'),
842		array('oldpath'	=> 'sitebutton_menu',	'newpath' => 'siteinfo',	'menu' => 'sitebutton_menu'),
843		array('oldpath'	=> 'counter_menu',		'newpath' => 'siteinfo',	'menu' => 'counter_menu'),
844		array('oldpath'	=> 'usertheme_menu',	'newpath' => 'user',		'menu' => 'usertheme_menu'),
845		array('oldpath'	=> 'userlanguage_menu',	'newpath' => 'user',		'menu' => 'userlanguage_menu'),
846		array('oldpath'	=> 'lastseen_menu',		'newpath' => 'online',		'menu' => 'lastseen_menu'),
847		array('oldpath'	=> 'other_news_menu',	'newpath' => 'news',		'menu' => 'other_news_menu'),
848		array('oldpath'	=> 'other_news_menu',	'newpath' => 'news',		'menu' => 'other_news2_menu'),
849		array('oldpath'	=> 'user_menu',			'newpath' => 'user',		'menu' => 'usertheme_menu'),
850		array('oldpath'	=> 'user_menu',			'newpath' => 'user',		'menu' => 'userlanguage_menu'),
851		array('oldpath'	=> 'poll_menu',			'newpath' => 'poll',		'menu' => 'poll_menu'),
852		array('oldpath'	=> 'banner_menu',		'newpath' => 'banner',		'menu' => 'banner_menu'),
853		array('oldpath'	=> 'online_menu',		'newpath' => 'online',		'menu' => 'online_menu'),
854	);
855
856
857	// List of DB tables (key) and field (value) which need changing to accommodate IPV6 addresses
858	$ip_upgrade = array('download_requests' => 'download_request_ip',
859						'submitnews' 		=> 'submitnews_ip',
860						'tmp' 				=> 'tmp_ip',
861						'chatbox' 			=> 'cb_ip'
862						);
863
864	$db_parser = new db_table_admin;				// Class to read table defs and process them
865	$do_save = FALSE;								// Set TRUE to update prefs when update complete
866	$updateMessages = array();						// Used to log actions for the admin log - TODO: will go once all converted to new class
867
868	$just_check = ($type == 'do') ? FALSE : TRUE;		// TRUE if we're just seeing whether an update is needed
869
870//	if (!$just_check)
871//	{
872	//	foreach(vartrue($setCorePrefs) as $k=>$v)
873	//	{
874	//		$pref[$k] = $v;
875	//	}
876//	}
877
878	if (!$just_check)
879	{
880		$log->logMessage(LAN_UPDATE_14.$e107info['e107_version'], E_MESSAGE_NODISPLAY);
881	}
882
883
884
885
886
887
888
889	$statusTexts = array(E_MESSAGE_SUCCESS => 'Success', E_MESSAGE_ERROR => 'Fail', E_MESSAGE_INFO => 'Info');
890
891
892
893	if($pref['admintheme'] == 'bootstrap')//TODO Force an admin theme update or not?
894	{
895		if ($just_check) return update_needed('pref: Admin theme upgrade to bootstrap3 ');
896
897		$pref['admintheme'] = 'bootstrap3';
898		$pref['admincss']    = 'admin_dark.css';
899
900		$do_save = true;
901	}
902
903	// convert all serialized core prefs to e107 ArrayStorage;
904	$serialz_qry = "SUBSTRING( e107_value,1,5)!='array' AND e107_value !='' ";
905    $serialz_qry .= "AND e107_name IN (".implode(",",$serialized_prefs).") ";
906	if(e107::getDb()->select("core", "*", $serialz_qry))
907	{
908		if($just_check) return update_needed('Convert serialized core prefs');
909		while ($row = e107::getDb()->fetch())
910		{
911
912			$status = e107::getDb('sql2')->update('core',"e107_value=\"".convert_serialized($row['e107_value'])."\" WHERE e107_name='".$row['e107_name']."'") ? E_MESSAGE_SUCCESS : E_MESSAGE_ERROR;
913
914			$log->addDebug(LAN_UPDATE_22.$row['e107_name'].": ". $status);
915		}
916	}
917
918
919	if(e107::getDb()->select("core", "*", "e107_name='pm_prefs' LIMIT 1"))
920	{
921		if ($just_check) return update_needed('Rename the pm prefs');
922		e107::getDb()->update("core",  "e107_name='plugin_pm' WHERE e107_name = 'pm_prefs'");
923	}
924
925
926	//@TODO de-serialize the user_prefs also.
927
928
929	// Banlist
930
931	if(!$sql->field('banlist','banlist_id'))
932	{
933		if ($just_check) return update_needed('Banlist table requires updating.');
934		$sql->gen("ALTER TABLE #banlist DROP PRIMARY KEY");
935		$sql->gen("ALTER TABLE `#banlist` ADD `banlist_id` INT( 11 ) unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST");
936	}
937
938
939
940
941
942
943	// Move the maximum online counts from menu prefs to a separate pref - 'history'
944	e107::getCache()->clear_sys('Config');
945	$menuConfig = e107::getConfig('menu',true,true);
946
947	if ($menuConfig->get('most_members_online') || $menuConfig->get('most_guests_online') || $menuConfig->get('most_online_datestamp'))
948	{
949		$status = E_MESSAGE_DEBUG;
950		if ($just_check) return update_needed('Move online counts from menupref');
951		$newPrefs = e107::getConfig('history');
952		foreach (array('most_members_online', 'most_guests_online', 'most_online_datestamp') as $v)
953		{
954			if (FALSE === $newPrefs->get($v, FALSE))
955			{
956				if (FALSE !== $menuConfig->get($v, FALSE))
957				{
958					$newPrefs->set($v,$menuConfig->get($v));
959				}
960				else
961				{
962					$newPrefs->set($v, 0);
963				}
964			}
965			$menuConfig->remove($v);
966		}
967		$result = $newPrefs->save(false, true, false);
968		if ($result === TRUE)
969		{
970			$resultMessage = 'Historic member counts updated';
971			$result = $menuConfig->save(false, true, false); // Only re-save if successul.
972		}
973		elseif ($result === FALSE)
974		{
975			$resultMessage = 'moving historic member counts';
976			$status = E_MESSAGE_ERROR;
977		}
978		else
979		{	// No change
980			$resultMessage = 'Historic member counts already updated';
981			$status = E_MESSAGE_INFO;
982		}
983		// $result = $menuConfig->save(false, true, false);	// Save updated menuprefs - without the counts - don't delete them if it fails.
984		//$updateMessages[] = $statusTexts[$status].': '.$resultMessage;		// Admin log message
985		$log->logMessage($resultMessage,$status);									// User message
986	}
987
988
989
990	// ++++++++ Modify Menu Paths +++++++.
991	if(varset($changeMenuPaths))
992	{
993		foreach($changeMenuPaths as $val)
994		{
995			$qry = "SELECT menu_path FROM `#menus` WHERE menu_name = '".$val['menu']."' AND (menu_path='".$val['oldpath']."' || menu_path='".$val['oldpath']."/' ) LIMIT 1";
996			if($sql->gen($qry))
997			{
998				if ($just_check) return update_needed('Menu path changed required:  '.$val['menu'].' ');
999				$updqry = "menu_path='".$val['newpath']."/' WHERE menu_name = '".$val['menu']."' AND (menu_path='".$val['oldpath']."' || menu_path='".$val['oldpath']."/' ) ";
1000				$status = $sql->update('menus', $updqry) ? E_MESSAGE_DEBUG : E_MESSAGE_ERROR;
1001				$log->logMessage(LAN_UPDATE_23.'<b>'.$val['menu'].'</b> : '.$val['oldpath'].' => '.$val['newpath'], $status); // LAN_UPDATE_25;
1002				// catch_error($sql);
1003			}
1004		}
1005	}
1006
1007	// Leave this one here.. just in case..
1008	//delete record for online_extended_menu (now only using one online menu)
1009	if($sql->db_Select('menus', '*', "menu_path='online_extended_menu' || menu_path='online_extended_menu/'"))
1010	{
1011		if ($just_check) return update_needed("The Menu table needs to have some paths corrected in its data.");
1012
1013		$row=$sql->db_Fetch();
1014
1015		//if online_extended is activated, we need to activate the new 'online' menu, and delete this record
1016		if($row['menu_location']!=0)
1017		{
1018			$status = $sql->update('menus', "menu_name='online_menu', menu_path='online/' WHERE menu_path='online_extended_menu' || menu_path='online_extended_menu/' ") ? E_MESSAGE_DEBUG : E_MESSAGE_ERROR;
1019			$log->logMessage(LAN_UPDATE_23."<b>online_menu</b> : online/", $status);
1020		}
1021		else
1022		{	//else if the menu is not active
1023			//we need to delete the online_extended menu row, and change the online_menu to online
1024			$sql->delete('menus', " menu_path='online_extended_menu' || menu_path='online_extended_menu/' ");
1025			$log->logMessage(LAN_UPDATE_31, E_MESSAGE_DEBUG);
1026		}
1027		catch_error($sql);
1028	}
1029
1030	//change menu_path for online_menu (if it still exists)
1031	if($sql->db_Select('menus', 'menu_path', "menu_path='online_menu' || menu_path='online_menu/'"))
1032	{
1033		if ($just_check) return update_needed('change menu_path for online menu');
1034
1035		$status = $sql->update('menus', "menu_path='online/' WHERE menu_path='online_menu' || menu_path='online_menu/' ") ? E_MESSAGE_DEBUG : E_MESSAGE_ERROR;
1036		$log->logMessage(LAN_UPDATE_23."<b>online_menu</b> : online/", $status);
1037		catch_error($sql);
1038	}
1039
1040	if (!$just_check)
1041	{
1042		// Alert Admin to delete deprecated menu folders.
1043		$chgPath = array();
1044		foreach($changeMenuPaths as $cgpArray)
1045		{
1046			if(is_dir(e_PLUGIN.$cgpArray['oldpath']))
1047			{
1048				if(!in_array($cgpArray['oldpath'],$chgPath))
1049				{
1050					$chgPath[] = $cgpArray['oldpath'];
1051				}
1052			}
1053		}
1054
1055		if(count($chgPath))
1056		{
1057			$log->addWarning(LAN_UPDATE_57.' ');
1058			array_unique($chgPath);
1059			asort($chgPath);
1060			foreach($chgPath as $cgp)
1061			{
1062				$log->addWarning(e_PLUGIN_ABS."<b>".$cgp."</b>");
1063			}
1064		}
1065
1066	}
1067
1068
1069
1070//---------------------------------------------------------
1071//			Comments - split user field
1072//---------------------------------------------------------
1073	if($sql->db_Field('comments','comment_author'))
1074	{
1075		if ($just_check) return update_needed('Comment table author field update');
1076
1077		if ((!$sql->db_Field('comments','comment_author_id'))		// Check to see whether new fields already added - maybe data copy failed part way through
1078			&& (!$sql->gen("ALTER TABLE `#comments`
1079				ADD COLUMN comment_author_id int(10) unsigned NOT NULL default '0' AFTER `comment_author`,
1080				ADD COLUMN comment_author_name varchar(100) NOT NULL default '' AFTER `comment_author_id`")))
1081		{
1082			// Flag error
1083			// $commentMessage = LAN_UPDAXXTE_34;
1084			$log->logMessage(LAN_UPDATE_21."comments", E_MESSAGE_ERROR);
1085		}
1086		else
1087		{
1088			if (FALSE ===$sql->update('comments',"comment_author_id=SUBSTRING_INDEX(`comment_author`,'.',1),  comment_author_name=SUBSTRING(`comment_author` FROM POSITION('.' IN `comment_author`)+1)"))
1089			{
1090				// Flag error
1091				$log->logMessage(LAN_UPDATE_21.'comments', E_MESSAGE_ERROR);
1092			}
1093			else
1094			{	// Delete superceded field - comment_author
1095				if (!$sql->gen("ALTER TABLE `#comments` DROP COLUMN `comment_author`"))
1096				{
1097					// Flag error
1098					$log->logMessage(LAN_UPDATE_24.'comments - comment_author', E_MESSAGE_ERROR);
1099				}
1100			}
1101		}
1102
1103		$log->logMessage(LAN_UPDATE_21.'comments', E_MESSAGE_DEBUG);
1104	}
1105
1106
1107
1108	//	Add index to download history
1109	// Deprecated by db-verify-class
1110	// if (FALSE !== ($temp = addIndexToTable('download_requests', 'download_request_datestamp', $just_check, $updateMessages)))
1111	// {
1112		// if ($just_check)
1113		// {
1114			// return update_needed($temp);
1115		// }
1116	// }
1117
1118	// Extra index to tmp table
1119	// Deprecated by db-verify-class
1120	// if (FALSE !== ($temp = addIndexToTable('tmp', 'tmp_time', $just_check, $updateMessages)))
1121	// {
1122		// if ($just_check)
1123		// {
1124			// return update_needed($temp);
1125		// }
1126	// }
1127
1128	// Extra index to rss table (if used)
1129	// Deprecated by db-verify-class
1130	// if (FALSE !== ($temp = addIndexToTable('rss', 'rss_name', $just_check, $updateMessages, TRUE)))
1131	// {
1132		// if ($just_check)
1133		// {
1134			// return update_needed($temp);
1135		// }
1136	// }
1137
1138	// Front page prefs (logic has changed)
1139	if (!isset($pref['frontpage_force'])) // Just set basic options; no real method of converting the existing
1140	{
1141		if ($just_check) return update_needed('Change front page prefs');
1142		$pref['frontpage_force'] = array(e_UC_PUBLIC => '');
1143
1144		$fpdef = vartrue($pref['frontpage']['all']) == 'index.php' ? 'index.php' : 'news.php';
1145
1146		$pref['frontpage'] = array(e_UC_PUBLIC => $fpdef);
1147		// $_pdateMessages[] = LAN_UPDATE_38; //FIXME
1148		$log->logMessage(LAN_UPDATE_20."frontpage",E_MESSAGE_DEBUG);
1149
1150		e107::getConfig()->add('frontpage_force', $pref['frontpage_force']);
1151		e107::getConfig()->add('frontpage', $pref['frontpage']);
1152		unset($pref['frontpage_force'], $pref['frontpage']);
1153		$do_save = TRUE;
1154	}
1155
1156	// Check need for user timezone before we delete the field
1157//	if (vartrue($pref['signup_option_timezone']))
1158	{
1159		if ($sql->field('user', 'user_timezone')===true && $sql->field('user_extended','user_timezone')===false)
1160		{
1161			if ($just_check) return update_needed('Move user timezone info');
1162			if (!copy_user_timezone())
1163			{  // Error doing the transfer
1164				//$updateMessages[] = LAN_UPDATE_42;
1165				$log->logMessage(LAN_UPDATE_42, E_MESSAGE_ERROR);
1166				return FALSE;
1167			}
1168			//$updateMessages[] = LAN_UPDATE_41;
1169			$log->logMessage(LAN_UPDATE_41, E_MESSAGE_DEBUG);
1170		}
1171	}
1172
1173
1174	// Tables defined in core_sql.php to be RENAMED.
1175
1176
1177	// Next bit will be needed only by the brave souls who used an early CVS - probably delete before release
1178	if ($sql->isTable('rl_history') && !$sql->isTable('dblog'))
1179	{
1180		if ($just_check) return update_needed('Rename rl_history to dblog');
1181		$sql->gen('ALTER TABLE `'.MPREFIX.'rl_history` RENAME `'.MPREFIX.'dblog`');
1182		//$updateMessages[] = LAN_UPDATE_44;
1183		$log->logMessage(LAN_UPDATE_44, E_MESSAGE_DEBUG);
1184		catch_error($sql);
1185	}
1186
1187
1188
1189	//---------------------------------
1190	if ($sql->isTable('dblog') && !$sql->isTable('admin_log'))
1191	{
1192		if ($just_check) return update_needed('Rename dblog to admin_log');
1193		$sql->gen('ALTER TABLE `'.MPREFIX.'dblog` RENAME `'.MPREFIX.'admin_log`');
1194		catch_error($sql);
1195		//$updateMessages[] = LAN_UPDATE_43;
1196		$log->logMessage(LAN_UPDATE_43, E_MESSAGE_DEBUG);
1197	}
1198
1199
1200	if($sql->isTable('forum_t') && $sql->isEmpty('forum') && $sql->isEmpty('forum_t'))
1201	{
1202		if ($just_check) return update_needed('Empty forum tables need to be removed.');
1203		$obs_tables[] = 'forum_t';
1204		$obs_tables[] = 'forum';
1205
1206	}
1207
1208
1209	// Obsolete tables (list at top)
1210	$sql->mySQLtableList = false; // clear the cached table list.
1211	foreach ($obs_tables as $ot)
1212	{
1213		if ($sql->isTable($ot))
1214		{
1215			if ($just_check) return update_needed("Delete table: ".$ot);
1216
1217			$status = $sql->gen('DROP TABLE `'.MPREFIX.$ot.'`') ? E_MESSAGE_DEBUG : E_MESSAGE_ERROR;
1218			$log->logMessage(LAN_UPDATE_25.$ot, $status);
1219		}
1220	}
1221
1222
1223	// Tables where IP address field needs updating to accommodate IPV6
1224	// Set to varchar(45) - just in case something uses the IPV4 subnet (see http://en.wikipedia.org/wiki/IPV6#Notation)
1225	foreach ($ip_upgrade as $t => $f)
1226	{
1227	  if ($sql->isTable($t))
1228	  {		// Check for table - might add some core plugin tables in here
1229	    if ($field_info = ($sql->db_Field($t, $f, '', TRUE)))
1230	    {
1231		  if (strtolower($field_info['Type']) != 'varchar(45)')
1232		  {
1233            if ($just_check) return update_needed('Update IP address field '.$f.' in table '.$t);
1234			$status = $sql->gen("ALTER TABLE `".MPREFIX.$t."` MODIFY `{$f}` VARCHAR(45) NOT NULL DEFAULT '';") ? E_MESSAGE_DEBUG : E_MESSAGE_ERROR;
1235			$log->logMessage(LAN_UPDATE_26.$t.' - '.$f, $status);
1236			// catch_error($sql);
1237		  }
1238	    }
1239	    else
1240		{
1241			// Got a strange error here
1242		}
1243	  }
1244	}
1245
1246
1247
1248
1249
1250
1251
1252	// Obsolete prefs (list at top)
1253	// Intentionally do this last - we may check some of them during the update
1254	$accum = array();
1255	foreach ($obs_prefs as $p)
1256	{
1257	  if (isset($pref[$p]))
1258	  {
1259	    if ($just_check) return update_needed('Remove obsolete prefs');
1260		unset($pref[$p]);
1261		e107::getConfig()->remove($p);
1262		$do_save = true;
1263		$log->addDebug('Removed obsolete pref: '.$p);
1264	//	$accum[] = $p;
1265	  }
1266	}
1267
1268
1269
1270
1271
1272	/* -------------- Upgrade Entire Table Structure - Multi-Language Supported ----------------- */
1273	// ONLY ever add fields, never deletes.
1274
1275//	require_once(e_HANDLER."db_verify_class.php");
1276//	$dbv = new db_verify;
1277	$dbv = e107::getSingleton('db_verify', e_HANDLER."db_verify_class.php");
1278
1279	if($plugUpgradeReq = e107::getPlugin()->updateRequired())
1280	{
1281		$exclude =  array_keys($plugUpgradeReq); // search xxxxx_setup.php and check for 'upgrade_required()' == true.
1282		asort($exclude);
1283	}
1284	else
1285	{
1286		$exclude = false;
1287	}
1288
1289	$dbv->compareAll($exclude); // core & plugins, but not plugins calling for an update with xxxxx_setup.php
1290
1291	if(count($dbv->errors))
1292	{
1293		if ($just_check)
1294		{
1295			$mes = e107::getMessage();
1296		//	$mes->addDebug(print_a($dbv->errors,true));
1297			$log->addDebug(print_a($dbv->errors,true));
1298		//	return update_needed("Database Tables require updating."); //
1299		}
1300		else
1301		{
1302			$dbv->compileResults();
1303			$dbv->runFix(); // Fix entire core database structure and plugins too.
1304		}
1305	}
1306
1307	// print_a($dbv->results);
1308	// print_a($dbv->fixList);
1309
1310
1311	//TODO - send notification messages to Log.
1312
1313
1314	if($sql->field('page','page_theme') && $sql->gen("SELECT * FROM `#page` WHERE page_theme != '' AND menu_title = '' LIMIT 1"))
1315	{
1316		if ($just_check)
1317		{
1318			return update_needed("Pages/Menus Table requires updating.");
1319		}
1320
1321		if($sql->update('page',"menu_name = page_theme, menu_title = page_title, menu_text = page_text, menu_template='default', page_title = '', page_text = '' WHERE page_theme !='' AND menu_title = '' AND menu_text IS NULL "))
1322		{
1323			$sql->gen("ALTER TABLE `#page` DROP page_theme ");
1324			$mes = e107::getMessage();
1325			$log->addDebug("Successfully updated pages/menus table to new format. ");
1326		}
1327		else
1328		{
1329			$log->addDebug("FAILED to update pages/menus table to new format. ");
1330			//$sql->gen("ALTER TABLE `#page` DROP page_theme ");
1331		}
1332
1333	}
1334
1335	if($sql->field('plugin','plugin_releaseUrl'))
1336	{
1337		if ($just_check) return update_needed('plugin_releaseUrl is deprecated and needs to be removed. ');
1338		if($sql->gen("ALTER TABLE `#plugin` DROP `plugin_releaseUrl`"))
1339		{
1340			$log->addDebug("Successfully removed plugin_releaseUrl. ");
1341		}
1342
1343	}
1344
1345
1346	// --- Notify Prefs
1347
1348//	$notify_prefs = $sysprefs -> get('notify_prefs');
1349//	$notify_prefs = $eArrayStorage -> ReadArray($notify_prefs);
1350	e107::getCache()->clear_sys('Config');
1351
1352	$notify_prefs = e107::getConfig('notify',true,true)->getPref();
1353
1354	$nt_changed = 0;
1355	if(vartrue($notify_prefs['event']))
1356	{
1357		foreach ($notify_prefs['event'] as $e => $d)
1358		{
1359			if (isset($d['type']))
1360			{
1361				if ($just_check) return update_needed('Notify pref: '.$e.' outdated');
1362				switch ($d['type'])
1363				{
1364					case 'main' :
1365						$notify_prefs['event'][$e]['class'] = e_UC_MAINADMIN;
1366						break;
1367					case 'class' :		// Should already have class defined
1368						break;
1369					case 'email' :
1370						$notify_prefs['event'][$e]['class'] = 'email';
1371						break;
1372					case 'off' :		// Need to disable
1373					default :
1374						$notify_prefs['event'][$e]['class'] = e_UC_NOBODY;		// Just disable if we don't know what else to do
1375				}
1376				$nt_changed++;
1377				$notify_prefs['event'][$e]['legacy'] = 1;
1378				unset($notify_prefs['event'][$e]['type']);
1379			}
1380		}
1381	}
1382
1383	if ($nt_changed)
1384	{
1385		$s_prefs = $tp -> toDB($notify_prefs);
1386		$s_prefs = $eArrayStorage -> WriteArray($s_prefs);
1387		// Could we use $sysprefs->set($s_prefs,'notify_prefs') instead - avoids caching problems  ????
1388		$status = ($sql -> update("core", "e107_value='".$s_prefs."' WHERE e107_name='notify_prefs'") !== FALSE) ? E_MESSAGE_DEBUG : E_MESSAGE_ERROR;
1389		$message = str_replace('[x]',$nt_changed,LAN_UPDATE_20);
1390		$log->logMessage($message, $status);
1391	}
1392
1393
1394
1395
1396	if (isset($pref['forum_user_customtitle']) && !isset($pref['signup_option_customtitle']))
1397	{
1398		if ($just_check) return update_needed('pref: forum_user_customtitle needs to be renamed');
1399		//	$pref['signup_option_customtitle'] = $pref['forum_user_customtitle'];
1400		e107::getConfig()->add('signup_option_customtitle', $pref['forum_user_customtitle']);
1401		e107::getConfig()->remove('forum_user_customtitle');
1402
1403		$log->logMessage(LAN_UPDATE_20.'customtitle', E_MESSAGE_SUCCESS);
1404		$do_save = TRUE;
1405	}
1406
1407
1408	// ---------------  Saved emails - copy across
1409
1410	if (!$just_check && $sql->select('generic', '*', "gen_type='massmail'"))
1411	{
1412		if ($just_check) return update_needed('Copy across saved emails');
1413		require_once(e_HANDLER.'mail_manager_class.php');
1414		$mailHandler = new e107MailManager;
1415		$i = 0;
1416		while ($row = $sql->fetch())
1417		{
1418			$mailRecord = array(
1419				'mail_create_date' => $row['gen_datestamp'],
1420				'mail_creator' => $row['gen_user_id'],
1421				'mail_title' => $row['gen_ip'],
1422				'mail_subject' => $row['gen_ip'],
1423				'mail_body' => $row['gen_chardata'],
1424				'mail_content_status' => MAIL_STATUS_SAVED
1425			);
1426			$mailHandler->mailToDb($mailRecord, TRUE);
1427			$mailHandler->saveEmail($mailRecord, TRUE);
1428			$sql2->delete('generic', 'gen_id='.intval($row['gen_id']));		// Delete as we go in case operation fails part way through
1429			$i++;
1430		}
1431		unset($mailHandler);
1432		$log->logMessage(str_replace('[x]', $i, LAN_UPDATE_28));
1433	}
1434
1435
1436
1437
1438	// -------------------  Populate Plugin Table With Changes ------------------
1439
1440	if (!isset($pref['shortcode_legacy_list']))
1441	{
1442	  	if ($just_check) return update_needed('Legacy shortcode conversion');
1443	 	// Reset, legacy and new shortcode list will be generated in plugin update routine
1444	 // 	$pref['shortcode_legacy_list'] = array();
1445	// 	$pref['shortcode_list'] = array();
1446
1447	 	e107::getConfig()->add('shortcode_legacy_list', array());
1448		e107::getConfig()->set('shortcode_list', array());
1449		e107::getConfig()->save(false,true,false);
1450
1451	  	$ep = e107::getPlugin();
1452		$ep->update_plugins_table(); // scan for e_xxx changes and save to plugin table.
1453		$ep->save_addon_prefs(); // generate global e_xxx_list prefs from plugin table.
1454	}
1455
1456
1457
1458	// This has to be done after the table is upgraded
1459	if($sql->select('plugin', 'plugin_category', "plugin_category = ''"))
1460	{
1461		if ($just_check) return update_needed('Update plugin table');
1462		require_once(e_HANDLER.'plugin_class.php');
1463		$ep = new e107plugin;
1464		$ep->update_plugins_table('update');
1465	//	$_pdateMessages[] = LAN_UPDATE_XX24;
1466	 //	catch_error($sql);
1467	}
1468
1469
1470	//-- Media-manger import --------------------------------------------------
1471
1472
1473
1474	// Autogenerate filetypes.xml if not found.
1475	if(!is_readable(e_SYSTEM."filetypes.xml"))
1476	{
1477		$data = '<?xml version="1.0" encoding="utf-8"?>
1478<e107Filetypes>
1479	<class name="253" type="zip,gz,jpg,jpeg,png,gif,xml,pdf" maxupload="2M" />
1480</e107Filetypes>';
1481
1482		file_put_contents(e_SYSTEM."filetypes.xml",$data);
1483	}
1484
1485
1486
1487	$root_media = str_replace(basename(e_MEDIA)."/","",e_MEDIA);
1488	$user_media_dirs = array("images","avatars", "avatars/default", "avatars/upload", "files","temp","videos","icons");
1489
1490	// check for old paths and rename.
1491	if(is_dir($root_media."images") || is_dir($root_media."temp"))
1492	{
1493		foreach($user_media_dirs as $md)
1494		{
1495			@rename($root_media.$md,e_MEDIA.$md);
1496		}
1497	}
1498
1499	// create sub-directories if they do not exist.
1500	if(!is_dir(e_MEDIA."images") || !is_dir(e_MEDIA."temp") || !is_dir(e_AVATAR_UPLOAD) || !is_dir(e_AVATAR_DEFAULT) )
1501	{
1502		foreach($user_media_dirs as $md)
1503		{
1504			if(!is_dir(e_MEDIA.$md))
1505			{
1506				if(mkdir(e_MEDIA.$md)===false)
1507				{
1508					e107::getMessage()->addWarning("Unable to create ".e_MEDIA.$md.".");
1509				}
1510			}
1511		}
1512	}
1513
1514	// Move Avatars to new location
1515	$av1 = e107::getFile()->get_files(e_FILE.'public/avatars','.jpg|.gif|.png|.GIF|.jpeg|.JPG|.PNG');
1516	$av2 = e107::getFile()->get_files(e_IMAGE.'avatars','.jpg|.gif|.png|.GIF|.jpeg|.JPG|.PNG');
1517
1518	$avatar_images = array_merge($av1,$av2);
1519
1520	if(count($avatar_images))
1521	{
1522		if ($just_check) return update_needed('Avatar paths require updating.');
1523		foreach($avatar_images as $av)
1524		{
1525			$apath = (strstr($av['path'],'public/')) ? e_AVATAR_UPLOAD : e_AVATAR_DEFAULT;
1526
1527			if(rename($av['path'].$av['fname'], $apath. $av['fname'])===false)
1528			{
1529				e107::getMessage()->addWarning("Unable to more ".$av['path'].$av['fname']." to ".$apath. $av['fname'].". Please move manually.");
1530			}
1531		}
1532	}
1533
1534	// -------------------------------
1535
1536	if (!e107::isInstalled('download') && $sql->gen("SELECT * FROM #links WHERE link_url LIKE 'download.php%' AND link_class != '".e_UC_NOBODY."' LIMIT 1"))
1537	{
1538		if ($just_check) return update_needed('Download Plugin needs to be installed.');
1539	//	e107::getSingleton('e107plugin')->install('download',array('nolinks'=>true));
1540		e107::getSingleton('e107plugin')->refresh('download');
1541	}
1542
1543
1544
1545	if (!e107::isInstalled('banner') && $sql->isTable('banner'))
1546	{
1547		if ($just_check) return update_needed('Banner Table found, but plugin not installed. Needs to be refreshed.');
1548		e107::getSingleton('e107plugin')->refresh('banner');
1549	}
1550
1551	// ---------------------------------
1552
1553
1554	$med = e107::getMedia();
1555
1556	// Media Category Update
1557	if($sql->db_Field("core_media_cat","media_cat_nick"))
1558	{
1559		$count = $sql->gen("SELECT * FROM `#core_media_cat` WHERE media_cat_nick = '_common'  ");
1560		if($count ==1)
1561		{
1562			if ($just_check) return update_needed('Media-Manager Categories needs to be updated.');
1563			$sql->update('core_media_cat', "media_cat_owner = media_cat_nick, media_cat_category = media_cat_nick WHERE media_cat_nick REGEXP '_common|news|page|_icon_16|_icon_32|_icon_48|_icon_64' ");
1564			$sql->update('core_media_cat', "media_cat_owner = '_icon', media_cat_category = media_cat_nick WHERE media_cat_nick REGEXP '_icon_16|_icon_32|_icon_48|_icon_64' ");
1565			$sql->update('core_media_cat', "media_cat_owner = 'download', media_cat_category='download_image' WHERE media_cat_nick = 'download' ");
1566			$sql->update('core_media_cat', "media_cat_owner = 'download', media_cat_category='download_thumb' WHERE media_cat_nick = 'downloadthumb' ");
1567			$sql->update('core_media_cat', "media_cat_owner = 'news', media_cat_category='news_thumb' WHERE media_cat_nick = 'newsthumb' ");
1568			$log->addDebug("core-media-cat Categories and Ownership updated");
1569			if($sql->gen("ALTER TABLE `".MPREFIX."core_media_cat` DROP `media_cat_nick`"))
1570			{
1571				$log->addDebug("core-media-cat `media_cat_nick` field removed.");
1572			}
1573
1574	//		$query = "INSERT INTO `".MPREFIX."core_media_cat` (`media_cat_id`, `media_cat_owner`, `media_cat_category`, `media_cat_title`, `media_cat_diz`, `media_cat_class`, `media_cat_image`, `media_cat_order`) VALUES
1575	//		(0, 'gallery', 'gallery_1', 'Gallery 1', 'Visible to the public at /gallery.php', 0, '', 0);
1576	///		";
1577	//
1578	//		if(mysql_query($query))
1579	//		{
1580	//			$log->addDebug("Added core-media-cat Gallery.");
1581	//		}
1582		}
1583	}
1584
1585
1586	// Media Update
1587	$count = $sql->gen("SELECT * FROM `#core_media` WHERE media_category = 'newsthumb' OR media_category = 'downloadthumb'  LIMIT 1 ");
1588	if($count ==1)
1589	{
1590		if ($just_check) return update_needed('Media-Manager Data needs to be updated.');
1591		$sql->update('core_media', "media_category='download_image' WHERE media_category = 'download' ");
1592		$sql->update('core_media', "media_category='download_thumb' WHERE media_category = 'downloadthumb' ");
1593		$sql->update('core_media', "media_category='news_thumb' WHERE media_category = 'newsthumb' ");
1594		$log->addDebug("core-media Category names updated");
1595	}
1596
1597
1598	// Media Update - core media and core-file.
1599	/*
1600	$count = $sql->gen("SELECT * FROM `#core_media` WHERE media_category = '_common' LIMIT 1 ");
1601	if($count ==1)
1602	{
1603		if ($just_check) return update_needed('Media-Manager Category Data needs to be updated.');
1604		$sql->update('core_media', "media_category='_common_image' WHERE media_category = '_common' ");
1605		$log->addDebug("core-media _common Category updated");
1606	}
1607	*/
1608
1609
1610	// Media Update - core media and core-file. CATEGORY
1611	$count = $sql->gen("SELECT * FROM `#core_media_cat` WHERE media_cat_category = '_common' LIMIT 1 ");
1612	if($count ==1)
1613	{
1614		if ($just_check) return update_needed('Media-Manager Category Data needs to be updated.');
1615		$sql->update('core_media_cat', "media_cat_category='_common_image' WHERE media_cat_category = '_common' ");
1616		$sql->gen("INSERT INTO `".MPREFIX."core_media_cat` VALUES(0, '_common', '_common_file', '(Common Area)', 'Media in this category will be available in all areas of admin. ', 253, '', 0);");
1617		$sql->gen("INSERT INTO `".MPREFIX."core_media_cat` VALUES(0, 'download', 'download_file', 'Download Files', '', 253, '', 0);");
1618		$log->addDebug("core-media-cat _common Category updated");
1619	}
1620
1621	$count = $sql->gen("SELECT * FROM `#core_media_cat` WHERE `media_cat_owner` = '_common' LIMIT 1 ");
1622
1623	if($count != 1)
1624	{
1625		if ($just_check) return update_needed('Add Media-Manager Categories and Import existing images.');
1626
1627		$e107_core_media_cat = array(
1628		  	array('media_cat_id'=>0,'media_cat_owner'=>'_common','media_cat_category'=>'_common_image','media_cat_title'=>'(Common Images)','media_cat_sef'=>'','media_cat_diz'=>'Media in this category will be available in all areas of admin.','media_cat_class'=>'253','media_cat_image'=>'','media_cat_order'=>'0'),
1629		  	array('media_cat_id'=>0,'media_cat_owner'=>'_common','media_cat_category'=>'_common_file','media_cat_title'=>'(Common Files)','media_cat_sef'=>'','media_cat_diz'=>'Media in this category will be available in all areas of admin.','media_cat_class'=>'253','media_cat_image'=>'','media_cat_order'=>'0'),
1630		 	array('media_cat_id'=>0,'media_cat_owner'=>'news','media_cat_category'=>'news','media_cat_title'=>'News','media_cat_sef'=>'','media_cat_diz'=>'Will be available in the news area.','media_cat_class'=>'253','media_cat_image'=>'','media_cat_order'=>'1'),
1631		 	array('media_cat_id'=>0,'media_cat_owner'=>'page','media_cat_category'=>'page','media_cat_title'=>'Custom Pages','media_cat_sef'=>'','media_cat_diz'=>'Will be available in the custom pages area of admin.','media_cat_class'=>'253','media_cat_image'=>'','media_cat_order'=>'0'),
1632		  	array('media_cat_id'=>0,'media_cat_owner'=>'download','media_cat_category'=>'download_image','media_cat_title'=>'Download Images','media_cat_sef'=>'','media_cat_diz'=>'','media_cat_class'=>'253','media_cat_image'=>'','media_cat_order'=>'0'),
1633		  	array('media_cat_id'=>0,'media_cat_owner'=>'download','media_cat_category'=>'download_thumb','media_cat_title'=>'Download Thumbnails','media_cat_sef'=>'','media_cat_diz'=>'','media_cat_class'=>'253','media_cat_image'=>'','media_cat_order'=>'0'),
1634		  	array('media_cat_id'=>0,'media_cat_owner'=>'download','media_cat_category'=>'download_file','media_cat_title'=>'Download Files','media_cat_sef'=>'','media_cat_diz'=>'','media_cat_class'=>'253','media_cat_image'=>'','media_cat_order'=>'0'),
1635		  	array('media_cat_id'=>0,'media_cat_owner'=>'news','media_cat_category'=>'news_thumb','media_cat_title'=>'News Thumbnails (Legacy)','media_cat_sef'=>'','media_cat_diz'=>'Legacy news thumbnails.','media_cat_class'=>'253','media_cat_image'=>'','media_cat_order'=>'1'),
1636		);
1637
1638
1639		foreach($e107_core_media_cat as $insert)
1640		{
1641			$sql->insert('core_media_cat', $insert);
1642		}
1643
1644
1645
1646
1647	//	$sql->gen("INSERT INTO `".MPREFIX."core_media_cat` VALUES(0, '_common', '_common_image', '(Common Images)', '', 'Media in this category will be available in all areas of admin. ', 253, '', 1);");
1648	//	$sql->gen("INSERT INTO `".MPREFIX."core_media_cat` VALUES(0, '_common', '_common_file', '(Common Files)', '', 'Media in this category will be available in all areas of admin. ', 253, '', 2);");
1649
1650	//	$sql->gen("INSERT INTO `".MPREFIX."core_media_cat` VALUES(0, 'news', 'news', 'News', '', 'Will be available in the news area. ', 253, '', 3);");
1651	//	$sql->gen("INSERT INTO `".MPREFIX."core_media_cat` VALUES(0, 'page', 'page', 'Custom Pages', '', 'Will be available in the custom pages area of admin. ', 253, '', 4);");
1652
1653	//	$sql->gen("INSERT INTO `".MPREFIX."core_media_cat` VALUES(0, 'download', 'download_image','', 'Download Images', '', 253, '', 5);");
1654	//	$sql->gen("INSERT INTO `".MPREFIX."core_media_cat` VALUES(0, 'download', 'download_thumb', '', 'Download Thumbnails', '', 253, '', 6);");
1655	//	$sql->gen("INSERT INTO `".MPREFIX."core_media_cat` VALUES(0, 'download', 'download_file', '', 'Download Files', '', 253, '', 7);");
1656
1657	//	mysql_query("INSERT INTO `".MPREFIX."core_media_cat` VALUES(0, 'gallery', 'gallery_1', 'Gallery', 'Visible to the public at /gallery.php', 0, '', 0);");
1658
1659	//	$sql->gen("INSERT INTO `".MPREFIX."core_media_cat` VALUES(0, 'news', 'news_thumb', 'News Thumbnails (Legacy)', '', 'Legacy news thumbnails. ', 253, '', 8);");
1660
1661		$med->import('news_thumb', e_IMAGE.'newspost_images',"^thumb_");
1662		$med->import('news',e_IMAGE.'newspost_images');
1663		$med->import('page',e_IMAGE.'custom');
1664
1665	}
1666	else
1667	{
1668//		$log->addDebug("Media COUNT was ".$count. " LINE: ".__LINE__);
1669	}
1670
1671	// Check for Legacy Download Images.
1672
1673	$fl = e107::getFile();
1674	$dl_images = $fl->get_files(e_FILE.'downloadimages');
1675
1676	if(count($dl_images) && !$sql->gen("SELECT * FROM `#core_media` WHERE `media_category` = 'download_image' "))
1677	{
1678		if ($just_check) return update_needed('Import Download Images into Media Manager');
1679		$med->import('download_image',e_FILE.'downloadimages');
1680		$med->import('download_thumb',e_FILE.'downloadthumbs');
1681	}
1682
1683	$dl_files = $fl->get_files(e_FILE.'downloads', "","standard",5); // don't use e_DOWNLOAD or a loop may occur.
1684
1685
1686	$publicFilter = array('_FT', '^thumbs\.db$','^Thumbs\.db$','.*\._$','^\.htaccess$','^\.cvsignore$','^\.ftpquota$','^index\.html$','^null\.txt$','\.bak$','^.tmp'); // Default file filter (regex format)
1687//	$publicFilter = array(1);
1688	$public_files = $fl->get_files(e_FILE.'public','',$publicFilter);
1689
1690	if((count($dl_files) || count($public_files)) && !$sql->gen("SELECT * FROM `#core_media` WHERE `media_category` = 'download_file' OR  `media_category` = '_common_file' "))
1691	{
1692		if ($just_check) return update_needed('Import '.count($dl_files).' Download File(s) and '.count($public_files).' Public File(s) into Media Manager');
1693
1694		if($sql->gen("SELECT download_url FROM `#download` "))
1695		{
1696			$allowed_types = array();
1697
1698			while($row = $sql->fetch())
1699			{
1700				$ext = strrchr($row['download_url'], ".");
1701				$suffix = ltrim($ext,".");
1702
1703				if(!isset($allowed_types[$suffix]))
1704				{
1705					$allowed_types[$suffix] = $suffix;
1706				}
1707
1708			}
1709
1710			$allowed_types = array_unique($allowed_types);
1711		}
1712		else
1713		{
1714			$allowed_types = array('zip','gz','pdf');
1715		}
1716
1717		$fmask = '[a-zA-Z0-9_.-]+\.('.implode('|',$allowed_types).')$';
1718
1719		$med->import('download_file',e_DOWNLOAD, $fmask);
1720
1721		// add found Public file-types.
1722		foreach($public_files as $v)
1723		{
1724			$ext = strrchr($v['fname'], ".");
1725			$suffix = ltrim($ext,".");
1726			if(!isset($allowed_types[$suffix]))
1727			{
1728				$allowed_types[$suffix] = $suffix;
1729			}
1730		}
1731
1732		$publicFmask = '[a-zA-Z0-9_.-]+\.('.implode('|',$allowed_types).')$';
1733		$med->import('_common_file', e_FILE.'public', $publicFmask);
1734	}
1735
1736
1737
1738
1739	$count = $sql->gen("SELECT * FROM `#core_media_cat` WHERE media_cat_owner='_icon'  ");
1740
1741	if(!$count)
1742	{
1743		if ($just_check) return update_needed('Add icons to media-manager');
1744
1745		$query = "INSERT INTO `".MPREFIX."core_media_cat` (`media_cat_id`, `media_cat_owner`, `media_cat_category`, `media_cat_title`, `media_cat_diz`, `media_cat_class`, `media_cat_image`, `media_cat_order`) VALUES
1746		(0, '_icon', '_icon_16', 'Icons 16px', 'Available where icons are used in admin. ', 253, '', 0),
1747		(0, '_icon', '_icon_32', 'Icons 32px', 'Available where icons are used in admin. ', 253, '', 0),
1748		(0, '_icon', '_icon_48', 'Icons 48px', 'Available where icons are used in admin. ', 253, '', 0),
1749		(0, '_icon', '_icon_64', 'Icons 64px', 'Available where icons are used in admin. ', 253, '', 0);
1750		";
1751
1752		if(!$sql->gen($query))
1753		{
1754			// echo "mysyql error";
1755		 	// error or already exists.
1756		}
1757
1758		$med->importIcons(e_PLUGIN);
1759		$med->importIcons(e_IMAGE."icons/");
1760		$med->importIcons(e_THEME.$pref['sitetheme']."/images/");
1761		$log->addDebug("Icon category added");
1762	}
1763
1764	// Search Clean up ----------------------------------
1765
1766	$searchPref = e107::getConfig('search');
1767
1768	if($searchPref->getPref('core_handlers/news'))
1769	{
1770		if ($just_check) return update_needed('Core search handlers need to be updated.');
1771		$searchPref->removePref('core_handlers/news')->save(false,true,false);
1772	}
1773
1774	if($searchPref->getPref('core_handlers/downloads'))
1775	{
1776		if ($just_check) return update_needed('Core search handlers need to be updated.');
1777		$searchPref->removePref('core_handlers/downloads')->save(false,true,false);
1778	}
1779
1780	if($searchPref->getPref('core_handlers/pages'))
1781	{
1782		if ($just_check) return update_needed('Core search handlers need to be updated.');
1783		$searchPref->removePref('core_handlers/pages')->save(false,true,false);
1784		e107::getSingleton('e107plugin')->refresh('page');
1785	}
1786
1787	// Clean up news keywords. - remove spaces between commas.
1788	if($sql->select('news', 'news_id', "news_meta_keywords LIKE '%, %' LIMIT 1"))
1789	{
1790		if ($just_check) return update_needed('News keywords contain spaces between commas and needs to be updated. ');
1791		$sql->update('news', "news_meta_keywords = REPLACE(news_meta_keywords, ', ', ',')");
1792	}
1793
1794
1795
1796
1797	// Any other images should be imported manually via Media Manager batch-import.
1798
1799	// ------------------------------------------------------------------
1800
1801	// Check that custompages have been imported from current theme.php file
1802
1803
1804
1805	if (!$just_check)  // Running the Upgrade Process.
1806	{
1807
1808		if(!is_array($pref['sitetheme_layouts']) || !vartrue($pref['sitetheme_deflayout']))
1809		{
1810			$th = e107::getSingleton('themeHandler');
1811			$tmp = $th->getThemeInfo($pref['sitetheme']);
1812			if($th->setTheme($pref['sitetheme'], false))
1813			{
1814				$log->addDebug("Updated SiteTheme prefs");
1815			}
1816			else
1817			{
1818				$log->addDebug("Couldn't update SiteTheme prefs");
1819			}
1820		}
1821
1822		$log->toFile('upgrade_v1_to_v2');
1823
1824
1825		if ($do_save)
1826		{
1827		//	save_prefs();
1828			e107::getConfig()->setPref($pref)->save(false,true,false);
1829		//	$log->logMessage(LAN_UPDATE_50);
1830		//	$log->logMessage(implode(', ', $accum), E_MESSAGE_NODISPLAY);
1831			//$updateMessages[] = LAN_UPDATE_50.implode(', ',$accum); 	// Note for admin log
1832		}
1833
1834		$log->flushMessages('UPDATE_01');		// Write admin log entry, update message handler
1835
1836	}
1837	else
1838	{
1839		$log->toFile('upgrade_v1_to_v2_check');
1840
1841	}
1842
1843
1844
1845
1846
1847
1848
1849	//FIXME grab message-stack from $log for the log.
1850
1851	//if ($just_check) return TRUE;
1852
1853
1854
1855
1856
1857	//e107::getLog()->add('UPDATE_01',LAN_UPDATE_14.$e107info['e107_version'].'[!br!]'.implode('[!br!]',$updateMessages),E_LOG_INFORMATIVE,'');	// Log result of actual update
1858	return $just_check;
1859}
1860
1861/* No Longed Used I think
1862function core_media_import($cat,$epath)
1863{
1864	if(!vartrue($cat)){ return;}
1865
1866	if(!is_readable($epath))
1867	{
1868		return;
1869	}
1870
1871	$fl = e107::getFile();
1872	$tp = e107::getParser();
1873	$sql = e107::getDb();
1874	$mes = e107::getMessage();
1875
1876	$fl->setFileInfo('all');
1877	$img_array = $fl->get_files($epath,'','',2);
1878
1879	if(!count($img_array)){ return;}
1880
1881	foreach($img_array as $f)
1882	{
1883		$fullpath = $tp->createConstants($f['path'].$f['fname'],1);
1884
1885		$insert = array(
1886		'media_caption'		=> $f['fname'],
1887		'media_description'	=> '',
1888		'media_category'	=> $cat,
1889		'media_datestamp'	=> $f['modified'],
1890		'media_url'	=> $fullpath,
1891		'media_userclass'	=> 0,
1892		'media_name'	=> $f['fname'],
1893		'media_author'	=> USERID,
1894		'media_size'	=> $f['fsize'],
1895		'media_dimensions'	=> $f['img-width']." x ".$f['img-height'],
1896		'media_usedby'	=> '',
1897		'media_tags'	=> '',
1898		'media_type'	=> $f['mime']
1899		);
1900
1901		if(!$sql->db_Select('core_media','media_url',"media_url = '".$fullpath."' LIMIT 1"))
1902		{
1903			if($sql->db_Insert("core_media",$insert))
1904			{
1905				$mes->add("Importing Media: ".$f['fname'], E_MESSAGE_SUCCESS);
1906			}
1907		}
1908	}
1909}
1910*/
1911
1912function update_70x_to_706($type='')
1913{
1914
1915	global $sql,$ns, $pref, $e107info, $admin_log, $emessage;
1916
1917	$just_check = $type == 'do' ? FALSE : TRUE;
1918	if(!$sql->db_Field("plugin",5))  // not plugin_rss so just add the new one.
1919	{
1920	  if ($just_check) return update_needed();
1921      $sql->gen("ALTER TABLE `".MPREFIX."plugin` ADD `plugin_addons` TEXT NOT NULL ;");
1922	  catch_error($sql);
1923	}
1924
1925	//rename plugin_rss field
1926	if($sql->db_Field("plugin",5) == "plugin_rss")
1927	{
1928	  if ($just_check) return update_needed();
1929	  $sql->gen("ALTER TABLE `".MPREFIX."plugin` CHANGE `plugin_rss` `plugin_addons` TEXT NOT NULL;");
1930	  catch_error($sql);
1931	}
1932
1933
1934	if($sql->db_Field("dblog",5) == "dblog_query")
1935	{
1936      if ($just_check) return update_needed();
1937	  $sql->gen("ALTER TABLE `".MPREFIX."dblog` CHANGE `dblog_query` `dblog_title` VARCHAR( 255 ) NOT NULL DEFAULT '';");
1938	  catch_error($sql);
1939	  $sql->gen("ALTER TABLE `".MPREFIX."dblog` CHANGE `dblog_remarks` `dblog_remarks` TEXT NOT NULL;");
1940	  catch_error($sql);
1941	}
1942
1943	if(!$sql->db_Field("plugin","plugin_path","UNIQUE"))
1944	{
1945      if ($just_check) return update_needed();
1946      if(!$sql->gen("ALTER TABLE `".MPREFIX."plugin` ADD UNIQUE (`plugin_path`);"))
1947	  {
1948		$mesg = LAN_UPDATE_12." : <a href='".e_ADMIN."db.php?plugin'>".ADLAN_145."</a>.";
1949        //$ns -> tablerender(LAN_ERROR,$mes);
1950        e107::getMessage()->add($mesg, E_MESSAGE_ERROR);
1951       	catch_error($sql);
1952	  }
1953	}
1954
1955	if(!$sql->db_Field("online",6)) // online_active field
1956	{
1957	  if ($just_check) return update_needed();
1958	  $sql->gen("ALTER TABLE ".MPREFIX."online ADD online_active INT(10) UNSIGNED NOT NULL DEFAULT '0'");
1959	  catch_error($sql);
1960	}
1961
1962	if ($sql -> db_Query("SHOW INDEX FROM ".MPREFIX."tmp"))
1963	{
1964	  $row = $sql -> db_Fetch();
1965	  if (!in_array('tmp_ip', $row))
1966	  {
1967		if ($just_check) return update_needed();
1968		$sql->gen("ALTER TABLE `".MPREFIX."tmp` ADD INDEX `tmp_ip` (`tmp_ip`);");
1969		$sql->gen("ALTER TABLE `".MPREFIX."upload` ADD INDEX `upload_active` (`upload_active`);");
1970		$sql->gen("ALTER TABLE `".MPREFIX."generic` ADD INDEX `gen_type` (`gen_type`);");
1971	  }
1972	}
1973
1974	if (!$just_check)
1975	{
1976		// update new fields
1977        require_once(e_HANDLER."plugin_class.php");
1978		$ep = new e107plugin;
1979		$ep->update_plugins_table('update');
1980		$ep->save_addon_prefs('update');
1981	}
1982
1983	if (!isset($pref['displayname_maxlength']))
1984	{
1985	  if ($just_check) return update_needed();
1986	  $pref['displayname_maxlength'] = 15;
1987	  save_prefs();
1988	}
1989
1990
1991	// If we get to here, in checking mode no updates are required. In update mode, all done.
1992	if ($just_check) return TRUE;
1993	e107::getLog()->add('UPDATE_02',LAN_UPDATE_14.$e107info['e107_version'],E_LOG_INFORMATIVE,'');	// Log result of actual update
1994	return $just_check;		// TRUE if no updates needed, FALSE if updates needed and completed
1995
1996}
1997
1998
1999
2000/**
2001 *	Carries out the copy of timezone data from the user record to an extended user field
2002 *	@return boolean TRUE on success, FALSE on failure
2003 */
2004function copy_user_timezone()
2005{
2006	$sql = e107::getDb();
2007	$sql2 = e107::getDb('sql2');
2008	$tp = e107::getParser();
2009
2010	// require_once(e_HANDLER.'user_extended_class.php');
2011	$ue = e107::getUserExt();
2012	$tmp = $ue->parse_extended_xml('getfile');
2013
2014	$tmp['timezone']['parms'] = $tp->toDB($tmp['timezone']['parms']);
2015
2016	if(!$ue->user_extended_add($tmp['timezone']))
2017	{
2018		e107::getMessage()->addError("Unable to add user_timezone field to user_extended table.");
2019		return false;
2020	}
2021
2022	if($sql->field('user_extended', 'user_timezone')===false)
2023	{
2024		e107::getMessage()->addError("user_timezone field missing from user_extended table.");
2025		return false;
2026	}
2027
2028	e107::getMessage()->addDebug("Line:".__LINE__);
2029	// Created the field - now copy existing data
2030	if ($sql->db_Select('user','user_id, user_timezone'))
2031	{
2032		while ($row = $sql->db_Fetch())
2033		{
2034			$sql2->update('user_extended',"`user_timezone`='{$row['user_timezone']}' WHERE `user_extended_id`={$row['user_id']}");
2035		}
2036	}
2037	return true;		// All done!
2038}
2039
2040
2041
2042
2043function update_needed($message='')
2044{
2045
2046	if(E107_DEBUG_LEVEL)
2047	{
2048		$tmp = debug_backtrace();
2049		//$ns->tablerender("", "<div style='text-align:center'>Update required in ".basename(__FILE__)." on line ".$tmp[0]['line']."</div>");
2050		e107::getMessage()->add("Update required in ".basename(__FILE__)." on line ".$tmp[0]['line']." (".$message.")", E_MESSAGE_DEBUG);
2051	}
2052	return FALSE;
2053}
2054
2055
2056
2057
2058/**
2059 *	Add index to a table. Returns FALSE if not required. Returns a message if required and just checking
2060 *
2061 *	@todo - get rid of $updateMessages parameter once log/message display method finalised, call the relevant method
2062 */
2063function addIndexToTable($target, $indexSpec, $just_check, &$updateMessages, $optionalTable=FALSE)
2064{
2065	global $sql;
2066	if (!$sql->isTable($target))
2067	{
2068		if ($optionalTable)
2069		{
2070			return !$just_check;		// Nothing to do it table is optional and not there
2071		}
2072		$updateMessages[] = str_replace(array('[y]','[x]'),array($target,$indexSpec),LAN_UPDATE_54);
2073		return !$just_check;		// No point carrying on - return 'nothing to do'
2074	}
2075	if ($sql->gen("SHOW INDEX FROM ".MPREFIX.$target))
2076	{
2077		$found = FALSE;
2078		while ($row = $sql -> db_Fetch())
2079		{		// One index per field
2080			if (in_array($indexSpec, $row))
2081			{
2082				return !$just_check;		// Found - nothing to do
2083			}
2084		}
2085		// Index not found here
2086		if ($just_check)
2087		{
2088			return 'Required to add index to '.$target;
2089		}
2090		$sql->gen("ALTER TABLE `".MPREFIX.$target."` ADD INDEX `".$indexSpec."` (`".$indexSpec."`);");
2091		$updateMessages[] = str_replace(array('[y]','[x]'),array($target,$indexSpec),LAN_UPDATE_37);
2092	}
2093	return FALSE;
2094}
2095
2096
2097/**	Check for database access errors
2098 *	@param object e_db $target - pointer to db object
2099 *	@return null
2100 */
2101function catch_error(&$target)
2102{
2103	if (vartrue($target->getLastErrorText()) && E107_DEBUG_LEVEL != 0)
2104	{
2105		$tmp2 = debug_backtrace();
2106		$tmp = $target->getLastErrorText();
2107		echo $tmp." [ ".basename(__FILE__)." on line ".$tmp2[0]['line']."] <br />";
2108	}
2109	return null;
2110}
2111
2112
2113function get_default_prefs()
2114{
2115	e107::getDebug()->log("Retrieving default prefs from xml file");
2116	$xmlArray = e107::getSingleton('xmlClass')->loadXMLfile(e_CORE."xml/default_install.xml",'advanced');
2117	$pref = e107::getSingleton('xmlClass')->e107ImportPrefs($xmlArray,'core');
2118	return $pref;
2119}
2120
2121function convert_serialized($serializedData, $type='')
2122{
2123	$arrayData = unserialize($serializedData);
2124	$data = e107::serialize($arrayData,FALSE);
2125	return $data;
2126}
2127
2128function theme_foot()
2129{
2130	global $pref;
2131
2132	if(!empty($_POST['update_core']['706_to_800']))
2133	{
2134		$data = array('name'=>SITENAME, 'theme'=>$pref['sitetheme'], 'language'=>e_LANGUAGE, 'url'=>SITEURL, 'type'=>'upgrade');
2135		$base = base64_encode(http_build_query($data, null, '&'));
2136		$url = "https://e107.org/e-install/".$base;
2137		return "<img src='".$url."' style='width:1px; height:1px;border:0' />";
2138	}
2139
2140}
2141
2142?>
2143