PHP userland backwards compatibility layer that emulates PHP 5.5+ core functions.

⌈⌋ ⎇ branch:  upgrade.php


Check-in [eb603f1c4e]

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:upgradephp-1
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: eb603f1c4e4751ea0422341bc224870f681f32a8
User & Date: mario 2010-06-22 16:19:43
Context
2010-06-22
16:20
upgradephp-2 check-in: d25900af3e user: mario tags: trunk
16:19
upgradephp-1 check-in: eb603f1c4e user: mario tags: trunk
15:04
initial empty check-in check-in: 1e0f19e437 user: mario tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Added README.













































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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

PHP downwards compatibility functions
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
Because web hosters often use outdated PHP script versions, there
are regularily functions missing, what prevents certains scripts
from running (if those were written with later interpeter versions
in mind). Sourceforge.net makes a good example. The include script
presented here emulates some of those functions, if it detects that
they are missing.

You can therefore now reliably use a few of the advanced (later
introduced) PHP core functions, by simply loading this script. This
effectively frees you from wasting time with backwards compatibility
problems and even avoiding certain useful additions from newer PHP
versions.

Of course, some later introduced PHP extensions cannot be emulated.
For example you still had to avoid some of the added optional
function arguments, because this script cannot override and extend
any native function implementations.
Language syntax and behaviour changes of PHP5 also cannot be
emulated in older versions, like it is impossible to make any PHP
4.0.x version compatible to 4.1.x and later (all superglobals like
$_REQUEST, are only provided since then). That is, you still have
a "minimum required PHP version" if you use this emulation. But
with it you now have the choice to use 4.3 and 5.0 functions while
producing "PHP 4.1+ COMPATIBLE" scripts.

Some of the functions that get defined here, are also simply stubs
without function body or real logic; merely to provide the standard
function name. The emulated functions sometimes run slower than the
native variant would, but it generally shouldn't be slower than any
workaround you used for the advanced but not everywhere available
functions until now.



core
¯¯¯¯
Simply include("upgrade.php"); in any of your scripts, if you want
to use some of the newer PHP4.3 or PHP5 functions like stripos() or
so. The functions get declared on demand then, but only on outdated
PHP interpreter versions. On up-to-date servers speed won't suffer,
because the native functions are already there.

You could additionally check the PHP_VERSION (by using the function
version_compare() for example), and only include the emulation
wrapper if you depend on features from a certain PHP interpreter
release.

Currently following functions can be emulated:
· stripos
· strripos
· str_ireplace
· get_headers
· headers_list
· fprintf
· vfprintf
· str_split
· http_build_query
· convert_uuencode
· convert_uudecode
· scandir
· idate
· time_nanosleep
· strpbrk
· file_get_contents
· file_put_contents
· glob
· array_key_exists
· array_intersect_assoc
· array_diff_assoc
· html_entity_decode
· str_wordcount
· str_rot13
· array_change_key_case
· array_fill
· array_chunk
· md5_file
· diskfreespace
· disktotalspace
· vprintf
· vprintf
· gzdecode

On a side note: You don't have to include() this func emulation
script yourself. Leave this to your users if they use an older PHP
version; a note often suffices. It however may be senseful to ship
this together with your scripts - that's also why it is PD.

It is safe to extract a few function bodies/definitions out of the
script to make a shorter version (use only the needed functions);
but you shoudl keep the "if (function_exists(...))" wrapper code
then.



ext/
¯¯¯¯
The ext/ subdirectory in here provides a few more or less useful
emulation functions, most notably a function collection resembling
the PHP ftp module.

A few snippets in there provide experimental features that aren't
found in any current PHP version.



