Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 771 lines (719 sloc) 22.623 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
3f5b683 Reintegrate sqlite branch
jakubvrana authored
138 /** Get INI boolean value
139 * @param string
140 * @return bool
141 */
142 function ini_bool($ini) {
143 $val = ini_get($ini);
144 return (eregi('^(on|true|yes)$', $val) || (int) $val); // boolean values set by php_value are strings
145 }
146
7e644b4 @vrana Save bytes ($connection->quote shortcut)
authored
147 function q($string) {
148 global $connection;
149 return $connection->quote($string);
150 }
151
9a176b0 Comments
jakubvrana authored
152 /** Get list of values from database
153 * @param string
154 * @param mixed
155 * @return array
156 */
0bd864e Allow specifying column in get_vals
jakubvrana authored
157 function get_vals($query, $column = 0) {
64d616c Rename get_dbh to connection
jakubvrana authored
158 global $connection;
7769f2c Separate get_vals
jakubvrana authored
159 $return = array();
64d616c Rename get_dbh to connection
jakubvrana authored
160 $result = $connection->query($query);
b84252f Display SQLite compile options
jakubvrana authored
161 if (is_object($result)) {
49f7886 SHOW DATABASES can be revoked
jakubvrana authored
162 while ($row = $result->fetch_row()) {
0bd864e Allow specifying column in get_vals
jakubvrana authored
163 $return[] = $row[$column];
49f7886 SHOW DATABASES can be revoked
jakubvrana authored
164 }
7769f2c Separate get_vals
jakubvrana authored
165 }
166 return $return;
167 }
168
3f5b683 Reintegrate sqlite branch
jakubvrana authored
169 /** Get keys from first column and values from second
170 * @param string
171 * @param Min_DB
172 * @return array
173 */
174 function get_key_vals($query, $connection2 = null) {
175 global $connection;
176 if (!is_object($connection2)) {
177 $connection2 = $connection;
178 }
179 $return = array();
180 $result = $connection2->query($query);
181 while ($row = $result->fetch_row()) {
182 $return[$row[0]] = $row[1];
183 }
184 return $return;
185 }
186
b0d637b @vrana Avoid fatal errors
authored
187 /** Get all rows of result
188 * @param string
189 * @return array associative
190 */
96544ba @vrana Report errors in get_rows()
authored
191 function get_rows($query, $connection2 = null, $error = "<p class='error'>") {
b0d637b @vrana Avoid fatal errors
authored
192 global $connection;
193 if (!is_object($connection2)) {
194 $connection2 = $connection;
195 }
196 $return = array();
197 $result = $connection2->query($query);
198 if (is_object($result)) { // can return true
199 while ($row = $result->fetch_assoc()) {
200 $return[] = $row;
201 }
352fd58 @vrana Don't report no error
authored
202 } elseif (!$result && $error && (headers_sent() || ob_get_level())) {
96544ba @vrana Report errors in get_rows()
authored
203 echo $error . error() . "\n";
b0d637b @vrana Avoid fatal errors
authored
204 }
205 return $return;
206 }
207
9a176b0 Comments
jakubvrana authored
208 /** Find unique identifier of a row
209 * @param array
210 * @param array result of indexes()
35ec64c Link COUNT(*) result to listing
jakubvrana authored
211 * @return array
9a176b0 Comments
jakubvrana authored
212 */
35ec64c Link COUNT(*) result to listing
jakubvrana authored
213 function unique_array($row, $indexes) {
720f5fc Restructure indexes
jakubvrana authored
214 foreach ($indexes as $index) {
4b3d569 Save bytes
jakubvrana authored
215 if (ereg("PRIMARY|UNIQUE", $index["type"])) {
720f5fc Restructure indexes
jakubvrana authored
216 $return = array();
217 foreach ($index["columns"] as $key) {
64ba924 Comments
jakubvrana authored
218 if (!isset($row[$key])) { // NULL is ambiguous
720f5fc Restructure indexes
jakubvrana authored
219 continue 2;
667bfec Decomposition
jakubvrana authored
220 }
35ec64c Link COUNT(*) result to listing
jakubvrana authored
221 $return[$key] = $row[$key];
667bfec Decomposition
jakubvrana authored
222 }
720f5fc Restructure indexes
jakubvrana authored
223 return $return;
667bfec Decomposition
jakubvrana authored
224 }
225 }
226 $return = array();
227 foreach ($row as $key => $val) {
26c9d64 Fix long SQL query crash (bug #2839231)
jakubvrana authored
228 if (!preg_match('~^(COUNT\\((\\*|(DISTINCT )?`(?:[^`]|``)+`)\\)|(AVG|GROUP_CONCAT|MAX|MIN|SUM)\\(`(?:[^`]|``)+`\\))$~', $key)) { //! columns looking like functions
35ec64c Link COUNT(*) result to listing
jakubvrana authored
229 $return[$key] = $val;
988a29f Don't use aggregation functions in unique_idf
jakubvrana authored
230 }
430034c Cottage homework
jakubvrana authored
231 }
232 return $return;
233 }
234
9a176b0 Comments
jakubvrana authored
235 /** Create SQL condition from parsed query string
236 * @param array parsed query string
237 * @return string
238 */
9ea3112 Mandatory $where in where()
jakubvrana authored
239 function where($where) {
1a8d7f1 @vrana Use LIKE for text comparison in MS SQL (bug #3088222)
authored
240 global $jush;
430034c Cottage homework
jakubvrana authored
241 $return = array();
341362a Driver specific INSERT INTO
jakubvrana authored
242 foreach ((array) $where["where"] as $key => $val) {
66ff153 Use bracket_escape function
jakubvrana authored
243 $return[] = idf_escape(bracket_escape($key, 1)) // 1 - back
1a8d7f1 @vrana Use LIKE for text comparison in MS SQL (bug #3088222)
authored
244 . (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
245 ; //! enum and set
341362a Driver specific INSERT INTO
jakubvrana authored
246 }
247 foreach ((array) $where["null"] as $key) {
248 $return[] = idf_escape($key) . " IS NULL";
667bfec Decomposition
jakubvrana authored
249 }
c16c57b E-mail sending
jakubvrana authored
250 return implode(" AND ", $return);
667bfec Decomposition
jakubvrana authored
251 }
252
9a176b0 Comments
jakubvrana authored
253 /** Create SQL condition from query string
254 * @param string
255 * @return string
256 */
0cd2afb Remove single item clone
jakubvrana authored
257 function where_check($val) {
258 parse_str($val, $check);
72f4d9e @vrana Function parse_str respects magic_quotes_gpc (bug #3034575)
authored
259 remove_slashes(array(&$check));
0cd2afb Remove single item clone
jakubvrana authored
260 return where($check);
261 }
262
9a176b0 Comments
jakubvrana authored
263 /** Create query string where condition from value
264 * @param int condition order
265 * @param string column identifier
266 * @param string
267 * @return string
186c058 Utilize where_link function
jakubvrana authored
268 * @return string
9a176b0 Comments
jakubvrana authored
269 */
186c058 Utilize where_link function
jakubvrana authored
270 function where_link($i, $column, $value, $operator = "=") {
271 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
272 }
273
319cba4 Save e-mail from to cookie
jakubvrana authored
274 /** Set cookie valid for 1 month
275 * @param string
276 * @param string
277 * @return bool
278 */
279 function cookie($name, $value) {
2cec758 @vrana Direct links from HTTPS to HTTP
authored
280 global $HTTPS;
3f5b683 Reintegrate sqlite branch
jakubvrana authored
281 $params = array(
282 $name,
283 (ereg("\n", $value) ? "" : $value), // HTTP Response Splitting protection in PHP < 5.1.2
284 time() + 2592000, // 2592000 - 30 days
285 preg_replace('~\\?.*~', '', $_SERVER["REQUEST_URI"]),
286 "",
2cec758 @vrana Direct links from HTTPS to HTTP
authored
287 $HTTPS
3f5b683 Reintegrate sqlite branch
jakubvrana authored
288 );
c2334db Secure cookies
jakubvrana authored
289 if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
290 $params[] = true; // HttpOnly
291 }
292 return call_user_func_array('setcookie', $params);
319cba4 Save e-mail from to cookie
jakubvrana authored
293 }
294
f9a2023 Improve concurrency
jakubvrana authored
295 /** Restart stopped session
296 * @return null
297 */
298 function restart_session() {
3f5b683 Reintegrate sqlite branch
jakubvrana authored
299 if (!ini_bool("session.use_cookies")) {
f9a2023 Improve concurrency
jakubvrana authored
300 session_start();
301 }
302 }
303
3f5b683 Reintegrate sqlite branch
jakubvrana authored
304 /** Get session variable for current server
305 * @param string
306 * @return mixed
307 */
308 function &get_session($key) {
309 return $_SESSION[$key][DRIVER][SERVER][$_GET["username"]];
310 }
311
312 /** Set session variable for current server
313 * @param string
314 * @param mixed
315 * @return mixed
316 */
317 function set_session($key, $val) {
318 $_SESSION[$key][DRIVER][SERVER][$_GET["username"]] = $val; // used also in auth.inc.php
319 }
320
605b093 @vrana List authentications
authored
321 /** Get authenticated URL
322 * @param string
323 * @param string
324 * @param string
325 * @return string
326 */
327 function auth_url($driver, $server, $username) {
328 global $drivers;
329 preg_match('~([^?]*)\\??(.*)~', remove_from_uri(implode("|", array_keys($drivers)) . "|username|" . session_name()), $match);
330 return "$match[1]?"
dea324f @vrana Store several permanent logins
authored
331 . (SID && !$_COOKIE ? SID . "&" : "")
605b093 @vrana List authentications
authored
332 . ($driver != "server" || $server != "" ? urlencode($driver) . "=" . urlencode($server) . "&" : "")
333 . "username=" . urlencode($username)
334 . ($match[2] ? "&$match[2]" : "")
335 ;
336 }
337
9a176b0 Comments
jakubvrana authored
338 /** Send Location header and exit
9bb1909 Fix Save and continue edit
jakubvrana authored
339 * @param string null to only set a message
9a176b0 Comments
jakubvrana authored
340 * @param string
341 * @return null
342 */
430034c Cottage homework
jakubvrana authored
343 function redirect($location, $message = null) {
344 if (isset($message)) {
be49e08 Improve session restarting
jakubvrana authored
345 restart_session();
ff74bf0 Allow multiple messages
jakubvrana authored
346 $_SESSION["messages"][] = $message;
430034c Cottage homework
jakubvrana authored
347 }
de24145 @vrana Clear POST with AJAX redirect
authored
348 if (isset($location)) {
349 if ($_SERVER["HTTP_X_REQUESTED_WITH"] != "XMLHttpRequest") {
350 header("Location: " . ($location != "" ? $location : "."));
351 exit;
352 }
353 $_POST = array();
9bb1909 Fix Save and continue edit
jakubvrana authored
354 }
430034c Cottage homework
jakubvrana authored
355 }
356
9a176b0 Comments
jakubvrana authored
357 /** Execute query and redirect if successful
358 * @param string
359 * @param string
360 * @param string
361 * @param bool
362 * @param bool
363 * @param bool
364 * @return bool
365 */
748ee83 Print SQL command with multiple queries
jakubvrana authored
366 function query_redirect($query, $location, $message, $redirect = true, $execute = true, $failed = false) {
64d616c Rename get_dbh to connection
jakubvrana authored
367 global $connection, $error, $adminer;
f9a2023 Improve concurrency
jakubvrana authored
368 if ($execute) {
369 $failed = !$connection->query($query);
370 }
10bdbed Save queries to history
jakubvrana authored
371 $sql = "";
372 if ($query) {
c64c4fd Adminer class
jakubvrana authored
373 $sql = $adminer->messageQuery($query);
10bdbed Save queries to history
jakubvrana authored
374 }
748ee83 Print SQL command with multiple queries
jakubvrana authored
375 if ($failed) {
c1130ed Simplify SQL syntax errors everywhere
jakubvrana authored
376 $error = error() . $sql;
c48a017 Print SQL query by error
jakubvrana authored
377 return false;
f91b2c4 Print SQL query by message
jakubvrana authored
378 }
c48a017 Print SQL query by error
jakubvrana authored
379 if ($redirect) {
380 redirect($location, $message . $sql);
381 }
382 return true;
f91b2c4 Print SQL query by message
jakubvrana authored
383 }
384
9a176b0 Comments
jakubvrana authored
385 /** Execute and remember query
386 * @param string null to return remembered queries
387 * @return Min_Result
388 */
748ee83 Print SQL command with multiple queries
jakubvrana authored
389 function queries($query = null) {
64d616c Rename get_dbh to connection
jakubvrana authored
390 global $connection;
748ee83 Print SQL command with multiple queries
jakubvrana authored
391 static $queries = array();
392 if (!isset($query)) {
64ba924 Comments
jakubvrana authored
393 // return executed queries without parameter
36950eb Tables and views
jakubvrana authored
394 return implode(";\n", $queries);
748ee83 Print SQL command with multiple queries
jakubvrana authored
395 }
396 $queries[] = $query;
64d616c Rename get_dbh to connection
jakubvrana authored
397 return $connection->query($query);
748ee83 Print SQL command with multiple queries
jakubvrana authored
398 }
399
f9bb1c5 @vrana Introduce apply_queries function
authored
400 /** Apply command to all array items
401 * @param string
402 * @param array
403 * @param callback
404 * @return bool
405 */
406 function apply_queries($query, $tables, $escape = 'table') {
407 foreach ($tables as $table) {
408 if (!queries("$query " . $escape($table))) {
409 return false;
410 }
411 }
412 return true;
413 }
414
dbdd40a Introduce queries_redirect function
jakubvrana authored
415 /** Redirect by remembered queries
416 * @param string
417 * @param string
418 * @param bool
52b9820 @vrana Comment
authored
419 * @return bool
dbdd40a Introduce queries_redirect function
jakubvrana authored
420 */
421 function queries_redirect($location, $message, $redirect) {
422 return query_redirect(queries(), $location, $message, $redirect, false, !$redirect);
423 }
424
9a176b0 Comments
jakubvrana authored
425 /** Remove parameter from query string
426 * @param string
427 * @return string
428 */
d41d446 remove_from_uri()
jakubvrana authored
429 function remove_from_uri($param = "") {
483d7dc Remove session_name() only without SID (bug #2910681)
jakubvrana authored
430 return substr(preg_replace("~(?<=[?&])($param" . (SID ? "" : "|" . session_name()) . ")=[^&]*&~", '', "$_SERVER[REQUEST_URI]&"), 0, -1);
d41d446 remove_from_uri()
jakubvrana authored
431 }
432
9a176b0 Comments
jakubvrana authored
433 /** Generate page number for pagination
434 * @param int
435 * @return string
436 */
bd25295 Don't redirect from last page
jakubvrana authored
437 function pagination($page, $current) {
438 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
439 }
440
3e9b1ba Don't store files in hidden fields
jakubvrana authored
441 /** Get file contents from $_FILES
9a176b0 Comments
jakubvrana authored
442 * @param string
443 * @param bool
3e9b1ba Don't store files in hidden fields
jakubvrana authored
444 * @return mixed int for error, string otherwise
9a176b0 Comments
jakubvrana authored
445 */
25f01d3 Compress export and import
jakubvrana authored
446 function get_file($key, $decompress = false) {
447 $file = $_FILES[$key];
448 if (!$file || $file["error"]) {
449 return $file["error"];
430034c Cottage homework
jakubvrana authored
450 }
0a2d81d Bzip2 import
jakubvrana authored
451 return file_get_contents($decompress && ereg('\\.gz$', $file["name"]) ? "compress.zlib://$file[tmp_name]"
452 : ($decompress && ereg('\\.bz2$', $file["name"]) ? "compress.bzip2://$file[tmp_name]"
453 : $file["tmp_name"]
454 )); //! may not be reachable because of open_basedir
430034c Cottage homework
jakubvrana authored
455 }
456
9a176b0 Comments
jakubvrana authored
457 /** Determine upload error
458 * @param int
459 * @return string
460 */
e2a03c0 Show upload_max_filesize
jakubvrana authored
461 function upload_error($error) {
462 $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
463 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
464 }
465
9a176b0 Comments
jakubvrana authored
466 /** Generate class for odd rows
467 * @param string return this for odd rows, empty to reset counter
468 * @return string
469 */
470 function odd($return = ' class="odd"') {
4e5b126 Highlight odd and hover rows
jakubvrana authored
471 static $i = 0;
9a176b0 Comments
jakubvrana authored
472 if (!$return) { // reset counter
1b97f48 Reset odd() for each result
jakubvrana authored
473 $i = -1;
4e5b126 Highlight odd and hover rows
jakubvrana authored
474 }
9a176b0 Comments
jakubvrana authored
475 return ($i++ % 2 ? $return : '');
4e5b126 Highlight odd and hover rows
jakubvrana authored
476 }
477
9a176b0 Comments
jakubvrana authored
478 /** Check whether the string is in UTF-8
479 * @param string
480 * @return bool
481 */
017ffb5 Better UTF-8 detection
jakubvrana authored
482 function is_utf8($val) {
64ba924 Comments
jakubvrana authored
483 // don't print control chars except \t\r\n
017ffb5 Better UTF-8 detection
jakubvrana authored
484 return (preg_match('~~u', $val) && !preg_match('~[\\0-\\x8\\xB\\xC\\xE-\\x1F]~', $val));
485 }
486
9a176b0 Comments
jakubvrana authored
487 /** Shorten UTF-8 string
488 * @param string
489 * @param int
490 * @param string
491 * @return string escaped string with appended ...
492 */
cd07584 Save SQL query to history
jakubvrana authored
493 function shorten_utf8($string, $length = 80, $suffix = "") {
11982f1 Shorten printed SQL query
jakubvrana authored
494 if (!preg_match("(^([\t\r\n -\x{FFFF}]{0,$length})($)?)u", $string, $match)) { // ~s causes trash in $match[2] under some PHP versions, (.|\n) is slow
495 preg_match("(^([\t\r\n -~]{0,$length})($)?)", $string, $match);
95764b0 Shorten binary strings
jakubvrana authored
496 }
687b3fd @vrana Replace <strong> by <b> and <em> by <i>
authored
497 return h($match[1]) . $suffix . (isset($match[2]) ? "" : "<i>...</i>");
02a851c Shorten texts in PHP
jakubvrana authored
498 }
3920ebb Remove InnoDB table comment in Tables and views
jakubvrana authored
499
9a176b0 Comments
jakubvrana authored
500 /** Generate friendly URL
501 * @param string
502 * @return string
503 */
8251896 Downloaded file name
jakubvrana authored
504 function friendly_url($val) {
64ba924 Comments
jakubvrana authored
505 // used for blobs and export
8251896 Downloaded file name
jakubvrana authored
506 return preg_replace('~[^a-z0-9_]~i', '-', $val);
507 }
508
9a176b0 Comments
jakubvrana authored
509 /** Print hidden fields
510 * @param array
511 * @param array
512 * @return null
513 */
820c882 Bulk clone
jakubvrana authored
514 function hidden_fields($process, $ignore = array()) {
5d7071a Choose language through option-list
jakubvrana authored
515 while (list($key, $val) = each($process)) {
516 if (is_array($val)) {
517 foreach ($val as $k => $v) {
518 $process[$key . "[$k]"] = $v;
519 }
520 } elseif (!in_array($key, $ignore)) {
689699a Shortcut for htmlspecialchars
jakubvrana authored
521 echo '<input type="hidden" name="' . h($key) . '" value="' . h($val) . '">';
5d7071a Choose language through option-list
jakubvrana authored
522 }
523 }
524 }
61640ee Move common functions
jakubvrana authored
525
3f5b683 Reintegrate sqlite branch
jakubvrana authored
526 /** Print hidden fields for GET forms
527 * @return null
528 */
529 function hidden_fields_get() {
530 echo (SID && !$_COOKIE ? '<input type="hidden" name="' . session_name() . '" value="' . h(session_id()) . '">' : '');
531 echo (SERVER !== null ? '<input type="hidden" name="' . DRIVER . '" value="' . h(SERVER) . '">' : "");
532 echo '<input type="hidden" name="username" value="' . h($_GET["username"]) . '">';
533 }
534
9a176b0 Comments
jakubvrana authored
535 /** Find out foreign keys for each column
536 * @param string
537 * @return array array($col => array())
538 */
1e4d11e Select from foreign keys in Editor
jakubvrana authored
539 function column_foreign_keys($table) {
540 $return = array();
541 foreach (foreign_keys($table) as $foreign_key) {
542 foreach ($foreign_key["source"] as $val) {
543 $return[$val][] = $foreign_key;
544 }
545 }
546 return $return;
547 }
548
3f5b683 Reintegrate sqlite branch
jakubvrana authored
549 /** Print enum input field
550 * @param string "radio"|"checkbox"
551 * @param string
552 * @param array
553 * @param mixed int|string|array
554 * @return null
555 */
454c80f @vrana Save bytes
authored
556 function enum_input($type, $attrs, $field, $value) {
3f5b683 Reintegrate sqlite branch
jakubvrana authored
557 preg_match_all("~'((?:[^']|'')*)'~", $field["length"], $matches);
558 foreach ($matches[1] as $i => $val) {
559 $val = stripcslashes(str_replace("''", "'", $val));
560 $checked = (is_int($value) ? $value == $i+1 : (is_array($value) ? in_array($i+1, $value) : $value === $val));
454c80f @vrana Save bytes
authored
561 echo " <label><input type='$type'$attrs value='" . ($i+1) . "'" . ($checked ? ' checked' : '') . '>' . h($val) . '</label>';
3f5b683 Reintegrate sqlite branch
jakubvrana authored
562 }
563 }
564
9a176b0 Comments
jakubvrana authored
565 /** Print edit input field
566 * @param array one field from fields()
567 * @param mixed
568 * @param string
569 * @return null
570 */
1e4d11e Select from foreign keys in Editor
jakubvrana authored
571 function input($field, $value, $function) {
e672694 @vrana Rename $driver to $jush
authored
572 global $types, $adminer, $jush;
689699a Shortcut for htmlspecialchars
jakubvrana authored
573 $name = h(bracket_escape($field["field"]));
61640ee Move common functions
jakubvrana authored
574 echo "<td class='function'>";
6758477 Hide NULL in Editor enum
jakubvrana authored
575 $functions = (isset($_GET["select"]) ? array("orig" => lang('original')) : array()) + $adminer->editFunctions($field);
454c80f @vrana Save bytes
authored
576 $attrs = " name='fields[$name]'";
61640ee Move common functions
jakubvrana authored
577 if ($field["type"] == "enum") {
454c80f @vrana Save bytes
authored
578 echo nbsp($functions[""]) . "<td>" . ($functions["orig"] ? "<label><input type='radio'$attrs value='-1' checked><i>$functions[orig]</i></label> " : "");
579 echo $adminer->editInput($_GET["edit"], $field, $attrs, $value);
580 enum_input("radio", $attrs, $field, $value);
61640ee Move common functions
jakubvrana authored
581 } else {
9903946 Use original values in Editor multi edit
jakubvrana authored
582 $first = 0;
583 foreach ($functions as $key => $val) {
584 if ($key === "" || !$val) {
585 break;
586 }
587 $first++;
588 }
689699a Shortcut for htmlspecialchars
jakubvrana authored
589 $onchange = ($first ? " onchange=\"var f = this.form['function[" . addcslashes($name, "\r\n'\\") . "]']; if ($first > f.selectedIndex) f.selectedIndex = $first;\"" : "");
454c80f @vrana Save bytes
authored
590 $attrs .= $onchange;
c5a1a77 @vrana Functions translation
authored
591 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
592 $input = $adminer->editInput($_GET["edit"], $field, $attrs, $value); // usage in call is without a table
7352c28 Replace strlen() by != ""
jakubvrana authored
593 if ($input != "") {
e1abcda Treat tinyint(1) as boolean
jakubvrana authored
594 echo $input;
1e4d11e Select from foreign keys in Editor
jakubvrana authored
595 } elseif ($field["type"] == "set") { //! 64 bits
26c9d64 Fix long SQL query crash (bug #2839231)
jakubvrana authored
596 preg_match_all("~'((?:[^']|'')*)'~", $field["length"], $matches);
61640ee Move common functions
jakubvrana authored
597 foreach ($matches[1] as $i => $val) {
598 $val = stripcslashes(str_replace("''", "'", $val));
599 $checked = (is_int($value) ? ($value >> $i) & 1 : in_array($val, explode(",", $value), true));
4cead56 Edit default values directly in table creation
jakubvrana authored
600 echo " <label><input type='checkbox' name='fields[$name][$i]' value='" . (1 << $i) . "'" . ($checked ? ' checked' : '') . "$onchange>" . h($val) . '</label>';
61640ee Move common functions
jakubvrana authored
601 }
5a73c01 @vrana Treat binary type as hex
authored
602 } elseif (ereg('blob|bytea|raw|file', $field["type"]) && ini_bool("file_uploads")) {
a561252 Use distinct name for blob inputs
jakubvrana authored
603 echo "<input type='file' name='fields-$name'$onchange>";
375a5c8 @vrana Non-MySQL binary types
authored
604 } elseif (ereg('text|lob', $field["type"])) {
644c355 @vrana Send the form by Ctrl+Enter in all textareas
authored
605 echo "<textarea " . ($jush != "sqlite" || ereg("\n", $value) ? "cols='50' rows='12'" : "cols='30' rows='1' style='height: 1.2em;'") . "$attrs onkeydown='return textareaKeydown(this, event);'>" . h($value) . '</textarea>'; // 1.2em - line-height
61640ee Move common functions
jakubvrana authored
606 } else {
607 // int(3) is only a display hint
5a73c01 @vrana Treat binary type as hex
authored
608 $maxlength = (!ereg('int', $field["type"]) && preg_match('~^([0-9]+)(,([0-9]+))?$~', $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));
609 echo "<input value='" . h($value) . "'" . ($maxlength ? " maxlength='$maxlength'" : "") . (ereg('char|binary', $field["type"]) && $maxlength > 20 ? " size='40'" : "") . "$attrs>";
61640ee Move common functions
jakubvrana authored
610 }
611 }
612 }
613
9a176b0 Comments
jakubvrana authored
614 /** Process edit input field
615 * @param one field from fields()
616 * @return string
617 */
a0def47 Date localization
jakubvrana authored
618 function process_input($field) {
7e644b4 @vrana Save bytes ($connection->quote shortcut)
authored
619 global $adminer;
a0def47 Date localization
jakubvrana authored
620 $idf = bracket_escape($field["field"]);
61640ee Move common functions
jakubvrana authored
621 $function = $_POST["function"][$idf];
622 $value = $_POST["fields"][$idf];
3f5b683 Reintegrate sqlite branch
jakubvrana authored
623 if ($field["type"] == "enum") {
624 if ($value == -1) {
625 return false;
626 }
627 if ($value == "") {
628 return "NULL";
629 }
630 return intval($value);
631 }
632 if ($field["auto_increment"] && $value == "") {
633 return null;
634 }
635 if ($function == "orig") {
61640ee Move common functions
jakubvrana authored
636 return false;
3f5b683 Reintegrate sqlite branch
jakubvrana authored
637 }
638 if ($function == "NULL") {
61640ee Move common functions
jakubvrana authored
639 return "NULL";
3f5b683 Reintegrate sqlite branch
jakubvrana authored
640 }
641 if ($field["type"] == "set") {
4cead56 Edit default values directly in table creation
jakubvrana authored
642 return array_sum((array) $value);
3f5b683 Reintegrate sqlite branch
jakubvrana authored
643 }
5a73c01 @vrana Treat binary type as hex
authored
644 if (ereg('blob|bytea|raw|file', $field["type"]) && ini_bool("file_uploads")) {
a561252 Use distinct name for blob inputs
jakubvrana authored
645 $file = get_file("fields-$idf");
61640ee Move common functions
jakubvrana authored
646 if (!is_string($file)) {
647 return false; //! report errors
648 }
7e644b4 @vrana Save bytes ($connection->quote shortcut)
authored
649 return q($file);
61640ee Move common functions
jakubvrana authored
650 }
3f5b683 Reintegrate sqlite branch
jakubvrana authored
651 return $adminer->processInput($field, $value, $function);
61640ee Move common functions
jakubvrana authored
652 }
653
db07325 Search in all tables
jakubvrana authored
654 /** Print results of search in all tables
655 * @uses $_GET["where"][0]
656 * @uses $_POST["tables"]
657 * @return null
658 */
659 function search_tables() {
660 global $adminer, $connection;
dfa6cbf @vrana Show tables overview in Editor
authored
661 $_GET["where"][0]["op"] = "LIKE %%";
662 $_GET["where"][0]["val"] = $_POST["query"];
db07325 Search in all tables
jakubvrana authored
663 $found = false;
664 foreach (table_status() as $table => $table_status) {
665 $name = $adminer->tableName($table_status);
666 if (isset($table_status["Engine"]) && $name != "" && (!$_POST["tables"] || in_array($table, $_POST["tables"]))) {
ee3e045 @vrana Separate $where in limit function
authored
667 $result = $connection->query("SELECT" . limit("1 FROM " . table($table), " WHERE " . implode(" AND ", $adminer->selectSearchProcess(fields($table), array())), 1));
782921b @vrana Finish SQLite
authored
668 if ($result->fetch_row()) {
db07325 Search in all tables
jakubvrana authored
669 if (!$found) {
670 echo "<ul>\n";
671 $found = true;
672 }
673 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";
674 }
675 }
676 }
677 echo ($found ? "</ul>" : "<p class='message'>" . lang('No tables.')) . "\n";
678 }
679
9a176b0 Comments
jakubvrana authored
680 /** Print CSV row
681 * @param array
682 * @return null
683 */
61640ee Move common functions
jakubvrana authored
684 function dump_csv($row) {
685 foreach ($row as $key => $val) {
3f5b683 Reintegrate sqlite branch
jakubvrana authored
686 if (preg_match("~[\"\n,;]~", $val) || $val === "") {
61640ee Move common functions
jakubvrana authored
687 $row[$key] = '"' . str_replace('"', '""', $val) . '"';
688 }
689 }
acf7a42 Improve CSV; export
jakubvrana authored
690 echo implode(($_POST["format"] == "csv" ? "," : ";"), $row) . "\n";
61640ee Move common functions
jakubvrana authored
691 }
c16c57b E-mail sending
jakubvrana authored
692
9a176b0 Comments
jakubvrana authored
693 /** Apply SQL function
694 * @param string
695 * @param string escaped column identifier
696 * @return string
697 */
e331067 Move apply_sql_function
jakubvrana authored
698 function apply_sql_function($function, $column) {
3f5b683 Reintegrate sqlite branch
jakubvrana authored
699 return ($function ? ($function == "unixepoch" ? "DATETIME($column, '$function')" : ($function == "count distinct" ? "COUNT(DISTINCT " : strtoupper("$function(")) . "$column)") : $column);
e331067 Move apply_sql_function
jakubvrana authored
700 }
701
4ba2d85 @vrana Allow permanent login without customization
authored
702 /** Read password from file adminer.key in temporary directory or create one
703 * @return string or false if the file can not be created
704 */
705 function password_file() {
706 $dir = ini_get("upload_tmp_dir"); // session_save_path() may contain other storage path
707 if (!$dir) {
708 if (function_exists('sys_get_temp_dir')) {
709 $dir = sys_get_temp_dir();
710 } else {
711 $filename = @tempnam("", ""); // @ - temp directory can be disabled by open_basedir
712 if (!$filename) {
713 return false;
714 }
715 $dir = dirname($filename);
716 unlink($filename);
717 }
718 }
719 $filename = "$dir/adminer.key";
720 $return = @file_get_contents($filename); // @ - can not exist
721 if ($return) {
722 return $return;
723 }
724 $fp = @fopen($filename, "w"); // @ - can have insufficient rights //! is not atomic
725 if ($fp) {
726 $return = md5(uniqid(mt_rand(), true));
727 fwrite($fp, $return);
728 fclose($fp);
729 }
730 return $return;
731 }
732
9a176b0 Comments
jakubvrana authored
733 /** Check whether the string is e-mail address
734 * @param string
735 * @return bool
736 */
1cf374b @vrana Rename functions (avoid conflict with WordPress)
authored
737 function is_mail($email) {
c16c57b E-mail sending
jakubvrana authored
738 $atom = '[-a-z0-9!#$%&\'*+/=?^_`{|}~]'; // characters of local-name
739 $domain = '[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])'; // one domain component
28e1dd2 Allow multiple e-mails
jakubvrana authored
740 $pattern = "$atom+(\\.$atom+)*@($domain?\\.)+$domain";
741 return preg_match("(^$pattern(,\\s*$pattern)*\$)i", $email);
c16c57b E-mail sending
jakubvrana authored
742 }
dc667ea Hide select export and import
jakubvrana authored
743
bc78866 Link URLs in select
jakubvrana authored
744 /** Check whether the string is URL address
745 * @param string
2cec758 @vrana Direct links from HTTPS to HTTP
authored
746 * @return string "http", "https" or ""
bc78866 Link URLs in select
jakubvrana authored
747 */
748 function is_url($string) {
2cec758 @vrana Direct links from HTTPS to HTTP
authored
749 $domain = '[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])'; // one domain component //! IDN
750 return (preg_match("~^(https?)://($domain?\\.)+$domain(:[0-9]+)?(/.*)?(\\?.*)?(#.*)?\$~i", $string, $match) ? strtolower($match[1]) : ""); //! restrict path, query and fragment characters
bc78866 Link URLs in select
jakubvrana authored
751 }
752
dc667ea Hide select export and import
jakubvrana authored
753 /** Print header for hidden fieldset (close by </div></fieldset>)
754 * @param string
755 * @param string
756 * @param bool
757 * @return null
758 */
759 function print_fieldset($id, $legend, $visible = false) {
760 echo "<fieldset><legend><a href='#fieldset-$id' onclick=\"return !toggle('fieldset-$id');\">$legend</a></legend><div id='fieldset-$id'" . ($visible ? "" : " class='hidden'") . ">\n";
761 }
94a2be5 Highlight current links
jakubvrana authored
762
763 /** Enclose $string to <b> if $bold is true
764 * @param string
765 * @param bool
766 * @return string
767 */
768 function bold($string, $bold) {
769 return ($bold ? "<b>$string</b>" : $string);
770 }
Something went wrong with that request. Please try again.