Issues (1098)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

src/engine/utility.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
//------------------------------------------------------------------------------
4
//
5
//  eTraxis - Records tracking web-based system
6
//  Copyright (C) 2004-2011  Artem Rodygin
7
//
8
//  This program is free software: you can redistribute it and/or modify
9
//  it under the terms of the GNU General Public License as published by
10
//  the Free Software Foundation, either version 3 of the License, or
11
//  (at your option) any later version.
12
//
13
//  This program is distributed in the hope that it will be useful,
14
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
15
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
//  GNU General Public License for more details.
17
//
18
//  You should have received a copy of the GNU General Public License
19
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
//
21
//------------------------------------------------------------------------------
22
23
/**
24
 * Utility functions
25
 *
26
 * This module contains several wide-purpose utility functions.
27
 *
28
 * @package Engine
29
 */
30
31
/**#@+
32
 * Dependency.
33
 */
34
require_once('../engine/debug.php');
35
require_once('../engine/smtp.php');
36
/**#@-*/
37
38
//------------------------------------------------------------------------------
39
//  Definitions.
40
//------------------------------------------------------------------------------
41
42
/**
43
 * Maximum integer value.
44
 */
45
define('MAXINT', 0x7FFFFFFF);
46
47
/**#@+
48
 * Number of seconds.
49
 */
50
define('SECS_IN_HOUR',    3600);    // 60 * 60
51
define('SECS_IN_DAY',     86400);   // 60 * 60 * 24
52
define('SECS_IN_WEEK',    604800);  // 60 * 60 * 24 * 7
53
define('MSECS_IN_MINUTE', 60000);   // 60 * 1000
54
/**#@-*/
55
56
/**
57
 * Allowed CSV-delimiters.
58
 */
59
define('CSV_DELIMITERS', '!#$%&\'()*+,-./:;<=>?@[\]^_`{|}~');
60
61
//------------------------------------------------------------------------------
62
//  Functions.
63
//------------------------------------------------------------------------------
64
65
/**
66
 * Unicode (UTF-8) analogue of standard {@link http://www.php.net/strlen strlen} PHP function.
67
 *
68
 * Returns the length of the given string.
69
 *
70
 * @param string $str The UTF-8 encoded string being measured for length.
71
 * @return int The length (amount of UTF-8 characters) of the string on success, and 0 if the string is empty.
72
 */
73
function ustrlen ($str)
74
{
75
    return mb_strlen($str, 'UTF-8');
76
}
77
78
/**
79
 * Unicode (UTF-8) analogue of standard {@link http://www.php.net/strpos strpos} PHP function.
80
 *
81
 * Find position of first occurrence of a case-sensitive UTF-8 encoded string.
82
 * Returns the numeric position (offset in amount of UTF-8 characters) of the first occurrence of <i>needle</i> in the <i>haystack</i> string.
83
 *
84
 * @param string $haystack The UTF-8 encoded string being searched in.
85
 * @param string $needle The UTF-8 encoded string being searched for.
86
 * @param int $offset The optional <i>offset</i> parameter allows you to specify which character in <i>haystack</i> to start searching.
87
 * The position returned is still relative to the beginning of <i>haystack</i>.
88
 * @return int Returns the position as an integer. If <i>needle</i> is not found, the function will return boolean FALSE.
89
 */
90
function ustrpos ($haystack, $needle, $offset = 0)
91
{
92
    return mb_strpos($haystack, $needle, $offset, 'UTF-8');
93
}
94
95
/**
96
 * Unicode (UTF-8) analogue of standard {@link http://www.php.net/stripos stripos} PHP function.
97
 *
98
 * Find position of first occurrence of a case-insensitive UTF-8 encoded string.
99
 * Returns the numeric position (offset in amount of UTF-8 characters) of the first occurrence of <i>needle</i> in the <i>haystack</i> string.
100
 *
101
 * @param string $haystack The UTF-8 encoded string being searched in.
102
 * @param string $needle The UTF-8 encoded string being searched for.
103
 * @param int $offset The optional <i>offset</i> parameter allows you to specify which character in <i>haystack</i> to start searching.
104
 * The position returned is still relative to the beginning of <i>haystack</i>.
105
 * @return int Returns the position as an integer. If <i>needle</i> is not found, the function will return boolean FALSE.
106
 */
