Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 354 lines (298 sloc) 10.708 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
<?php /*

ocPortal
Copyright (c) ocProducts, 2004-2012

See text/EN/licence.txt for full licencing information.


NOTE TO PROGRAMMERS:
Do not edit this file. If you need to make changes, save your changed file to the appropriate *_custom folder
**** If you ignore this advice, then your website upgrades (e.g. for bug fixes) will likely kill your changes ****

*/

/**
* Script to handle XML DB/MySQL chain synching.
*/
function xml_dump_script()
{
// Run checks and set up chain DB
if (get_db_type()!='xml') warn_exit('It makes no sense to run this script if you are not running the XML database driver.');
global $SITE_INFO;
if (array_key_exists('db_chain_type',$SITE_INFO))
{
require_code('database/'.$SITE_INFO['db_chain_type']);
$chain_db=new database_driver($SITE_INFO['db_chain'],$SITE_INFO['db_chain_host'],$SITE_INFO['db_chain_user'],$SITE_INFO['db_chain_password'],get_table_prefix(),false,object_factory('Database_Static_'.$SITE_INFO['db_chain_type']));
} else
{
warn_exit('It makes no sense to run this script if you have not set up the following config options in info.php: db_chain_type, db_chain_host, db_chain_user, db_chain_password, db_chain');
}
$chain_connection=&$chain_db->connection_write;
if (count($chain_connection)>4) // Okay, we can't be lazy anymore
{
$chain_connection=call_user_func_array(array($chain_db->static_ob,'db_get_connection'),$chain_connection);
_general_db_init();
}

if (function_exists('set_time_limit')) @set_time_limit(0);
$GLOBALS['DEBUG_MODE']=false;
$GLOBALS['SEMI_DEBUG_MODE']=false;

@ini_set('ocproducts.xss_detect','0');

if (strtolower(ocp_srv('REQUEST_METHOD'))=='get') // Interface
{
$from=get_param('from',NULL);
$skip=get_param('skip',NULL);
$only=get_param('only',NULL);

echo '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>XML/MySQL DB syncher</title>
</head>
<body>
';

echo '<p>Select the tables to sync below. Tables have been auto-ticked based on what seems to need re-synching.</p>';
$keep=symbol_tempcode('KEEP',array('1'));
echo '<form title="Choose tables" method="post" action="'.escape_html(find_script('xml_db_import').$keep->evaluate()).'">';

$tables=array_keys(find_all_tables($GLOBALS['SITE_DB']));
$mysql_status=list_to_map('Name',$chain_db->query('SHOW TABLE STATUS'));
$mysql_tables=array_keys($mysql_status);
foreach ($tables as $table_name)
{
$default_selected=
(((!is_null($from)) && ($table_name>=$from)) ||
((!is_null($only)) && (in_array($table_name,explode(',',$only))))) &&
((!is_null($skip)) || (!in_array($table_name,explode(',',$skip))))
;

$missing=!in_array(get_table_prefix().$table_name,$mysql_tables);
$count_mismatch=!$missing && $chain_db->query_value($table_name,'COUNT(*)')!=$GLOBALS['SITE_DB']->query_value($table_name,'COUNT(*)');
$date_mismatch=false;
if ((!$missing) && (!$count_mismatch))
{
$last_m_time=NULL;
$path=get_custom_file_base().'/uploads/website_specific/'.get_db_site().'/'.get_table_prefix().$table_name;
$dh=@opendir($path);
if ($dh!==false)
{
while (($f=readdir($dh))!==false)
{
if ((substr($f,-4)=='.dat') || (substr($f,-4)=='.xml'))
$last_m_time=@max($last_m_time,filemtime($path.'/'.$f)); // @ because of the 255 read filepath limit on Windows
}
closedir($dh);
}
if (!is_null($last_m_time))
{
$mysql_time=strtotime($mysql_status[get_table_prefix().$table_name]['Update_time']);
$date_mismatch=($mysql_time<$last_m_time); // We can't do "!=" as last m-time for MySQL could well by the last sync time
}
}

$needs_doing=$count_mismatch || $date_mismatch || $missing || $default_selected;

echo '
<div style="width: 500px">
<span style="float: right; font-style: italic">
'.($missing?'[table is missing]':'').'
'.($count_mismatch?'[different record-counts]':'').'
'.($date_mismatch?'[different last-modified-time]':'').'
</span>

<input '.(($needs_doing)?'checked="checked" ':'').'type="checkbox" name="table_'.htmlentities($table_name).'" id="table_'.htmlentities($table_name).'" value="1" />
<label for="table_'.htmlentities($table_name).'">'.htmlentities($table_name).'</label>
</div>
';
}

echo '<p><input type="submit" value="Sync" /> &nbsp;&nbsp;&nbsp;&nbsp; [<a href="#" onclick="var form=document.getElementsByTagName(\'form\')[0]; for (var i=0;i&lt;form.elements.length;i++) if (form.elements[i].checked) form.elements[i].checked=false; return false;">un-tick all</a>]</p>';
echo '</form>';

echo '
</body>
</html>
';

exit();
}

// Actualiser

$from=NULL;
$skip=NULL;
$only='';
foreach (array_keys($_POST) as $key)
{
if (substr($key,0,6)=='table_')
{
if ($only!='') $only.=',';
$only.=substr($key,6);
}
}
if ($only=='') $only=NULL;


@header('Content-type: text/plain');
@ob_end_clean();

$sql=get_sql_dump(true,true,$from,is_null($skip)?array():explode(',',$skip),is_null($only)?NULL:explode(',',$only));

$cnt=count($sql);
foreach ($sql as $i=>$s)
{
print('Executing query '.strval($i+1).'/'.strval($cnt).' ... '.$s."\n\n");
flush();

$fail_ok=(substr($s,0,5)=='ALTER');
$chain_db->static_ob->db_query($s,$chain_connection,NULL,NULL,$fail_ok,false);
}

print('!!Done!!');
}

