Skip to content

HTTPS clone URL

Subversion checkout URL

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