107
function ustripos ($haystack, $needle, $offset = 0)
108
{
109
    $haystack = mb_strtolower($haystack, 'UTF-8');
110
    $needle   = mb_strtolower($needle,   'UTF-8');
111
112
    return mb_strpos($haystack, $needle, $offset, 'UTF-8');
113
}
114
115
/**
116
 * Unicode (UTF-8) analogue of standard {@link http://www.php.net/strrpos strrpos} PHP function.
117
 *
118
 * Find position of last occurrence of a case-sensitive UTF-8 encoded string.
119
 * Returns the numeric position (offset in amount of UTF-8 characters) of the last occurrence of <i>needle</i> in the <i>haystack</i> string.
120
 *
121
 * @param string $haystack The UTF-8 encoded string being searched in.
122
 * @param string $needle The UTF-8 encoded string being searched for.
123
 * @return int Returns the position as an integer. If <i>needle</i> is not found, the function will return boolean FALSE.
124
 */
125
function ustrrpos ($haystack, $needle)
126
{
127
    return mb_strrpos($haystack, $needle, 'UTF-8');
128
}
129
130
/**
131
 * Unicode (UTF-8) analogue of standard {@link http://www.php.net/strtolower strtolower} PHP function.
132
 *
133
 * Make a string lowercase.
134
 *
135
 * @param string $str The UTF-8 encoded string to be lowercased.
136
 * @return string Specified string with all alphabetic characters converted to lowercase.
137
 */
138
function ustrtolower ($str)
139
{
140
    return mb_strtolower($str, 'UTF-8');
141
}
142
143
/**
144
 * Unicode (UTF-8) analogue of standard {@link http://www.php.net/substr substr} PHP function.
145
 *
146
 * Returns the portion of string specified by the <i>start</i> and <i>length</i> parameters.
147
 *
148
 * @param string $str The UTF-8 encoded string.
149
 * @param int $start Start of portion to be returned. Position is counted in amount of UTF-8 characters from the beginning of <i>str</i>.
150
 * First character's position is 0. Second character position is 1, and so on.
151
 * @param int $length If <i>length</i> is given, the string returned will contain at most <i>length</i> characters beginning from <i>start</i> (depending on the length of string).
152
 * If <i>length</i> is omitted, the rest of string from <i>start</i> will be returned.
153
 * @return string The extracted UTF-8 encoded part of input string.
154
 */
155
function usubstr ($str, $start, $length = NULL)
156
{
157
    return mb_substr($str, $start, (is_null($length) ? mb_strlen($str, 'UTF-8') : $length), 'UTF-8');
158
}
159
160
/**
161
 * Unicode (UTF-8) analogue of standard {@link http://www.php.net/str-replace str_replace} PHP function.
162
 *
163
 * Replace all occurrences of the search string with the replacement string.
164
 *
165
 * @param string $search The UTF-8 encoded string being searched for.
166
 * @param string $replace The UTF-8 encoded string being replaced with.
167
 * @param string $subject The UTF-8 encoded string being searched in.
168
 * @return string The UTF-8 encoded string with the replaced values.
169
 */
