File: patchutils.php

package info (click to toggle)
opendb 0.81p18-2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 4,716 kB
  • ctags: 6,787
  • sloc: php: 50,213; sql: 3,098; sh: 272; makefile: 54; xml: 48
file content (482 lines) | stat: -rw-r--r-- 14,952 bytes parent folder | download
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
<?php
/* 	OpenDb - Open Media Lending Database
	Copyright (C) 2001,2002 by Jason Pell

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program 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.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

include_once("./functions/database.php");
include_once("./functions/logging.php");
include_once("./functions/fileutils.php");
include_once("./functions/utils.php");

/**
	simple function to return substring prefix of string
*/
function excerpt($message, $length)
{
	if( $length<=0 ) $length = 20;

	// only show the first $length characters of msg	
	$text = substr($message, 0, $length);

 	// append eplisis if cut short	
	if( strlen($message)>$length ) $text = $text."...";
	
	return $text;
}

function get_patch_file_list($from, $ext)
{
	return get_file_list("./patch/$from", $ext);
}

/**
 * A _slightly_ modified version of this function from phpMyAdmin
 *
 * Note: This function is a little slow, but the benefit is, that you can correctly
 * process a sql file where statements are not necessarily formatted in a consistent manner!
 *
 * Removes comment lines and splits up large sql files into individual queries
 *
 * Last revision: September 23, 2001 - gandon
 *
 * @param   array    the splitted sql commands
 * @param   string   the sql commands
 *
 * @return  boolean  always true
 *
 * @access  public
 */
function split_sql_file($sql, &$pieces)
{
	// Quick hack to support end of file comments!
	$sql			= trim($sql)."\n";
    $sql_len		= strlen($sql);
    $char			= '';
    $string_start	= '';
    $in_string		= FALSE;

    for ($i = 0; $i < $sql_len; ++$i) {
        $char = $sql[$i];

        // We are in a string, check for not escaped end of strings except for
        // backquotes that can't be escaped
        if ($in_string) {
            for (;;) {
                $i         = strpos($sql, $string_start, $i);
                // No end of string found -> add the current substring to the
                // returned array
                if (!$i) {
                    $pieces[] = $sql;
                    return TRUE;
                }
                // Backquotes or no backslashes before quotes: it's indeed the
                // end of the string -> exit the loop
                else if ($string_start == '`' || $sql[$i-1] != '\\') {
                    $string_start      = '';
                    $in_string         = FALSE;
                    break;
                }
                // one or more Backslashes before the presumed end of string...
                else {
                    // ... first checks for escaped backslashes
                    $j                     = 2;
                    $escaped_backslash     = FALSE;
                    while ($i-$j > 0 && $sql[$i-$j] == '\\') {
                        $escaped_backslash = !$escaped_backslash;
                        $j++;
                    }
                    // ... if escaped backslashes: it's really the end of the
                    // string -> exit the loop
                    if ($escaped_backslash) {
                        $string_start  = '';
                        $in_string     = FALSE;
                        break;
                    }
                    // ... else loop
                    else {
                        $i++;
                    }
                } // end if...elseif...else
            } // end for
        } // end if (in string)

        // We are not in a string, first check for delimiter...
        else if ($char == ';') {
            // if delimiter found, add the parsed part to the returned array

            $pieces[]	= substr($sql, 0, $i);
            $sql        = ltrim(substr($sql, min($i + 1, $sql_len)));
            $sql_len    = strlen($sql);
            if ($sql_len) {
                $i      = -1;
            } else {
                // The submited statement(s) end(s) here
                return TRUE;
            }
        } // end else if (is delimiter)

        // ... then check for start of a string,...
        else if (($char == '"') || ($char == '\'') || ($char == '`')) {
            $in_string    = TRUE;
            $string_start = $char;
        } // end else if (is start of string)

        // ... for start of a comment (and remove this comment if found)...
        else if ($char == '#'
                 || ($char == ' ' && $i > 1 && $sql[$i-2] . $sql[$i-1] == '--')) {
			// starting position of the comment depends on the comment type
            $start_of_comment = (($sql[$i] == '#') ? $i : $i-2);
            // if no "\n" exists in the remaining string, checks for "\r"
            // (Mac eol style)
			$end_of_comment   = (strpos(' ' . $sql, "\012", $i+2))
                              ? strpos(' ' . $sql, "\012", $i+2)
                              : strpos(' ' . $sql, "\015", $i+2);

			if (!$end_of_comment) {
                // no eol found after '#', add the parsed part to the returned
                // array and exit
                $pieces[] = trim(substr($sql, 0, $i-1));
                return TRUE;
            } else {
                $sql     = substr($sql, 0, $start_of_comment)
                         . ltrim(substr($sql, $end_of_comment));
                $sql_len = strlen($sql);
                $i--;
            } // end if...else
        } // end else if (is comment)
    } // end for

    // add any rest to the returned array
    if (strlen($sql)>0 && ereg('[^[:space:]]+', $sql)) {
        $pieces[] = $sql;
    }

	// Return array of sql lines.
    return $pieces;
} // end of the 'split_sql_file()' function