/**
* Get a list of the defines tables.
*
* @param object Database connection to look in
* @return array The tables
*/
function find_all_tables($db)
{
$fields=$db->query_select('db_meta',array('m_table','m_name','m_type'),NULL,'ORDER BY m_table');
$tables=array();
foreach ($fields as $field)
{
if (!isset($tables[$field['m_table']])) $tables[$field['m_table']]=array();
$tables[$field['m_table']][$field['m_name']]=$field['m_type'];
}
$tables['db_meta']=array('m_table'=>'*ID_TEXT','m_name'=>'*ID_TEXT','m_type'=>'ID_TEXT');
$tables['db_meta_indices']=array('i_table'=>'*ID_TEXT','i_name'=>'*ID_TEXT','i_fields'=>'*ID_TEXT');

ksort($tables);

return $tables;
}

/**
* Get MySQL SQL code for the currently loaded database.
*
* @param boolean Whether to include 'DROP' statements
* @param boolean Whether to output status as we go
* @param ?ID_TEXT Table to look from (NULL: first table)
* @param ?array Array of table names to skip (NULL: none)
* @param ?array Array of only table names to do (NULL: all)
* @return array The SQL statements
*/
function get_sql_dump($include_drops=false,$output_statuses=false,$from=NULL,$skip=NULL,$only=NULL)
{
if (is_null($skip)) $skip=array();

$tables=find_all_tables($GLOBALS['SITE_DB']);

$out=array();

// Tables
foreach ($tables as $table_name=>$fields)
{
if ((!is_null($from)) && ($table_name<$from)) continue;
if (in_array($table_name,$skip)) continue;
if ((!is_null($only)) && (!in_array($table_name,$only))) continue;

if ($output_statuses)
{
print('Working out SQL for table: '.$table_name."\n");
flush();
}

if ($include_drops)
{
$out[]='DROP TABLE IF EXISTS '.get_table_prefix().$table_name.';';
}

$out[]=db_create_table($table_name,$fields);

// Data
$data=$GLOBALS['SITE_DB']->query_select($table_name,array('*'),NULL,'',NULL,NULL,false,array());
foreach ($data as $map)
{
$keys='';
$all_values=array();

foreach ($map as $key=>$value)
{
if ($keys!='') $keys.=', ';
$keys.=$key;

$_value=(!is_array($value))?array($value):$value;

$v=mixed();
foreach ($_value as $i=>$v)
{
if (!array_key_exists($i,$all_values)) $all_values[$i]='';
$values=$all_values[$i];

if ($values!='') $values.=', ';

if (is_null($value))
{
$values.='NULL';
}
else
{
if (is_float($v)) $values.=float_to_raw_string($v);
elseif (is_integer($v)) $values.=strval($v);
else $values.='\''.db_escape_string($v).'\'';
}

$all_values[$i]=$values; // essentially appends, as $values was loaded from former $all_values[$i] value
}
}

$out[]='INSERT INTO '.get_table_prefix().$table_name.' ('.$keys.') VALUES ('.$all_values[0].')'.";";
}
}

// Indexes
$indexes=$GLOBALS['SITE_DB']->query_select('db_meta_indices',array('*'));
foreach ($indexes as $index)
{
$index_name=$index['i_name'];
if ($index_name[0]=='#')
{
$index_name=substr($index_name,1);
$type='FULLTEXT';
} else $type='INDEX';
$out[]='ALTER TABLE '.get_table_prefix().$index['i_table'].' ADD '.$type.' '.$index_name.' ('.$index['i_fields'].')'.";";
}

return $out;
}