170
function ustr_replace ($search, $replace, $subject)
171
{
172
    $from = 0;
173
    $len  = ustrlen($search);
174
175
    while (TRUE)
176
    {
177
        $from = ustripos($subject, $search, $from);
178
179
        if ($from === FALSE)
180
        {
181
            break;
182
        }
183
184
        $subject = usubstr($subject, 0, $from) . $replace . usubstr($subject, $from + $len);
185
        $from += ustrlen($replace);
186
    }
187
188
    return $subject;
189
}
190
191
/**
192
 * Trims UTF-8 encoded string and then cuts it to specified length.
193
 *
194
 * @param string $str The UTF-8 encoded string being cut.
195
 * @param int $maxlen New length of the string (amount of UTF-8 characters).
196
 * @param bool $trim Whether to trim string before cutting it.
197
 * @return string Cut string.
198
 */
199
function ustrcut ($str, $maxlen, $trim = TRUE)
200
{
201
    if ($trim)
202
    {
203
        $str = trim($str);
204
    }
205
206
    return mb_substr($str, 0, $maxlen, 'UTF-8');
207
}
208
209
/**
210
 * The function accepts variable number of arguments and replaces each "%i" (where <i>i</i> is
211
 * a natural number) substring of input string with related argument.
212
 *
213
 * Passed arguments can be any type of; in case of string they should be UTF-8 encoded.
214
 *
215
 * @param string $str The UTF-8 encoded string being processed.
216
 * @param mixed Value, which each "%1" substring will be replaced with.
217
 * @param mixed Value, which each "%2" substring will be replaced with.
218
 * @param mixed ... (and so on)
219
 * @return string Processed string.
220
 *
221
 * <br/>Example:<br/>
222
 * <code>
223
 * ustrprocess("Name: %1\nSex: %3\nAge: %2", "Artem", 30, "male");
224
 * </code>
225
 * <br/>will output<br/>
226
 * <pre>
227
 * Name: Artem
228
 * Sex: male
229
 * Age: 30
230
 * </pre>
231
 */
232
function ustrprocess ($str)
233
{
234
    for ($i = func_num_args(); $i > 1; $i--)
235
    {
236
        $search  = '%' . ($i - 1);
237
        $replace = func_get_arg($i - 1);
238
        $str     = ustr_replace($search, $replace, $str);
239
    }
240
241
    return $str;
242
}
243
244
/**
245
 * Converts UTF-8 encoded string to integer (natural) value.
246
 *
247
 * If resulted integer value is less then specified <i>min</i> value, the <i>min</i> value will be returned.
248
 * If resulted integer value is greater then specified <i>max</i> value, the <i>max</i> value will be returned.
249
 *
250
 * @param string $str The UTF-8 encoded string being converted.
251
 * @param int $min Minimum allowed result value.
252
 * @param int $max Maximum allowed result value.
253
 * @return int Natural value of range from <i>min</i> to <i>max</i>.
254
 */
255
function ustr2int ($str, $min = 0, $max = MAXINT)
256
{
257
    $res = (ustrlen($str) == 0 ? $min : intval($str));
258
259
    if ($res < $min)
260
    {
261
        $res = $min;
262
    }
263
    elseif ($res > $max)
264
    {
265
        $res = $max;
266
    }
267
268
    return $res;
269
}
270
271
/**
272
 * Converts specified amount of minutes to its string representation in format "hh:mm".
273
 *
274
 * @param int $time Amount of minutes.
275
 * @return string String representation (e.g. for 127 it will be "2:07").
276
 */
277
function time2ustr ($time)
278
{
279
    return intval(floor($time / 60)) . ':' . str_pad($time % 60, 2, '0', STR_PAD_LEFT);
280
}
281
282
/**
283
 * Strips HTML-tags from UTF-8 encoded string.
284
 *
285
 * @param string $str The UTF-8 encoded string.
286
 * @return string HTML-safe UTF-8 encoded string.
287
 */
288
function ustr2html ($str)
289
{
290
    if (is_null($str)) return NULL;
291
292
    $str = mb_ereg_replace("([\x00-\x08]|[\x0B-\x0C]|[\x0E-\x1F])", NULL, $str);
293
    return @htmlspecialchars($str, ENT_COMPAT, 'UTF-8');
294
}
295
296
/**
297
 * Strips quotes from UTF-8 encoded string.
298
 *
299
 * @param string $str The UTF-8 encoded string.
300
 * @return string JavaScript-safe UTF-8 encoded string.
301
 */
