forked from MythTV/mythweb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.php
413 lines (391 loc) · 14.4 KB
/
utils.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
<?php
/**
* Utility routines used throughout mythweb
*
* This file was originally written by Chris Petersen for several different open
* source projects. It is distrubuted under the GNU General Public License.
* I (Chris Petersen) have also granted a special LGPL license for *portions* of
* this code to several companies I do work for on the condition that these
* companies will release any changes to this back to me and the open source
* community as GPL, thus continuing to improve the open source version of the
* library. If you would like to inquire about the status of this arrangement,
* please contact me personally.
*
* @url $URL$
* @date $Date$
* @version $Revision$
* @author $Author$
* @license GPL
*
* @package MythWeb
*
/**/
// Set up some constants used by nice_filesystem()
define('kb', 1024); // Kilobyte
define('mb', 1024 * kb); // Megabyte
define('gb', 1024 * mb); // Gigabyte
define('tb', 1024 * gb); // Terabyte
/**
* Get or set a database setting.
*
* @param string $field The field (settings.value) to retrieve/set.
* @param string $hostname Hostname (or null) associated with $field.
* @param string $new_value New value (settings.data) to set.
*
* @return string The value (settings.data) associated with $field and $hostname.
/**/
function setting($field, $hostname=null, $new_value = "old\0old") {
global $db;
static $cache = array();
// Best not to have an array index that's null
$h = is_null($hostname) ? '-null-' : $hostname;
if (!is_array($cache[$h]))
$cache[$h] = array();
// Assigning a new value
if ($new_value !== "old\0old") {
if (is_null($hostname))
$db->query('DELETE FROM settings
WHERE value=? AND hostname IS NULL',
$field);
else
$db->query('DELETE FROM settings
WHERE value=? AND hostname=?',
$field, $hostname);
$db->query('INSERT INTO settings (value, data, hostname) VALUES (?,?,?)',
$field, $new_value, $hostname);
$cache[$h][$field] = $new_value;
}
// Not cached?
elseif (!array_key_exists($field, $cache[$h])) {
if (is_null($hostname))
$cache[$h][$field] = $db->query_col('SELECT data
FROM settings
WHERE value=? AND hostname IS NULL',
$field);
else
$cache[$h][$field] = $db->query_col('SELECT data
FROM settings
WHERE value=? AND hostname=?',
$field, $hostname);
}
// Return the cached value
return $cache[$h][$field];
}
/**
* Find a particular file in the current include_path
*
* @param string $file Name of the file to look for
* @return mixed Full path to the requested file, or null if it isn't found.
/**/
function find_in_path($file) {
// Split out each of the search paths
foreach (explode(PATH_SEPARATOR, ini_get('include_path')) as $path) {
// Formulate the absolute path
$full_path = $path . DIRECTORY_SEPARATOR . $file;
// Exists?
if (file_exists($full_path))
return $full_path;
}
return null;
}
/**
* I like how in perl, you can pass variables into functions in lists or
* arrays, and they all show up to the function as one giant list. This takes
* an array containing scalars and arrays of scalars, and returns one clean
* array of all values.
/**/
function smart_args($args) {
$new_args = array();
// Not an array
if (!is_array($args))
return array($args);
// Loop
foreach ($args as $arg) {
foreach (smart_args($arg) as $arg2) {
$new_args[] = $arg2;
}
}
// Return
return $new_args;
}
/**
* Recursively fixes silly \r\n stuff that some browsers send.
* Also adds a generic entry for fiends ending in _x or _y to better deal
* with image inputs.
/**/
function &fix_crlfxy(&$array) {
foreach ($array as $key => $val) {
if (is_array($val))
fix_crlfxy($array[$key]);
elseif (is_string($val)) {
$array[$key] = str_replace("\r\n", "\n", $val);
// Process any imagemap submissions to make sure we also get the name itself
if ($key != ($new_key = preg_replace('/_[xy]$/', '', $key))) {
if (!array_key_exists($new_key, $array))
$array[$new_key] = true;
}
}
}
return $array;
}
/**
* Recursively strip slashes from an array (eg. $_GET).
/**/
function &fix_magic_quotes(&$array) {
foreach ($array as $key => $val) {
if (is_array($val))
fix_magic_quotes($array[$key]);
else
$array[$key] = stripslashes($val);
}
return $array;
}
/**
* Strips slashes ONLY before quotes, to get around php adding slashes in
* preg_replace //e but not in such a way that stripslashes works properly.
/*/
function strip_quote_slashes($str) {
return preg_replace("/\\\\([\"'])/", '$1', $str);
}
/**
* Print a redirect header and exit
/**/
function redirect_browser($url) {
header("Location: $url");
echo "\n";
exit;
}
/**
* Pass in a filesize in bytes, and receive a more human-readable version
* JS: adapted from php.net: sponger 10-Jun-2002 12:28
/**/
function nice_filesize($size) {
// If it's less than a kb we just return the size
if ($size < kb)
return t('$1 B', t($size));
// Otherwise we keep going until the size is in the appropriate measurement range.
elseif ($size < mb)
return t('$1 KB', t(round($size / kb, ($size < 10 * kb))));
elseif ($size < gb)
return t('$1 MB', t(round($size / mb, ($size < 10 * mb))));
elseif ($size < tb)
return t('$1 GB', t(round($size / gb, ($size < 10 * gb))));
else
return t('$1 TB', t(round($size / tb, ($size < 10 * tb))));
}
/**
* Convert a unix timestamp into an day/hour/minute string
*
* @param int $length time to convert.
*
* @return string Translated hour/minute string.
/**/
function nice_length($length) {
$days = intVal($length / (24 * 3600));
$hours = intVal(($length % (24 * 3600)) / 3600);
$mins = intVal(($length % 3600) / 60);
if ($days > 0)
$ret = tn('$1 day', '$1 days', $days);
else
$ret = '';
if ($hours > 0) {
if ($ret)
$ret .= ' ';
$ret .= tn('$1 hr', '$1 hrs', $hours);
}
if ($mins > 0) {
if ($ret)
$ret .= ' ';
$ret .= tn('$1 min', '$1 mins', $mins);
}
return $ret;
}
/**
* Converts an sql timestamp into unixtime
/**/
function unixtime($sql_timestamp) {
return mktime(substr($sql_timestamp, 8, 2), // hour
substr($sql_timestamp, 10, 2), // minute
substr($sql_timestamp, 12, 2), // second
substr($sql_timestamp, 4, 2), // month
substr($sql_timestamp, 6, 2), // day
substr($sql_timestamp, 0, 4)); // year
}
/**
* DEPRECATED (use the Database object instead)
*
* For lack of a function that escapes strings AND adds quotes, I wrote one
* myself to make the rest of my code read a bit easier.
/**/
function escape($string, $allow_null = false) {
// Null?
if ($allow_null && is_null($string))
return $string = 'NULL';
// Just a string
return $string = "'".mysql_real_escape_string($string)."'";
}
/**
* Overloaded version of htmlentities() that requests the UTF-8 entities rather
* than the default ISO-9660
*
* @param string $str String to convert to html entities
*
* @return UTF-8 entities for $str
/**/
function html_entities($str) {
return htmlentities($str, ENT_COMPAT, 'UTF-8');
}
/**
* Returns a sorted list of files in a directory, minus . and ..
/**/
function get_sorted_files($dir = '.', $regex = '', $negate = false) {
$list = array();
$handle = opendir($dir);
while(false != ($file = readdir($handle))) {
if ($file == '.' || $file == '..') continue;
if (!$regex || (!$negate && preg_match($regex, $file)) || ($negate && !preg_match($regex, $file)))
$list[] = $file;
}
closedir($handle);
sort($list);
return $list;
}
/**
* Start/display a microtime timer
*
* @param mixed $message The message to echo, or another value (see return)
* @param int $index The index value of the cache to store the timer.
* Useful for handling multiple simultaneous timers.
*
* @return mixed If $message is ommitted or null, the current time is returned.
* If a string, the string is returned after being passed through
* sprintf() with the current time delta (float) as an argument.
* If anything else, the current time differential is returned.
/**/
function timer($message=null, $index=0) {
static $cache = array();
// Get the current time
if (intVal(phpversion()) >= 5) {
$time = microtime(true);
}
else {
list($usec, $sec) = explode(' ', microtime());
$time = floatVal($usec) + floatVal($sec);
}
// Print a string
if (is_string($message))
$ret = sprintf($message, $time - $cache[$index]);
elseif (is_null($message))
$ret = $time;
else
$ret = $time - $cache[$index];
// Start/update the timer
$cache[$index] = $time;
// Return
return $ret;
}
/**
* returns $this or $or_this
* if $gt is set to true, $this will only be returned if it's > 0
* if $gt is set to a number, $this will only be returned if it's > $gt
/**/
function _or($this, $or_this, $gt = false) {
if ($gt === true)
return $this > 0 ? $this : $or_this;
if (!empty($gt))
return $this > $gt ? $this : $or_this;
return $this ? $this : $or_this;
}
/**
* Someday, we may even be able to pass in a recording and get back a specific
* hostname. For now, you get either the hard-coded global video_url, or one
* determined based on the browser.
*
* @return string URL to access recordings
/**/
function video_url($show) {
// URL override?
if ($_SESSION['file_url_override'])
return 'file://'.$_SESSION['file_url_override'].str_replace('%2F', '/', rawurlencode(basename($show->filename)));
// Mac and Linux just get a link to the streaming module, along with any
// session marked to not use the myth:// URI
if (preg_match('/\b(?:linux|macintosh|mac\s+os\s*x)\b/i', $_SERVER['HTTP_USER_AGENT'])
|| !$_SESSION['use_myth_uri'])
return root."pl/stream/$show->chanid/$show->recstartts";
// Windows likely gets a myth:// url -- grab the master host and port
global $Master_Host, $Master_Port;
// Is either the browser xor the master in an rfc 1918 zone?
if (preg_match('/^(?:10|192\.168|172\.(?:1[6-9]|2[0-9]|3[0-6]))\./', $Master_Host)
xor preg_match('/^(?:10|192\.168|172\.(?:1[6-9]|2[0-9]|3[0-6]))\./', $_SERVER['REMOTE_ADDR'])) {
return root."pl/stream/$show->chanid/$show->recstartts";
}
// Send the myth url
else {
return "myth://$Master_Host:$Master_Port/"
.str_replace('%2F', '/', rawurlencode(basename($show->filename)));
}
}
/**
* @return $str converted UTF-8 to local encoding
/**/
function utf8tolocal($str) {
if (empty($_SERVER['fs_encoding']))
return $str;
if (function_exists('mb_convert_encoding'))
return mb_convert_encoding($str, $_SERVER['fs_encoding'], 'UTF-8');
if (function_exists('iconv'))
return iconv('UTF-8', $_SERVER['fs_encoding'], $str);
if (function_exists('recode_string'))
return recode_string('UTF-8..' . $_SERVER['fs_encoding'], $str);
return $str;
}
/**
* Prints out a piece of data to a popup window.
/**/
function debug($data, $file = false, $force = false) {
if(!dev_domain && !$force)
return;
static $first_run=true;
if($first_run) {
$first_run=false;
echo '<script type="text/javascript" src="/js/debug.js"></script>';
}
// Put our data into a string
if (is_array($data) || is_object($data))
$str = print_r($data, TRUE);
elseif (isset($data))
$str = $data;
$search = array("\n", '"');
$replace = array("\\n", '\"');
$back_trace = debug_backtrace();
// If this is a string, int or float
if (is_string($str) || is_int($str) || is_float($str)) {
// Allow XML/HTML to be treated as normal text
$str = htmlspecialchars($str, ENT_NOQUOTES);
}
// If this is a boolean
elseif (is_bool($str))
$str = $str ? '<i>**TRUE**</i>' : '<i>**FALSE**</i>';
// If this is null
elseif (is_null($str))
$str = '<i>**NULL**</i>';
// If it is not a string, we return a get_type, because it would be hard to generically come up with a way
// to display anything
else
$str = '<i>Type : '.gettype($str).'</i>';
// Show which line caused the debug message
$str = $str."\n<hr>\n".'Line #'.$back_trace[0]['line'].' in file '.$back_trace[0]['file']."\n";
// Print the message
echo '<script language="javascript">debug_window("'.str_replace($search, $replace, $str).'");</script>';
echo '<noscript><pre>'.$str.'</pre></noscript>';
// Print to a file?
if ($file) {
$out = fopen('/tmp/debug.txt', 'a');
fwrite($out, "$str\n");
fclose($out);
}
}
function fequals($lhs, $rhs) {
$epsilon = 1e-3;
return abs($lhs - $rhs) <= $epsilon * abs($lhs);
}