//Stub for old functionality.
function exec_sql($sqltext, $do_prefix=TRUE){ exec_patch_sql($sqltext, $do_prefix);}
function exec_sql_file($sqltext, $do_prefix=TRUE){ exec_patch_sql_file($sqltext, $do_prefix);}
function print_sql_file($from, $filename){ echo_patch_sql_file($from, $filename);}

/**
	Evaluate each of the sql statements $sql.  The $sql will first be split up
	into individual statements for easier processing.
*/
function exec_patch_sql($sqltext, $do_prefix=TRUE)
{
	global $CONFIG_VARS;

	$queries = array();
	split_sql_file($sqltext, $queries);

	while (list(,$sql) = each($queries))
	{
		exec_patch_sql_statement($sql, $do_prefix);
	}

	echo( "<p><div class=\"success\">Done!</div></p>");
}

function exec_patch_sql_statement($sql, $do_prefix=TRUE)
{
	global $CONFIG_VARS;
	
	// Do it this way, so we can actually display the prefix SQL statement
	// in the output.
	if($do_prefix && strlen($CONFIG_VARS['db_server.table_prefix'])>0)
		$sql = parse_sql_statement($sql, $CONFIG_VARS['db_server.table_prefix']);

	// display query to screen
	echo("<div class=\"code\"><pre>".htmlspecialchars($sql).";</pre></div>\n");
		
	// evaluate query - We have already prefixed above, so no need to do again!
	$result = run_opendb_query($sql, FALSE);
	if($result)
	{
		echo( "<div class=\"upgrade_success\">SQL query evaluated successfully (".mysql_affected_rows()." Rows affected).</div>\n" );
		return TRUE;
	}
	else
	{
		$errno = mysql_errno();
		// Duplicate Entry!
		if($errno == 1062)
			echo( "<div class=\"upgrade_warning\">Row already exists.</div>\n" );
		else
			echo( "<div class=\"upgrade_failure\">SQL query evaluation failed. (".mysql_error().")</div>\n" );
			
		return FALSE;
	}
}

/**
	Loads the $filename from patch/$from/ directory and calls exec_sql($text) on the 
	contents.  This function and the exec_sql(...) one will display results of
	queries executed.
*/
function exec_patch_sql_file($from, $filename, $do_prefix=TRUE)
{
	$sqlfile = "./patch/$from/$filename";

	echo("<p class=\"querytitle\">Evaluating SQL queries for <i>$filename</i></p>");

	$errors = "";
	$sqltext = read_file_contents($sqlfile, $errors);
	if($sqltext===FALSE)
	{
		echo ("<div class=\"error\">Error loading $filename&nbsp;&nbsp;$errors</div>");
		return FALSE;
	}

	// evaulate the sql contents of this textfile
	exec_patch_sql($sqltext, $do_prefix);
}