302
function ustr2js ($str)
303
{
304
    $str = htmlspecialchars($str, ENT_NOQUOTES, 'UTF-8');
305
    return ustr_replace('"', '\"', $str);
306
}
307
308
/**
309
 * Strips apostrophes from UTF-8 encoded string.
310
 *
311
 * @param string $str The UTF-8 encoded string.
312
 * @return string SQL-safe UTF-8 encoded string.
313
 */
314
function ustr2sql ($str)
315
{
316
    if ((DATABASE_DRIVER == 1) ||
317
        (DATABASE_DRIVER == 4))
318
    {
319
        $str = ustr_replace('\\', '\\\\', $str);
320
    }
321
322
    $str = ustr_replace('\'', '\'\'', $str);
323
324
    return $str;
325
}
326
327
/**
328
 * Convert UTF-8 encoded string to CSV format.
329
 *
330
 * @param string $str The UTF-8 encoded string.
331
 * @param string $enclosure CSV enclosure.
332
 * @return string CSV string (UTF-8 encoded).
333
 */
334
function ustr2csv ($str, $enclosure = '"')
335
{
336
    $str = ustr_replace($enclosure, $enclosure . $enclosure, $str);
337
338
    return $enclosure . $str . $enclosure;
339
}
340
341
/**
342
 * Parse UTF-8 encoded CSV string into an array.
343
 *
344
 * @param string $str The UTF-8 encoded CSV string.
345
 * @param string $delimiter CSV delimiter.
346
 * @param string $enclosure CSV enclosure.
347
 * @return array Indexed array containing the fields read (UTF-8 encoded), or NULL on error.
348
 */
349
function ustr_getcsv ($str, $delimiter = ',', $enclosure = '"')
350
{
351
    $csv = mb_split($delimiter, $str);
352
353
    for ($i = 0; $i < count($csv); $i++)
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
354
    {
355
        if (usubstr($csv[$i], 0, ustrlen($enclosure)) == $enclosure)
356
        {
357
            while ($i < count($csv) &&
358
                   usubstr($csv[$i], ustrlen($csv[$i]) - ustrlen($enclosure)) != $enclosure)
359
            {
360
                $csv[$i] .= $delimiter . $csv[$i + 1];
361
                array_splice($csv, $i + 1, 1);
362
            }
363
364
            $csv[$i] = usubstr($csv[$i], ustrlen($enclosure), ustrlen($csv[$i]) - ustrlen($enclosure) * 2);
365
        }
366
    }
367
368
    return $csv;
369
}
370
371
/**
372
 * Converts boolean value to integer for use in SQL queries.
373
 *
374
 * @param bool $value Boolean value.
375
 * @return int '1' on TRUE, or '0' on FALSE.
376
 */
377
function bool2sql ($value)
378
{
379
    return ($value ? 1 : 0);
380
}
381
382
/**
383
 * Returns value of user HTML-form request, if it exists; otherwise returns specified default value.
384
 *
385
 * @param string $request Name of user HTML-form request.
386
 * @param mixed $value Default value.
387
 * @return mixed User HTML-form request, or default value if specified request cannot be found.
388
 */
389
function try_request ($request, $value = NULL)
390
{
391
    global $_REQUEST;
392
    return (isset($_REQUEST[$request]) ? $_REQUEST[$request] : $value);
393
}
394
395
/**
396
 * Exchanges values of two variables.
397
 *
398
 * @param mixed &$value1 First variable.
399
 * @param mixed &$value2 Second variable.
400
 */