/**
* Get a map of ocPortal field types, to actual mySQL types.
*
* @return array The map
*/
function db_get_type_remap()
{
$type_remap=array(
'AUTO'=>'integer unsigned auto_increment',
'AUTO_LINK'=>'integer', // not unsigned because it's useful to have -ve for temporary usage whilst importing
'INTEGER'=>'integer',
'UINTEGER'=>'integer unsigned',
'SHORT_INTEGER'=>'tinyint',
'REAL'=>'real',
'BINARY'=>'tinyint(1)',
'USER'=>'integer', // not unsigned because it's useful to have -ve for temporary usage whilst importing
'GROUP'=>'integer', // not unsigned because it's useful to have -ve for temporary usage whilst importing
'TIME'=>'integer unsigned',
'LONG_TRANS'=>'integer unsigned',
'SHORT_TRANS'=>'integer unsigned',
'SHORT_TEXT'=>'varchar(255)',
'LONG_TEXT'=>'longtext',
'ID_TEXT'=>'varchar(80)',
'MINIID_TEXT'=>'varchar(40)',
'IP'=>'varchar(40)', // 15 for ip4, but we now support ip6
'LANGUAGE_NAME'=>'varchar(5)',
'URLPATH'=>'varchar(255)',
'MD5'=>'varchar(33)'
);
return $type_remap;
}

/**
* Create a new table.
*
* @param ID_TEXT The table name
* @param array A map of field names to ocPortal field types (with *#? encodings)
* @return string The SQL for it
*/
function db_create_table($table_name,$fields)
{
$type_remap=db_get_type_remap();

/*if (multi_lang()==0)
{
$type_remap['LONG_TRANS']=$type_remap['LONG_TEXT'];
$type_remap['SHORT_TRANS']=$type_remap['SHORT_TEXT'];
}*/

$_fields='';
$keys='';
foreach ($fields as $name=>$type)
{
if ($type[0]=='*') // Is a key
{
$type=substr($type,1);
if ($keys!='') $keys.=', ';
$keys.=$name;
}

if ($type[0]=='?') // Is perhaps null
{
$type=substr($type,1);
$perhaps_null='NULL';
} else $perhaps_null='NOT NULL';

$type=$type_remap[$type];

$_fields.=' '.$name.' '.$type.' '.$perhaps_null.','.chr(10);
}

$query='CREATE TABLE '.get_table_prefix().$table_name.' (
'.$_fields.'
PRIMARY KEY ('.$keys.')
) type='.('MyISAM').';';
return $query;
}
Something went wrong with that request. Please try again.