Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 843 lines (785 sloc) 24.476 kB
667bfec Decomposition
jakubvrana authored
1 <?php
9a176b0 Comments
jakubvrana authored
2 /** Get database connection
3 * @return Min_DB
4 */
64d616c Rename get_dbh to connection
jakubvrana authored
5 function connection() {
6 // can be used in customization, $connection is minified
7 global $connection;
8 return $connection;
c64c4fd Adminer class
jakubvrana authored
9 }
10
9a176b0 Comments
jakubvrana authored
11 /** Unescape database identifier
12 * @param string text inside ``
13 * @return string
14 */
667bfec Decomposition
jakubvrana authored
15 function idf_unescape($idf) {
a29ac72 Improve drivers
jakubvrana authored
16 $last = substr($idf, -1);
17 return str_replace($last . $last, $last, substr($idf, 1, -1));
667bfec Decomposition
jakubvrana authored
18 }
19
5e01a62 Prepare for SQLite
jakubvrana authored
20 /** Escape string to use inside ''
21 * @param string
22 * @return string
23 */
24 function escape_string($val) {
7e644b4 @vrana Save bytes ($connection->quote shortcut)
authored
25 return substr(q($val), 1, -1);
5e01a62 Prepare for SQLite
jakubvrana authored
26 }
27
72f4d9e @vrana Function parse_str respects magic_quotes_gpc (bug #3034575)
authored
28 /** Disable magic_quotes_gpc
29 * @param array e.g. (&$_GET, &$_POST, &$_COOKIE)
30 * @return null modified in place
31 */
32 function remove_slashes($process) {
33 if (get_magic_quotes_gpc()) {
34 while (list($key, $val) = each($process)) {
35 foreach ($val as $k => $v) {
36 unset($process[$key][$k]);
37 if (is_array($v)) {
38 $process[$key][stripslashes($k)] = $v;
39 $process[] = &$process[$key][stripslashes($k)];
40 } else {
41 $process[$key][stripslashes($k)] = ($filter ? $v : stripslashes($v));
42 }
43 }
44 }
45 }
46 }
47
9a176b0 Comments
jakubvrana authored
48 /** Escape or unescape string to use inside form []
49 * @param string
50 * @param bool
51 * @return string
52 */
667bfec Decomposition
jakubvrana authored
53 function bracket_escape($idf, $back = false) {
64ba924 Comments
jakubvrana authored
54 // escape brackets inside name="x[]"
73e8631 Move stuff to functions.inc.php
jakubvrana authored
55 static $trans = array(':' => ':1', ']' => ':2', '[' => ':3');
667bfec Decomposition
jakubvrana authored
56 return strtr($idf, ($back ? array_flip($trans) : $trans));
57 }
58
9a176b0 Comments
jakubvrana authored
59 /** Escape for HTML
60 * @param string
61 * @return string
62 */
689699a Shortcut for htmlspecialchars
jakubvrana authored
63 function h($string) {
64 return htmlspecialchars($string, ENT_QUOTES);
65 }
66
9a176b0 Comments
jakubvrana authored
67 /** Escape for TD
68 * @param string
69 * @return string
70 */
c196985 Function nbsp
jakubvrana authored
71 function nbsp($string) {
7352c28 Replace strlen() by != ""
jakubvrana authored
72 return (trim($string) != "" ? h($string) : "&nbsp;");
c196985 Function nbsp
jakubvrana authored
73 }
74
3f5b683 Reintegrate sqlite branch
jakubvrana authored
75 /** Convert \n to <br>
76 * @param string
77 * @return string
78 */
79 function nl_br($string) {
80 return str_replace("\n", "<br>", $string); // nl2br() uses XHTML before PHP 5.3
81 }
82
6b30cfa Separate checkbox
jakubvrana authored
83 /** Generate HTML checkbox
84 * @param string
85 * @param string
86 * @param bool
87 * @param string
88 * @param string
89 * @return string
90 */
91 function checkbox($name, $value, $checked, $label = "", $onclick = "") {
c4fe12a Clickable labels in IE6
jakubvrana authored
92 static $id = 0;
93 $id++;
3f5b683 Reintegrate sqlite branch
jakubvrana authored
94 $return = "<input type='checkbox'" . ($name ? " name='$name' value='" . h($value) . "'" : "") . ($checked ? " checked" : "") . ($onclick ? " onclick=\"$onclick\"" : "") . " id='checkbox-$id'>";
7352c28 Replace strlen() by != ""
jakubvrana authored
95 return ($label != "" ? "<label for='checkbox-$id'>$return" . h($label) . "</label>" : $return);
6b30cfa Separate checkbox
jakubvrana authored
96 }
97
9a176b0 Comments
jakubvrana authored
98 /** Generate list of HTML options
99 * @param array array of strings or arrays (creates optgroup)
100 * @param mixed
101 * @param bool always use array keys for value="", otherwise only string keys are used
102 * @return string
103 */
1e4d11e Select from foreign keys in Editor
jakubvrana authored
104 function optionlist($options, $selected = null, $use_keys = false) {
667bfec Decomposition
jakubvrana authored
105 $return = "";
106 foreach ($options as $k => $v) {
107 if (is_array($v)) {
689699a Shortcut for htmlspecialchars
jakubvrana authored
108 $return .= '<optgroup label="' . h($k) . '">';
667bfec Decomposition
jakubvrana authored
109 }
ced9de9 Create single column foreign key in table structure
jakubvrana authored
110 foreach ((is_array($v) ? $v : array($k => $v)) as $key => $val) {
cb6d36c HTML instead of XHTML
jakubvrana authored
111 $return .= '<option' . ($use_keys || is_string($key) ? ' value="' . h($key) . '"' : '') . (($use_keys || is_string($key) ? (string) $key : $val) === $selected ? ' selected' : '') . '>' . h($val);
667bfec Decomposition
jakubvrana authored
112 }
113 if (is_array($v)) {
114 $return .= '</optgroup>';
115 }
116 }
117 return $return;
118 }
119
098b74b Move function
jakubvrana authored
120 /** Generate HTML radio list
121 * @param string
122 * @param array
123 * @param string
124 * @param string true for no onchange, false for radio
125 * @return string
126 */
127 function html_select($name, $options, $value = "", $onchange = true) {
128 if ($onchange) {
129 return "<select name='" . h($name) . "'" . (is_string($onchange) ? " onchange=\"$onchange\"" : "") . ">" . optionlist($options, $value) . "</select>";
130 }
131 $return = "";
132 foreach ($options as $key => $val) {
133 $return .= "<label><input type='radio' name='" . h($name) . "' value='" . h($key) . "'" . ($key == $value ? " checked" : "") . ">" . h($val) . "</label>";
134 }
135 return $return;
136 }
137
a93bc19 @vrana Create confirm function
authored
138 /** Get onclick confirmation
139 * @param string JavaScript expression
b7cd652 @vrana No AJAX in drop table, drop database and logout
authored
140 * @param bool stop event propagation
a93bc19 @vrana Create confirm function
authored
141 * @return string
142 */
b7cd652 @vrana No AJAX in drop table, drop database and logout
authored
143 function confirm($count = "", $stop = false) {
144 return " onclick=\"" . ($stop ? "eventStop(event); " : "") . "return confirm('" . lang('Are you sure?') . ($count ? " (' + $count + ')" : "") . "');\"";
a93bc19 @vrana Create confirm function
authored
145 }
146
28f21aa @vrana Escape JavaScript strings (bug #3093243)
authored
147 /** Escape string for JavaScript apostrophes
148 * @param string
149 * @return string
150 */
151 function js_escape($string) {
152 return addcslashes($string, "\r\n'\\/"); // slash for <script>
153 }
154
3f5b683 Reintegrate sqlite branch
jakubvrana authored
155 /** Get INI boolean value
156 * @param string
157 * @return bool
158 */
159 function ini_bool($ini) {
160 $val = ini_get($ini);
161 return (eregi('^(on|true|yes)$', $val) || (int) $val); // boolean values set by php_value are strings
162 }
163
f30fd12 @vrana Work without session.use_cookies (bug #3138640)
authored
164 /** Check if SID is neccessary
165 * @return bool
166 */
167 function sid() {
876af58 @vrana Fix sid function
authored
168 static $return;
169 if (!isset($return)) { // restart_session() defines SID
170 $return = (SID && !($_COOKIE && ini_bool("session.use_cookies"))); // $_COOKIE - don't pass SID with permanent login
171 }
172 return $return;
f30fd12 @vrana Work without session.use_cookies (bug #3138640)
authored
173 }
174
175 /** Shortcut for $connection->quote($string)
176 * @param string
177 * @return string
178 */
7e644b4 @vrana Save bytes ($connection->quote shortcut)
authored
179 function q($string) {
180 global $connection;
181 return $connection->quote($string);
182 }
183
9a176b0 Comments
jakubvrana authored
184 /** Get list of values from database
185 * @param string
186 * @param mixed
187 * @return array
188 */
0bd864e Allow specifying column in get_vals
jakubvrana authored
189 function get_vals($query, $column = 0) {
64d616c Rename get_dbh to connection
jakubvrana authored
190 global $connection;
7769f2c Separate get_vals
jakubvrana authored
191 $return = array();
64d616c Rename get_dbh to connection
jakubvrana authored
192 $result = $connection->query($query);
b84252f Display SQLite compile options
jakubvrana authored
193 if (is_object($result)) {
49f7886 SHOW DATABASES can be revoked
jakubvrana authored
194 while ($row = $result->fetch_row()) {
0bd864e Allow specifying column in get_vals
jakubvrana authored
195 $return[] = $row[$column];
49f7886 SHOW DATABASES can be revoked
jakubvrana authored
196 }
7769f2c Separate get_vals
jakubvrana authored
197 }
198 return $return;
199 }
200
3f5b683 Reintegrate sqlite branch
jakubvrana authored
201 /** Get keys from first column and values from second
202 * @param string
203 * @param Min_DB
204 * @return array
205 */
206 function get_key_vals($query, $connection2 = null) {
207 global $connection;
208 if (!is_object($connection2)) {
209 $connection2 = $connection;
210 }
211 $return = array();
212 $result = $connection2->query($query);
213 while ($row = $result->fetch_row()) {
214 $return[$row[0]] = $row[1];
215 }
216 return $return;
217 }
218
b0d637b @vrana Avoid fatal errors
authored
219 /** Get all rows of result
220 * @param string
221 * @return array associative
222 */
96544ba @vrana Report errors in get_rows()
authored
223 function get_rows($query, $connection2 = null, $error = "<p class='error'>") {
b0d637b @vrana Avoid fatal errors
authored
224 global $connection;
225 if (!is_object($connection2)) {
226 $connection2 = $connection;
227 }
228 $return = array();
229 $result = $connection2->query($query);
230 if (is_object($result)) { // can return true
231 while ($row = $result->fetch_assoc()) {
232 $return[] = $row;
233 }
850d1aa @vrana Report errors only
authored
234 } elseif (!$result && $connection->error && $error && defined("PAGE_HEADER")) {
96544ba @vrana Report errors in get_rows()
authored
235 echo $error . error() . "\n";
b0d637b @vrana Avoid fatal errors
authored
236 }
237 return $return;
238 }
239
9a176b0 Comments
jakubvrana authored
240 /** Find unique identifier of a row
241 * @param array
242 * @param array result of indexes()
35ec64c Link COUNT(*) result to listing
jakubvrana authored
243 * @return array
9a176b0 Comments
jakubvrana authored
244 */
35ec64c Link COUNT(*) result to listing
jakubvrana authored
245 function unique_array($row, $indexes) {
720f5fc Restructure indexes
jakubvrana authored
246 foreach ($indexes as $index) {
4b3d569 Save bytes
jakubvrana authored
247 if (ereg("PRIMARY|UNIQUE", $index["type"])) {
720f5fc Restructure indexes
jakubvrana authored
248 $return = array();
249 foreach ($index["columns"] as $key) {
64ba924 Comments
jakubvrana authored
250 if (!isset($row[$key])) { // NULL is ambiguous
720f5fc Restructure indexes
jakubvrana authored
251 continue 2;
667bfec Decomposition
jakubvrana authored
252 }
35ec64c Link COUNT(*) result to listing
jakubvrana authored
253 $return[$key] = $row[$key];
667bfec Decomposition
jakubvrana authored
254 }
720f5fc Restructure indexes
jakubvrana authored
255 return $return;
667bfec Decomposition
jakubvrana authored
256 }
257 }
258 $return = array();
259 foreach ($row as $key => $val) {
26c9d64 Fix long SQL query crash (bug #2839231)
jakubvrana authored
260 if (!preg_match('~^(COUNT\\((\\*|(DISTINCT )?`(?:[^`]|``)+`)\\)|(AVG|GROUP_CONCAT|MAX|MIN|SUM)\\(`(?:[^`]|``)+`\\))$~', $key)) { //! columns looking like functions
35ec64c Link COUNT(*) result to listing
jakubvrana authored
261 $return[$key] = $val;
988a29f Don't use aggregation functions in unique_idf
jakubvrana authored
262 }
430034c Cottage homework
jakubvrana authored
263 }
264 return $return;
265 }
266
9a176b0 Comments
jakubvrana authored
267 /** Create SQL condition from parsed query string
268 * @param array parsed query string
269 * @return string
270 */
9ea3112 Mandatory $where in where()
jakubvrana authored
271 function where($where) {
1a8d7f1 @vrana Use LIKE for text comparison in MS SQL (bug #3088222)
authored
272 global $jush;
430034c Cottage homework
jakubvrana authored
273 $return = array();
341362a Driver specific INSERT INTO
jakubvrana authored
274 foreach ((array) $where["where"] as $key => $val) {
66ff153 Use bracket_escape function
jakubvrana authored
275 $return[] = idf_escape(bracket_escape($key, 1)) // 1 - back
1a8d7f1 @vrana Use LIKE for text comparison in MS SQL (bug #3088222)
authored
276 . (ereg('\\.', $val) || $jush == "mssql" ? " LIKE " . exact_value(addcslashes($val, "%_")) : " = " . exact_value($val)) // LIKE because of floats, but slow with ints, in MS SQL because of text
66ff153 Use bracket_escape function
jakubvrana authored
277 ; //! enum and set
341362a Driver specific INSERT INTO
jakubvrana authored
278 }
279 foreach ((array) $where["null"] as $key) {
280 $return[] = idf_escape($key) . " IS NULL";
667bfec Decomposition
jakubvrana authored
281 }
c16c57b E-mail sending
jakubvrana authored
282 return implode(" AND ", $return);
667bfec Decomposition
jakubvrana authored
283 }
284
9a176b0 Comments
jakubvrana authored
285 /** Create SQL condition from query string
286 * @param string
287 * @return string
288 */
0cd2afb Remove single item clone
jakubvrana authored
289 function where_check($val) {
290 parse_str($val, $check);
72f4d9e @vrana Function parse_str respects magic_quotes_gpc (bug #3034575)
authored
291 remove_slashes(array(&$check));
0cd2afb Remove single item clone
jakubvrana authored
292 return where($check);
293 }
294
9a176b0 Comments
jakubvrana authored
295 /** Create query string where condition from value
296 * @param int condition order
297 * @param string column identifier
298 * @param string
299 * @return string
186c058 Utilize where_link function
jakubvrana authored
300 * @return string
9a176b0 Comments
jakubvrana authored
301 */
186c058 Utilize where_link function
jakubvrana authored
302 function where_link($i, $column, $value, $operator = "=") {
303 return "&where%5B$i%5D%5Bcol%5D=" . urlencode($column) . "&where%5B$i%5D%5Bop%5D=" . urlencode($operator) . "&where%5B$i%5D%5Bval%5D=" . urlencode($value);
c42c46a Table relations
jakubvrana authored
304 }
305
319cba4 Save e-mail from to cookie
jakubvrana authored
306 /** Set cookie valid for 1 month
307 * @param string
308 * @param string
309 * @return bool
310 */
311 function cookie($name, $value) {
2cec758 @vrana Direct links from HTTPS to HTTP
authored
312 global $HTTPS;
3f5b683 Reintegrate sqlite branch
jakubvrana authored
313 $params = array(
314 $name,
315 (ereg("\n", $value) ? "" : $value), // HTTP Response Splitting protection in PHP < 5.1.2
316 time() + 2592000, // 2592000 - 30 days
317 preg_replace('~\\?.*~', '', $_SERVER["REQUEST_URI"]),
318 "",
2cec758 @vrana Direct links from HTTPS to HTTP
authored
319 $HTTPS
3f5b683 Reintegrate sqlite branch
jakubvrana authored
320 );
c2334db Secure cookies
jakubvrana authored
321 if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
322 $params[] = true; // HttpOnly
323 }
324 return call_user_func_array('setcookie', $params);
319cba4 Save e-mail from to cookie
jakubvrana authored
325 }
326
f9a2023 Improve concurrency
jakubvrana authored
327 /** Restart stopped session
328 * @return null
329 */
330 function restart_session() {
3f5b683 Reintegrate sqlite branch
jakubvrana authored
331 if (!ini_bool("session.use_cookies")) {
f9a2023 Improve concurrency
jakubvrana authored
332 session_start();
333 }
334 }
335
3f5b683 Reintegrate sqlite branch
jakubvrana authored
336 /** Get session variable for current server
337 * @param string
338 * @return mixed
339 */
340 function &get_session($key) {
341 return $_SESSION[$key][DRIVER][SERVER][$_GET["username"]];
342 }
343
344 /** Set session variable for current server
345 * @param string
346 * @param mixed
347 * @return mixed
348 */
349 function set_session($key, $val) {
350 $_SESSION[$key][DRIVER][SERVER][$_GET["username"]] = $val; // used also in auth.inc.php
351 }
352
605b093 @vrana List authentications
authored
353 /** Get authenticated URL
354 * @param string
355 * @param string
356 * @param string
357 * @return string
358 */
359 function auth_url($driver, $server, $username) {
360 global $drivers;
361 preg_match('~([^?]*)\\??(.*)~', remove_from_uri(implode("|", array_keys($drivers)) . "|username|" . session_name()), $match);
362 return "$match[1]?"
f30fd12 @vrana Work without session.use_cookies (bug #3138640)
authored
363 . (sid() ? SID . "&" : "")
605b093 @vrana List authentications
authored
364 . ($driver != "server" || $server != "" ? urlencode($driver) . "=" . urlencode($server) . "&" : "")
365 . "username=" . urlencode($username)
366 . ($match[2] ? "&$match[2]" : "")
367 ;
368 }
369
390e38b @vrana Load long texts for inline-edit by AJAX
authored
370 /** Find whether it is an AJAX request
371 * @return bool
372 */
373 function is_ajax() {
38894b2 @vrana Send all forms by AJAX
authored
374 return ($_SERVER["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest" || $_GET["ajax"]);
390e38b @vrana Load long texts for inline-edit by AJAX
authored
375 }
376
9a176b0 Comments
jakubvrana authored
377 /** Send Location header and exit
9bb1909 Fix Save and continue edit
jakubvrana authored
378 * @param string null to only set a message
9a176b0 Comments
jakubvrana authored
379 * @param string
380 * @return null
381 */
430034c Cottage homework
jakubvrana authored
382 function redirect($location, $message = null) {
383 if (isset($message)) {
be49e08 Improve session restarting
jakubvrana authored
384 restart_session();
ff74bf0 Allow multiple messages
jakubvrana authored
385 $_SESSION["messages"][] = $message;
430034c Cottage homework
jakubvrana authored
386 }
de24145 @vrana Clear POST with AJAX redirect
authored
387 if (isset($location)) {
b535853 @vrana Full AJAX only with pushState to work correctly with history
authored
388 if ($location == "") {
389 $location = ".";
390 }
38894b2 @vrana Send all forms by AJAX
authored
391 header("Location: $location" . (is_ajax() ? (strpos($location, "?") !== false ? "&" : "?") . "ajax=1" : ""));
392 exit;
9bb1909 Fix Save and continue edit
jakubvrana authored
393 }
430034c Cottage homework
jakubvrana authored
394 }
395
9a176b0 Comments
jakubvrana authored
396 /** Execute query and redirect if successful
397 * @param string
398 * @param string
399 * @param string
400 * @param bool
401 * @param bool
402 * @param bool
403 * @return bool
404 */
748ee83 Print SQL command with multiple queries
jakubvrana authored
405 function query_redirect($query, $location, $message, $redirect = true, $execute = true, $failed = false) {
64d616c Rename get_dbh to connection
jakubvrana authored
406 global $connection, $error, $adminer;
f9a2023 Improve concurrency
jakubvrana authored
407 if ($execute) {
408 $failed = !$connection->query($query);
409 }
10bdbed Save queries to history
jakubvrana authored
410 $sql = "";
411 if ($query) {
c64c4fd Adminer class
jakubvrana authored
412 $sql = $adminer->messageQuery($query);
10bdbed Save queries to history
jakubvrana authored
413 }
748ee83 Print SQL command with multiple queries
jakubvrana authored
414 if ($failed) {
c1130ed Simplify SQL syntax errors everywhere
jakubvrana authored
415 $error = error() . $sql;
c48a017 Print SQL query by error
jakubvrana authored
416 return false;
f91b2c4 Print SQL query by message
jakubvrana authored
417 }
c48a017 Print SQL query by error
jakubvrana authored
418 if ($redirect) {
419 redirect($location, $message . $sql);
420 }
421 return true;
f91b2c4 Print SQL query by message
jakubvrana authored
422 }
423
9a176b0 Comments
jakubvrana authored
424 /** Execute and remember query
425 * @param string null to return remembered queries
426 * @return Min_Result
427 */
748ee83 Print SQL command with multiple queries
jakubvrana authored
428 function queries($query = null) {
64d616c Rename get_dbh to connection
jakubvrana authored
429 global $connection;
748ee83 Print SQL command with multiple queries
jakubvrana authored
430 static $queries = array();
431 if (!isset($query)) {
64ba924 Comments
jakubvrana authored
432 // return executed queries without parameter
36950eb Tables and views
jakubvrana authored
433 return implode(";\n", $queries);
748ee83 Print SQL command with multiple queries
jakubvrana authored
434 }
435 $queries[] = $query;
64d616c Rename get_dbh to connection
jakubvrana authored
436 return $connection->query($query);
748ee83 Print SQL command with multiple queries
jakubvrana authored
437 }
438
f9bb1c5 @vrana Introduce apply_queries function
authored
439 /** Apply command to all array items
440 * @param string
441 * @param array
442 * @param callback
443 * @return bool
444 */
445 function apply_queries($query, $tables, $escape = 'table') {
446 foreach ($tables as $table) {
447 if (!queries("$query " . $escape($table))) {
448 return false;
449 }
450 }
451 return true;
452 }
453
dbdd40a Introduce queries_redirect function
jakubvrana authored
454 /** Redirect by remembered queries
455 * @param string
456 * @param string
457 * @param bool
52b9820 @vrana Comment
authored
458 * @return bool
dbdd40a Introduce queries_redirect function
jakubvrana authored
459 */
460 function queries_redirect($location, $message, $redirect) {
461 return query_redirect(queries(), $location, $message, $redirect, false, !$redirect);
462 }
463
9a176b0 Comments
jakubvrana authored
464 /** Remove parameter from query string
465 * @param string
466 * @return string
467 */
d41d446 remove_from_uri()
jakubvrana authored
468 function remove_from_uri($param = "") {
483d7dc Remove session_name() only without SID (bug #2910681)
jakubvrana authored
469 return substr(preg_replace("~(?<=[?&])($param" . (SID ? "" : "|" . session_name()) . ")=[^&]*&~", '', "$_SERVER[REQUEST_URI]&"), 0, -1);
d41d446 remove_from_uri()
jakubvrana authored
470 }
471
9a176b0 Comments
jakubvrana authored
472 /** Generate page number for pagination
473 * @param int
474 * @return string
475 */
bd25295 Don't redirect from last page
jakubvrana authored
476 function pagination($page, $current) {
6585b23 @vrana Generic AJAX links
authored
477 return " " . ($page == $current ? $page + 1 : '<a href="' . h(remove_from_uri("page") . ($page ? "&page=$page" : "")) . '">' . ($page + 1) . "</a>");
1456283 Pages on last page
jakubvrana authored
478 }
479
3e9b1ba Don't store files in hidden fields
jakubvrana authored
480 /** Get file contents from $_FILES
9a176b0 Comments
jakubvrana authored
481 * @param string
482 * @param bool
3e9b1ba Don't store files in hidden fields
jakubvrana authored
483 * @return mixed int for error, string otherwise
9a176b0 Comments
jakubvrana authored
484 */
25f01d3 Compress export and import
jakubvrana authored
485 function get_file($key, $decompress = false) {
486 $file = $_FILES[$key];
487 if (!$file || $file["error"]) {
488 return $file["error"];
430034c Cottage homework
jakubvrana authored
489 }
0a2d81d Bzip2 import
jakubvrana authored
490 return file_get_contents($decompress && ereg('\\.gz$', $file["name"]) ? "compress.zlib://$file[tmp_name]"
491 : ($decompress && ereg('\\.bz2$', $file["name"]) ? "compress.bzip2://$file[tmp_name]"
492 : $file["tmp_name"]
493 )); //! may not be reachable because of open_basedir
430034c Cottage homework
jakubvrana authored
494 }
495
9a176b0 Comments
jakubvrana authored
496 /** Determine upload error
497 * @param int
498 * @return string
499 */
e2a03c0 Show upload_max_filesize
jakubvrana authored
500 function upload_error($error) {
501 $max_size = ($error == UPLOAD_ERR_INI_SIZE ? ini_get("upload_max_filesize") : null); // post_max_size is checked in index.php
b2a7c7a Execute SQL file stored on server disk
jakubvrana authored
502 return ($error ? lang('Unable to upload a file.') . ($max_size ? " " . lang('Maximum allowed file size is %sB.', $max_size) : "") : lang('File does not exist.'));
e2a03c0 Show upload_max_filesize
jakubvrana authored
503 }
504
9a176b0 Comments
jakubvrana authored
505 /** Generate class for odd rows
506 * @param string return this for odd rows, empty to reset counter
507 * @return string
508 */
509 function odd($return = ' class="odd"') {
4e5b126 Highlight odd and hover rows
jakubvrana authored
510 static $i = 0;
9a176b0 Comments
jakubvrana authored
511 if (!$return) { // reset counter
1b97f48 Reset odd() for each result
jakubvrana authored
512 $i = -1;
4e5b126 Highlight odd and hover rows
jakubvrana authored
513 }
9a176b0 Comments
jakubvrana authored
514 return ($i++ % 2 ? $return : '');
4e5b126 Highlight odd and hover rows
jakubvrana authored
515 }
516
c313dd8 @vrana Deferred operations by AJAX instead of JS (doesn't require sending to…
authored
517 /** Print one row in JSON object
518 * @param string or "" to close the object
519 * @param string
520 * @return null
521 */
522 function json_row($key, $val = null) {
523 static $first = true;
524 if ($first) {
525 echo "{";
526 }
527 if ($key != "") {
be58b9c @vrana Escape \n in JSON
authored
528 echo ($first ? "" : ",") . "\n\t\"" . addcslashes($key, "\r\n\"\\") . '": ' . (isset($val) ? '"' . addcslashes($val, "\r\n\"\\") . '"' : 'undefined');
c313dd8 @vrana Deferred operations by AJAX instead of JS (doesn't require sending to…
authored
529 $first = false;
530 } else {
531 echo "\n}\n";
532 $first = true;
533 }
534 }
535
9a176b0 Comments
jakubvrana authored
536 /** Check whether the string is in UTF-8
537 * @param string
538 * @return bool
539 */
017ffb5 Better UTF-8 detection
jakubvrana authored
540 function is_utf8($val) {
64ba924 Comments
jakubvrana authored
541 // don't print control chars except \t\r\n
017ffb5 Better UTF-8 detection
jakubvrana authored
542 return (preg_match('~~u', $val) && !preg_match('~[\\0-\\x8\\xB\\xC\\xE-\\x1F]~', $val));
543 }
544
1315537 @vrana No error for big text length (bug #264133)
authored
545 /** Create repeat pattern for preg
546 * @param string
547 * @param int
548 * @return string
549 */
550 function repeat_pattern($pattern, $length) {
551 // fix for Compilation failed: number too big in {} quantifier
552 return str_repeat("$pattern{0,65535}", $length / 65535) . "$pattern{0," . ($length % 65535) . "}"; // can create {0,0} which is OK
553 }
554
9a176b0 Comments
jakubvrana authored
555 /** Shorten UTF-8 string
556 * @param string
557 * @param int
558 * @param string
559 * @return string escaped string with appended ...
560 */
cd07584 Save SQL query to history
jakubvrana authored
561 function shorten_utf8($string, $length = 80, $suffix = "") {
1315537 @vrana No error for big text length (bug #264133)
authored
562 if (!preg_match("(^(" . repeat_pattern("[\t\r\n -\x{FFFF}]", $length) . ")($)?)u", $string, $match)) { // ~s causes trash in $match[2] under some PHP versions, (.|\n) is slow
563 preg_match("(^(" . repeat_pattern("[\t\r\n -~]", $length) . ")($)?)", $string, $match);
95764b0 Shorten binary strings
jakubvrana authored
564 }
687b3fd @vrana Replace <strong> by <b> and <em> by <i>
authored
565 return h($match[1]) . $suffix . (isset($match[2]) ? "" : "<i>...</i>");
02a851c Shorten texts in PHP
jakubvrana authored
566 }
3920ebb Remove InnoDB table comment in Tables and views
jakubvrana authored
567
9a176b0 Comments
jakubvrana authored
568 /** Generate friendly URL
569 * @param string
570 * @return string
571 */
8251896 Downloaded file name
jakubvrana authored
572 function friendly_url($val) {
64ba924 Comments
jakubvrana authored
573 // used for blobs and export
8251896 Downloaded file name
jakubvrana authored
574 return preg_replace('~[^a-z0-9_]~i', '-', $val);
575 }
576
9a176b0 Comments
jakubvrana authored
577 /** Print hidden fields
578 * @param array
579 * @param array
580 * @return null
581 */
820c882 Bulk clone
jakubvrana authored
582 function hidden_fields($process, $ignore = array()) {
5d7071a Choose language through option-list
jakubvrana authored
583 while (list($key, $val) = each($process)) {
584 if (is_array($val)) {
585 foreach ($val as $k => $v) {
586 $process[$key . "[$k]"] = $v;
587 }
588 } elseif (!in_array($key, $ignore)) {
689699a Shortcut for htmlspecialchars
jakubvrana authored
589 echo '<input type="hidden" name="' . h($key) . '" value="' . h($val) . '">';
5d7071a Choose language through option-list
jakubvrana authored
590 }
591 }
592 }
61640ee Move common functions
jakubvrana authored
593
3f5b683 Reintegrate sqlite branch
jakubvrana authored
594 /** Print hidden fields for GET forms
595 * @return null
596 */
597 function hidden_fields_get() {
f30fd12 @vrana Work without session.use_cookies (bug #3138640)
authored
598 echo (sid() ? '<input type="hidden" name="' . session_name() . '" value="' . h(session_id()) . '">' : '');
3f5b683 Reintegrate sqlite branch
jakubvrana authored
599 echo (SERVER !== null ? '<input type="hidden" name="' . DRIVER . '" value="' . h(SERVER) . '">' : "");
600 echo '<input type="hidden" name="username" value="' . h($_GET["username"]) . '">';
601 }
602
9a176b0 Comments
jakubvrana authored
603 /** Find out foreign keys for each column
604 * @param string
605 * @return array array($col => array())
606 */
1e4d11e Select from foreign keys in Editor
jakubvrana authored
607 function column_foreign_keys($table) {
753909e @vrana Support for virtual foreign keys
authored
608 global $adminer;
1e4d11e Select from foreign keys in Editor
jakubvrana authored
609 $return = array();
753909e @vrana Support for virtual foreign keys
authored
610 foreach ($adminer->foreignKeys($table) as $foreign_key) {
1e4d11e Select from foreign keys in Editor
jakubvrana authored
611 foreach ($foreign_key["source"] as $val) {
612 $return[$val][] = $foreign_key;
613 }
614 }
615 return $return;
616 }
617
3f5b683 Reintegrate sqlite branch
jakubvrana authored
618 /** Print enum input field
619 * @param string "radio"|"checkbox"
620 * @param string
621 * @param array
622 * @param mixed int|string|array
623 * @return null
624 */
454c80f @vrana Save bytes
authored
625 function enum_input($type, $attrs, $field, $value) {
3f5b683 Reintegrate sqlite branch
jakubvrana authored
626 preg_match_all("~'((?:[^']|'')*)'~", $field["length"], $matches);
fe06908 @vrana Allow redefining editInput for enum (bug #3048711)
authored
627 $return = "";
3f5b683 Reintegrate sqlite branch
jakubvrana authored
628 foreach ($matches[1] as $i => $val) {
629 $val = stripcslashes(str_replace("''", "'", $val));
630 $checked = (is_int($value) ? $value == $i+1 : (is_array($value) ? in_array($i+1, $value) : $value === $val));
fe06908 @vrana Allow redefining editInput for enum (bug #3048711)
authored
631 $return .= " <label><input type='$type'$attrs value='" . ($i+1) . "'" . ($checked ? ' checked' : '') . '>' . h($val) . '</label>';
3f5b683 Reintegrate sqlite branch
jakubvrana authored
632 }
fe06908 @vrana Allow redefining editInput for enum (bug #3048711)
authored
633 return $return;
3f5b683 Reintegrate sqlite branch
jakubvrana authored
634 }
635
9a176b0 Comments
jakubvrana authored
636 /** Print edit input field
637 * @param array one field from fields()
638 * @param mixed
639 * @param string
640 * @return null
641 */
1e4d11e Select from foreign keys in Editor
jakubvrana authored
642 function input($field, $value, $function) {
e672694 @vrana Rename $driver to $jush
authored
643 global $types, $adminer, $jush;
689699a Shortcut for htmlspecialchars
jakubvrana authored
644 $name = h(bracket_escape($field["field"]));
61640ee Move common functions
jakubvrana authored
645 echo "<td class='function'>";
9f69d7a @vrana MS SQL: Do not update AI value
authored
646 $reset = ($jush == "mssql" && $field["auto_increment"]);
647 if ($reset && !$_POST["save"]) {
648 $function = null;
649 }
650 $functions = (isset($_GET["select"]) || $reset ? array("orig" => lang('original')) : array()) + $adminer->editFunctions($field);
454c80f @vrana Save bytes
authored
651 $attrs = " name='fields[$name]'";
61640ee Move common functions
jakubvrana authored
652 if ($field["type"] == "enum") {
fe06908 @vrana Allow redefining editInput for enum (bug #3048711)
authored
653 echo nbsp($functions[""]) . "<td>" . $adminer->editInput($_GET["edit"], $field, $attrs, $value);
61640ee Move common functions
jakubvrana authored
654 } else {
9903946 Use original values in Editor multi edit
jakubvrana authored
655 $first = 0;
656 foreach ($functions as $key => $val) {
657 if ($key === "" || !$val) {
658 break;
659 }
660 $first++;
661 }
28f21aa @vrana Escape JavaScript strings (bug #3093243)
authored
662 $onchange = ($first ? " onchange=\"var f = this.form['function[" . js_escape($name) . "]']; if ($first > f.selectedIndex) f.selectedIndex = $first;\"" : "");
454c80f @vrana Save bytes
authored
663 $attrs .= $onchange;
c5a1a77 @vrana Functions translation
authored
664 echo (count($functions) > 1 ? html_select("function[$name]", $functions, !isset($function) || in_array($function, $functions) || isset($functions[$function]) ? $function : "") : nbsp(reset($functions))) . '<td>';
a561252 Use distinct name for blob inputs
jakubvrana authored
665 $input = $adminer->editInput($_GET["edit"], $field, $attrs, $value); // usage in call is without a table
7352c28 Replace strlen() by != ""
jakubvrana authored
666 if ($input != "") {
e1abcda Treat tinyint(1) as boolean
jakubvrana authored
667 echo $input;
1e4d11e Select from foreign keys in Editor
jakubvrana authored
668 } elseif ($field["type"] == "set") { //! 64 bits
26c9d64 Fix long SQL query crash (bug #2839231)
jakubvrana authored
669 preg_match_all("~'((?:[^']|'')*)'~", $field["length"], $matches);
61640ee Move common functions
jakubvrana authored
670 foreach ($matches[1] as $i => $val) {
671 $val = stripcslashes(str_replace("''", "'", $val));
672 $checked = (is_int($value) ? ($value >> $i) & 1 : in_array($val, explode(",", $value), true));
4cead56 Edit default values directly in table creation
jakubvrana authored
673 echo " <label><input type='checkbox' name='fields[$name][$i]' value='" . (1 << $i) . "'" . ($checked ? ' checked' : '') . "$onchange>" . h($val) . '</label>';
61640ee Move common functions
jakubvrana authored
674 }
5a73c01 @vrana Treat binary type as hex
authored
675 } elseif (ereg('blob|bytea|raw|file', $field["type"]) && ini_bool("file_uploads")) {
a561252 Use distinct name for blob inputs
jakubvrana authored
676 echo "<input type='file' name='fields-$name'$onchange>";
375a5c8 @vrana Non-MySQL binary types
authored
677 } elseif (ereg('text|lob', $field["type"])) {
71438d5 @vrana Handle keypress instead of keydown (bug #3112458)
authored
678 echo "<textarea " . ($jush != "sqlite" || ereg("\n", $value) ? "cols='50' rows='12'" : "cols='30' rows='1' style='height: 1.2em;'") . "$attrs onkeypress='return textareaKeypress(this, event);'>" . h($value) . '</textarea>'; // 1.2em - line-height
61640ee Move common functions
jakubvrana authored
679 } else {
680 // int(3) is only a display hint
5002b89 @vrana Big numbers without E
authored
681 $maxlength = (!ereg('int', $field["type"]) && preg_match('~^(\\d+)(,(\\d+))?$~', $field["length"], $match) ? ((ereg("binary", $field["type"]) ? 2 : 1) * $match[1] + ($match[3] ? 1 : 0) + ($match[2] && !$field["unsigned"] ? 1 : 0)) : ($types[$field["type"]] ? $types[$field["type"]] + ($field["unsigned"] ? 0 : 1) : 0));
5a73c01 @vrana Treat binary type as hex
authored
682 echo "<input value='" . h($value) . "'" . ($maxlength ? " maxlength='$maxlength'" : "") . (ereg('char|binary', $field["type"]) && $maxlength > 20 ? " size='40'" : "") . "$attrs>";
61640ee Move common functions
jakubvrana authored
683 }
684 }
685 }
686
9a176b0 Comments
jakubvrana authored
687 /** Process edit input field
688 * @param one field from fields()
689 * @return string
690 */
a0def47 Date localization
jakubvrana authored
691 function process_input($field) {
7e644b4 @vrana Save bytes ($connection->quote shortcut)
authored
692 global $adminer;
a0def47 Date localization
jakubvrana authored
693 $idf = bracket_escape($field["field"]);
61640ee Move common functions
jakubvrana authored
694 $function = $_POST["function"][$idf];
695 $value = $_POST["fields"][$idf];
3f5b683 Reintegrate sqlite branch
jakubvrana authored
696 if ($field["type"] == "enum") {
697 if ($value == -1) {
698 return false;
699 }
700 if ($value == "") {
701 return "NULL";
702 }
04eccba @vrana Allow bigger numbers under 32 bits
authored
703 return +$value;
3f5b683 Reintegrate sqlite branch
jakubvrana authored
704 }
705 if ($field["auto_increment"] && $value == "") {
706 return null;
707 }
708 if ($function == "orig") {
61640ee Move common functions
jakubvrana authored
709 return false;
3f5b683 Reintegrate sqlite branch
jakubvrana authored
710 }
711 if ($function == "NULL") {
61640ee Move common functions
jakubvrana authored
712 return "NULL";
3f5b683 Reintegrate sqlite branch
jakubvrana authored
713 }
714 if ($field["type"] == "set") {
4cead56 Edit default values directly in table creation
jakubvrana authored
715 return array_sum((array) $value);
3f5b683 Reintegrate sqlite branch
jakubvrana authored
716 }
5a73c01 @vrana Treat binary type as hex
authored
717 if (ereg('blob|bytea|raw|file', $field["type"]) && ini_bool("file_uploads")) {
a561252 Use distinct name for blob inputs
jakubvrana authored
718 $file = get_file("fields-$idf");
61640ee Move common functions
jakubvrana authored
719 if (!is_string($file)) {
720 return false; //! report errors
721 }
7e644b4 @vrana Save bytes ($connection->quote shortcut)
authored
722 return q($file);
61640ee Move common functions
jakubvrana authored
723 }
3f5b683 Reintegrate sqlite branch
jakubvrana authored
724 return $adminer->processInput($field, $value, $function);
61640ee Move common functions
jakubvrana authored
725 }
726
db07325 Search in all tables
jakubvrana authored
727 /** Print results of search in all tables
728 * @uses $_GET["where"][0]
729 * @uses $_POST["tables"]
730 * @return null
731 */
732 function search_tables() {
733 global $adminer, $connection;
dfa6cbf @vrana Show tables overview in Editor
authored
734 $_GET["where"][0]["op"] = "LIKE %%";
735 $_GET["where"][0]["val"] = $_POST["query"];
db07325 Search in all tables
jakubvrana authored
736 $found = false;
737 foreach (table_status() as $table => $table_status) {
738 $name = $adminer->tableName($table_status);
739 if (isset($table_status["Engine"]) && $name != "" && (!$_POST["tables"] || in_array($table, $_POST["tables"]))) {
ee3e045 @vrana Separate $where in limit function
authored
740 $result = $connection->query("SELECT" . limit("1 FROM " . table($table), " WHERE " . implode(" AND ", $adminer->selectSearchProcess(fields($table), array())), 1));
782921b @vrana Finish SQLite
authored
741 if ($result->fetch_row()) {
db07325 Search in all tables
jakubvrana authored
742 if (!$found) {
743 echo "<ul>\n";
744 $found = true;
745 }
746 echo "<li><a href='" . h(ME . "select=" . urlencode($table) . "&where[0][op]=" . urlencode($_GET["where"][0]["op"]) . "&where[0][val]=" . urlencode($_GET["where"][0]["val"])) . "'>" . h($name) . "</a>\n";
747 }
748 }
749 }
750 echo ($found ? "</ul>" : "<p class='message'>" . lang('No tables.')) . "\n";
751 }
752
9a176b0 Comments
jakubvrana authored
753 /** Print CSV row
754 * @param array
755 * @return null
756 */
61640ee Move common functions
jakubvrana authored
757 function dump_csv($row) {
758 foreach ($row as $key => $val) {
e225d22 @vrana TSV export and import (bug #3097657)
authored
759 if (preg_match("~[\"\n,;\t]~", $val) || $val === "") {
61640ee Move common functions
jakubvrana authored
760 $row[$key] = '"' . str_replace('"', '""', $val) . '"';
761 }
762 }
02d6b90 @vrana CR+LF in CSV export
authored
763 echo implode(($_POST["format"] == "csv" ? "," : ($_POST["format"] == "tsv" ? "\t" : ";")), $row) . "\r\n";
61640ee Move common functions
jakubvrana authored
764 }
c16c57b E-mail sending
jakubvrana authored
765
9a176b0 Comments
jakubvrana authored
766 /** Apply SQL function
767 * @param string
768 * @param string escaped column identifier
769 * @return string
770 */
e331067 Move apply_sql_function
jakubvrana authored
771 function apply_sql_function($function, $column) {
3f5b683 Reintegrate sqlite branch
jakubvrana authored
772 return ($function ? ($function == "unixepoch" ? "DATETIME($column, '$function')" : ($function == "count distinct" ? "COUNT(DISTINCT " : strtoupper("$function(")) . "$column)") : $column);
e331067 Move apply_sql_function
jakubvrana authored
773 }
774
4ba2d85 @vrana Allow permanent login without customization
authored
775 /** Read password from file adminer.key in temporary directory or create one
776 * @return string or false if the file can not be created
777 */
778 function password_file() {
779 $dir = ini_get("upload_tmp_dir"); // session_save_path() may contain other storage path
780 if (!$dir) {
781 if (function_exists('sys_get_temp_dir')) {
782 $dir = sys_get_temp_dir();
783 } else {
784 $filename = @tempnam("", ""); // @ - temp directory can be disabled by open_basedir
785 if (!$filename) {
786 return false;
787 }
788 $dir = dirname($filename);
789 unlink($filename);
790 }
791 }
792 $filename = "$dir/adminer.key";
793 $return = @file_get_contents($filename); // @ - can not exist
794 if ($return) {
795 return $return;
796 }
797 $fp = @fopen($filename, "w"); // @ - can have insufficient rights //! is not atomic
798 if ($fp) {
799 $return = md5(uniqid(mt_rand(), true));
800 fwrite($fp, $return);
801 fclose($fp);
802 }
803 return $return;
804 }
805
9a176b0 Comments
jakubvrana authored
806 /** Check whether the string is e-mail address
807 * @param string
808 * @return bool
809 */
1cf374b @vrana Rename functions (avoid conflict with WordPress)
authored
810 function is_mail($email) {
c16c57b E-mail sending
jakubvrana authored
811 $atom = '[-a-z0-9!#$%&\'*+/=?^_`{|}~]'; // characters of local-name
812 $domain = '[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])'; // one domain component
28e1dd2 Allow multiple e-mails
jakubvrana authored
813 $pattern = "$atom+(\\.$atom+)*@($domain?\\.)+$domain";
814 return preg_match("(^$pattern(,\\s*$pattern)*\$)i", $email);
c16c57b E-mail sending
jakubvrana authored
815 }
dc667ea Hide select export and import
jakubvrana authored
816
bc78866 Link URLs in select
jakubvrana authored
817 /** Check whether the string is URL address
818 * @param string
2cec758 @vrana Direct links from HTTPS to HTTP
authored
819 * @return string "http", "https" or ""
bc78866 Link URLs in select
jakubvrana authored
820 */
821 function is_url($string) {
2cec758 @vrana Direct links from HTTPS to HTTP
authored
822 $domain = '[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])'; // one domain component //! IDN
5002b89 @vrana Big numbers without E
authored
823 return (preg_match("~^(https?)://($domain?\\.)+$domain(:\\d+)?(/.*)?(\\?.*)?(#.*)?\$~i", $string, $match) ? strtolower($match[1]) : ""); //! restrict path, query and fragment characters
bc78866 Link URLs in select
jakubvrana authored
824 }
825
dc667ea Hide select export and import
jakubvrana authored
826 /** Print header for hidden fieldset (close by </div></fieldset>)
827 * @param string
828 * @param string
829 * @param bool
830 * @return null
831 */
832 function print_fieldset($id, $legend, $visible = false) {
833 echo "<fieldset><legend><a href='#fieldset-$id' onclick=\"return !toggle('fieldset-$id');\">$legend</a></legend><div id='fieldset-$id'" . ($visible ? "" : " class='hidden'") . ">\n";
834 }
94a2be5 Highlight current links
jakubvrana authored
835
8ad4809 @vrana Use class="active" instead of <b>
authored
836 /** Return class='active' if $bold is true
94a2be5 Highlight current links
jakubvrana authored
837 * @param bool
838 * @return string
839 */
8ad4809 @vrana Use class="active" instead of <b>
authored
840 function bold($bold) {
841 return ($bold ? " class='active'" : "");
94a2be5 Highlight current links
jakubvrana authored
842 }
Something went wrong with that request. Please try again.