401
function swap (&$value1, &$value2)
402
{
403
    $temp   = $value1;
404
    $value1 = $value2;
405
    $value2 = $temp;
406
}
407
408
/**
409
 * Finds whether the given UTF-8 encoded string contains valid integer value.
410
 *
411
 * @param string $str The UTF-8 encoded string being evaluated.
412
 * @return bool TRUE if <i>str</i> contains valid integer value, FALSE otherwise.
413
 */
414
function is_intvalue ($str)
415
{
416
    mb_regex_encoding('UTF-8');
417
    return mb_eregi('^(\+|\-)*([0-9])+$', $str);
418
}
419
420
/**
421
 * Finds whether the given UTF-8 encoded string contains valid float value.
422
 *
423
 * @param string $str The UTF-8 encoded string being evaluated.
424
 * @return bool TRUE if <i>str</i> contains valid float value, FALSE otherwise.
425
 */
426
function is_floatvalue ($str)
427
{
428
    mb_regex_encoding('UTF-8');
429
    return mb_eregi('^(\+|\-)*([0-9]){1,10}(\.([0-9]){1,10})?$', $str);
430
}
431
432
/**
433
 * Finds whether the given UTF-8 encoded string contains valid login
434
 * (only latin characters, digits, and underline are allowed).
435
 *
436
 * @param string $str The UTF-8 encoded string being evaluated.
437
 * @return bool TRUE if <i>str</i> contains valid login, FALSE otherwise.
438
 */
439
function is_username ($str)
440
{
441
    mb_regex_encoding('UTF-8');
442
    return mb_eregi('^([_0-9a-z\.\-])+$', $str);
443
}
444
445
/**
446
 * Finds whether the given UTF-8 encoded string contains valid email address.
447
 *
448
 * @param string $str The UTF-8 encoded string being evaluated.
449
 * @return bool TRUE if <i>str</i> contains valid email address, FALSE otherwise.
450
 */
451
function is_email ($str)
452
{
453
    mb_regex_encoding('UTF-8');
454
455
    $atom   = '[-a-z0-9!#$%&\'*+/=?^_`{|}~]';      // allowed characters for part before "at" character
456
    $domain = '([a-z0-9]([-a-z0-9]*[a-z0-9]+)?)';  // allowed characters for part after "at" character
457
458
    return mb_eregi("^{$atom}+(\\.{$atom}+)*@({$domain}{1,63}\\.)+{$domain}{2,63}$", $str);
459
}
460
461
/**
462
 * Sends email notification.
463
 *
464
 * @param string $sender Name of sender.
465
 * @param string $from Email address of sender.
466
 * @param string $to Email addresses of recipients (comma-separated).
467
 * @param string $subject Subject of the notification.
468
 * @param string $message Body of the notification.
469
 * @param int $attachment_id ID of attachment if it should be included in email, NULL otherwise.
470
 * @param string $attachment_name Name of attachment if it should be included in email, NULL otherwise.
471
 * @param string $attachment_type MIME type of attachment if it should be included in email, NULL otherwise.
472
 * @param int $attachment_size Size of attachment if it should be included in email, NULL otherwise.
473
 * @return bool TRUE if the mail was successfully accepted for delivery, FALSE otherwise.
474
 */