/**
	Will display queries as they appear in the script, will
	not attempt to prefix, as this is only a print SQL
	operation.
*/
function echo_patch_sql_file($from, $filename)
{
	$sqlfile = "./patch/$from/$filename";

	echo("<p class=\"querytitle\">Printing SQL queries for <i>$filename</i></p>");

	$errors = "";
	$lines = @file($sqlfile);
	if(!$lines)
	{
		echo ("<div class=\"error\">Error loading $filename&nbsp;&nbsp;$errors</DIV>");
		return false;
	}

	while (list(,$line) = each($lines))
	{
		if(strlen(trim($line))===0)
			echo("<br>");
		else
		{
			if(strpos($line,"#") === 0)
				echo( "<div class=\"code\"><b>$line</b></div>\n" );
			else
			{
				echo( "<div class=\"code\">$line</div>");
			}
		}
	}
}

// stub
function check_table($table, $do_prefix=TRUE, $alt_db_server=NULL)
{
	return check_opendb_table($table, $do_prefix, $alt_db_server);
}

/**
	Check if a given table exists or not
*/
function check_opendb_table($table, $do_prefix=TRUE, $alt_db_server=NULL)
{
	// In this case the run_opendb_query() would return FALSE, if
    // table does not exist.
	$result = run_opendb_query("SELECT 'x' FROM $table LIMIT 0,1", $do_prefix, $alt_db_server);
	if($result)	
	{
		mysql_free_result($result);

		// The table exists (Does not have to have any records!)
		return TRUE;
	}

	//else
	return FALSE;
}

/**
	Check if a table has any records.
*/
function count_opendb_table_rows($table, $do_prefix=TRUE, $alt_db_server=NULL)
{
	// Only get one row, to save processing them.
	$result = run_opendb_query("SELECT count(*) as count FROM $table", $do_prefix, $alt_db_server);
	// In this case the run_opendb_query() would return FALSE, if table does not exist.
	if($result)
	{
		if(mysql_num_rows($result)>0)
		{
			$found = mysql_fetch_array($result, MYSQL_ASSOC);
			mysql_free_result($result);
			if ($found !== FALSE)
			{
				return (int)$found['count'];// So that === will evaluate successfully!
			}
		}
		else
		{
			mysql_free_result($result);
			return 0;
		}
	}
	
	//else
	return FALSE;
}

/**
	count the number fields in table
*/
function count_opendb_table_columns($table, $do_prefix=TRUE, $alt_db_server=NULL)
{
	$result = run_opendb_query("SELECT * FROM $table LIMIT 0,1", $do_prefix, $alt_db_server);
	if($result)
	{
		// count fields (columns) in table
		return mysql_num_fields($result);
	}
	
	//else
	return FALSE;
}

/**
**/
function is_exists_opendb_database(&$mysql_error)
{
	// from config.php
	global $CONFIG_VARS;
	
	$link = @mysql_connect($CONFIG_VARS['db_server.host'],
   				$CONFIG_VARS['db_server.username'],
   				$CONFIG_VARS['db_server.passwd']);
				
	if($link)
	{
		if(@mysql_select_db($CONFIG_VARS['db_server.dbname'], $link))
		{
			return TRUE;
		}
		else
		{
			$mysql_error = mysql_error();
			return FALSE;
		}
	}
	else
	{
		$mysql_error = mysql_error();
		return FALSE;
	}
}

