summaryrefslogtreecommitdiff
path: root/it.class
blob: 754f7b99ac19fdea4126efc0c9ca574a610ecc17 (plain)
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
<?php
/*
**	$Id$
**
**	Copyright (C) 1995-2007 by the ITools Authors.
**	This file is part of ITools - the Internet Tools Library
**
**	ITools is free software; you can redistribute it and/or modify
**	it under the terms of the GNU General Public License as published by
**	the Free Software Foundation; either version 3 of the License, or
**	(at your option) any later version.
**
**	ITools is distributed in the hope that it will be useful,
**	but WITHOUT ANY WARRANTY; without even the implied warranty of
**	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
**	GNU General Public License for more details.
**
**	You should have received a copy of the GNU General Public License
**	along with this program.  If not, see <http://www.gnu.org/licenses/>.
**
**	it.class - static functions
*/

class it
{
/**
 * Create config class with static members initialized (e.g. $home).
 * NOTE: PHP5 ONLY
 * @param $p Static members to be generated in newly created class
 *      service: Class name of created class (default: from caller path)
 *      home: Home directory of application (default: from caller path)
 *      site: Domain name of application (default: from caller path)
 *      db: Database of application (default: from caller path)
 */
static function createconfig($p = array())
{
	$stack = debug_backtrace();
	$filename = $stack[0]['file'];
	preg_match('!/www/((\w+)[^/]+)!', $filename, $parts);

	$p += array(
		'home' => $parts[0],
		'site' => $parts[1],
		'db' => strtr($parts[1], ".-", "__"),
		'service' => $parts[2],
	);

	if (class_exists($p['service'] . "_tools"))
		$extends = "extends {$p['service']}_tools ";

	$code = array("class {$p['service']} $extends{");

	foreach ($p as $name => $value)
		$code[] = "static \$$name = " . var_export($value, true) . ";";

	$code[] = "}";
	eval(join("\n", $code));
}


/**
 * Clone an object and return copy, works for all PHP versions
 */
static function &cloneobj(&$object)
{
	$result = (is_object($object) && version_compare(zend_version(), 2, '>=')) ? clone($object) : $object;

	return $result;	# PHP internals need a tmp var to return by ref
}


/**
 * Append all arguments to a logfile (tab separated). Date will be added to filename and line
 * @param $name Name of logfile. Will be in log/ of service unless it starts with /
 * @param $line1 Line to append (varargs)
 */
static function log($name /* ... */)
{
	$args = func_get_args();
	$line = date("Y-m-d H:i:s") . "\t" . implode("\t", array_slice($args, 1)) . "\n";
	$basefn = substr($name, 0, 1) == "/" ? $name : $GLOBALS['ULTRAHOME'] . "/log/$name";
	$fullfn = $basefn . "-" . date('Ymd');

	if (substr($fullfn, 0, 1) == "/")
	{
		if (!file_exists($fullfn))
		{
			$tmp = getmypid();
			@touch("$fullfn.$tmp");
			@chgrp("$fullfn.$tmp", "www");
			@chmod("$fullfn.$tmp", 0664);
			@rename("$fullfn.$tmp", $fullfn);
			@unlink($basefn);
			@symlink($fullfn, $basefn);
		}

		file_put_contents($fullfn, $line, FILE_APPEND);
	}	
}


/**
 * Store timings for appending to log/timer_log-* in auto_append.php
 */
static function timerlog($label = '')
{
	if ($GLOBALS['debug_timerlog'])
		$GLOBALS['ULTRATIMERLOG'] .= sprintf(" %s:%d", $label, (microtime(true) - $GLOBALS['ULTRATIME'])*1000);
}


/**
 * Send verbose error report to browser or (if display_errors is off) by email to .diffnotice gods, file owner or SERVER_ADMIN
 * All params optional. Single string parameter means 'title'.
 * @param $p['title'] error title, one line
 * @param $p['body'] error body, multiline
 * @param $p['to'] comma separated recipient list
 * @param $p['id'] identifier of error. if given, only subsequent errors of same id will trigger message
 * @param $p['graceperiod'] number of seconds within which additional errors are ignored if id is set [60]
 * @param $p['timewindow'] number of seconds after graceperiod within which the second error must occur if id is set [25*3600]
 * @param $p['backtraceskip'] number of stack levels to drop
 * @param $p['skipfiles'] files to skip in backtrace
 * @param $p['blockmail'] number of seconds to block mails after having sent a mail [3600]
 * @param $p['blockmailid'] block mail for $p['blockmail'] seconds with same id. Default: $p['to']
 * @param $p['omitdebuginfo'] Do not add stack dump, locals and environment to output [false]
 * @return true if a mail was sent
 */
static function error($p = array(), $body = null, $to = null) # $body and $to deprecated
{
	if (!is_array($p))
		$p = array('title' => $p, 'body' => $body, 'to' => $to);

	if ($_SERVER['REMOTE_ADDR'])
		$url = ($_SERVER['HTTPS'] ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
	else
		$url = $_SERVER['SCRIPT_NAME'] . " " . join(" ", array_slice($GLOBALS['argv'], 1)) . " (pwd " . $_SERVER['PWD'] . ")";

	$gods = strtr(trim(@file_get_contents($GLOBALS['ULTRAHOME'] . "/.diffnotice")), array("\n"=>', '));
	if (!$p['to'])
		unset($p['to']); # allow defaults to kick in
	$p += array(
		'title' => "it::error",
		'to' => $gods ? $gods : (get_current_user() ? get_current_user() : $_SERVER['SERVER_ADMIN']),
		'graceperiod' => 60, 
		'timewindow' => 25*3600,
		'backtraceskip' => 0,
		'blockmail' => 3600,
		'omitdebuginfo' => false,
	);
	$p += array('blockmailid' => md5($p['to']));

	@mkdir("/tmp/alertdata");
	@chmod("/tmp/alertdata", 0777);		

	$toscreen = ini_get('display_errors') || (defined("STDOUT") && posix_isatty(STDOUT)) || EDC('astwin') || EDC('asdevel');
	@fseek(STDOUT, 0, SEEK_END);    # Work around PHP bug 49819: posix_isatty seeks to start

	if ($toscreen && !it::is_live())
		$GLOBALS['debug_noredir'] = 1;

	if (!$toscreen) # this error can only be sent by mail: find out if we want to suppress it
	{
		if (!$p['id'])
			$sendmail = true;
		else
		{
			$errstampfn = "/tmp/alertdata/errstamp_" . urlencode($p['id']);
			$errstampage = time() - @filemtime($errstampfn);
			$sendmail = $errstampage >= $p['graceperiod'] && $errstampage <= $p['graceperiod'] + $p['timewindow'];
			if ($errstampage > $p['graceperiod'])
			{
				@unlink($errstampfn);
				@touch($errstampfn);
			}
		}

		if ($sendmail)
		{
			$lastsentfn = "/tmp/alertdata/lastsent_" . getmyuid() . "." . $p['blockmailid'];
			$now = time();
			clearstatcache();
			$lastsenttime = @filemtime($lastsentfn);
			$sendmail = $now - $lastsenttime > $p['blockmail'];
			if ($sendmail)
			{
				@unlink($lastsentfn);
				@touch($lastsentfn);
			}
		}
	}

	if ($toscreen || $sendmail)
	{
		$trace = it_debug::backtrace(array('skiplevels' => $p['backtraceskip'], 'skipfiles' => $p['skipfiles'])); # moved in here for performance in mass error case

		if (strlen($p['body']) > 500000)
		{
			file_put_contents($datafn = "/tmp/alertdata/error-" . substr(md5($p['body']), 0, 2), $p['body']);
			$p['body'] = "Body: " . getenv('HOSTNAME') . ":$datafn";
		}

		$body = ($p['body'] ? trim($p['body'])."\n\n" : "") . ($url && !$toscreen? "{$p['title']}\n\nUrl: $url\n\n" : "") . ($trace ? ($sendmail?"" :"  ")."Trace: $trace\n\n" : "");

		if ($sendmail) # we're mailing: send maximum info
		{
			$p['title'] = "Alert: " . $p['title'] . " (on " . getenv('HOSTNAME') . ")";

			if (!$p['omitdebuginfo'])
			{
				foreach (($trace ? debug_backtrace() : array()) as $level => $stackframe)
					if ($level >= $p['backtraceskip'] && $tracesize < 100000 && ($tracesize += strlen(print_r($stackframe, true))) < 100000) # save mem
						$stackframes[] = $stackframe;

				$body .= "Host: " . getenv('HOSTNAME') . "\n\n";
				$body .= $p['id']     ? "Filter: graceperiod={$p['graceperiod']} timewindow={$p['timewindow']}\n\n" : "";
				$body .= "Time: " . it::date() . "\n\n";
				$body .= $_GET        ? "\$_GET: "    . var_export($_GET, true) . "\n\n" : "";
				$body .= $_POST       ? "\$_POST: "   . var_export($_POST, true) . "\n\n" : "";
				$body .= $_COOKIE     ? "\$_COOKIE: " . var_export($_COOKIE, true) . "\n\n" : "";
				$body .= $_SERVER     ? "\$_SERVER: " . var_export($_SERVER, true) . "\n\n" : "";
				$body .= $_FILES      ? "\$_FILES:  " . var_export($_FILES, true) . "\n\n" : "";
				$body .= $stackframes ? "Stack: "     . print_r($stackframes, true) . "\n\n" : "";
				$body  = it::replace(array('(pw|passw|password|secret)\] => .*' => '$1] => ********'), $body, array('utf8' => false));
			}

			it::mail(array('To' => $p['to'], 'Subject' => substr($p['title'], 0, 160), 'Body' => $body, 'Cc' => $GLOBALS['it_defaultconfig']['error_cc'], 'forcemail' => !it::is_devel()));
		}
		else if ($_SERVER['REMOTE_ADDR']) # toscreen mode: web
			echo "<pre>" . htmlspecialchars($p['title'] . "\n" . rtrim($body), ENT_COMPAT, "iso-8859-1") . "</pre>"; # works with iso-8859-1 or utf-8, UTF8SAFE
		else  # toscreen mode: shell (outputs to stderr)
			error_log(substr($p['title'], 0, 100000) . " in " . ($trace ? $trace : "{$p['file']}:{$p['line']} Url: $url") . " " . (EDC('verboseerrors') ? D($p['locals']) : ""));
	}

	if ($_SERVER['REMOTE_ADDR']) # additional entry in log/error_log
		error_log("it::error: " . $p['title'] . " Url: $url");

	file_put_contents("/tmp/alertdata/alert.log", it::date() . " " . $p['title'] . " in " . ($trace ? $trace : "{$p['file']}:{$p['line']} Url: $url") . "\n", FILE_APPEND);
	@chmod("/tmp/alertdata/alert.log", 0777);

	return $sendmail;
}


/**
 * Same as it::error(), plus exit
 * @see error()
 */
static function fatal($title='', $body='', $to='')
{
	$p = is_array($title) ? $title : array('title' => $title, 'body' => $body, 'to' => $to);
	$p['backtraceskip']++;
	it::error($p);
	exit(1);
}


/**
 * Print message to stderr and exit with error code
 */
static function bail($message = "Bailed.\n")
{
	fputs(STDERR, $message);
	exit(1);
}


/**
 * Check wether I am on a live server for this service. Honors 'aslive' and 'asdevel' debug vars
 * @return true if servertype is 'live'
 */
static function is_live()
{
	return (preg_match("/^live/", $GLOBALS['ULTRASERVERTYPE']) || !$GLOBALS['ULTRASERVERTYPE'] || EDC('aslive')) && !EDC('asdevel');
}


/**
 * Check wether I am on a development server for this service. Honors 'aslive' and 'asdevel' debug vars
 * @return true if servertype is 'devel'
 */
static function is_devel()
{
	return (preg_match("/^devel/", $GLOBALS['ULTRASERVERTYPE']) || EDC('asdevel')) && !EDC('aslive');
}


/**
 * Convert a string to ASCII-only chars, map/strip ISO-8859-1 accents
 * @param $text Text to convert
 * @return mapped/stripped version of $text contains only chars [0..127]
 */
static function toascii($text)
{
	return strtr(strtr($text,
		utf8_decode(	'ÇéâàåçêëèïîìÅÉôòûùÿøØáíóúñÑÁÂÀãÃÊËÈÍÎÏÓÔõÕÚÛÙýÝ'),
				'CeaaaceeeiiiAEoouuyooaiounNAAAaAEEEIIIOOoOUUUyY'),
		array("\xe4" => 'ae', "\xf6" => 'oe', "\xfc" => 'ue', "\xc4" => 'Ae', "\xd6" => 'Oe', "\xdc" => 'Ue', "\xe6" => 'ae', "\xc6" => 'Ae', "\xdf" => 'ss'));
}


/**
 * Convert regex for preg (adds and escapes delimiter, adds modifiers)
 * @param $pattern Regex to convert
 * @param $p['casesensitive'] Regex is case sensitive (omit modifier i)
 * @param $p['multiline'] add modifier m: ^ and $ match \n
 * @param $p['singleline'] add modifier s: . matches \n
 * @param $p['utf8'] add modifier u. This is the default if default_charset is utf-8, override with $p['utf8'] = false
 * @param $p['extended'] add modifier x (non signifcant whitespace)
 * @return converted regex to use with preg
 */
static function convertregex($pattern, $p = null)
{
	if ($p['exec'])
		it::fatal("Option exec to it::replace has been removed for security reasons");

	return '/' . strtr($pattern, array('/' => '\/')) . '/' .
		(!$p['casesensitive'] ? 'i' : '') .
		($p['multiline'] ? 'm' : '') .
		($p['singleline'] ? 's' : '') .
		($p['extended'] ? 'x' : '') .
		((!isset($p['utf8']) && ini_get('default_charset') == 'utf-8' || $p['utf8']) ? 'u' : '');
}


/**
 * Try to match string against regex. Case insensitive by default.
 * @param $pattern Regex to match against
 * @param $string String to match
 * @param $p['offset_capture'] Set flag preg_offset_capture (returns offsets with the matches).
 * @param $p['all'] Return every match as array instead of first match.
 * @param $p contains pattern modifiers, @see convertregex()
 * @return Matched string or false 
 */
static function match($pattern, $string, $p = null)
{
	if (!preg_match('/\\\\[wb]|[!\x80-\xff]|\[\[:/i', $pattern) && !$p)
		$r = preg_match('!' . $pattern . '!i' . (ini_get('default_charset') == 'utf-8' ? 'u' : ''), $string, $m); # fast path for simple patterns
	else
	{
		$flags = $p['offset_capture'] ? PREG_OFFSET_CAPTURE : 0;

		if ($p['all'])
			$r = preg_match_all(it::convertregex($pattern, $p), $string, $m, $flags | PREG_PATTERN_ORDER, $p['offset']);
		else
			$r = preg_match(it::convertregex($pattern, $p), $string, $m, $flags, $p['offset']);
	}

	if (!$r)	# no match
	{
		if (preg_last_error() == PREG_BACKTRACK_LIMIT_ERROR)
			it::error("Exceeded pcre.backtrack_limit of " . ini_get('pcre.backtrack_limit') . " bytes");
		else if (preg_last_error() == PREG_BAD_UTF8_ERROR)
			it::error("Invalid utf-8 in it::match haystack: " . substr($string, 0, 500)); # UTF8SAFE

		$result = $p['all'] ? array() : null;
	}
	else if (count($m) == 1)	# no capture
		$result = $m[0];
	else if (count($m) == 2)	# one capture
		$result = $m[1];
	else if ($p['all'] && !$p['pattern_order'])	# captures, reorder pattern_order to set_order but without first element
		$result = call_user_func_array('array_map', array_merge(array(null), array_slice($m, 1)));
	else	# captures, don't return first element (matched string)
		$result = array_slice($m, 1);

	return $result;
}


/**
 * Replace parts of a string matched by a pattern with according replacement string. See convertregex for named parameters.
 * @param $replacementes Array with patterns as keys and replacement strings as values
 * @param $string String to change
 * @param $p['limit'] limit number of replacements (default: all)
 * @return New string
 * @see convertregex for more options in $p
 */
static function replace($replacements, $string, $p = array())
{
	$encoding = ini_get('default_charset') == 'utf-8' ? 'u' : '';
	foreach ($replacements as $pattern => $dummy)
		$patterns[] = !preg_match('/\\\\[wb]|[!\x80-\xff]|\[\[:/i', $pattern) && !$p ? "!$pattern!i$encoding" : it::convertregex($pattern, $p);

	$result = preg_replace($patterns, $replacements, $string, isset($p['limit']) ? $p['limit'] : -1);

	 if ($result === null && preg_last_error() == PREG_BAD_UTF8_ERROR)
		it::error("Invalid utf-8 in it::replace haystack: " . substr($string, 0, 500)); # UTF8SAFE

	return $result;
}

/**
 * Returns only the array elements matching the given regex
 * @param $pattern Regex to match against
 * @param $array   array to grep
 * @return New array
 */
static function grep($pattern, $array, $p = array())
{
	if (!preg_match('/\\\\[wb]|[!\x80-\xff]|\[\[:/i', $pattern) && !$p)
		$result = preg_grep('!' . $pattern . '!i' . (ini_get('default_charset') == 'utf-8' ? 'u' : ''), $array); # fast path for simple patterns
	else
		$result = preg_grep(it::convertregex($pattern, $p), $array);

	return $result;
}

/**
 * Convert string or array to utf8 if it was not already utf-8 before. Also handles double encoding
 * @param $value String or array to convert
 * @param $errprefix Error message to output if anything needed to be done
 * @return Same string in utf-8 encoding
 */
static function any2utf8($value, $errprefix = "")
{
	if (is_array($value))
	{
		foreach ($value as $idx => $v)
			if (is_string($v) || is_array($v))
				$value[$idx] = self::any2utf8($v, $errprefix);
	}
	else if (is_string($value))
	{
		if (grapheme_strlen($value) === null)
			list($value, $error) = array(utf8_encode($value), utf8_encode("incorrect utf8-encoding. input=$value"));
		if (preg_match('/\xc3[\x82\x83]\xc2[\x82\x83\xbc\xa9\xa4\xb6\xa8\xa2\xa0\xb4\xaa\xa7\x84\xab\xae\x9c\xaf\x96\xb2\xbb\xb9\x9f]/', $value))
			list($value, $error) = array(it::any2utf8(preg_replace_callback('/\xc3[\x82\x83]\xc2[\x82\x83\xbc\xa9\xa4\xb6\xa8\xa2\xa0\xb4\xaa\xa7\x84\xab\xae\x9c\xaf\x96\xb2\xbb\xb9\x9f]/', function($m) {return utf8_decode($m[0]);}, $value)), "double utf8-encoding. input=$value");
		if (preg_match('/\xef\xb7[\x90-\xaf]|\xef\xbf[\xbe\xbf]/', $value))
			list($value, $error) = array(preg_replace('/\xef\xb7[\x90-\xaf]|\xef\xbf[\xbe\xbf]/', " ", $value), "forbidden utf-8 character. input=$value");
		if ($error && $errprefix)
			it::error(array('title' => "$errprefix: " . trim($error)));
	}

	return $value;
}

/**
 * Uppercase first character similar to ucfirst() but for mbstring.internal_encoding
 */
static function ucfirst($string)
{
	return mb_strtoupper(mb_substr($string, 0, 1)) . mb_substr($string, 1);
}

/**
 * Lowercase first character similar to lcfirst() but for mbstring.internal_encoding
 */
static function lcfirst($string)
{
	return mb_strtolower(mb_substr($string, 0, 1)) . mb_substr($string, 1);
}

/**
 * Uppercase first character of each word similar to ucwords() but for mbstring.internal_encoding
 */
static function ucwords($string)
{
	return preg_replace_callback('/\b\w/u', function($m) { return mb_strtoupper($m[0]); }, mb_strtolower($string));
}

static function substr_replace($string, $replacement, $start, $length)
{
	return grapheme_substr($string, 0, $start) . $replacement . grapheme_substr($string, $start + $length);
} 

/**
 * Extract key => value pairs from assoc array by key
 * @param $array array to filter
 * @param $keys array or comma separated list of keys to keep
 * @param $p['reorder'] reorder pairs to the order of the $keys array
 */
static function filter_keys($array, $keys, $p = array())
{
	$result = array();
	if (is_string($keys))
		$keys = explode(",", $keys);
	if ($p['reorder'])
	{
		foreach ((array)$keys as $key)
			$result[$key] = $array[$key];
	}
	else
	{
		$keep = array_flip((array)$keys);
		foreach ($array as $key => $val)
			if (isset($keep[$key]))
				$result[$key] = $val;
	}

	return $result;
}


/**
 * Construct shell command using it::shell_command, log it, execute it and return output as string.
 * {keyword} quotes and inserts value from assoc array like ET()
 * {0} .. {n} quotes and inserts positional arguments
 * {-opts} takes an array and inserts options a la it_html attributes (value, true, false or null)
 * @param $cmd Format string with {keywords} a la ET()
 * @param $values (zero, one or more arrays can be passed)
 * @return output of command. shell errors not detectable, see error_log in /www/server/logs
 */
static function exec(/* $cmd, $values1 = array(), ... */)
{
	$args = func_get_args();
	$cmd = call_user_func_array('it::shell_command', $args);

	$before = microtime(true);
	$result = EDC('noexec') ? "" : (string)shell_exec($cmd);

	@it::log('exec', round((microtime(true) - $before)*1000) . "\t$cmd");

	return $result;
}

/**
 * Construct shell command using it::shell_command, log it, execute it and return exit code.
 * stdout/stderr is forwarded to stdout/stderror of calling script
 * {keyword} quotes and inserts value from assoc array like ET()
 * {0} .. {n} quotes and inserts positional arguments
 * {-opts} takes an array and inserts options a la it_html attributes (value, true, false or null)
 * @param $cmd Format string with {keywords} a la ET()
 * @param $values (zero, one or more arrays can be passed)
 * @return exit code of command.
 */
static function system(/* $cmd, $values1 = array(), ... */)
{
	$args = func_get_args();
	$cmd = call_user_func_array('it::shell_command', $args);

	$before = microtime(true);
	if (!EDC('noexec'))
		system($cmd, $result);
	else
		$result = 0;

	@it::log('exec', round((microtime(true) - $before)*1000) . "\t$cmd");

	return $result;
}

/**
 * Construct shell command
 * Keywords {keyword} are replace a la ET(), {-opts} takes an array and
 * inserts options a la it_html attributes (value, true, false or null)
 * @param $cmd Format string with {keywords} replace a la ET()
 * @param $values (zero, one or more arrays can be passed)
 * @return output of command. shell errors not detectable, see error_log in /www/server/logs
 */
static function shell_command(/* $cmd, $values1 = array(), ... */)
{
	$args = func_get_args();
	$cmd = array_shift($args);
	$values = array();

	# Merge values into one array
	foreach ($args as $arg)
		$values = array_merge($values, (array)$arg);

	#for escapeshellarg in it::_exec_quotevalue
	$oldlocale = setlocale(LC_CTYPE, 0);
	setlocale(LC_CTYPE, 'de_CH');
	foreach (it::match('({(-?)([a-z0-9]\w*)})', $cmd, array('all' => true)) as $tags)
	{
		list($tag, $option, $key) = $tags;
		$parts = array();

		if ($option)
		{
			foreach ((array)$values["-$key"] as $key => $value)
			{
				if ($key[0] != '-')
					$key = ($key[1] ? '--' : '-') . $key;
				if ($value === true || $value === false || $value === null)
					$parts[] = $value ? $key : "";
				else foreach ((array)$value as $val)
					$parts[] = "$key " . it::_exec_quotevalue($val, "cmd=$cmd key=$key val=$val");
			}
		}
		else
		{
			foreach ((array)$values[$key] as $value)
				$parts[] = it::_exec_quotevalue($value, "cmd=$cmd key=$key val=$value");
		}

		$replacements[$tag] = join(" ", $parts);
	}

	$cmd = strtr($cmd, (array)$replacements);	# Use strtr behaviour of going through source string once
	setlocale(LC_CTYPE, $oldlocale);
	return $cmd;
}

#fails with C locale!!!
static function _exec_quotevalue($value, $errmsg = "")
{
	$result = strval($value);

	if (it::match('^-', $result))
		it::fatal("leading - in value: " . $errmsg);

	return preg_match('#^[-a-zA-Z0-9./_:,]+$#', $result) ? $result : escapeshellarg($result);
}


/**
 * Convert an image to a given size and type (ensures input is an image)
 * @param $p['in']		Input filename (mandatory)
 * @param $p['out']		Output filename (mandatory)
 * @param $p['size']		Width x height of resulting image, e.g. "160x60"
 * @param $p['type']		Output file type, e.g. "jpg"
 * @param $p['types']		Comma separated list of accepted input types, default "bmp,eps,gif,jp2,jpg,png,svg,tif"
 * @param $p['quality']		JPEG quality (0-100), default is 75
 * @param $p['keepalpha']	Don't add option --flatten to preserve alpha channel
 * @param $p['-opts']		Custom command line options to ImageMagick convert
 * @return Success of convert as true/false
 */
static function imageconvert($p)
{
	if (!(($imagetype = @exif_imagetype($p['in'])) && ($type = image_type_to_extension($imagetype, false))))
	{
		if (@get_class(it_xml::create(fopen($p['in'], "r"), array('prefix' => "_imageconvert_", 'safety' => 0))) == "_imageconvert_svg")
			$type = "svg"; # Accept SVG files if they are valid XML and root tag is svg
		else
			list(, $type) = explode(' ', strtolower(it::exec('identify 2>/dev/null {in}', $p))); # for things like eps
	}

	# emulate -auto-orient which is not supported by GM
	if ($p['-opts']['-auto-orient'])
	{
		$exif = @exif_read_data($p['in'], 'IFD0');
		switch ($exif['Orientation'])
		{
			case 2: $p['-opts']['-flop'] = true;  break;
			case 3: $p['-opts']['-rotate'] = 180; break;
			case 4: $p['-opts']['-flip'] = true;  break;
			case 6: $p['-opts']['-rotate'] = 90;  break;
			case 8: $p['-opts']['-rotate'] = 270; break;
		}

		unset($p['-opts']['-auto-orient']);
	}

	$type = strtr($type, array("jpeg" => "jpg", "tiff" => "tif", "ps" => "eps", "ept" => "eps"));
	$p += array('type' => $type, 'types' => "bmp,eps,gif,jp2,jpg,png,svg,tif", 'quality' => 75);
	$p['-opts'] = array('-thumbnail' => $p['size'], '-quality' => $p['quality']) + (array)$p['-opts'];

	if (!$p['keepalpha'])
		$p['-opts'] = array_merge(array('-flatten' => true), $p['-opts']);	# Option -flatten must be first

	$ultratimeout = file_exists("/opt/ultra/bin/ultratimeout") ? "/opt/ultra/bin/ultratimeout 30 " : "";

	if (in_array($type, explode(',', $p['types'])))	# Valid type?
		$cmdoutput = it::exec($ultratimeout . 'gm convert 2>&1 {-opts} {in} {type}:{out} || echo "SHELL ERROR $?"', $p);

	return $cmdoutput === "";
}


/**
 * Parse command line options with Usage given as template and return assoc array. Example: (like grep --help)
 * Usage: myprogram.php [OPTIONS] PATTERN
 *  -s, --short      Use short ouput
 *  -f, --file=FILE  Use FILE for input [foo.txt]
 *  -x EXTENSION     Ignore EXTENSION
 * Mandatory arguments from the Usage: line are returned under their (lowercased!) name.
 * All non-option arguments are returned in 'args'
 * Option text must be indented; if long and short option present, value is stored in long one.
 * For long opts with arguments, = is mandatory. Defaults in [ ] at end of line
 * Options without arguments store true or false under their key
 * Options -h and --help will be handled internally by printing usage and exiting
 * When printing, the usage will be de-indented so the first line starts in the first column
 * Two or more blanks must be in front of option explanation
 * If an option 'verbose' is set, it will be set as debug variable as well so EDC('verbose', $bar) works
 * @param $helplines Usage parsed to determine options
 * @return Associative array of options
 */
static function getopt($helplines)
{
	$GLOBALS['it_stdin'] = array(
		'fd' => null,
		'args' => array(),
		'filename' => "",
		'line' => 0,
	);

	$result = array('args' => array());

	if ($indentation = it::match('^\s+', $helplines))
		$helplines = it::replace(array($indentation => "\n"), $helplines);

	foreach(explode("\n", trim($helplines)) as $helpline)
	{
		$shortoptname = $shortoptarg = $longoptname = $longoptarg = "";
		foreach (explode(',', $helpline) as $optdesc)
		{
			$optdesc = trim($optdesc);
			if ($matches = (array)it::match('^--(\w[\w-]*)(=[A-Z])?', $optdesc))
				list($longoptname, $longoptarg) = $matches;
			elseif ($matches = (array)it::match('^-(\w)( [A-Z])?', $optdesc))
				list($shortoptname, $shortoptarg) = $matches;
		}	

		if (($longoptarg || $shortoptarg) && ($default = it::match('\[(.*)\]\s*$', $helpline)))
			$defaults[$longoptname ? $longoptname : $shortoptname] = it::replace(array('^default:?\s*' => ""), trim($default));

		if ($longoptname || $shortoptname)
		{
			if ($longoptname && ($shortoptname || $shortoptname === "0"))
				$alias[$shortoptname] = $longoptname;

			$witharg[$longoptname ? $longoptname : $shortoptname] = $longoptarg || $shortoptarg;
		}
	}
	$witharg['debug'] = true;

	$mandatoryargs = array();
	if ($tmp = trim(it::replace(array("\n.*" => "", "^\S+\s+\S+\s*" => "", "\[.*?\]\s*" => ""), trim($helplines))))
		$mandatoryargs = preg_split('/\s+/', $tmp);

	foreach (array_slice($_SERVER['argv'], 1) as $arg)
	{
		if ($noopts)
			$result['args'][] = $arg;
		else if ($eat)
		{
			if (it::match('^--?\w', $arg))	# Already next option => Missing argument?
				$err = true;
			else
				$result[array_shift($eat)] = $arg;
		}
		else if ($arg == "--")
			$noopts = true;
		elseif ($matches = (array)it::match('^--(\w[\w-]*)(=.*)?', $arg))
		{
			list($optname, $val) = $matches;
			if (!isset($witharg[$optname]) || isset($val) && !$witharg[$optname])
				$err = true;
			else if($witharg[$optname] && !$val)
				$eat[] = $optname;
			else
				$result[$optname] = $val ? substr($val, 1) : true;
		}
		else if (($letters = it::match('^-(\w+)', $arg)) || $letters === "0")
		{
			foreach (explode("\n", trim(chunk_split($letters, 1, "\n"))) as $letter)
			{
				$optname = $alias[$letter] ? $alias[$letter] : $letter;
				if ($witharg[$optname])
					$eat[] = $optname;
				else if (!isset($witharg[$optname]))
					$err = true;
				else
					$result[$optname] = true;
			}
		}
		elseif($mandatoryargs)
			$result[strtolower(array_shift($mandatoryargs))] = $arg;
		else
			$result['args'][] = $arg;
	}

	if ($err || $eat || $result['h'] || $result['help'] || $mandatoryargs)
	{
		fputs(($result['h'] || $result['help'] ? STDOUT : STDERR), trim($helplines) . "\n");
		exit(1);
	}

	if ($result['debug'])    
	{
		foreach (preg_split('/[.,]/', $result['debug']) as $ultrad)
		{
			$ultravar = preg_split('/[-=:]/', $ultrad);
			$GLOBALS["debug_$ultravar[0]"] = isset($ultravar[1]) ? $ultravar[1] : 1;
		}
	}

	$GLOBALS['it_stdin']['args'] = $result['args'] ? $result['args'] : array("-");
	it::_stdin_next();

	if ($result['verbose'])
		$GLOBALS['debug_verbose']++;

	return $result + (array)$defaults;
}

static function _stdin_next()
{
	if ($result = $GLOBALS['it_stdin']['args'])
	{
		$GLOBALS['it_stdin']['filename'] = array_shift($GLOBALS['it_stdin']['args']);
		$GLOBALS['it_stdin']['fd'] = ($GLOBALS['it_stdin']['filename'] == "-") ? STDIN : @fopen($GLOBALS['it_stdin']['filename'], "r");
		$GLOBALS['it_stdin']['line'] = 0;
	}

	return $result;
}

/**
 * Get one line from stdin (or files given on command line) a la Perl <>.
 * Note: You need to call getopt() before using this function.
 * @return Line (including newline) or false on eof
 */
static function gets()
{
	do {
		$result = fgets($GLOBALS['it_stdin']['fd']);
	} while (($result === false) && it::_stdin_next());

	$GLOBALS['it_stdin']['line']++;
	return $result;
}

/**
 * Output formatted and localized date
 * @param format optional format (default is 2007-01-02 03:04:05).
 *        Other formats are "date", "datetime", "time".
 *        Formats can be qualified with language, e.g. "date:en"
 *        Special formats without language support are "icsdate", "icsdatetime".
 * @param stamp optional unix timestamp (default is now).
 *        If it contains nondigits, it is fed to strtotime
 */
static function date($format = "", $stamp = null)
{
	if (!isset($stamp))
		$stamp = time();
	else if (is_string($stamp) && !ctype_digit($stamp))
		$stamp = strtotime($stamp);

	list($name, $language) = explode(":", $format);

	if ($format && !$language)
		$language = T_lang();

	$formats = array(
		"" => "Y-m-d H:i:s",
		"date" => "d.m.Y",
		"datetime" => "d.m.Y H:i",
		"time" => "H:i",
		"date:en" => "m/d/Y",
		"datetime:en" => "m/d/Y H:i",
		"icsdate" => "Ymd",
	);

	if (!($formatstring = $formats["$name:$language"]) && !($formatstring = $formats[$name]))
	{
		if ($format == "icsdatetime")	# Special icsdate or icsdatetime format? Use UTC time format for Google Calendar to be happy
			return gmdate("Ymd", $stamp) . "T" . gmdate("His", $stamp) . "Z";
		else
			$formatstring = $format;
	}

	return date($formatstring, $stamp);
}

/**
 * Iterate over an array, replacing every element by expression
 * @param $expression The expression to apply, may contain $k for keys and $v for values
 * @param $array The array to iterate over
 */
static function map($expression, $array)
{
	static $cache = array();

	if (!($func = $cache[$expression]))
		$func = $cache[$expression] = create_function('$k,$v', "return $expression;");

	foreach ($array as $k => $v)
		$result[$k] = $func($k, $v);

	return (array)$result;
}

/**
 * Send a mail.
 * @param $p Header => Content