475
function sendmail ($sender, $from, $to, $subject, $message, $attachment_id = NULL, $attachment_name = NULL, $attachment_type = NULL, $attachment_size = NULL)
476
{
477
    debug_write_log(DEBUG_TRACE, '[sendmail]');
478
479
    if (strtolower(substr(PHP_OS, 0, 3)) == 'win')
480
    {
481
        $eol = "\r\n";
482
483
        // When PHP is talking to a SMTP server directly, if a full stop is found on the start of
484
        // a line, it is removed. To counter-act this, replace these occurrences with a double dot.
485
        $message = ustr_replace("\n.", "\n..", $message);
486
    }
487
    elseif (strtolower(substr(PHP_OS, 0, 3)) == 'mac')
488
    {
489
        $eol = "\r";
490
    }
491
    else
492
    {
493
        $eol = "\n";
494
    }
495
496
    $sender        = '=?utf-8?b?' . base64_encode($sender) . '?=';
497
    $is_attachment = ($attachment_size <= EMAIL_ATTACHMENTS_MAXSIZE * 1024 && !is_null($attachment_id));
498
    $boundary      = 'eTraxis-boundary:' . md5(uniqid(time()));
499
500
    $headers = implode($eol, array('Date: ' . date(DATE_RFC2822),
501
                                   'From: ' . $sender . ' <' . (EMAIL_NOTIFICATIONS_ENABLED == SMTP_CLIENT_BUILDIN ? SMTP_MAILFROM : $from) . '>',
502
                                   'Reply-To: ' . $from,
503
                                   'Return-Path: ' . $from,
504
                                   'Message-ID: <' . md5(uniqid(time())) . '@' . php_uname('n') . '>',
505
                                   'X-Priority: 3',
506
                                   'X-Mailer: eTraxis ' . VERSION,
507
                                   'MIME-Version: 1.0',
508
                                   ($is_attachment ? 'Content-Type: multipart/mixed; boundary="' . $boundary . '"'
509
                                                   : 'Content-Type: text/html; charset="utf-8"')
510
                                   ));
511
512
    if ($is_attachment)
513
    {
514
        $message = implode($eol, array('This is a multi-part message in MIME format.',
515
                                       NULL,
516
                                       '--' . $boundary,
517
                                       'Content-Type: text/html; charset="utf-8"',
518
                                       NULL,
519
                                       $message,
520
                                       NULL,
521
                                       '--' . $boundary,
522
                                       'Content-Type: ' . $attachment_type . '; name="' . $attachment_name . '"',
523
                                       'Content-Transfer-Encoding: base64',
524
                                       'Content-Disposition: attachment; filename="=?utf-8?b?' . base64_encode($attachment_name) . '?="',
525
                                       NULL,
526
                                       chunk_split(base64_encode(gzfile_get_contents(ATTACHMENTS_PATH . $attachment_id, $attachment_size))),
527
                                       NULL,
528
                                       '--' . $boundary . '--'));
529
    }
530
531
    debug_write_log(DEBUG_DUMP, '[sendmail] $to = ' . $to);
532
    debug_write_log(DEBUG_DUMP, '[sendmail] $subject = ' . $subject);
533
    debug_write_log(DEBUG_DUMP, "[sendmail] \$headers =\n{$headers}");
534
    debug_write_log(DEBUG_DUMP, "[sendmail] \$message =\n{$message}");
535
536
    // MS Outlook cuts email subjects to 255 chars,
537
    // so we have to cut original subject if its base64-version is longer.
538
    $trailing = NULL;
539
540
    while (strlen(base64_encode($subject . $trailing)) > 243)
541
    {
542
        $subject  = substr($subject, 0, -1);
543
        $trailing = '...';
544
    }
545
546
    $subject = '=?utf-8?b?' . base64_encode($subject . $trailing) . '?=';
547
548
    switch (EMAIL_NOTIFICATIONS_ENABLED)
549
    {
550
        case SMTP_CLIENT_PHP:
551
            return @mail($to, $subject, $message, $headers);
552
        case SMTP_CLIENT_BUILDIN:
553
            return smtp_send_mail($to, $subject, $message, $headers);
554
        default:
555
            debug_write_log(DEBUG_WARNING, '[sendmail] Email notifications are disabled.');
556
    }
557
558
    return FALSE;
559
}
560
561
/**
562
 * Round specified timestamp down to midnight.
563
 *
564
 * @param int $timestamp Unix timestamp (see {@link http://en.wikipedia.org/wiki/Unix_time})
565
 * @return int Unix timestamp (see {@link http://en.wikipedia.org/wiki/Unix_time}) for midnight of the same date.
566
 */