/**
* Will check the database to make sure its up to date.  The checks
* will include:
* 	Does the database actually exist
* 	Are all the any tables in the database
* 	Are the system tables populated
* 
* @return	"INSTALL" - New install required
* @return	"PARTIAL_INSTALL" - Installation has missing tables
* @return	TRUE - if all up to date
*/
function is_opendb_upto_date()
{
	// lists all core tables in current OpenDb release.
	$_OPENDB_CORE_TABLE_LIST = array(
				array(name=>'user', column_cnt=>8, default_records_installed=>FALSE),
				array(name=>'user_address', column_cnt=>6, default_records_installed=>FALSE),
				array(name=>'user_address_attribute', column_cnt=>6, default_records_installed=>FALSE),
				array(name=>'review', column_cnt=>6, default_records_installed=>FALSE),
				array(name=>'item', column_cnt=>5, default_records_installed=>FALSE),
				array(name=>'item_instance', column_cnt=>7, default_records_installed=>FALSE),
				array(name=>'item_attribute', column_cnt=>6, default_records_installed=>FALSE),
				array(name=>'borrowed_item', column_cnt=>8, default_records_installed=>FALSE),
				array(name=>'s_item_type', column_cnt=>4, default_records_installed=>TRUE),
				array(name=>'s_item_type_group', column_cnt=>3, default_records_installed=>TRUE),
				array(name=>'s_item_type_group_rltshp', column_cnt=>2, default_records_installed=>TRUE),
				array(name=>'s_attribute_type', column_cnt=>7, default_records_installed=>TRUE),
				array(name=>'s_attribute_type_lookup', column_cnt=>6, default_records_installed=>TRUE),
				array(name=>'s_item_attribute_type', column_cnt=>5, default_records_installed=>TRUE),
				array(name=>'s_status_type', column_cnt=>15, default_records_installed=>TRUE),
				array(name=>'s_address_type', column_cnt=>7, default_records_installed=>TRUE),
				array(name=>'s_addr_attribute_type_rltshp', column_cnt=>8, default_records_installed=>TRUE),
				array(name=>'s_site_plugin', column_cnt=>9, default_records_installed=>FALSE),
				array(name=>'s_site_plugin_conf', column_cnt=>5, default_records_installed=>FALSE),
				array(name=>'s_site_plugin_input_field', column_cnt=>8, default_records_installed=>FALSE),
				array(name=>'s_site_plugin_s_attribute_type_map', column_cnt=>6, default_records_installed=>FALSE),
				array(name=>'s_site_plugin_s_attribute_type_lookup_map', column_cnt=>5, default_records_installed=>FALSE),
				array(name=>'s_site_plugin_link', column_cnt=>8, default_records_installed=>FALSE),
				array(name=>'import_cache', column_cnt=>4, default_records_installed=>FALSE),
				array(name=>'file_cache', column_cnt=>10, default_records_installed=>FALSE),
			);
		
 	$tableFound = FALSE;
 	$tableNotFound = FALSE;
 	$sysRecordsNotFound = FALSE;
	$tablesNotUpgraded = FALSE;
 	
	while(list(, $table_r) = each($_OPENDB_CORE_TABLE_LIST))
 	{
 		$result = count_opendb_table_rows($table_r['name']);
 		if($result === FALSE)
 		{
 			$tableNotFound = TRUE;
 		}
 		else 
 		{
			$tableFound = TRUE;
			
 			// yep table exists, and has records
 			if($result > 0)
 			{
				if($table_r['column_cnt'] != count_opendb_table_columns($table_r['name']))
				{
					$tablesNotUpgraded = TRUE;
				}
			}
			else // $result === 0
			{
				if($table_r['default_records_installed']!==FALSE)
 				{
 					$sysRecordsNotFound = TRUE;
 				}
 			}
 		}
 	}
 	
 	if($tableFound && $tableNotFound)
 	{
 		return "PARTIAL_INSTALL";
 	}
 	else if($tableNotFound)
 	{
 		return "INSTALL";
 	}
 	else if($sysRecordsNotFound || $tablesNotUpgraded)
 	{
 		return "PARTIAL_INSTALL";
 	}
 	else
 	{
 		// as far as we can tell, you have a full installation.
 		return TRUE;
 	}
}
?>