dtools/
¯¯¯¯¯¯¯
The "updoc" commandline script updates your local PHP documentation
to carry hints about emulatated functions. It simply will add a
small "EMU" on top of the supported functions` description pages (in
the line typically listing the PHP versions).

The small "ckavail.php" was used to check for added functions
between different PHP interpreter versions.



License
¯¯¯¯¯¯¯
Everything in here is Public Domain. Ask Google if you don't know
what this means.



Author
¯¯¯¯¯¯
The current maintainer can be contacted under <milky*users·sf·net>




Added dtools/ckavail.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
<?php
/*
   Run this first with an older PHP interpreter, and then with a newer
   version. This way you get a list (once) of added functions (the func
   list is stored in a temporary file).
*/

#-- load last list
if ($f = @fopen("ckavail.last", "r")) {
   $oldl = unserialize(fread($f, 1<<20));
   fclose($f);
}

#-- current func list
$curl = get_defined_functions();
$curl = $curl["internal"];

#-- save this one
if ($f = fopen("ckavail.last", "w")) {
   fwrite($f, serialize($curl));
   fclose($f);
}

#-- comparison of  current / last run
echo "old(".count($oldl)."), new(".count($curl).")\n";
if ($oldl) {
   $new = array_diff($curl, $oldl);
   echo "New functions added in PHP ". PHP_VERSION ." interpreter:\n";
   print_r($new);
}
else {
   echo "Now start this script a 2nd time with the newer interpreter version.\n";
}


?>

Added dtools/updoc.































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
#!/usr/local/bin/php -qC
<?php
/*
   Adds hints about emulation functions to your local PHP documentation.
*/

#-- help
if ($_SERVER["argc"] != 3) {

   echo<<<END

Usage: updoc [.../upgrade.php] [/path/to/your/php-doc/directory/]
 
   This script will update your PHP documentation, if you have the
   (DocBook-converted) multi-html-files version installed. The first
   parameter must be the filepath to the 'upgrade.php' script, so the
   names of the emulated functions are known.

   You will afterwards find the abbreviation "EMU" in the required-
   PHP-version line throughout the documentation, so you know which
   functions you could safely use from now on (= without backwards
   compatibility stomachaches).


END;

}

#-- run
else {
   error_reporting(0);

   #-- params
   $emu = $_SERVER["argv"][1];
   $dir = $_SERVER["argv"][2];
   if (!is_dir($dir)) {
      die("The given 'PHP doc directory' of \"$dir\" isn't!\n");
   }
   if (!file_exists($emu)) {
      die("Couldn't find 'upgrade.php' script under the given name \"$emu\".\n");
   }
   
   #-- grep for function definitions
   $text = implode("", file($emu));
   if (preg_match_all("/function\s+([_\w\d]+)\s*\(/", $text, $uu)) {
      $list = $uu[1];
   }
   
   #-- go thru doc
   if ($list) {
      $chng = 0;
      foreach ($list as $func) {
      
         #-- doc filename
         if (file_exists($fn = "$dir/function.".strtr($func, "_", "-").".html")) {
            $f = fopen($fn, "r");
            $html = fread($f, 1<<20);
            fclose($f);
            
            #-- update if no hint found yet
            if (!preg_match('/\(.*?(EMU|UP).*?\)/i', $html)) {
               $l = strpos($html, ")"); 
               $html = substr($html, 0, $l)
                     . ", EMU"
                     . substr($html, $l);
               $f = fopen($fn, "w");
               fwrite($f, $html);
               fclose($f);
               
               $chng += 1;
            }
         }
      }
      
      echo "$chng documentation files updated.\n";
   }

   #-- add some special files
   if (!file_exists($fn = "$dir/function.gzdecode.html")) {
      echo "adding \"$fn\"\n";
      $f = fopen($fn, "w");
      fwrite($f, base64_decode("PGh0bWw+PGhlYWQ+PHRpdGxlPmd6ZGVjb2RlPC90aXRsZT48L2hlYWQ+Cjxib2R5Pgo8ZGl2IGFsaWduPSJjZW50ZXIiPnVwZ3JhZGUucGhwIGRvYzwvZGl2Pgo8aHIgYWxpZ249IkxFRlQiIHdpZHRoPSIxMDAlIj4KPGgxPmd6ZGVjb2RlPC9oMT4KCjxwPihQSFAgNiwgRU1VKTwvcD4KCmd6ZGVjb2RlJm5ic3A7LS0mbmJzcDtEZWNvZGVzIGEgZ3ppcCBjb21wcmVzc2VkIHN0cmluZzwvZGl2PgoKPGgyPkRlc2NyaXB0aW9uPC9oMj4KCnN0cmluZyA8YiBjbGFzcz0ibWV0aG9kbmFtZSI+Z3pkZWNvZGU8L2I+ICggc3RyaW5nIGRhdGEgWywgaW50IG1heGxlbl0pPGJyPgo8YnI+CjxwPlRoaXMgZnVuY3Rpb24gZGVjb2RlcyBhIHN0cmluZyBjb21wcmVzc2VkIGJ5IHRoZSAKPGEgaHJlZj0iZmlsZTovLy91c3Ivc2hhcmUvbWFuL21hbjEvZ3ppcC4xLmd6Ij5nemlwKDEpPC9hPiB1dGlsaXR5IG9yCnRoZSA8YSBjbGFzcz0iZnVuY3Rpb24iIGhyZWY9ImZ1bmN0aW9uLmd6ZW5jb2RlLmh0bWwiPmd6ZW5jb2RlKCk8L2E+CmZ1bmN0aW9uLiBUaGUgb3B0aW9uYWwgcGFyYW1ldGVyIG1heGxlbiBsaW1pdHMgdGhlIGxlbmd0aCBvZiB0aGUgcmV0dXJuZWQKc3RyaW5nLCBpZiB0aGUgaW5mbGF0aW9uIHByb2Nlc3MgcmV0dXJucyBhIGJpZ2dlciByZXN1bHQgaXQgd2lsbCBiZSBkcm9wcGVkLgo8L3A+Cgo8cD5UaGUgZ3ppcCBmb3JtYXQgaW50ZXJuYWxseSB1c2VzIHRoZSBkZWZsYXRlIGFsZ29ydGlobSwgYW5kIGFkZHMgYSBmZXcKY2hlY2tzdW1zIGFuZCBvcHRpb25hbCBtZXRhIGRhdGEgZmllbGRzLiBJdCBpcyByZWd1bGFyaWx5IHVzZWQgYXMKY29udGVudC1jb2RpbmcgaW4gSFRUUCByZXF1ZXN0cyBhbmQgcmVzcG9uc2VzLjwvcD4KCjxwPgpTZWUgYWxzbyA8YSBocmVmPSJmdW5jdGlvbi5nemVuY29kZS5odG1sIj48YiBjbGFzcz0iZnVuY3Rpb24iPmd6ZW5jb2RlKCk8L2I+PC9hPgphbmQgPGEgaHJlZj0iZnVuY3Rpb24uZ3ppbmZsYXRlLmh0bWwiPjxiIGNsYXNzPSJmdW5jdGlvbiI+Z3ppbmZsYXRlKCk8L2I+PC9hPi4KPC9wPgoKPGhyPgoKPC9ib2R5Pgo8L2h0bWw+Cg=="));
      fclose($f);

      #-- update zlib function list page
      $fn = array("$dir/ref.zlib.html", "$dir/index.functions.html");
      update_files($fn, '/(<a\s+href="function.gzencode)/ims',
        "<a href=\"function.gzdecode.html\">gzdecode</a> -- Decode a gzip compressed string.</dt>\n<dt> $1"
      );
   }

}


#-- inject something into a file
function update_files($list, $regex, $replace) {
   if (!is_array($list)) {
      $list = array($list);
   }
   foreach ($list as $fn) {
      $f = fopen($fn, "r");
      $html = fread($f, 1<<20);
      fclose($f);
      $html = preg_replace($regex, $replace, $html);
      $f = fopen($fn, "w");
      fwrite($f, $html);
      fclose($f);
   }
}

?>

Added ext/dba.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
<?php
/*
   Load this with plugins/db/dba.php if your PHP provides only the
   older dbm_*() functions.
*/


#-- fake dba_* using dbm_* functions
if (!function_exists("dba_open") && function_exists("dbm_open")) {

   function dba_open($path, $mode, $handler, $a1=0) {
      if ($handler == "dbm") {
         return(dbmopen($path, $mode));
      }
      else return(false);
   }

   function dba_popen($a, $b, $c, $d=0) {
      return(dba_open($a, $b, $c));
   }

   function dba_exists($key, $handle) {
      return(dbmexists($handle, $key));
   }

   function dba_fetch($key, $handle) {
      return(dbmfetch($handle, $key));
   }

   function dba_insert($key, $string, $handle) {
      return(dbminsert($handle, $key, $string));
   }

   function dba_replace($key, $string, $handle) {
      return(dbmreplace($handle, $key, $string));
   }

   function dba_delete($key, $handle) {
      return(dbmdelete($handle, $key));
   }

   function dba_firstkey($handle) {
      return($GLOBALS["dbm_lastkey"] = dbmfirstkey($handle));
   }

   function dba_nextkey($handle) {
      return(dbmnextkey($handle, $GLOBALS["dbm_lastkey"]));
   }

   function dba_close($handle) {
      return(dbmclose($handle));
   }

   function dba_handlers() {
      return(array("dbm"));
   }

}


?>

Added ext/ftp.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
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
<?php
/*
   Provides the usual ftp_() functions (or at least work-alikes)
   for PHP versions compiled without.

   Hint: If you want to use it with PHP versions with compiled-in FTP
   support, then simply let your text editor replace all occourences
   of "ftp_" into "xftp_" or something similar.

   FreeWare, 2004, milky*users·sf·net
*/

if (!function_exists("ftp_connect")) {

 #-- config
 define("FTP_DEBUG", 0);
 define("FTP_PASV", 0);   // default data transfer mode

 #-- constants
 define("FTP_ASCII", "A");
 define("FTP_BINARY", "I");


 #-- establish socket connection,
 #   returns status+data array
 function ftp_connect($server, $port=21, $proxy_server=NULL, $proxy_port=21) {
    $fc = array();

    #-- proxy or direct connection
    if ($proxy_server) {
       $f = fsockopen($proxy_server, $proxy_port, $errno, $errstr, 15);
       $fc["proxy"] = 1;
    }
    else {
       if (strpos($server, ":")) {
          $server = strtok($server, ":");
          $port = strtok(":");
       }
       $f = fsockopen($server, (int)$port, $errno, $errstr, 15);
    }

    #-- socket connection established
    if ($f) {
       #-- socket connection settings
       socket_set_blocking($f, 1);

       #-- mk connection data hash
       $fc["host"] = $server;
       $fc["port"] = $port;
       $fc["f"] = $f;
       $fc["d"] = false;
       $fc["dport"] = false;
       $fc["pasv"] = FTP_PASV;

       #-- read greeting
       ftp_send($fc, "", 1);
       if (!$fc["err"] == 220) {
          ftp_err("server rejected further communication (after successful TCP/IP connection)");
          return(false);
       }

       #-- ret handle
       return($fc);
    }
    else {
       ftp_err("connecting to $server:$port$add_err failed [err$errno: \"$errstr\"]");
       return(false);
    }
 }


 #-- internal use
 function ftp_send(&$fc, $command, $wait100=0, $break100=0) {
    if ($fc) {

       #-- send command
       fwrite($fc["f"], $command);

       #-- read reply, line by line
       $r = "";
       while (!feof($fc["f"]) && ($line = fgets($fc["f"], 768))) {
          $r .= $line;

          #-- error/status number separated by space
          if ($line{3} === " ") {
             $err = (int) substr($line, 0, 3);
             if ($err >= 100) {
                $fc["err"] = $err;
                $fc["msg"] = rtrim(substr($line, 4));
                if (($err >= 200) || $break100) {
                   break;
                }
                elseif ($wait100) {
                   // nop, loop on until real status reply
                }
                elseif (FTP_DEBUG) {
                   trigger_error("ftp delay ($err): $fc[msg]", E_USER_NOTICE);
                }
          }  }
       }

       #-- general faults, closed connection
       switch ($err) {

          case 421:
            ftp_err("server closed connection - $fc[msg]");
            ftp_close($fc);
            $fc = false;
            break;

          case 332:
            $r = ftp_send("ACCT $fc[user]");
            break;

          default:
            if ($err >= 400) {
               trigger_error("ftp ($err): $fc[msg]", E_USER_NOTICE);
            }
       }

       #-- done
       if (FTP_DEBUG) {
          echo "»»» $command";
          echo "««« $r";
       }
       return($r);
    }
    else {
       ftp_err("invalid connection handle passed to ftp_send() function");
    }
 }


 #-- simply check for successful result
 function ftp_result(&$fc) {
    if ( ($fc["err"] <= 399) && ($fc["err"] >= 200) ) {
       return(true);
    }
 }


 #-- internal use
 function ftp_err($str) {
    if (is_array($str)) {
       $str = $str["err"] . " " . $str["msg"];
    }
    trigger_error("ftp: $str", E_USER_WARNING);
 }


 #-- authentification
 function ftp_login(&$fc, $user, $pw="") {

    #-- send user name
    $fc["user"] = $user;
    if ($user) {
       $user .= ($fc["proxy"] ? "@".$fc["host"] : "");
       ftp_send($fc, "USER $user\n");

       #-- password if required
       if ($pw || ($fc["err"] == 331)) {
          ftp_send($fc, "PASS $pw\n");
       }
       $r = ftp_result($fc);

       if ($fc["err"] != 230) {
          ftp_err("unsuccessful login");
       }
    }

    #-- check capabilities
    @ftp_send($fc, "MODE B\n");     // block mode supported?
    if ($fc["err"] == 200) {
       $fc["mode"] = "B";
    }
    else {
       $fc["mode"] = "S";
       ftp_send($fc, "MODE S\n");   // else stream mode (unreliable)
    }

    #-- pre-fetch system type
    ftp_send($fc, "SYST\n");
    $fc["sys"] = strtok($fc["msg"], " \r\n\t\f");

    #-- set default options
    @ftp_send($fc, "SITE UMASK 0022\n");
    ftp_send($fc, "TYPE A\n");
    ftp_send($fc, "PWD\n");
    if ($fc["err"] != 257)  {
       ftp_err("incompatible connection");
    }

    return($r);
 }


 #-- set data connection method/mode (will later be negotiated with server)
 function ftp_pasv(&$fc, $bool=1) {
    $fc["pasv"] = $bool ?1:0;
    // ftp_err("this ftp:// access module always uses the PASV server data connection mode");
 }


 #-- terminate ftp session
 function ftp_quit(&$fc) {
    ftp_send($fc, "QUIT\n");   // the server closes the tcp/ip connection
    ftp_close($fc);            // so this is not necessary
    $fc = false;
 }


 #-- close connections
 function ftp_close(&$fc) {
    if ($fc["d"] && !feof($fc["d"])) {
       @fclose($fc["d"]);
    }
    if (!feof($fc["f"])) {
       @fclose($fc["f"]);
    }
 }


 #-- simple functions -----------------------------------------------------

 function ftp_cdup(&$fc) {
    ftp_send($fc, "CDUP\n");
    return ftp_result($fc);
 }
 function ftp_chdir(&$fc, $path) {
    ftp_send($fc, "CWD $path\n");
    return ftp_result($fc);
 }
 function ftp_mkdir(&$fc, $path) {
    ftp_send($fc, "MKD $path\n");
    return ftp_result($fc);
 }
 function ftp_rmdir(&$fc, $path) {
    ftp_send($fc, "RMD $path\n");
    return ftp_result($fc);
 }
 function ftp_pwd(&$fc) {
    ftp_send($fc, "PWD $path\n");
    $d = $fc["msg"];
    $l = strpos($d, '"');
    $d = substr($d, $l+1, strrpos($d, '"')-$l-1);
    return($d);
 }

 function ftp_delete(&$fc, $file) {
    ftp_send($fc, "DELE $path\n");
    return ftp_result($fc);
 }
 function ftp_mv(&$fc, $from, $to) {
    ftp_send($fc, "RNFR $from\n");
    ftp_send($fc, "RNTO $to\n");
    return ftp_result($fc);
 }
 function ftp_chmod(&$fc, $perm, $path) {
    $perm = "0" . base_convert($perm, 10, 8);
    ftp_send($fc, "SITE CHMOD $perm $path\n");
    return ftp_result($fc);
 }

 function ftp_site(&$fc, $cmd) {
    $cmd = rtrim($cmd);
    ftp_send($fc, "SITE $cmd\n");
    return ftp_result($fc);
 }
 function ftp_exec(&$fc, $cmd) {
    ftp_site($fc, "EXEC $cmd\n");
    return ftp_result($fc);
 }
 function ftp_raw(&$fc, $str) {
    $str = rtrim($str) . "\n";
    $r = ftp_send($fc, $str);
    return(explode("\n", $r));
 }

 function ftp_systype(&$fc) {
    return $fc["sys"];
 }


 #-- file transfer calls --------------------------------------------------


 #-- file upload
 function ftp_fput(&$fc, $to, $fh, $mode=FTP_BINARY, $chunksize=65536) {
    if (!$fh) { return; }

    #-- data connection
    ftp_data_connection($fc);
    if ($chunksize >= 65536) {
       $chunksize = 65535;
    }

    #-- initiate file transfer
    ftp_send($fc, "TYPE $mode\n");
    set_time_limit(240);
    ftp_send($fc, "STOR $to\n", 0, 1);

    #-- server waiting for transfer?
    if (($fc["err"] == 150) || ($fc["err"] == 125)) {

       #-- connection mode
       if (!$fc["pasv"]) {
          $d = socket_accept($fc["s"]);
          $data_write = "socket_write";
          $data_close = "socket_close";
       }
       else {
          $d = & $fc["d"];
          $data_write = "fwrite";
          $data_close = "fclose";
       }

       #-- stream mode, simple
       if ($fc["mode"] == "S") {
          while ($fh && !feof($fh)) {
             $dat = fread($fh, $chunksize);
             $data_write($d, $dat);
          }
       }
       else {
          while ($fh && !feof($fh)) {
             $dat = fread($fh, $chunksize);
             $n = strlen($dat);
             $data_write($d, pack("cn", 0, $n));   // block header
             $data_write($d, $dat);
          }
          $data_write($fc["d"], pack("ccc", 0x40, 0, 0));   // EOF
       }

       #-- close server socket
       if (!$fc["pasv"]) {
          socket_close($d);
       }

       #-- transmission ok
       ftp_data_end($fc);
       ftp_send($fc, "", 1);
       $r = ($fc["err"] == 226) || ($fc["err"] == 250);

       #-- reset options
       if ($mode != FTP_ASCII) {
          ftp_send($fc, "TYPE A\n");
       }

    }
    else {
       ftp_err("$fc[err] $fc[msg]");
       $r = 0;
    }

    return($r);
 }


 function ftp_put(&$fc, $to, $fn, $mode=FTP_BINARY) {
    if (!is_resource($fn)) {
       $fn = fopen($fn, "rb");
    }
    $r = ftp_fput($fc, $to, $fn, $mode);
    fclose($fn);
    return($r);
 }




 #-- download
 function ftp_fget(&$fc, $to, $fh, $mode=FTP_BINARY, $chunksize=65536) {
    if (!$fh) { return; }

    #-- open connection
    ftp_data_connection($fc);

    #-- initiate file transfer
    ftp_send($fc, "TYPE $mode\n");
    set_time_limit(240);
    ftp_send($fc, "RETR $to\n", 0, 1);

    #-- server waiting for transfer?
    if (($fc["err"] == 150) || ($fc["err"] == 125)) {

       #-- connection mode
       if (!$fc["pasv"]) {
          $d = socket_accept($fc["s"]);
          $data_read = "socket_read";
          $data_close = "socket_close";
       }
       else {
          $d = & $fc["d"];
          $data_read = "fread";
          $data_close = "fclose";
       }

       #-- stream mode, simple
       if ($fc["mode"] == "S") {
          $dat = "+";
          while (strlen($dat)) {
             $dat = $data_read($d, $chunksize);
             fwrite($fh, $dat);
          }
       }
       else {
          $eof = 0;
          while (!$eof) {
             list($flags, $len) = unpack("cn", $data_read($d, 3));
             $eof = $flags & (0x40|0x80);

             if ($len) {
                $dat = $data_read($d, $len);
                fwrite($fh, $dat);
             }
          }
       }

       #-- close server socket
       if (!$fc["pasv"]) {
          $data_close($d);
       }

       #-- transmission ok
       ftp_data_end($fc);
       ftp_send($fc, "", 1);
       $r = ($fc["err"] == 226) || ($fc["err"] == 250);

       #-- reset options
       if ($mode != FTP_ASCII) {
          ftp_send($fc, "TYPE A\n");
       }

    }
    else {
       ftp_err("$fc[err] $fc[msg]");
       $r = 0;
    }

    return($r);
 }


 #-- directly into file
 function ftp_get(&$fc, $to, $fn, $mode=FTP_BINARY) {
    if (!is_resource($fn)) {
       $fn = fopen($fn, "wb");
    }
    $r = ftp_fget($fc, $to, $fn, $mode);
    fclose($fn);
    return($r);
 }



 #-- establishes a data connection ---------------------------------------
 function ftp_data_connection(&$fc) {
    if (!$fc["d"] || feof($fc["d"])) {

       #-- make client establish connection (PASsiVe server)
       if ($fc["pasv"]) {
          ftp_send($fc, "PASV\n");

          #-- reply ok?
          if ($fc["err"] == 227) {
             $l = strpos($fc["msg"], "(");
             $r = strpos($fc["msg"], ")", $l);
             $uu = explode(",", substr($fc["msg"], $l + 1, $r - $l - 1));
             $ip = "$uu[0].$uu[1].$uu[2].$uu[3]";
             $port = ((int)$uu[4]<<8) + ((int)$uu[5]);

             #-- all done
             if ($port) {
                if (!$fc["d"] = @fsockopen($ip, $port, $errno, $errstr, 25)) {
                   ftp_err("data socket connection could not be established [$errno - $errstr]");
                }
             }
             else {
                ftp_err("data connection negotiation problem (server uses wrong syntax)");
             }
          }

          #-- fall back
          else {
             $fc["pasv"] = 0;
             ftp_err("falling back to standard (ACTiVe server) connection mode");
             ftp_data_connection($fc);
          }
       }

       #-- else choose port we wish the server to contact us
       elseif (!$fc["s"]) {
          if (!function_exists("socket_listen")) {
             ftp_err("could not establish data connection, because PHP socket I/O functions are absent");
          }
          else {
             $ip = strtr(gethostbyname("localhost"), ".", ",");

             #-- loop, test randomly choosen ports
             $retry = 20;
             $s = 0;
             while ((!$s) && ($retry-- >= 0)) {
                $port = rand(3072, 65535);
                $p1 = ($port >> 8);
                $p2 = ($port & 0xFF);
                ftp_send($fc, "PORT $ip,$p1,$p2\n");
                if ($fc["err"] == 200) {
                   $s = socket_create_listen($port);
                }
             }
             if ($s) {
                $fc["s"] = $s;
             }
             else {
                ftp_err("could not create listening socket for (ACTiVe server) data connection");
             }
       }  }
    }
 }


 #-- closes data connection, (in stream mode)
 function ftp_data_end(&$fc) {
    if (($fc["d"]) && ($fc["mode"] == "S")) {
       if ($fc["pasv"]) {
          fclose($fc["d"]);
       }
       else {
          socket_close($fc["d"]);
       }
       $fc["d"] = false;
    }
 }


}



#------------------------------------------------------------- add-ons ---
# require a connection in $GLOBALS['fc'];


#-- transfers a file tree from source dir to destination on connected server
function ftp_xcopy($from, $to=NULL) {
   global $fc, $DEBUG;
   #-- dir
   if ($to) {
      ftp_xmkdir($to);
   }
   else {
      ftp_xmkdir($from);
      $to = $from;
   }
   if (!$from) {
      return;
   }
   #-- store files
   if (is_dir($from)) {
      if ($dh = opendir($from)) {
         $from = trim($from, "/");
         while ($fn = readdir($dh)) {
            if ($fn[0] != ".") {
               ftp_xcopy("$from/$fn");
            }
         }
         closedir($dh);
      }
      else {
         echo "error reading directory '$from'<br>\n";
      }
   }
   else {
      if ($f = fopen($from, "rb")) {
         if (!$DEBUG) {
#$cwd=getcwd(); echo "PUT $cwd/$from to $to  <br>\n";
            ftp_put($fc, $to, $from, FTP_BINARY);
            ftp_site($fc, "CHMOD 0644 $to");
         }
         else {
            echo "upload '$from' to 'ftp://.../$to'<br>\n";
         }
         fclose($f);
      }
      else {
         echo "error reading file '$from'<br>\n";
      }
   }
}


#-- creates directory trees for given filename strings and keeps track
#   of what it created, so you can call it without thought
function ftp_xmkdir($file) {
   global $fc, $ftp_dirs, $DEBUG;
   $p = strrpos($file, "/");
   if (!$p) {
      return;
   }
   $file = substr($file, 0, $p);
   if (in_array($file, $ftp_dirs)) {
      return;
   }
   $p = 0;
   $file .= "/";
   while ($p = strpos($file, "/", $p+1)) {
      $dir = substr($file, 0, $p);
      if (!in_array($dir, $ftp_dirs)) {
         if (!$DEBUG) {
            @ftp_mkdir($fc, $dir);
            @ftp_site($fc, "CHMOD 0755 $dir");
         }
         $ftp_dirs[] = $dir;
      }
   }
}


?>

Added ext/phprequest.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
<?php
/*
   Allows http "POST" and "PUSH" requests with a Content-Type of
   "application/vnd.php.serialized". This isn't used in the wild.
*/

if (empty($_POST)
and (strtoupper($_SERVER["REQUEST_METHOD"][0]) == "P")
and (strtolower(trim(strtok($_SERVER["HTTP_CONTENT_TYPE"], ";,")))
     == "application/vnd.php.serialized"))   )
{
   #-- search for bare request body
   if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
      $_POST = $GLOBALS["HTTP_RAW_POST_DATA"];
   }
   else {
      $f = fopen("php://input", "rb");
      $_POST = fread($f, 1<<22);
      fclose($f);
   }

   #-- read in as-is
   if ($_POST) {

      #-- strip known/supported encodings
      $enc = trim(strtok(strtolower($_SERVER["HTTP_CONTENT_ENCODING"]), ",;"));
      if ($enc == "deflate") {
         $_POST = gzinflate($_POST);
      }
      elseif ($enc == "compress") {
         $_POST = gzuncompress($_POST);
      }
      elseif ($enc == "gzip") {
         $_POST = function_exists("gzdecode") ? gzdecode($_POST) : gzinflate(substr($_POST, 10, strlen($_POST) - 18);
      }
      elseif (($enc == "x-bzip2") or ($enc == "bzip2")) {
         $_POST = function_exists("bzdecompress") ? bzdecompress($_POST) : NULL;
      }

      #-- decipher
      if ($_POST) {
         $_POST = unserialize($_POST);
      }
      #-- merge
      if ($_POST) {
         $_REQUEST = array_merge($_REQUEST, $_POST);
      }

   }
}

?>

Added upgrade.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
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
<?php
/*
   This include() script adds missing PHP functions to earlier interpreter
   versions, so you can make downwards compatible scripts without having
   to stick to the least common denominator. It only defines the ones that
   are really missing; native functions will so get used, where available.

   - many of the emulation functions are one-liners
   - a few features have been added that never made it into one of the
     official versions (CVS code and the ever-absent "gzdecode" and
     "file_put_contents" for example)
   - many things are still missing, and external add-ons are provided to
     mimic certain other PHP core extension modules
   - the extended OO-capabilities and language syntax extensions of PHP5
     and ZE2 cannot seriously be emulated here, this script only takes care
     about functional interfaces
   - this is PuplicDomain (no authorship, no license, no warranty) so you
     can melt it into anything, regardless of your preferred license (you
     may strip this paragraph and turn it all into GPL, BSD, LGPL, CC*,
     Artistic, MPL, PHP license, M$ EULA, or whatever you like best)
     
   Get update notes via "http://freshmeat.net/projects/upgradephp" or
   google for it. Any contribution is appreciated. <milky*users·sf·net>
*/





#------------------------------------------------------------------ CVS ---
// most of this appeared in 5.0







#------------------------------------------------------------- optional ---
// these functions aren't present everywhere (regardless of version)


#-- mime-magic, type will be detected by analyzing the content
if (!function_exists("mime_content_type")) {
   function mime_content_type($fn) {
      # inj code from nw:getct
      # + orig magicdata dechunk/reader
      return "application/octet-stream";
   }
}







#------------------------------------------------------------------ 6.0 ---
// these functions were never implemented in PHP


#-- inflates a string enriched with gzip headers
if (!function_exists("gzdecode")) {   // hey, let's hope they get it someday ;)
   function gzdecode($data, $maxlen=NULL) {

      #-- decode header
      $len = strlen($data);
      if ($len < 20) {
         return;
      }
      $head = substr($data, 0, 10);
      $head = unpack("n1id/C1cm/C1flg/V1mtime/C1xfl/C1os", $head);
      list($ID, $CM, $FLG, $MTIME, $XFL, $OS) = array_values($head);
      $FTEXT = 1<<0;
      $FHCRC = 1<<1;
      $FEXTRA = 1<<2;
      $FNAME = 1<<3;
      $FCOMMENT = 1<<4;
      $head = unpack("V1crc/V1isize", substr($data, $len-8, 8));
      list($CRC32, $ISIZE) = array_values($head);

      #-- check gzip stream identifier
      if ($ID != 0x1f8b) {
         trigger_error("gzdecode: not in gzip format", E_USER_WARNING);
         return;
      }
      #-- check for deflate algorithm
      if ($CM != 8) {
         trigger_error("gzdecode: cannot decode anything but deflated streams", E_USER_WARNING);
         return;
      }

      #-- start of data, skip bonus fields
      $s = 10;
      if ($FLG & $FEXTRA) {
         $s += $XFL;
      }
      if ($FLG & $FNAME) {
         $s = strpos($data, "\000", $s) + 1;
      }
      if ($FLG & $FCOMMENT) {
         $s = strpos($data, "\000", $s) + 1;
      }
      if ($FLG & $FHCRC) {
         $s += 2;  // cannot check
      }
      
      #-- get data, uncompress
      $data = substr($data, $s, $len-$s);
      if ($maxlen) {
         $data = gzinflate($data, $maxlen);
         return($data);  // no checks(?!)
      }
      else {
         $data = gzinflate($data);
      }
      
      #-- check+fin
      $chk = crc32($data);
      if ($CRC32 != $chk) {
         trigger_error("gzdecode: checksum failed (real$chk != comp$CRC32)", E_USER_WARNING);
      }
      elseif ($ISIZE != strlen($data)) {
         trigger_error("gzdecode: stream size mismatch", E_USER_WARNING);
      }
      else {
         return($data);
      }
   }
}




#------------------------------------------------------------------ 5.0 ---
# set_exception_handler
# restore_exception_handler
# get_declared_interfaces
# debug_print_backtrace
# php_real_logo_guid
# php_egg_logo_guid
# substr_compare
# proc_terminate
# proc_get_status
# proc_nice
# php_strip_whitespace
# php_check_syntax
# setrawcookie
# dns_check_record
# dns_get_mx
# dns_get_record
# array_walk_recursive
# array_uintersect
# array_uintersect_assoc
# array_intersect_uassoc
# array_uintersect_uassoc
# array_udiff
# array_udiff_assoc
# array_diff_uassoc
# array_udiff_uassoc
# array_combine
# date_sunrise
# date_sunset
# spl_classes
# class_parents
# class_implements
# session_commit


#-- ci string search functions
if (!function_exists("stripos")) {
   #-- find position of first occourence of a case-insensitive string
   function stripos($haystack, $needle, $offset=NULL) {
      return strpos(strtolower($haystack), strtolower($needle), $offset);
   }
   #-- ... from end of string
   function strripos($haystack, $needle, $offset=NULL) {
      return strrpos(strtolower($haystack), strtolower($needle), $offset);
   }
}


#-- case-insensitive version of str_replace
if (!function_exists("str_ireplace")) {
   function str_ireplace($search, $replace, $subject, $count=NULL) {
      if (is_array($search)) {
         $replace = array_values($replace);
         foreach (array_values($search) as $i=>$srch) {
            $subject = str_ireplace($srch, $replace[$i], $subject);
         }
      }
      else {
         $search = "\007" . preg_quote($search) . "\007i";
         $replace = strtr($replace, array('$'=>'\\$', "\\"=>"\\\\"));
         $subject = preg_replace($search, $replace, $subject);
      }
      return($subject);
   }
}


#-- performs a http HEAD request
if (!function_exists("get_headers")) {
   function get_headers($url, $parse=0) {
      $c = parse_url($url);
      extract($c);
      if (!isset($port)) { 
         $port = 80;
      }
      if ($f = fsockopen($host, $port, $errno, $errstr, $timeout=5)) {
         fwrite($f, "HEAD $path HTTP/1.1\015\012"
                  . "Host: $host\015\012"
                  . "Connection: close\015\012"
                  . "Accept: text/html, application/xml, text/xml;q=0.75, application/xhtml+xml, text/plain;q=0.5, */*;q=0.01\015\012"
                  . "User-Agent: ".trim(ini_get("user_agent"))."\015\012"
                  . "\015\012");
         socket_set_blocking($f, true);
         $ls = array();
         while (!feof($f)) {
            $line = fgets($f, 1<<16);
            if (!($line = trim($line))) {
               break;
            }
            elseif ($parse) {
               if ($l = strpos($line, ":")) {
                  $name = substr($line, 0, $l);
                  $value = trim(substr($line, $l + 1));
                  if (isset($ls[$name])) {
                     $ls[$name] .= ", $value";
                  }
                  else {
                     $ls[$name] = $value;
                  }
               }
               else {
                  $ls[] = $line;
               }
            }
            else {
               $ls[] = $line;
            }
         }
         fclose($f);
         return($ls);
      }
      else {
         return(false);
      }
   }
}

#-- stub
if (!function_exists("headers_list")) {
   function headers_list() {
      trigger_error("headers_list: not supported by this PHP version", E_WARNING);
      return array();
   }
}


#-- write formatted string to stream / file
if (!function_exists("fprintf")) {
   function fprintf($stream, $format, $args=NULL) {
      return fwrite($stream, sprintf($format, $args));
   }
   function vfprintf($stream, $format, $args=NULL) {
      return fwrite($stream, vsprintf($format, $args));
   }
}


#-- splits a string in even sized chunks, returns an array
if (!function_exists("str_split")) {
   function str_split($str, $chunk=0) {
      $r = array();
      if ($chunk < 1) {
         $r[] = $str;
      }
      else {
         $len = strlen($str);
         for ($n=0; $n<$len; $n+=$chunk) {
            $r[] = substr($str, $n, $chunk);
         }
      }
      return($r);
   }
}


#-- mmmh?
if (!function_exists("http_build_query")) {
   function http_build_query($data, $prefix="", $fpfix="", $l=0) {
      $s = "";
      foreach ($data as $in=>$val) {
         $s_in = $in;
         if ($fpfix) {
            $s_in = $l ? "$fpfix[$s_in]" : "$fpfix$s_in";
         }
         elseif (is_int($s_in) && $prefix) {
            $s_in = "$prefix$s_in";
         }
         if (is_array($val)) {
            $val = http_build_query($val, "", $s_in, $l+1);
         }
         $s .= "&$s_in=$val";
      }
      $s = substr($s, 1);
      return($s);
   }
}


#-- transform into 3to4 uuencode (bare encoding, not the uu file format)
if (!function_exists("convert_uuencode")) {
   function convert_uuencode($data) {
      $out = "";
      $line = "";
      $len = strlen($data);
      $data .= "\252\252\252";   // PHP and uuencode(1) use some special garbage??
      for ($n=0; $n<$len; ) {
         $x = (ord($data[$n++]) << 16)
            + (ord($data[$n++]) <<  8)
            + (ord($data[$n++]) <<  0);
         $line .= chr( 32 + (($x >> 18) & 0x3f) )
               . chr( 32 + (($x >> 12) & 0x3f) )
               . chr( 32 + (($x >>  6) & 0x3f) )
               . chr( 32 + (($x >>  0) & 0x3f) );
         if (($n % 45) == 0) {
            $out .= chr(32+45) . "$line\n";
            $line = "";
         }
      }
      if ($trail = ($n % 45)) {
         $out .= chr(32 + $trail-1) . "$line\n";
      }
      return($out);
   }
}

#-- decodes again what the above mangled
if (!function_exists("convert_uudecode")) {
   function convert_uudecode($data) {
      $out = "";
      foreach(explode("\n", ltrim($data)) as $line) {
         if (!strlen($line)) {
            break;
         }
         unset($num);
         $num = ord($line{0}) - 32;
         if (!$num) {
            break;
         }
         $line = substr($line, 1);
         $add = "";
         for ($n=0; strlen($add)<$num; ) {
            $x = ((ord($line[$n++]) - 32) << 18)
               + ((ord($line[$n++]) - 32) << 12)
               + ((ord($line[$n++]) - 32) <<  6)
               + ((ord($line[$n++]) - 32) <<  0);
            $add .= chr( ($x >> 16) & 0xff )
                  . chr( ($x >>  8) & 0xff )
                  . chr( ($x >>  0) & 0xff );
         }
         $out .= substr($add, 0, $num);   // cut any trailing garbage (last two decoded chars may be wrong)
         $line="";
      }
      return($out);
   }
}


#-- return array of filenames in a given directory (only works for local files)
if (!function_exists("scandir")) {
   function scandir($dirname, $desc=0) {
      if (strpos($dirname, "file://") === 0) {
         $dirname = substr($dirname, 7);
         if (strpos($dirname, "localh") === 0) {
            $dirname = substr($dirname, strpos($dirname, "/"));
         }
      }
      if ($dh = opendir($dirname)) {
         $ls = array();
         while ($fn = readdir($dh)) {
            $ls[] = $fn;
         }
         closedir($dh);
         if ($desc) {
            rsort($fn);
         }
         else {
            sort($fn);
         }
         return $ls;
      }
      else {
         return false;
      }
   }
}


#-- like date(), but returns an integer for given one-letter format parameter
if (!function_exists("idate")) {
   function idate($formatchar, $timestamp=NULL) {
      if (strlen($formatchar) != 1) {
         return false;
      }
      if (!isset($timestamp)) {
         $timestamp = time();
      }
      return((int)(date($formatchar, $timestamp)));
   }
}



#-- combined sleep() and usleep() 
if (!function_exists("time_nanosleep")) {
   function time_nanosleep($sec, $nano) {
      sleep($sec);
      usleep($nano);
   }
}


#-- search first occourence of any of the given chars, returns rest of haystack
#   (char_list must be a string for compatibility with the real PHP func)
if (!function_exists("strpbrk")) {
   function strpbrk($haystack, $char_list) {
      $len = strlen($char_list);
      $min = $len;
      for ($n=0; $n<$len; $n++) {
         $l = strpos($haystack, $char_list[$n]);
         if ($l < $min) {
            $min = $l;
         }
      }
      return substr($haystack, $min);
   }
}





#------------------------------------------------------------------ 4.3 ---
# money_format - unimpl?
# sha1
# sha1_file
# str_shuffle


#-- simplified file read-at-once function
if (!function_exists("file_get_contents")) {
   function file_get_contents($filename, $use_include_path=1) {
      if ($f = fopen($filename, "rb", $use_include_path)) {
         $content = fread($f, 1<<19);  # max 512K
         fclose($f);
         return($content);
      }
   }
}

#-- the write-at-once equivalent
if (!function_exists("file_put_contents")) {
   function file_put_contents($filename, $data, $flags=0, $resource=NULL) {
      if ($f = fopen($filename, ($flags&FILE_APPEND?"a":"w")."b", $flags&FILE_USE_INCLUDE_PATH, $resource)) {
         fwrite($f, $data);
         fclose($f);
         return(TRUE);
      }
   }
}



#-- shell-like filename matching
if (!function_exists("glob")) {
   define("GLOB_MARK", 1<<0);
   define("GLOB_NOSORT", 1<<1);
   define("GLOB_NOCHECK", 1<<2);
   define("GLOB_NOESCAPE", 1<<3);
   define("GLOB_BRACE", 1<<4);
   define("GLOB_ONLYDIR", 1<<5);
   define("GLOB_NOCASE", 1<<6);
   define("GLOB_DOTS", 1<<7);
   // unlikely to work under Win(?), without replacing the explode() with
   // a preg_split() incorporating the native DIRECTORY_SEPARATOR as well

   function glob($pattern, $flags=0x0000) {
      $ls = array();
      $rxci = ($flags & GLOB_NOCASE) ? "i" : "";
#echo "\n=> glob($pattern)...\n";
      
      #-- transform glob pattern into regular expression
      if ($pattern) {

         #-- look at each directory/fn spec part separately
         $parts2 = explode("/", $pattern);
         $pat = preg_quote($pattern);
         $pat = strtr($pat, array("\\*"=>".*?", "\\?"=>".?"));
         if ($flags ^ GLOB_NOESCAPE) {
            // uh, oh, ouuch - the above is unclean enough...
         }
         if ($flags ^ GLOB_BRACE) {
            $pat = preg_replace("/\{(.+?)\}/e", 'strtr("[$1]", ",", "")', $pat);
         }
         $parts = explode("/", $pat);
#echo "parts == ".implode(" // ", $parts) . "\n";
         $lasti = count($parts) - 1;
         $dn = "";
         foreach ($parts as $i=>$p) {

            #-- basedir included (yet no pattern matching necessary)
            if (!strpos($p, "*?") && (strpos($p, ".?")===false)) {
               $dn .= $parts2[$i] . ($i!=$lasti ?"/" :"");
#echo "skip:$i, cause no pattern matching char found -> only a basedir spec\n";
               continue;
            }
            
            #-- start reading dir + match filenames against current pattern
            if ($dh = opendir($dn ?$dn:'.')) {
               $with_dot = ($p[1]==".") || ($flags & GLOB_DOTS);
#echo "part:$i:$p\n";
#echo "reading dir \"$dn\"\n";
               while ($fn = readdir($dh)) {
                  if (preg_match("\007^$p$\007$rxci", $fn)) {

                     #-- skip over 'hidden' files
                     if (($fn[0] == ".") && !$with_dot) {
                        continue;
                     }

                     #-- add filename only if last glob/pattern part
                     if ($i==$lasti) {
                        if (is_dir("$dn$fn")) {
                           if ($flags & GLOB_ONLYDIR) {
                              continue;
                           }
                           if ($flags & GLOB_MARK) {
                              $fn .= "/";
                           }
                        }
#echo "adding '$fn' for dn=$dn to list\n";
                        $ls[] = "$dn$fn";
                     }

                     #-- initiate a subsearch, merge result list in
                     elseif (is_dir("$dn$fn")) {
                        // add reamaining search patterns to current basedir
                        $remaind = implode("/", array_slice($parts2, $i+1));
                        $ls = array_merge($ls, glob("$dn$fn/$remaind", $flags));
                     }
                  }
               }
               closedir($dh);

               #-- prevent scanning a 2nd part/dir in same glob() instance:
               break;  
            }

            #-- given dirname doesn't exist
            else {
               return($ls);
            }

         }// foreach $parts
      }

      #-- return result list
      if (!$ls && ($flags & GLOB_NOCHECK)) {
         $ls[] = $pattern;
      }
      if ($flags ^ GLOB_NOSORT) {
         sort($ls);
      }
#print_r($ls);
#echo "<=\n";
      return($ls);
   }
}



#-- redundant alias for isset()
if (!function_exists("array_key_exists")) {
   function array_key_exists($key, $search) {
      return isset($search[$key]);
   }
}


#-- by all means - WHO needs that?
if (!function_exists("array_intersect_assoc")) {
   function array_intersect_assoc( /*array, array, array...*/ ) {
      $whatsleftover = array();
      $in = func_get_args();

      // (sort for shortest...)
      // ...

      foreach ($in[0] as $i=>$v) {
         for ($c=1; $c<=count($in); $c++) {
            if (!isset($in[$c][$i]) || ($in[$c][$i] != $v)) {
               break 2;
            }
         }
         $whatsleftover[$i] = $v;
      }
      return $whatsleftover;
   }
}


#-- the opposite of the above
if (!function_exists("array_diff_assoc")) {
   function array_diff_assoc( /*array, array, array...*/ ) {
      $diff = array();
      $in = func_get_args();
      foreach ($in[0] as $i=>$v) {
         for ($c=1; $c<=count($in); $c++) {
            if (isset($in[$c][$i]) && ($in[$c][$i] == $v)) {
               break 2;
            }
         }
         $diff[$i] = $v;
      }
      return $diff;
   }
}


#-- opposite of htmlentities
if (!function_exists("html_entity_decode")) {
   function html_entity_decode($string, $quote_style=ENT_COMPAT, $charset="ISO-8859-1") {
      // we fall short on anything other than Latin-1
      $y = array_flip(get_html_translation_table(HTML_ENTITIES, $quote_style));
      return strtr($string, $y);
   }
}


#-- extracts single words from a string
if (!function_exists("str_wordcount")) {
   function str_wordcount($string, $format=1) {
      preg_match_all('/([\w](?:[-\'\w]?[\w]+)+)/', $string, $uu);
      if ($format==1) {
         return($uu[1]);
      }
      else {
         $r = array();
         $l = 0;
         foreach ($uu[1] as $word) {
            $l = strpos($string, $word, $l);
            $r[$l] = $word;
            $l += strlen($word);
         }
         return($r);
      }
   }
}

#------------------------------------------------------------------ 4.2 ---


#-- shy away from this one - it was broken in all real PHP4.2 versions
if (!function_exists("str_rot13")) {
   function str_rot13($str) {
      static $from = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
      static $to = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm";
      return strtr($str, $from, $to);
   }
}


#-- well, if you need it
if (!function_exists("array_change_key_case")) {
   define("CASE_LOWER", 0);
   define("CASE_UPPER", 1);
   function array_change_key_case($array, $case=CASE_LOWER) {
      foreach ($array as $i=>$v) {
         unset($array);
         if (is_string($i)) {
            $i = ($case==CASE_LOWER) ? strtolower($i) : strtoupper($i);
         }
         $array[$i] = $v;
      }
      return($array);
   }
}


#-- hey, why not
if (!function_exists("array_fill")) {
   function array_fill($start_index, $num, $value) {
      $r = array();
      for ($i=$start_index,$end=$num+$i; $i<$end; $i++) {
         $r[$i] = $value;
      }
      return($r);
   }
}


#-- split an array into evenly sized parts
if (!function_exists("array_chunk")) {
   function array_chunk($input, $size, $preserve_keys=false) {
      $r = array();
      $n = -1;
      foreach ($input as $i=>$v) {
         if (($n < 0) || (count($r[$n]) == $size)) {
            $n++;
            $r[$n] = array();
         }
         if ($preserve_keys) {
            $r[$n][$i] = $v;
         }
         else {
            $r[$n][] = $v;
         }
      }
      return($r);
   }
}


if (!function_exists("md5_file")) {
   function md5_file($filename, $raw_output=false) {
      if ($f = fopen($filename, "rb")) {
         $data = fread($f, 1<<26);  // can be too large for mem
         fclose($f);
         $r = md5($data);
         $data = NULL;
         if ($raw_output) {
            $r = hexdec(decbin($r));
         }
         return $r;
      }
   }
}


#------------------------------------------------------------------ 4.1 ---


#function nl_langinfo($item) {
#   $all = localeconv();
#   // unimplementable??
#}


#-- a silly alias (an early fallen attempt to unify PHP function names)
if (!function_exists("diskfreespace")) {
   function diskfreespace() {
      return disk_free_sapce();
   }
   function disktotalspace() {
      return disk_total_sapce();
   }
}


if (!function_exists("vprintf")) {
   function vprintf($format, $args=NULL) {
      $args = array_values((array)$args);
      switch(count($args)) {
         case 0: printf($format);
            break;
         case 1: printf($format, $args[0]);
            break;
         case 2: printf($format, $args[0], $args[1]);
            break;
         case 3: printf($format, $args[0], $args[1], $args[2]);
            break;
         case 4: printf($format, $args[0], $args[1], $args[2], $args[3]);
            break;
         case 5: printf($format, $args[0], $args[1], $args[2], $args[3], $args[4]);
            break;
         default:
            $code = 'printf($format';
            foreach ($args as $i=>$uu) {
               $code .= ',$args[' . $i . ']';
            }
            $code .= ");";
            eval($code);
      }
   }
}


if (!function_exists("vsprintf")) {
   function vprintf($format, $args=NULL) {
      $args = array_values((array)$args);
      switch(count($args)) {
         case 0: return sprintf($format);
         case 1: return sprintf($format, $args[0]);
         case 2: return sprintf($format, $args[0], $args[1]);
         case 3: return sprintf($format, $args[0], $args[1], $args[2]);
         case 4: return sprintf($format, $args[0], $args[1], $args[2], $args[3]);
         case 5: return sprintf($format, $args[0], $args[1], $args[2], $args[3], $args[4]);
         default:
            $code = 'return sprintf($format';
            foreach ($args as $i=>$uu) {
               $code .= ',$args[' . $i . ']';
            }
            $code .= ");";
            eval($code);
      }
   }
}



#-- end
// no need to implement anything below that, because such old versions
// will be incompatbile anyhow (- none of the newer superglobals known)

#---------------------------------------------------------------- 4.0.6 ---
#array_filter
#_map
#_merge

#---------------------------------------------------------------- 4.0.5 ---
# localeconv - UNIMPL!!
# array_reduce
# array_search
# strcoll

#---------------------------------------------------------------- 4.0.4 ---
# array_sum

#---------------------------------------------------------------- 4.0.3 ---
# is_uplo
# move_uploaded_file

#---------------------------------------------------------------- 4.0.2 ---
# strncasecmp
# wordwrap

#---------------------------------------------------------------- 4.0.1 ---
# levensth
# fflush() - UNIMPLementable!!!
# array_unique
# array_diff
# array_intersect
# sscanf
# str_pad


?>