567
function date_floor ($timestamp)
568
{
569
    $date = getdate($timestamp);
570
    return mktime(0, 0, 0, $date['mon'], $date['mday'], $date['year']);
571
}
572
573
/**
574
 * Returns timestamp, shifted from specified for particular number of days.
575
 * Negative offset shifts to past, positive - to future.
576
 *
577
 * @param int $timestamp Unix timestamp (see {@link http://en.wikipedia.org/wiki/Unix_time}) to be shifted from
578
 * @param int $offset Number of days to be shifted for
579
 * @return int Unix timestamp (see {@link http://en.wikipedia.org/wiki/Unix_time}) for resulting shifted date.
580
 */
581
function date_offset ($timestamp, $offset)
582
{
583
    $now      = date_floor($timestamp);
584
    $min_date = date_floor(0);
585
    $max_date = date_floor(MAXINT);
586
587
    // Determine maximum allowed shifts to both past and future to avoid byte overflow error
588
    // (any timestamp must be in range from 0x00000000 to 0x7FFFFFFF)
589
    $max_backward = round(($min_date - $now) / SECS_IN_DAY);
590
    $max_forward  = round(($max_date - $now) / SECS_IN_DAY);
591
592
    // If specified offset looks to far in the past, adjust it to the maximum allowed offset.
593
    if ($offset < $max_backward)
594
    {
595
        $offset = $max_backward;
596
    }
597
598
    // If specified offset looks to far in the future, adjust it to the maximum allowed offset.
599
    if ($offset > $max_forward)
600
    {
601
        $offset = $max_forward;
602
    }
603
604
    return strtotime("{$offset} days", $timestamp);
605
}
606
607
/**
608
 * Generates Basic HTTP Authentication realm, based on client browser.
609
 *
610
 * @return string Generated realm.
611
 */
612
function get_http_auth_realm ()
613
{
614
    $realm = 'eTraxis';
615
616
    if (stripos($_SERVER['HTTP_USER_AGENT'], 'Konqueror') !== FALSE ||
617
        stripos($_SERVER['HTTP_USER_AGENT'], 'Opera')     !== FALSE ||
618
        stripos($_SERVER['HTTP_USER_AGENT'], 'Safari')    !== FALSE)
619
    {
620
        $realm .= '-' . time();
621
    }
622
623
    return $realm;
624
}
625
626
/**
627
 * Sends specified message with HTTP Error 500 header.
628
 *
629
 * @param string $msg
630
 */
631
function send_http_error ($msg)
632
{
633
    header('HTTP/1.0 500 Internal Server Error');
634
    echo($msg);
635
}
636
637
/**
638
 * Gzips specified file, keeping same name.
639
 *
640
 * @param string $srcName Name of the input file.
641
 */
642
function compressfile ($srcName)
643
{
644
    if (extension_loaded('zlib'))
645
    {
646
        $dstName = "{$srcName}.gz";
647
648
        $fp = fopen($srcName, 'rb');
649
        $data = fread($fp, filesize($srcName));
650
        fclose($fp);
651
652
        $zp = gzopen($dstName, 'wb6');
653
        gzwrite($zp, $data);
654
        gzclose($zp);
655
656
        unlink($srcName);
657
        rename($dstName, $srcName);
658
    }
659
}
660
661
/**
662
 * Equivalent of standard {@link http://www.php.net/file-get-contents file_get_contents} function for a gzipped attachment.
663
 *
664
 * @param string $srcName Name of the gzipped file.
665
 * @param int $uncompressedSize Uncompressed size of the input file.
666
 * @return string Uncompressed file contents.
667
 */
668
function gzfile_get_contents ($srcName, $uncompressedSize)
669
{
670
    if (extension_loaded('zlib'))
671
    {
672
        $fp = gzopen($srcName, 'rb');
673
        $data = gzread($fp, $uncompressedSize);
674
        gzclose($fp);
675
676
        return $data;
677
    }
678
    else
679
    {
680
        return file_get_contents($srcName);
681
    }
682
}
683
684
?>
685