1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 7                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2015 The PHP Group                                |
6   +----------------------------------------------------------------------+
7   | This source file is subject to version 3.01 of the PHP license,      |
8   | that is bundled with this package in the file LICENSE, and is        |
9   | available through the world-wide-web at the following url:           |
10   | http://www.php.net/license/3_01.txt                                  |
11   | If you did not receive a copy of the PHP license and are unable to   |
12   | obtain it through the world-wide-web, please send a note to          |
13   | license@php.net so we can mail you a copy immediately.               |
14   +----------------------------------------------------------------------+
15   | Authors: Rasmus Lerdorf <rasmus@php.net>                             |
16   |          Stig Bakken <ssb@php.net>                                   |
17   |          Andi Gutmans <andi@zend.com>                                |
18   |          Zeev Suraski <zeev@zend.com>                                |
19   | PHP 4.0 patches by Thies C. Arntzen (thies@thieso.net)               |
20   | PHP streams by Wez Furlong (wez@thebrainroom.com)                    |
21   +----------------------------------------------------------------------+
22*/
23
24/* $Id$ */
25
26/* Synced with php 3.0 revision 1.218 1999-06-16 [ssb] */
27
28/* {{{ includes */
29
30#include "php.h"
31#include "php_globals.h"
32#include "ext/standard/flock_compat.h"
33#include "ext/standard/exec.h"
34#include "ext/standard/php_filestat.h"
35#include "php_open_temporary_file.h"
36#include "ext/standard/basic_functions.h"
37#include "php_ini.h"
38#include "zend_smart_str.h"
39
40#include <stdio.h>
41#include <stdlib.h>
42#include <errno.h>
43#include <sys/types.h>
44#include <sys/stat.h>
45#include <fcntl.h>
46
47#ifdef PHP_WIN32
48# include <io.h>
49# define O_RDONLY _O_RDONLY
50# include "win32/param.h"
51# include "win32/winutil.h"
52# include "win32/fnmatch.h"
53#else
54# if HAVE_SYS_PARAM_H
55#  include <sys/param.h>
56# endif
57# if HAVE_SYS_SELECT_H
58#  include <sys/select.h>
59# endif
60# if defined(NETWARE) && defined(USE_WINSOCK)
61#  include <novsock2.h>
62# else
63#  include <sys/socket.h>
64#  include <netinet/in.h>
65#  include <netdb.h>
66# endif
67# if HAVE_ARPA_INET_H
68#  include <arpa/inet.h>
69# endif
70#endif
71
72#include "ext/standard/head.h"
73#include "php_string.h"
74#include "file.h"
75
76#if HAVE_PWD_H
77# ifdef PHP_WIN32
78#  include "win32/pwd.h"
79# else
80#  include <pwd.h>
81# endif
82#endif
83
84#ifdef HAVE_SYS_TIME_H
85# include <sys/time.h>
86#endif
87
88#include "fsock.h"
89#include "fopen_wrappers.h"
90#include "streamsfuncs.h"
91#include "php_globals.h"
92
93#ifdef HAVE_SYS_FILE_H
94# include <sys/file.h>
95#endif
96
97#if MISSING_FCLOSE_DECL
98extern int fclose(FILE *);
99#endif
100
101#ifdef HAVE_SYS_MMAN_H
102# include <sys/mman.h>
103#endif
104
105#include "scanf.h"
106#include "zend_API.h"
107
108#ifdef ZTS
109int file_globals_id;
110#else
111php_file_globals file_globals;
112#endif
113
114#if defined(HAVE_FNMATCH) && !defined(PHP_WIN32)
115# ifndef _GNU_SOURCE
116#  define _GNU_SOURCE
117# endif
118# include <fnmatch.h>
119#endif
120
121#ifdef HAVE_WCHAR_H
122# include <wchar.h>
123#endif
124
125#ifndef S_ISDIR
126# define S_ISDIR(mode)  (((mode)&S_IFMT) == S_IFDIR)
127#endif
128/* }}} */
129
130#define PHP_STREAM_TO_ZVAL(stream, arg) \
131    ZEND_ASSERT(Z_TYPE_P(arg) == IS_RESOURCE); \
132    php_stream_from_res(stream, Z_RES_P(arg));
133
134/* {{{ ZTS-stuff / Globals / Prototypes */
135
136/* sharing globals is *evil* */
137static int le_stream_context = FAILURE;
138
139PHPAPI int php_le_stream_context(void)
140{
141    return le_stream_context;
142}
143/* }}} */
144
145/* {{{ Module-Stuff
146*/
147static ZEND_RSRC_DTOR_FUNC(file_context_dtor)
148{
149    php_stream_context *context = (php_stream_context*)res->ptr;
150    if (Z_TYPE(context->options) != IS_UNDEF) {
151        zval_ptr_dtor(&context->options);
152        ZVAL_UNDEF(&context->options);
153    }
154    php_stream_context_free(context);
155}
156
157static void file_globals_ctor(php_file_globals *file_globals_p)
158{
159    memset(file_globals_p, 0, sizeof(php_file_globals));
160    file_globals_p->def_chunk_size = PHP_SOCK_CHUNK_SIZE;
161}
162
163static void file_globals_dtor(php_file_globals *file_globals_p)
164{
165}
166
167PHP_INI_BEGIN()
168    STD_PHP_INI_ENTRY("user_agent", NULL, PHP_INI_ALL, OnUpdateString, user_agent, php_file_globals, file_globals)
169    STD_PHP_INI_ENTRY("from", NULL, PHP_INI_ALL, OnUpdateString, from_address, php_file_globals, file_globals)
170    STD_PHP_INI_ENTRY("default_socket_timeout", "60", PHP_INI_ALL, OnUpdateLong, default_socket_timeout, php_file_globals, file_globals)
171    STD_PHP_INI_ENTRY("auto_detect_line_endings", "0", PHP_INI_ALL, OnUpdateLong, auto_detect_line_endings, php_file_globals, file_globals)
172PHP_INI_END()
173
174PHP_MINIT_FUNCTION(file)
175{
176    le_stream_context = zend_register_list_destructors_ex(file_context_dtor, NULL, "stream-context", module_number);
177
178#ifdef ZTS
179    ts_allocate_id(&file_globals_id, sizeof(php_file_globals), (ts_allocate_ctor) file_globals_ctor, (ts_allocate_dtor) file_globals_dtor);
180#else
181    file_globals_ctor(&file_globals);
182#endif
183
184    REGISTER_INI_ENTRIES();
185
186    REGISTER_LONG_CONSTANT("SEEK_SET", SEEK_SET, CONST_CS | CONST_PERSISTENT);
187    REGISTER_LONG_CONSTANT("SEEK_CUR", SEEK_CUR, CONST_CS | CONST_PERSISTENT);
188    REGISTER_LONG_CONSTANT("SEEK_END", SEEK_END, CONST_CS | CONST_PERSISTENT);
189    REGISTER_LONG_CONSTANT("LOCK_SH", PHP_LOCK_SH, CONST_CS | CONST_PERSISTENT);
190    REGISTER_LONG_CONSTANT("LOCK_EX", PHP_LOCK_EX, CONST_CS | CONST_PERSISTENT);
191    REGISTER_LONG_CONSTANT("LOCK_UN", PHP_LOCK_UN, CONST_CS | CONST_PERSISTENT);
192    REGISTER_LONG_CONSTANT("LOCK_NB", PHP_LOCK_NB, CONST_CS | CONST_PERSISTENT);
193
194    REGISTER_LONG_CONSTANT("STREAM_NOTIFY_CONNECT",         PHP_STREAM_NOTIFY_CONNECT,          CONST_CS | CONST_PERSISTENT);
195    REGISTER_LONG_CONSTANT("STREAM_NOTIFY_AUTH_REQUIRED",   PHP_STREAM_NOTIFY_AUTH_REQUIRED,    CONST_CS | CONST_PERSISTENT);
196    REGISTER_LONG_CONSTANT("STREAM_NOTIFY_AUTH_RESULT",     PHP_STREAM_NOTIFY_AUTH_RESULT,      CONST_CS | CONST_PERSISTENT);
197    REGISTER_LONG_CONSTANT("STREAM_NOTIFY_MIME_TYPE_IS",    PHP_STREAM_NOTIFY_MIME_TYPE_IS,     CONST_CS | CONST_PERSISTENT);
198    REGISTER_LONG_CONSTANT("STREAM_NOTIFY_FILE_SIZE_IS",    PHP_STREAM_NOTIFY_FILE_SIZE_IS,     CONST_CS | CONST_PERSISTENT);
199    REGISTER_LONG_CONSTANT("STREAM_NOTIFY_REDIRECTED",      PHP_STREAM_NOTIFY_REDIRECTED,       CONST_CS | CONST_PERSISTENT);
200    REGISTER_LONG_CONSTANT("STREAM_NOTIFY_PROGRESS",        PHP_STREAM_NOTIFY_PROGRESS,         CONST_CS | CONST_PERSISTENT);
201    REGISTER_LONG_CONSTANT("STREAM_NOTIFY_FAILURE",         PHP_STREAM_NOTIFY_FAILURE,          CONST_CS | CONST_PERSISTENT);
202    REGISTER_LONG_CONSTANT("STREAM_NOTIFY_COMPLETED",       PHP_STREAM_NOTIFY_COMPLETED,        CONST_CS | CONST_PERSISTENT);
203    REGISTER_LONG_CONSTANT("STREAM_NOTIFY_RESOLVE",         PHP_STREAM_NOTIFY_RESOLVE,          CONST_CS | CONST_PERSISTENT);
204
205    REGISTER_LONG_CONSTANT("STREAM_NOTIFY_SEVERITY_INFO",   PHP_STREAM_NOTIFY_SEVERITY_INFO,    CONST_CS | CONST_PERSISTENT);
206    REGISTER_LONG_CONSTANT("STREAM_NOTIFY_SEVERITY_WARN",   PHP_STREAM_NOTIFY_SEVERITY_WARN,    CONST_CS | CONST_PERSISTENT);
207    REGISTER_LONG_CONSTANT("STREAM_NOTIFY_SEVERITY_ERR",    PHP_STREAM_NOTIFY_SEVERITY_ERR,     CONST_CS | CONST_PERSISTENT);
208
209    REGISTER_LONG_CONSTANT("STREAM_FILTER_READ",            PHP_STREAM_FILTER_READ,             CONST_CS | CONST_PERSISTENT);
210    REGISTER_LONG_CONSTANT("STREAM_FILTER_WRITE",           PHP_STREAM_FILTER_WRITE,            CONST_CS | CONST_PERSISTENT);
211    REGISTER_LONG_CONSTANT("STREAM_FILTER_ALL",             PHP_STREAM_FILTER_ALL,              CONST_CS | CONST_PERSISTENT);
212
213    REGISTER_LONG_CONSTANT("STREAM_CLIENT_PERSISTENT",      PHP_STREAM_CLIENT_PERSISTENT,       CONST_CS | CONST_PERSISTENT);
214    REGISTER_LONG_CONSTANT("STREAM_CLIENT_ASYNC_CONNECT",   PHP_STREAM_CLIENT_ASYNC_CONNECT,    CONST_CS | CONST_PERSISTENT);
215    REGISTER_LONG_CONSTANT("STREAM_CLIENT_CONNECT",         PHP_STREAM_CLIENT_CONNECT,  CONST_CS | CONST_PERSISTENT);
216
217    REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_ANY_CLIENT",   STREAM_CRYPTO_METHOD_ANY_CLIENT,    CONST_CS|CONST_PERSISTENT);
218    REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_SSLv2_CLIENT", STREAM_CRYPTO_METHOD_SSLv2_CLIENT,  CONST_CS|CONST_PERSISTENT);
219    REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_SSLv3_CLIENT", STREAM_CRYPTO_METHOD_SSLv3_CLIENT,  CONST_CS|CONST_PERSISTENT);
220    REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_SSLv23_CLIENT",    STREAM_CRYPTO_METHOD_SSLv23_CLIENT, CONST_CS|CONST_PERSISTENT);
221    REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_TLS_CLIENT",   STREAM_CRYPTO_METHOD_TLS_CLIENT,    CONST_CS|CONST_PERSISTENT);
222    REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT",   STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT,    CONST_CS|CONST_PERSISTENT);
223    REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT",   STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT,    CONST_CS|CONST_PERSISTENT);
224    REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT",   STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT,    CONST_CS|CONST_PERSISTENT);
225    REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_ANY_SERVER",   STREAM_CRYPTO_METHOD_ANY_SERVER,    CONST_CS|CONST_PERSISTENT);
226    REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_SSLv2_SERVER", STREAM_CRYPTO_METHOD_SSLv2_SERVER,  CONST_CS|CONST_PERSISTENT);
227    REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_SSLv3_SERVER", STREAM_CRYPTO_METHOD_SSLv3_SERVER,  CONST_CS|CONST_PERSISTENT);
228    REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_SSLv23_SERVER",    STREAM_CRYPTO_METHOD_SSLv23_SERVER, CONST_CS|CONST_PERSISTENT);
229    REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_TLS_SERVER",   STREAM_CRYPTO_METHOD_TLS_SERVER,    CONST_CS|CONST_PERSISTENT);
230    REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_TLSv1_0_SERVER",   STREAM_CRYPTO_METHOD_TLSv1_0_SERVER,    CONST_CS|CONST_PERSISTENT);
231    REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_TLSv1_1_SERVER",   STREAM_CRYPTO_METHOD_TLSv1_1_SERVER,    CONST_CS|CONST_PERSISTENT);
232    REGISTER_LONG_CONSTANT("STREAM_CRYPTO_METHOD_TLSv1_2_SERVER",   STREAM_CRYPTO_METHOD_TLSv1_2_SERVER,    CONST_CS|CONST_PERSISTENT);
233
234    REGISTER_LONG_CONSTANT("STREAM_SHUT_RD",    STREAM_SHUT_RD,     CONST_CS|CONST_PERSISTENT);
235    REGISTER_LONG_CONSTANT("STREAM_SHUT_WR",    STREAM_SHUT_WR,     CONST_CS|CONST_PERSISTENT);
236    REGISTER_LONG_CONSTANT("STREAM_SHUT_RDWR",  STREAM_SHUT_RDWR,   CONST_CS|CONST_PERSISTENT);
237
238#ifdef PF_INET
239    REGISTER_LONG_CONSTANT("STREAM_PF_INET", PF_INET, CONST_CS|CONST_PERSISTENT);
240#elif defined(AF_INET)
241    REGISTER_LONG_CONSTANT("STREAM_PF_INET", AF_INET, CONST_CS|CONST_PERSISTENT);
242#endif
243
244#if HAVE_IPV6
245# ifdef PF_INET6
246    REGISTER_LONG_CONSTANT("STREAM_PF_INET6", PF_INET6, CONST_CS|CONST_PERSISTENT);
247# elif defined(AF_INET6)
248    REGISTER_LONG_CONSTANT("STREAM_PF_INET6", AF_INET6, CONST_CS|CONST_PERSISTENT);
249# endif
250#endif
251
252#ifdef PF_UNIX
253    REGISTER_LONG_CONSTANT("STREAM_PF_UNIX", PF_UNIX, CONST_CS|CONST_PERSISTENT);
254#elif defined(AF_UNIX)
255    REGISTER_LONG_CONSTANT("STREAM_PF_UNIX", AF_UNIX, CONST_CS|CONST_PERSISTENT);
256#endif
257
258#ifdef IPPROTO_IP
259    /* most people will use this one when calling socket() or socketpair() */
260    REGISTER_LONG_CONSTANT("STREAM_IPPROTO_IP", IPPROTO_IP, CONST_CS|CONST_PERSISTENT);
261#endif
262
263#ifdef IPPROTO_TCP
264    REGISTER_LONG_CONSTANT("STREAM_IPPROTO_TCP", IPPROTO_TCP, CONST_CS|CONST_PERSISTENT);
265#endif
266
267#ifdef IPPROTO_UDP
268    REGISTER_LONG_CONSTANT("STREAM_IPPROTO_UDP", IPPROTO_UDP, CONST_CS|CONST_PERSISTENT);
269#endif
270
271#ifdef IPPROTO_ICMP
272    REGISTER_LONG_CONSTANT("STREAM_IPPROTO_ICMP", IPPROTO_ICMP, CONST_CS|CONST_PERSISTENT);
273#endif
274
275#ifdef IPPROTO_RAW
276    REGISTER_LONG_CONSTANT("STREAM_IPPROTO_RAW", IPPROTO_RAW, CONST_CS|CONST_PERSISTENT);
277#endif
278
279    REGISTER_LONG_CONSTANT("STREAM_SOCK_STREAM", SOCK_STREAM, CONST_CS|CONST_PERSISTENT);
280    REGISTER_LONG_CONSTANT("STREAM_SOCK_DGRAM", SOCK_DGRAM, CONST_CS|CONST_PERSISTENT);
281
282#ifdef SOCK_RAW
283    REGISTER_LONG_CONSTANT("STREAM_SOCK_RAW", SOCK_RAW, CONST_CS|CONST_PERSISTENT);
284#endif
285
286#ifdef SOCK_SEQPACKET
287    REGISTER_LONG_CONSTANT("STREAM_SOCK_SEQPACKET", SOCK_SEQPACKET, CONST_CS|CONST_PERSISTENT);
288#endif
289
290#ifdef SOCK_RDM
291    REGISTER_LONG_CONSTANT("STREAM_SOCK_RDM", SOCK_RDM, CONST_CS|CONST_PERSISTENT);
292#endif
293
294    REGISTER_LONG_CONSTANT("STREAM_PEEK", STREAM_PEEK, CONST_CS | CONST_PERSISTENT);
295    REGISTER_LONG_CONSTANT("STREAM_OOB",  STREAM_OOB, CONST_CS | CONST_PERSISTENT);
296
297    REGISTER_LONG_CONSTANT("STREAM_SERVER_BIND",            STREAM_XPORT_BIND,                  CONST_CS | CONST_PERSISTENT);
298    REGISTER_LONG_CONSTANT("STREAM_SERVER_LISTEN",          STREAM_XPORT_LISTEN,                CONST_CS | CONST_PERSISTENT);
299
300    REGISTER_LONG_CONSTANT("FILE_USE_INCLUDE_PATH",         PHP_FILE_USE_INCLUDE_PATH,          CONST_CS | CONST_PERSISTENT);
301    REGISTER_LONG_CONSTANT("FILE_IGNORE_NEW_LINES",         PHP_FILE_IGNORE_NEW_LINES,          CONST_CS | CONST_PERSISTENT);
302    REGISTER_LONG_CONSTANT("FILE_SKIP_EMPTY_LINES",         PHP_FILE_SKIP_EMPTY_LINES,          CONST_CS | CONST_PERSISTENT);
303    REGISTER_LONG_CONSTANT("FILE_APPEND",                   PHP_FILE_APPEND,                    CONST_CS | CONST_PERSISTENT);
304    REGISTER_LONG_CONSTANT("FILE_NO_DEFAULT_CONTEXT",       PHP_FILE_NO_DEFAULT_CONTEXT,        CONST_CS | CONST_PERSISTENT);
305
306    REGISTER_LONG_CONSTANT("FILE_TEXT",                     0,                                  CONST_CS | CONST_PERSISTENT);
307    REGISTER_LONG_CONSTANT("FILE_BINARY",                   0,                                  CONST_CS | CONST_PERSISTENT);
308
309#ifdef HAVE_FNMATCH
310    REGISTER_LONG_CONSTANT("FNM_NOESCAPE", FNM_NOESCAPE, CONST_CS | CONST_PERSISTENT);
311    REGISTER_LONG_CONSTANT("FNM_PATHNAME", FNM_PATHNAME, CONST_CS | CONST_PERSISTENT);
312    REGISTER_LONG_CONSTANT("FNM_PERIOD",   FNM_PERIOD,   CONST_CS | CONST_PERSISTENT);
313# ifdef FNM_CASEFOLD /* a GNU extension */ /* TODO emulate if not available */
314    REGISTER_LONG_CONSTANT("FNM_CASEFOLD", FNM_CASEFOLD, CONST_CS | CONST_PERSISTENT);
315# endif
316#endif
317
318    return SUCCESS;
319}
320/* }}} */
321
322PHP_MSHUTDOWN_FUNCTION(file) /* {{{ */
323{
324#ifndef ZTS
325    file_globals_dtor(&file_globals);
326#endif
327    return SUCCESS;
328}
329/* }}} */
330
331static int flock_values[] = { LOCK_SH, LOCK_EX, LOCK_UN };
332
333/* {{{ proto bool flock(resource fp, int operation [, int &wouldblock])
334   Portable file locking */
335PHP_FUNCTION(flock)
336{
337    zval *res, *wouldblock = NULL;
338    int act;
339    php_stream *stream;
340    zend_long operation = 0;
341
342    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl|z/", &res, &operation, &wouldblock) == FAILURE) {
343        return;
344    }
345
346    PHP_STREAM_TO_ZVAL(stream, res);
347
348    act = operation & 3;
349    if (act < 1 || act > 3) {
350        php_error_docref(NULL, E_WARNING, "Illegal operation argument");
351        RETURN_FALSE;
352    }
353
354    if (wouldblock) {
355        zval_dtor(wouldblock);
356        ZVAL_LONG(wouldblock, 0);
357    }
358
359    /* flock_values contains all possible actions if (operation & 4) we won't block on the lock */
360    act = flock_values[act - 1] | (operation & PHP_LOCK_NB ? LOCK_NB : 0);
361    if (php_stream_lock(stream, act)) {
362        if (operation && errno == EWOULDBLOCK && wouldblock) {
363            ZVAL_LONG(wouldblock, 1);
364        }
365        RETURN_FALSE;
366    }
367    RETURN_TRUE;
368}
369/* }}} */
370
371#define PHP_META_UNSAFE ".\\+*?[^]$() "
372
373/* {{{ proto array get_meta_tags(string filename [, bool use_include_path])
374   Extracts all meta tag content attributes from a file and returns an array */
375PHP_FUNCTION(get_meta_tags)
376{
377    char *filename;
378    size_t filename_len;
379    zend_bool use_include_path = 0;
380    int in_tag = 0, done = 0;
381    int looking_for_val = 0, have_name = 0, have_content = 0;
382    int saw_name = 0, saw_content = 0;
383    char *name = NULL, *value = NULL, *temp = NULL;
384    php_meta_tags_token tok, tok_last;
385    php_meta_tags_data md;
386
387    /* Initiailize our structure */
388    memset(&md, 0, sizeof(md));
389
390    /* Parse arguments */
391    if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|b", &filename, &filename_len, &use_include_path) == FAILURE) {
392        return;
393    }
394
395    md.stream = php_stream_open_wrapper(filename, "rb",
396            (use_include_path ? USE_PATH : 0) | REPORT_ERRORS,
397            NULL);
398    if (!md.stream) {
399        RETURN_FALSE;
400    }
401
402    array_init(return_value);
403
404    tok_last = TOK_EOF;
405
406    while (!done && (tok = php_next_meta_token(&md)) != TOK_EOF) {
407        if (tok == TOK_ID) {
408            if (tok_last == TOK_OPENTAG) {
409                md.in_meta = !strcasecmp("meta", md.token_data);
410            } else if (tok_last == TOK_SLASH && in_tag) {
411                if (strcasecmp("head", md.token_data) == 0) {
412                    /* We are done here! */
413                    done = 1;
414                }
415            } else if (tok_last == TOK_EQUAL && looking_for_val) {
416                if (saw_name) {
417                    if (name) efree(name);
418                    /* Get the NAME attr (Single word attr, non-quoted) */
419                    temp = name = estrndup(md.token_data, md.token_len);
420
421                    while (temp && *temp) {
422                        if (strchr(PHP_META_UNSAFE, *temp)) {
423                            *temp = '_';
424                        }
425                        temp++;
426                    }
427
428                    have_name = 1;
429                } else if (saw_content) {
430                    if (value) efree(value);
431                    value = estrndup(md.token_data, md.token_len);
432                    have_content = 1;
433                }
434
435                looking_for_val = 0;
436            } else {
437                if (md.in_meta) {
438                    if (strcasecmp("name", md.token_data) == 0) {
439                        saw_name = 1;
440                        saw_content = 0;
441                        looking_for_val = 1;
442                    } else if (strcasecmp("content", md.token_data) == 0) {
443                        saw_name = 0;
444                        saw_content = 1;
445                        looking_for_val = 1;
446                    }
447                }
448            }
449        } else if (tok == TOK_STRING && tok_last == TOK_EQUAL && looking_for_val) {
450            if (saw_name) {
451                if (name) efree(name);
452                /* Get the NAME attr (Quoted single/double) */
453                temp = name = estrndup(md.token_data, md.token_len);
454
455                while (temp && *temp) {
456                    if (strchr(PHP_META_UNSAFE, *temp)) {
457                        *temp = '_';
458                    }
459                    temp++;
460                }
461
462                have_name = 1;
463            } else if (saw_content) {
464                if (value) efree(value);
465                value = estrndup(md.token_data, md.token_len);
466                have_content = 1;
467            }
468
469            looking_for_val = 0;
470        } else if (tok == TOK_OPENTAG) {
471            if (looking_for_val) {
472                looking_for_val = 0;
473                have_name = saw_name = 0;
474                have_content = saw_content = 0;
475            }
476            in_tag = 1;
477        } else if (tok == TOK_CLOSETAG) {
478            if (have_name) {
479                /* For BC */
480                php_strtolower(name, strlen(name));
481                if (have_content) {
482                    add_assoc_string(return_value, name, value);
483                } else {
484                    add_assoc_string(return_value, name, "");
485                }
486
487                efree(name);
488                if (value) efree(value);
489            } else if (have_content) {
490                efree(value);
491            }
492
493            name = value = NULL;
494
495            /* Reset all of our flags */
496            in_tag = looking_for_val = 0;
497            have_name = saw_name = 0;
498            have_content = saw_content = 0;
499            md.in_meta = 0;
500        }
501
502        tok_last = tok;
503
504        if (md.token_data)
505            efree(md.token_data);
506
507        md.token_data = NULL;
508    }
509
510    if (value) efree(value);
511    if (name) efree(name);
512    php_stream_close(md.stream);
513}
514/* }}} */
515
516/* {{{ proto string file_get_contents(string filename [, bool use_include_path [, resource context [, long offset [, long maxlen]]]])
517   Read the entire file into a string */
518PHP_FUNCTION(file_get_contents)
519{
520    char *filename;
521    size_t filename_len;
522    zend_bool use_include_path = 0;
523    php_stream *stream;
524    zend_long offset = -1;
525    zend_long maxlen = PHP_STREAM_COPY_ALL;
526    zval *zcontext = NULL;
527    php_stream_context *context = NULL;
528    zend_string *contents;
529
530    /* Parse arguments */
531    if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|br!ll", &filename, &filename_len, &use_include_path, &zcontext, &offset, &maxlen) == FAILURE) {
532        return;
533    }
534
535    if (ZEND_NUM_ARGS() == 5 && maxlen < 0) {
536        php_error_docref(NULL, E_WARNING, "length must be greater than or equal to zero");
537        RETURN_FALSE;
538    }
539
540    context = php_stream_context_from_zval(zcontext, 0);
541
542    stream = php_stream_open_wrapper_ex(filename, "rb",
543                (use_include_path ? USE_PATH : 0) | REPORT_ERRORS,
544                NULL, context);
545    if (!stream) {
546        RETURN_FALSE;
547    }
548
549    if (offset > 0 && php_stream_seek(stream, offset, SEEK_SET) < 0) {
550        php_error_docref(NULL, E_WARNING, "Failed to seek to position " ZEND_LONG_FMT " in the stream", offset);
551        php_stream_close(stream);
552        RETURN_FALSE;
553    }
554
555    if (maxlen > INT_MAX) {
556        php_error_docref(NULL, E_WARNING, "maxlen truncated from %pd to %d bytes", maxlen, INT_MAX);
557        maxlen = INT_MAX;
558    }
559    if ((contents = php_stream_copy_to_mem(stream, maxlen, 0)) != NULL) {
560        RETVAL_STR(contents);
561    } else {
562        RETVAL_EMPTY_STRING();
563    }
564
565    php_stream_close(stream);
566}
567/* }}} */
568
569/* {{{ proto int file_put_contents(string file, mixed data [, int flags [, resource context]])
570   Write/Create a file with contents data and return the number of bytes written */
571PHP_FUNCTION(file_put_contents)
572{
573    php_stream *stream;
574    char *filename;
575    size_t filename_len;
576    zval *data;
577    zend_long numbytes = 0;
578    zend_long flags = 0;
579    zval *zcontext = NULL;
580    php_stream_context *context = NULL;
581    php_stream *srcstream = NULL;
582    char mode[3] = "wb";
583    char ret_ok = 1;
584
585    if (zend_parse_parameters(ZEND_NUM_ARGS(), "pz/|lr!", &filename, &filename_len, &data, &flags, &zcontext) == FAILURE) {
586        return;
587    }
588
589    if (Z_TYPE_P(data) == IS_RESOURCE) {
590        php_stream_from_zval(srcstream, data);
591    }
592
593    context = php_stream_context_from_zval(zcontext, flags & PHP_FILE_NO_DEFAULT_CONTEXT);
594
595    if (flags & PHP_FILE_APPEND) {
596        mode[0] = 'a';
597    } else if (flags & LOCK_EX) {
598        /* check to make sure we are dealing with a regular file */
599        if (php_memnstr(filename, "://", sizeof("://") - 1, filename + filename_len)) {
600            if (strncasecmp(filename, "file://", sizeof("file://") - 1)) {
601                php_error_docref(NULL, E_WARNING, "Exclusive locks may only be set for regular files");
602                RETURN_FALSE;
603            }
604        }
605        mode[0] = 'c';
606    }
607    mode[2] = '\0';
608
609    stream = php_stream_open_wrapper_ex(filename, mode, ((flags & PHP_FILE_USE_INCLUDE_PATH) ? USE_PATH : 0) | REPORT_ERRORS, NULL, context);
610    if (stream == NULL) {
611        RETURN_FALSE;
612    }
613
614    if (flags & LOCK_EX && (!php_stream_supports_lock(stream) || php_stream_lock(stream, LOCK_EX))) {
615        php_stream_close(stream);
616        php_error_docref(NULL, E_WARNING, "Exclusive locks are not supported for this stream");
617        RETURN_FALSE;
618    }
619
620    if (mode[0] == 'c') {
621        php_stream_truncate_set_size(stream, 0);
622    }
623
624    switch (Z_TYPE_P(data)) {
625        case IS_RESOURCE: {
626            size_t len;
627            if (php_stream_copy_to_stream_ex(srcstream, stream, PHP_STREAM_COPY_ALL, &len) != SUCCESS) {
628                ret_ok = 0;
629            } else {
630                if (len > ZEND_LONG_MAX) {
631                    php_error_docref(NULL, E_WARNING, "content truncated from %zu to " ZEND_LONG_FMT " bytes", len, ZEND_LONG_MAX);
632                    len = ZEND_LONG_MAX;
633                }
634                numbytes = len;
635            }
636            break;
637        }
638        case IS_NULL:
639        case IS_LONG:
640        case IS_DOUBLE:
641        case IS_FALSE:
642        case IS_TRUE:
643            convert_to_string_ex(data);
644
645        case IS_STRING:
646            if (Z_STRLEN_P(data)) {
647                numbytes = php_stream_write(stream, Z_STRVAL_P(data), Z_STRLEN_P(data));
648                if (numbytes != Z_STRLEN_P(data)) {
649                    php_error_docref(NULL, E_WARNING, "Only %pl of %zd bytes written, possibly out of free disk space", numbytes, Z_STRLEN_P(data));
650                    numbytes = -1;
651                }
652            }
653            break;
654
655        case IS_ARRAY:
656            if (zend_hash_num_elements(Z_ARRVAL_P(data))) {
657                size_t bytes_written;
658                zval *tmp;
659
660                ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(data), tmp) {
661                    zend_string *str = zval_get_string(tmp);
662                    if (str->len) {
663                        numbytes += str->len;
664                        bytes_written = php_stream_write(stream, str->val, str->len);
665                        if (bytes_written != str->len) {
666                            php_error_docref(NULL, E_WARNING, "Failed to write %zd bytes to %s", str->len, filename);
667                            ret_ok = 0;
668                            zend_string_release(str);
669                            break;
670                        }
671                    }
672                    zend_string_release(str);
673                } ZEND_HASH_FOREACH_END();
674            }
675            break;
676
677        case IS_OBJECT:
678            if (Z_OBJ_HT_P(data) != NULL) {
679                zval out;
680
681                if (zend_std_cast_object_tostring(data, &out, IS_STRING) == SUCCESS) {
682                    numbytes = php_stream_write(stream, Z_STRVAL(out), Z_STRLEN(out));
683                    if (numbytes != Z_STRLEN(out)) {
684                        php_error_docref(NULL, E_WARNING, "Only %pd of %zd bytes written, possibly out of free disk space", numbytes, Z_STRLEN(out));
685                        numbytes = -1;
686                    }
687                    zval_dtor(&out);
688                    break;
689                }
690            }
691        default:
692            ret_ok = 0;
693            break;
694    }
695    php_stream_close(stream);
696
697    if (!ret_ok) {
698        RETURN_FALSE;
699    }
700
701    RETURN_LONG(numbytes);
702}
703/* }}} */
704
705#define PHP_FILE_BUF_SIZE   80
706
707/* {{{ proto array file(string filename [, int flags[, resource context]])
708   Read entire file into an array */
709PHP_FUNCTION(file)
710{
711    char *filename;
712    size_t filename_len;
713    char *p, *s, *e;
714    register int i = 0;
715    char eol_marker = '\n';
716    zend_long flags = 0;
717    zend_bool use_include_path;
718    zend_bool include_new_line;
719    zend_bool skip_blank_lines;
720    php_stream *stream;
721    zval *zcontext = NULL;
722    php_stream_context *context = NULL;
723    zend_string *target_buf;
724
725    /* Parse arguments */
726    if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|lr!", &filename, &filename_len, &flags, &zcontext) == FAILURE) {
727        return;
728    }
729    if (flags < 0 || flags > (PHP_FILE_USE_INCLUDE_PATH | PHP_FILE_IGNORE_NEW_LINES | PHP_FILE_SKIP_EMPTY_LINES | PHP_FILE_NO_DEFAULT_CONTEXT)) {
730        php_error_docref(NULL, E_WARNING, "'" ZEND_LONG_FMT "' flag is not supported", flags);
731        RETURN_FALSE;
732    }
733
734    use_include_path = flags & PHP_FILE_USE_INCLUDE_PATH;
735    include_new_line = !(flags & PHP_FILE_IGNORE_NEW_LINES);
736    skip_blank_lines = flags & PHP_FILE_SKIP_EMPTY_LINES;
737
738    context = php_stream_context_from_zval(zcontext, flags & PHP_FILE_NO_DEFAULT_CONTEXT);
739
740    stream = php_stream_open_wrapper_ex(filename, "rb", (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, context);
741    if (!stream) {
742        RETURN_FALSE;
743    }
744
745    /* Initialize return array */
746    array_init(return_value);
747
748    if ((target_buf = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, 0)) != NULL) {
749        s = target_buf->val;
750        e = target_buf->val + target_buf->len;
751
752        if (!(p = (char*)php_stream_locate_eol(stream, target_buf))) {
753            p = e;
754            goto parse_eol;
755        }
756
757        if (stream->flags & PHP_STREAM_FLAG_EOL_MAC) {
758            eol_marker = '\r';
759        }
760
761        /* for performance reasons the code is duplicated, so that the if (include_new_line)
762         * will not need to be done for every single line in the file. */
763        if (include_new_line) {
764            do {
765                p++;
766parse_eol:
767                add_index_stringl(return_value, i++, s, p-s);
768                s = p;
769            } while ((p = memchr(p, eol_marker, (e-p))));
770        } else {
771            do {
772                int windows_eol = 0;
773                if (p != target_buf->val && eol_marker == '\n' && *(p - 1) == '\r') {
774                    windows_eol++;
775                }
776                if (skip_blank_lines && !(p-s-windows_eol)) {
777                    s = ++p;
778                    continue;
779                }
780                add_index_stringl(return_value, i++, s, p-s-windows_eol);
781                s = ++p;
782            } while ((p = memchr(p, eol_marker, (e-p))));
783        }
784
785        /* handle any left overs of files without new lines */
786        if (s != e) {
787            p = e;
788            goto parse_eol;
789        }
790    }
791
792    if (target_buf) {
793        zend_string_free(target_buf);
794    }
795    php_stream_close(stream);
796}
797/* }}} */
798
799/* {{{ proto string tempnam(string dir, string prefix)
800   Create a unique filename in a directory */
801PHP_FUNCTION(tempnam)
802{
803    char *dir, *prefix;
804    size_t dir_len, prefix_len;
805    zend_string *opened_path;
806    int fd;
807    zend_string *p;
808
809    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ps", &dir, &dir_len, &prefix, &prefix_len) == FAILURE) {
810        return;
811    }
812
813    if (php_check_open_basedir(dir)) {
814        RETURN_FALSE;
815    }
816
817    p = php_basename(prefix, prefix_len, NULL, 0);
818    if (p->len > 64) {
819        p->val[63] = '\0';
820    }
821
822    RETVAL_FALSE;
823
824    if ((fd = php_open_temporary_fd_ex(dir, p->val, &opened_path, 1)) >= 0) {
825        close(fd);
826        RETVAL_STR(opened_path);
827    }
828    zend_string_release(p);
829}
830/* }}} */
831
832/* {{{ proto resource tmpfile(void)
833   Create a temporary file that will be deleted automatically after use */
834PHP_NAMED_FUNCTION(php_if_tmpfile)
835{
836    php_stream *stream;
837
838    if (zend_parse_parameters_none() == FAILURE) {
839        return;
840    }
841
842    stream = php_stream_fopen_tmpfile();
843
844    if (stream) {
845        php_stream_to_zval(stream, return_value);
846    } else {
847        RETURN_FALSE;
848    }
849}
850/* }}} */
851
852/* {{{ proto resource fopen(string filename, string mode [, bool use_include_path [, resource context]])
853   Open a file or a URL and return a file pointer */
854PHP_NAMED_FUNCTION(php_if_fopen)
855{
856    char *filename, *mode;
857    size_t filename_len, mode_len;
858    zend_bool use_include_path = 0;
859    zval *zcontext = NULL;
860    php_stream *stream;
861    php_stream_context *context = NULL;
862
863    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ps|br", &filename, &filename_len, &mode, &mode_len, &use_include_path, &zcontext) == FAILURE) {
864        RETURN_FALSE;
865    }
866
867    context = php_stream_context_from_zval(zcontext, 0);
868
869    stream = php_stream_open_wrapper_ex(filename, mode, (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, context);
870
871    if (stream == NULL) {
872        RETURN_FALSE;
873    }
874
875    php_stream_to_zval(stream, return_value);
876}
877/* }}} */
878
879/* {{{ proto bool fclose(resource fp)
880   Close an open file pointer */
881PHPAPI PHP_FUNCTION(fclose)
882{
883    zval *res;
884    php_stream *stream;
885
886#ifndef FAST_ZPP
887    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &res) == FAILURE) {
888        RETURN_FALSE;
889    }
890#else
891    ZEND_PARSE_PARAMETERS_START(1, 1)
892        Z_PARAM_RESOURCE(res)
893    ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
894#endif
895
896    PHP_STREAM_TO_ZVAL(stream, res);
897
898    if ((stream->flags & PHP_STREAM_FLAG_NO_FCLOSE) != 0) {
899        php_error_docref(NULL, E_WARNING, "%pd is not a valid stream resource", stream->res->handle);
900        RETURN_FALSE;
901    }
902
903    php_stream_free(stream,
904        PHP_STREAM_FREE_KEEP_RSRC |
905        (stream->is_persistent ? PHP_STREAM_FREE_CLOSE_PERSISTENT : PHP_STREAM_FREE_CLOSE));
906
907    RETURN_TRUE;
908}
909/* }}} */
910
911/* {{{ proto resource popen(string command, string mode)
912   Execute a command and open either a read or a write pipe to it */
913PHP_FUNCTION(popen)
914{
915    char *command, *mode;
916    size_t command_len, mode_len;
917    FILE *fp;
918    php_stream *stream;
919    char *posix_mode;
920
921    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ps", &command, &command_len, &mode, &mode_len) == FAILURE) {
922        return;
923    }
924
925    posix_mode = estrndup(mode, mode_len);
926#ifndef PHP_WIN32
927    {
928        char *z = memchr(posix_mode, 'b', mode_len);
929        if (z) {
930            memmove(z, z + 1, mode_len - (z - posix_mode));
931        }
932    }
933#endif
934
935    fp = VCWD_POPEN(command, posix_mode);
936    if (!fp) {
937        php_error_docref2(NULL, command, posix_mode, E_WARNING, "%s", strerror(errno));
938        efree(posix_mode);
939        RETURN_FALSE;
940    }
941
942    stream = php_stream_fopen_from_pipe(fp, mode);
943
944    if (stream == NULL) {
945        php_error_docref2(NULL, command, mode, E_WARNING, "%s", strerror(errno));
946        RETVAL_FALSE;
947    } else {
948        php_stream_to_zval(stream, return_value);
949    }
950
951    efree(posix_mode);
952}
953/* }}} */
954
955/* {{{ proto int pclose(resource fp)
956   Close a file pointer opened by popen() */
957PHP_FUNCTION(pclose)
958{
959    zval *res;
960    php_stream *stream;
961
962    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &res) == FAILURE) {
963        RETURN_FALSE;
964    }
965
966    PHP_STREAM_TO_ZVAL(stream, res);
967
968    FG(pclose_wait) = 1;
969    zend_list_close(stream->res);
970    FG(pclose_wait) = 0;
971    RETURN_LONG(FG(pclose_ret));
972}
973/* }}} */
974
975/* {{{ proto bool feof(resource fp)
976   Test for end-of-file on a file pointer */
977PHPAPI PHP_FUNCTION(feof)
978{
979    zval *res;
980    php_stream *stream;
981
982    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &res) == FAILURE) {
983        RETURN_FALSE;
984    }
985
986    PHP_STREAM_TO_ZVAL(stream, res);
987
988    if (php_stream_eof(stream)) {
989        RETURN_TRUE;
990    } else {
991        RETURN_FALSE;
992    }
993}
994/* }}} */
995
996/* {{{ proto string fgets(resource fp[, int length])
997   Get a line from file pointer */
998PHPAPI PHP_FUNCTION(fgets)
999{
1000    zval *res;
1001    zend_long len = 1024;
1002    char *buf = NULL;
1003    int argc = ZEND_NUM_ARGS();
1004    size_t line_len = 0;
1005    php_stream *stream;
1006
1007    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &res, &len) == FAILURE) {
1008        RETURN_FALSE;
1009    }
1010
1011    PHP_STREAM_TO_ZVAL(stream, res);
1012
1013    if (argc == 1) {
1014        /* ask streams to give us a buffer of an appropriate size */
1015        buf = php_stream_get_line(stream, NULL, 0, &line_len);
1016        if (buf == NULL) {
1017            goto exit_failed;
1018        }
1019    } else if (argc > 1) {
1020        if (len <= 0) {
1021            php_error_docref(NULL, E_WARNING, "Length parameter must be greater than 0");
1022            RETURN_FALSE;
1023        }
1024
1025        buf = ecalloc(len + 1, sizeof(char));
1026        if (php_stream_get_line(stream, buf, len, &line_len) == NULL) {
1027            goto exit_failed;
1028        }
1029    }
1030
1031    /* resize buffer if it's much larger than the result.
1032     * Only needed if the user requested a buffer size. */
1033//??    if (argc > 1 && line_len < len / 2) {
1034//???
1035        ZVAL_STRINGL(return_value, buf, line_len);
1036        efree(buf);
1037//??    } else {
1038//???
1039//???       ZVAL_STRINGL(return_value, buf, line_len);
1040//???   efree(buf);
1041//???   }
1042    return;
1043
1044exit_failed:
1045    RETVAL_FALSE;
1046    if (buf) {
1047        efree(buf);
1048    }
1049}
1050/* }}} */
1051
1052/* {{{ proto string fgetc(resource fp)
1053   Get a character from file pointer */
1054PHPAPI PHP_FUNCTION(fgetc)
1055{
1056    zval *res;
1057    char buf[2];
1058    int result;
1059    php_stream *stream;
1060
1061    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &res) == FAILURE) {
1062        RETURN_FALSE;
1063    }
1064
1065    PHP_STREAM_TO_ZVAL(stream, res);
1066
1067    result = php_stream_getc(stream);
1068
1069    if (result == EOF) {
1070        RETVAL_FALSE;
1071    } else {
1072        buf[0] = result;
1073        buf[1] = '\0';
1074
1075        RETURN_STRINGL(buf, 1);
1076    }
1077}
1078/* }}} */
1079
1080/* {{{ proto string fgetss(resource fp [, int length [, string allowable_tags]])
1081   Get a line from file pointer and strip HTML tags */
1082PHPAPI PHP_FUNCTION(fgetss)
1083{
1084    zval *fd;
1085    zend_long bytes = 0;
1086    size_t len = 0;
1087    size_t actual_len, retval_len;
1088    char *buf = NULL, *retval;
1089    php_stream *stream;
1090    zend_string *allowed = NULL;
1091    char *allowed_tags=NULL;
1092    size_t allowed_tags_len=0;
1093
1094    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|lS", &fd, &bytes, &allowed) == FAILURE) {
1095        RETURN_FALSE;
1096    }
1097
1098    PHP_STREAM_TO_ZVAL(stream, fd);
1099
1100    if (ZEND_NUM_ARGS() >= 2) {
1101        if (bytes <= 0) {
1102            php_error_docref(NULL, E_WARNING, "Length parameter must be greater than 0");
1103            RETURN_FALSE;
1104        }
1105
1106        len = (size_t) bytes;
1107        buf = safe_emalloc(sizeof(char), (len + 1), 0);
1108        /*needed because recv doesnt set null char at end*/
1109        memset(buf, 0, len + 1);
1110    }
1111
1112    if ((retval = php_stream_get_line(stream, buf, len, &actual_len)) == NULL)  {
1113        if (buf != NULL) {
1114            efree(buf);
1115        }
1116        RETURN_FALSE;
1117    }
1118
1119    if (allowed != NULL) {
1120// TODO: reimplement to avoid reallocation ???
1121        if (IS_INTERNED(allowed)) {
1122            allowed_tags = estrndup(allowed->val, allowed->len);
1123            allowed_tags_len = allowed->len;
1124        } else {
1125            allowed_tags = allowed->val;
1126            allowed_tags_len = allowed->len;
1127        }
1128    }
1129
1130    retval_len = php_strip_tags(retval, actual_len, &stream->fgetss_state, allowed_tags, allowed_tags_len);
1131
1132// TODO: reimplement to avoid reallocation ???
1133    if (allowed && IS_INTERNED(allowed)) {
1134        efree(allowed_tags);
1135    }
1136
1137    // TODO: avoid reallocation ???
1138    RETVAL_STRINGL(retval, retval_len);
1139    efree(retval);
1140}
1141/* }}} */
1142
1143/* {{{ proto mixed fscanf(resource stream, string format [, string ...])
1144   Implements a mostly ANSI compatible fscanf() */
1145PHP_FUNCTION(fscanf)
1146{
1147    int result, argc = 0;
1148    size_t format_len;
1149    zval *args = NULL;
1150    zval *file_handle;
1151    char *buf, *format;
1152    size_t len;
1153    void *what;
1154
1155    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs*", &file_handle, &format, &format_len, &args, &argc) == FAILURE) {
1156        return;
1157    }
1158
1159    what = zend_fetch_resource2(Z_RES_P(file_handle), "File-Handle", php_file_le_stream(), php_file_le_pstream());
1160
1161    /* we can't do a ZEND_VERIFY_RESOURCE(what), otherwise we end up
1162     * with a leak if we have an invalid filehandle. This needs changing
1163     * if the code behind ZEND_VERIFY_RESOURCE changed. - cc */
1164    if (!what) {
1165        RETURN_FALSE;
1166    }
1167
1168    buf = php_stream_get_line((php_stream *) what, NULL, 0, &len);
1169    if (buf == NULL) {
1170        RETURN_FALSE;
1171    }
1172
1173    result = php_sscanf_internal(buf, format, argc, args, 0, return_value);
1174
1175    efree(buf);
1176
1177    if (SCAN_ERROR_WRONG_PARAM_COUNT == result) {
1178        WRONG_PARAM_COUNT;
1179    }
1180}
1181/* }}} */
1182
1183/* {{{ proto int fwrite(resource fp, string str [, int length])
1184   Binary-safe file write */
1185PHPAPI PHP_FUNCTION(fwrite)
1186{
1187    zval *res;
1188    char *input;
1189    size_t inputlen;
1190    size_t ret;
1191    size_t num_bytes;
1192    zend_long maxlen = 0;
1193    php_stream *stream;
1194
1195    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs|l", &res, &input, &inputlen, &maxlen) == FAILURE) {
1196        RETURN_FALSE;
1197    }
1198
1199    if (ZEND_NUM_ARGS() == 2) {
1200        num_bytes = inputlen;
1201    } else if (maxlen <= 0) {
1202        num_bytes = 0;
1203    } else {
1204        num_bytes = MIN((size_t) maxlen, inputlen);
1205    }
1206
1207    if (!num_bytes) {
1208        RETURN_LONG(0);
1209    }
1210
1211    PHP_STREAM_TO_ZVAL(stream, res);
1212
1213    ret = php_stream_write(stream, input, num_bytes);
1214
1215    RETURN_LONG(ret);
1216}
1217/* }}} */
1218
1219/* {{{ proto bool fflush(resource fp)
1220   Flushes output */
1221PHPAPI PHP_FUNCTION(fflush)
1222{
1223    zval *res;
1224    int ret;
1225    php_stream *stream;
1226
1227    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &res) == FAILURE) {
1228        RETURN_FALSE;
1229    }
1230
1231    PHP_STREAM_TO_ZVAL(stream, res);
1232
1233    ret = php_stream_flush(stream);
1234    if (ret) {
1235        RETURN_FALSE;
1236    }
1237    RETURN_TRUE;
1238}
1239/* }}} */
1240
1241/* {{{ proto bool rewind(resource fp)
1242   Rewind the position of a file pointer */
1243PHPAPI PHP_FUNCTION(rewind)
1244{
1245    zval *res;
1246    php_stream *stream;
1247
1248    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &res) == FAILURE) {
1249        RETURN_FALSE;
1250    }
1251
1252    PHP_STREAM_TO_ZVAL(stream, res);
1253
1254    if (-1 == php_stream_rewind(stream)) {
1255        RETURN_FALSE;
1256    }
1257    RETURN_TRUE;
1258}
1259/* }}} */
1260
1261/* {{{ proto int ftell(resource fp)
1262   Get file pointer's read/write position */
1263PHPAPI PHP_FUNCTION(ftell)
1264{
1265    zval *res;
1266    zend_long ret;
1267    php_stream *stream;
1268
1269    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &res) == FAILURE) {
1270        RETURN_FALSE;
1271    }
1272
1273    PHP_STREAM_TO_ZVAL(stream, res);
1274
1275    ret = php_stream_tell(stream);
1276    if (ret == -1)  {
1277        RETURN_FALSE;
1278    }
1279    RETURN_LONG(ret);
1280}
1281/* }}} */
1282
1283/* {{{ proto int fseek(resource fp, int offset [, int whence])
1284   Seek on a file pointer */
1285PHPAPI PHP_FUNCTION(fseek)
1286{
1287    zval *res;
1288    zend_long offset, whence = SEEK_SET;
1289    php_stream *stream;
1290
1291    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl|l", &res, &offset, &whence) == FAILURE) {
1292        RETURN_FALSE;
1293    }
1294
1295    PHP_STREAM_TO_ZVAL(stream, res);
1296
1297    RETURN_LONG(php_stream_seek(stream, offset, (int) whence));
1298}
1299/* }}} */
1300
1301/* {{{ php_mkdir
1302*/
1303
1304/* DEPRECATED APIs: Use php_stream_mkdir() instead */
1305PHPAPI int php_mkdir_ex(const char *dir, zend_long mode, int options)
1306{
1307    int ret;
1308
1309    if (php_check_open_basedir(dir)) {
1310        return -1;
1311    }
1312
1313    if ((ret = VCWD_MKDIR(dir, (mode_t)mode)) < 0 && (options & REPORT_ERRORS)) {
1314        php_error_docref(NULL, E_WARNING, "%s", strerror(errno));
1315    }
1316
1317    return ret;
1318}
1319
1320PHPAPI int php_mkdir(const char *dir, zend_long mode)
1321{
1322    return php_mkdir_ex(dir, mode, REPORT_ERRORS);
1323}
1324/* }}} */
1325
1326/* {{{ proto bool mkdir(string pathname [, int mode [, bool recursive [, resource context]]])
1327   Create a directory */
1328PHP_FUNCTION(mkdir)
1329{
1330    char *dir;
1331    size_t dir_len;
1332    zval *zcontext = NULL;
1333    zend_long mode = 0777;
1334    zend_bool recursive = 0;
1335    php_stream_context *context;
1336
1337    if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|lbr", &dir, &dir_len, &mode, &recursive, &zcontext) == FAILURE) {
1338        RETURN_FALSE;
1339    }
1340
1341    context = php_stream_context_from_zval(zcontext, 0);
1342
1343    RETURN_BOOL(php_stream_mkdir(dir, (int)mode, (recursive ? PHP_STREAM_MKDIR_RECURSIVE : 0) | REPORT_ERRORS, context));
1344}
1345/* }}} */
1346
1347/* {{{ proto bool rmdir(string dirname[, resource context])
1348   Remove a directory */
1349PHP_FUNCTION(rmdir)
1350{
1351    char *dir;
1352    size_t dir_len;
1353    zval *zcontext = NULL;
1354    php_stream_context *context;
1355
1356    if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|r", &dir, &dir_len, &zcontext) == FAILURE) {
1357        RETURN_FALSE;
1358    }
1359
1360    context = php_stream_context_from_zval(zcontext, 0);
1361
1362    RETURN_BOOL(php_stream_rmdir(dir, REPORT_ERRORS, context));
1363}
1364/* }}} */
1365
1366/* {{{ proto int readfile(string filename [, bool use_include_path[, resource context]])
1367   Output a file or a URL */
1368PHP_FUNCTION(readfile)
1369{
1370    char *filename;
1371    size_t filename_len;
1372    size_t size = 0;
1373    zend_bool use_include_path = 0;
1374    zval *zcontext = NULL;
1375    php_stream *stream;
1376    php_stream_context *context = NULL;
1377
1378    if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|br!", &filename, &filename_len, &use_include_path, &zcontext) == FAILURE) {
1379        RETURN_FALSE;
1380    }
1381
1382    context = php_stream_context_from_zval(zcontext, 0);
1383
1384    stream = php_stream_open_wrapper_ex(filename, "rb", (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, context);
1385    if (stream) {
1386        size = php_stream_passthru(stream);
1387        php_stream_close(stream);
1388        RETURN_LONG(size);
1389    }
1390
1391    RETURN_FALSE;
1392}
1393/* }}} */
1394
1395/* {{{ proto int umask([int mask])
1396   Return or change the umask */
1397PHP_FUNCTION(umask)
1398{
1399    zend_long mask = 0;
1400    int oldumask;
1401
1402    oldumask = umask(077);
1403
1404    if (BG(umask) == -1) {
1405        BG(umask) = oldumask;
1406    }
1407
1408    if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &mask) == FAILURE) {
1409        RETURN_FALSE;
1410    }
1411
1412    if (ZEND_NUM_ARGS() == 0) {
1413        umask(oldumask);
1414    } else {
1415        umask((int) mask);
1416    }
1417
1418    RETURN_LONG(oldumask);
1419}
1420/* }}} */
1421
1422/* {{{ proto int fpassthru(resource fp)
1423   Output all remaining data from a file pointer */
1424PHPAPI PHP_FUNCTION(fpassthru)
1425{
1426    zval *res;
1427    size_t size;
1428    php_stream *stream;
1429
1430    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &res) == FAILURE) {
1431        RETURN_FALSE;
1432    }
1433
1434    PHP_STREAM_TO_ZVAL(stream, res);
1435
1436    size = php_stream_passthru(stream);
1437    RETURN_LONG(size);
1438}
1439/* }}} */
1440
1441/* {{{ proto bool rename(string old_name, string new_name[, resource context])
1442   Rename a file */
1443PHP_FUNCTION(rename)
1444{
1445    char *old_name, *new_name;
1446    size_t old_name_len, new_name_len;
1447    zval *zcontext = NULL;
1448    php_stream_wrapper *wrapper;
1449    php_stream_context *context;
1450
1451    if (zend_parse_parameters(ZEND_NUM_ARGS(), "pp|r", &old_name, &old_name_len, &new_name, &new_name_len, &zcontext) == FAILURE) {
1452        RETURN_FALSE;
1453    }
1454
1455    wrapper = php_stream_locate_url_wrapper(old_name, NULL, 0);
1456
1457    if (!wrapper || !wrapper->wops) {
1458        php_error_docref(NULL, E_WARNING, "Unable to locate stream wrapper");
1459        RETURN_FALSE;
1460    }
1461
1462    if (!wrapper->wops->rename) {
1463        php_error_docref(NULL, E_WARNING, "%s wrapper does not support renaming", wrapper->wops->label ? wrapper->wops->label : "Source");
1464        RETURN_FALSE;
1465    }
1466
1467    if (wrapper != php_stream_locate_url_wrapper(new_name, NULL, 0)) {
1468        php_error_docref(NULL, E_WARNING, "Cannot rename a file across wrapper types");
1469        RETURN_FALSE;
1470    }
1471
1472    context = php_stream_context_from_zval(zcontext, 0);
1473
1474    RETURN_BOOL(wrapper->wops->rename(wrapper, old_name, new_name, 0, context));
1475}
1476/* }}} */
1477
1478/* {{{ proto bool unlink(string filename[, context context])
1479   Delete a file */
1480PHP_FUNCTION(unlink)
1481{
1482    char *filename;
1483    size_t filename_len;
1484    php_stream_wrapper *wrapper;
1485    zval *zcontext = NULL;
1486    php_stream_context *context = NULL;
1487
1488    if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|r", &filename, &filename_len, &zcontext) == FAILURE) {
1489        RETURN_FALSE;
1490    }
1491
1492    context = php_stream_context_from_zval(zcontext, 0);
1493
1494    wrapper = php_stream_locate_url_wrapper(filename, NULL, 0);
1495
1496    if (!wrapper || !wrapper->wops) {
1497        php_error_docref(NULL, E_WARNING, "Unable to locate stream wrapper");
1498        RETURN_FALSE;
1499    }
1500
1501    if (!wrapper->wops->unlink) {
1502        php_error_docref(NULL, E_WARNING, "%s does not allow unlinking", wrapper->wops->label ? wrapper->wops->label : "Wrapper");
1503        RETURN_FALSE;
1504    }
1505    RETURN_BOOL(wrapper->wops->unlink(wrapper, filename, REPORT_ERRORS, context));
1506}
1507/* }}} */
1508
1509/* {{{ proto bool ftruncate(resource fp, int size)
1510   Truncate file to 'size' length */
1511PHP_NAMED_FUNCTION(php_if_ftruncate)
1512{
1513    zval *fp;
1514    zend_long size;
1515    php_stream *stream;
1516
1517    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &fp, &size) == FAILURE) {
1518        RETURN_FALSE;
1519    }
1520
1521    PHP_STREAM_TO_ZVAL(stream, fp);
1522
1523    if (!php_stream_truncate_supported(stream)) {
1524        php_error_docref(NULL, E_WARNING, "Can't truncate this stream!");
1525        RETURN_FALSE;
1526    }
1527
1528    RETURN_BOOL(0 == php_stream_truncate_set_size(stream, size));
1529}
1530/* }}} */
1531
1532/* {{{ proto array fstat(resource fp)
1533   Stat() on a filehandle */
1534PHP_NAMED_FUNCTION(php_if_fstat)
1535{
1536    zval *fp;
1537    zval stat_dev, stat_ino, stat_mode, stat_nlink, stat_uid, stat_gid, stat_rdev,
1538         stat_size, stat_atime, stat_mtime, stat_ctime, stat_blksize, stat_blocks;
1539    php_stream *stream;
1540    php_stream_statbuf stat_ssb;
1541    char *stat_sb_names[13] = {
1542        "dev", "ino", "mode", "nlink", "uid", "gid", "rdev",
1543        "size", "atime", "mtime", "ctime", "blksize", "blocks"
1544    };
1545
1546    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &fp) == FAILURE) {
1547        RETURN_FALSE;
1548    }
1549
1550    PHP_STREAM_TO_ZVAL(stream, fp);
1551
1552    if (php_stream_stat(stream, &stat_ssb)) {
1553        RETURN_FALSE;
1554    }
1555
1556    array_init(return_value);
1557
1558    ZVAL_LONG(&stat_dev, stat_ssb.sb.st_dev);
1559    ZVAL_LONG(&stat_ino, stat_ssb.sb.st_ino);
1560    ZVAL_LONG(&stat_mode, stat_ssb.sb.st_mode);
1561    ZVAL_LONG(&stat_nlink, stat_ssb.sb.st_nlink);
1562    ZVAL_LONG(&stat_uid, stat_ssb.sb.st_uid);
1563    ZVAL_LONG(&stat_gid, stat_ssb.sb.st_gid);
1564#ifdef HAVE_ST_RDEV
1565# ifdef PHP_WIN32
1566    /* It is unsigned, so if a negative came from userspace, it'll
1567       convert to UINT_MAX, but we wan't to keep the userspace value.
1568       Almost the same as in php_fstat. This is ugly, but otherwise
1569       we would have to maintain a fully compatible struct stat. */
1570    if ((int)stat_ssb.sb.st_rdev < 0) {
1571        ZVAL_LONG(&stat_rdev, (int)stat_ssb.sb.st_rdev);
1572    } else {
1573        ZVAL_LONG(&stat_rdev, stat_ssb.sb.st_rdev);
1574    }
1575# else
1576    ZVAL_LONG(&stat_rdev, stat_ssb.sb.st_rdev);
1577# endif
1578#else
1579    ZVAL_LONG(&stat_rdev, -1);
1580#endif
1581    ZVAL_LONG(&stat_size, stat_ssb.sb.st_size);
1582    ZVAL_LONG(&stat_atime, stat_ssb.sb.st_atime);
1583    ZVAL_LONG(&stat_mtime, stat_ssb.sb.st_mtime);
1584    ZVAL_LONG(&stat_ctime, stat_ssb.sb.st_ctime);
1585#ifdef HAVE_ST_BLKSIZE
1586    ZVAL_LONG(&stat_blksize, stat_ssb.sb.st_blksize);
1587#else
1588    ZVAL_LONG(&stat_blksize,-1);
1589#endif
1590#ifdef HAVE_ST_BLOCKS
1591    ZVAL_LONG(&stat_blocks, stat_ssb.sb.st_blocks);
1592#else
1593    ZVAL_LONG(&stat_blocks,-1);
1594#endif
1595    /* Store numeric indexes in proper order */
1596    zend_hash_next_index_insert(HASH_OF(return_value), &stat_dev);
1597    zend_hash_next_index_insert(HASH_OF(return_value), &stat_ino);
1598    zend_hash_next_index_insert(HASH_OF(return_value), &stat_mode);
1599    zend_hash_next_index_insert(HASH_OF(return_value), &stat_nlink);
1600    zend_hash_next_index_insert(HASH_OF(return_value), &stat_uid);
1601    zend_hash_next_index_insert(HASH_OF(return_value), &stat_gid);
1602    zend_hash_next_index_insert(HASH_OF(return_value), &stat_rdev);
1603    zend_hash_next_index_insert(HASH_OF(return_value), &stat_size);
1604    zend_hash_next_index_insert(HASH_OF(return_value), &stat_atime);
1605    zend_hash_next_index_insert(HASH_OF(return_value), &stat_mtime);
1606    zend_hash_next_index_insert(HASH_OF(return_value), &stat_ctime);
1607    zend_hash_next_index_insert(HASH_OF(return_value), &stat_blksize);
1608    zend_hash_next_index_insert(HASH_OF(return_value), &stat_blocks);
1609
1610    /* Store string indexes referencing the same zval*/
1611    zend_hash_str_update(HASH_OF(return_value), stat_sb_names[0], strlen(stat_sb_names[0]), &stat_dev);
1612    zend_hash_str_update(HASH_OF(return_value), stat_sb_names[1], strlen(stat_sb_names[1]), &stat_ino);
1613    zend_hash_str_update(HASH_OF(return_value), stat_sb_names[2], strlen(stat_sb_names[2]), &stat_mode);
1614    zend_hash_str_update(HASH_OF(return_value), stat_sb_names[3], strlen(stat_sb_names[3]), &stat_nlink);
1615    zend_hash_str_update(HASH_OF(return_value), stat_sb_names[4], strlen(stat_sb_names[4]), &stat_uid);
1616    zend_hash_str_update(HASH_OF(return_value), stat_sb_names[5], strlen(stat_sb_names[5]), &stat_gid);
1617    zend_hash_str_update(HASH_OF(return_value), stat_sb_names[6], strlen(stat_sb_names[6]), &stat_rdev);
1618    zend_hash_str_update(HASH_OF(return_value), stat_sb_names[7], strlen(stat_sb_names[7]), &stat_size);
1619    zend_hash_str_update(HASH_OF(return_value), stat_sb_names[8], strlen(stat_sb_names[8]), &stat_atime);
1620    zend_hash_str_update(HASH_OF(return_value), stat_sb_names[9], strlen(stat_sb_names[9]), &stat_mtime);
1621    zend_hash_str_update(HASH_OF(return_value), stat_sb_names[10], strlen(stat_sb_names[10]), &stat_ctime);
1622    zend_hash_str_update(HASH_OF(return_value), stat_sb_names[11], strlen(stat_sb_names[11]), &stat_blksize);
1623    zend_hash_str_update(HASH_OF(return_value), stat_sb_names[12], strlen(stat_sb_names[12]), &stat_blocks);
1624}
1625/* }}} */
1626
1627/* {{{ proto bool copy(string source_file, string destination_file [, resource context])
1628   Copy a file */
1629PHP_FUNCTION(copy)
1630{
1631    char *source, *target;
1632    size_t source_len, target_len;
1633    zval *zcontext = NULL;
1634    php_stream_context *context;
1635
1636    if (zend_parse_parameters(ZEND_NUM_ARGS(), "pp|r", &source, &source_len, &target, &target_len, &zcontext) == FAILURE) {
1637        return;
1638    }
1639
1640    if (php_check_open_basedir(source)) {
1641        RETURN_FALSE;
1642    }
1643
1644    context = php_stream_context_from_zval(zcontext, 0);
1645
1646    if (php_copy_file_ctx(source, target, 0, context) == SUCCESS) {
1647        RETURN_TRUE;
1648    } else {
1649        RETURN_FALSE;
1650    }
1651}
1652/* }}} */
1653
1654/* {{{ php_copy_file
1655 */
1656PHPAPI int php_copy_file(const char *src, const char *dest)
1657{
1658    return php_copy_file_ctx(src, dest, 0, NULL);
1659}
1660/* }}} */
1661
1662/* {{{ php_copy_file_ex
1663 */
1664PHPAPI int php_copy_file_ex(const char *src, const char *dest, int src_flg)
1665{
1666    return php_copy_file_ctx(src, dest, src_flg, NULL);
1667}
1668/* }}} */
1669
1670/* {{{ php_copy_file_ctx
1671 */
1672PHPAPI int php_copy_file_ctx(const char *src, const char *dest, int src_flg, php_stream_context *ctx)
1673{
1674    php_stream *srcstream = NULL, *deststream = NULL;
1675    int ret = FAILURE;
1676    php_stream_statbuf src_s, dest_s;
1677
1678    switch (php_stream_stat_path_ex(src, 0, &src_s, ctx)) {
1679        case -1:
1680            /* non-statable stream */
1681            goto safe_to_copy;
1682            break;
1683        case 0:
1684            break;
1685        default: /* failed to stat file, does not exist? */
1686            return ret;
1687    }
1688    if (S_ISDIR(src_s.sb.st_mode)) {
1689        php_error_docref(NULL, E_WARNING, "The first argument to copy() function cannot be a directory");
1690        return FAILURE;
1691    }
1692
1693    switch (php_stream_stat_path_ex(dest, PHP_STREAM_URL_STAT_QUIET | PHP_STREAM_URL_STAT_NOCACHE, &dest_s, ctx)) {
1694        case -1:
1695            /* non-statable stream */
1696            goto safe_to_copy;
1697            break;
1698        case 0:
1699            break;
1700        default: /* failed to stat file, does not exist? */
1701            return ret;
1702    }
1703    if (S_ISDIR(dest_s.sb.st_mode)) {
1704        php_error_docref(NULL, E_WARNING, "The second argument to copy() function cannot be a directory");
1705        return FAILURE;
1706    }
1707    if (!src_s.sb.st_ino || !dest_s.sb.st_ino) {
1708        goto no_stat;
1709    }
1710    if (src_s.sb.st_ino == dest_s.sb.st_ino && src_s.sb.st_dev == dest_s.sb.st_dev) {
1711        return ret;
1712    } else {
1713        goto safe_to_copy;
1714    }
1715no_stat:
1716    {
1717        char *sp, *dp;
1718        int res;
1719
1720        if ((sp = expand_filepath(src, NULL)) == NULL) {
1721            return ret;
1722        }
1723        if ((dp = expand_filepath(dest, NULL)) == NULL) {
1724            efree(sp);
1725            goto safe_to_copy;
1726        }
1727
1728        res =
1729#ifndef PHP_WIN32
1730            !strcmp(sp, dp);
1731#else
1732            !strcasecmp(sp, dp);
1733#endif
1734
1735        efree(sp);
1736        efree(dp);
1737        if (res) {
1738            return ret;
1739        }
1740    }
1741safe_to_copy:
1742
1743    srcstream = php_stream_open_wrapper_ex(src, "rb", src_flg | REPORT_ERRORS, NULL, ctx);
1744
1745    if (!srcstream) {
1746        return ret;
1747    }
1748
1749    deststream = php_stream_open_wrapper_ex(dest, "wb", REPORT_ERRORS, NULL, ctx);
1750
1751    if (srcstream && deststream) {
1752        ret = php_stream_copy_to_stream_ex(srcstream, deststream, PHP_STREAM_COPY_ALL, NULL);
1753    }
1754    if (srcstream) {
1755        php_stream_close(srcstream);
1756    }
1757    if (deststream) {
1758        php_stream_close(deststream);
1759    }
1760    return ret;
1761}
1762/* }}} */
1763
1764/* {{{ proto string fread(resource fp, int length)
1765   Binary-safe file read */
1766PHPAPI PHP_FUNCTION(fread)
1767{
1768    zval *res;
1769    zend_long len;
1770    php_stream *stream;
1771
1772    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &res, &len) == FAILURE) {
1773        RETURN_FALSE;
1774    }
1775
1776    PHP_STREAM_TO_ZVAL(stream, res);
1777
1778    if (len <= 0) {
1779        php_error_docref(NULL, E_WARNING, "Length parameter must be greater than 0");
1780        RETURN_FALSE;
1781    }
1782
1783    ZVAL_NEW_STR(return_value, zend_string_alloc(len, 0));
1784    Z_STRLEN_P(return_value) = php_stream_read(stream, Z_STRVAL_P(return_value), len);
1785
1786    /* needed because recv/read/gzread doesnt put a null at the end*/
1787    Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;
1788}
1789/* }}} */
1790
1791static const char *php_fgetcsv_lookup_trailing_spaces(const char *ptr, size_t len, const char delimiter) /* {{{ */
1792{
1793    int inc_len;
1794    unsigned char last_chars[2] = { 0, 0 };
1795
1796    while (len > 0) {
1797        inc_len = (*ptr == '\0' ? 1 : php_mblen(ptr, len));
1798        switch (inc_len) {
1799            case -2:
1800            case -1:
1801                inc_len = 1;
1802                php_mb_reset();
1803                break;
1804            case 0:
1805                goto quit_loop;
1806            case 1:
1807            default:
1808                last_chars[0] = last_chars[1];
1809                last_chars[1] = *ptr;
1810                break;
1811        }
1812        ptr += inc_len;
1813        len -= inc_len;
1814    }
1815quit_loop:
1816    switch (last_chars[1]) {
1817        case '\n':
1818            if (last_chars[0] == '\r') {
1819                return ptr - 2;
1820            }
1821            /* break is omitted intentionally */
1822        case '\r':
1823            return ptr - 1;
1824    }
1825    return ptr;
1826}
1827/* }}} */
1828
1829#define FPUTCSV_FLD_CHK(c) memchr(field_str->val, c, field_str->len)
1830
1831/* {{{ proto int fputcsv(resource fp, array fields [, string delimiter [, string enclosure [, string escape_char]]])
1832   Format line as CSV and write to file pointer */
1833PHP_FUNCTION(fputcsv)
1834{
1835    char delimiter = ',';    /* allow this to be set as parameter */
1836    char enclosure = '"';    /* allow this to be set as parameter */
1837    char escape_char = '\\'; /* allow this to be set as parameter */
1838    php_stream *stream;
1839    zval *fp = NULL, *fields = NULL;
1840    size_t ret;
1841    char *delimiter_str = NULL, *enclosure_str = NULL, *escape_str = NULL;
1842    size_t delimiter_str_len = 0, enclosure_str_len = 0, escape_str_len = 0;
1843
1844    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ra|sss",
1845            &fp, &fields, &delimiter_str, &delimiter_str_len,
1846            &enclosure_str, &enclosure_str_len,
1847            &escape_str, &escape_str_len) == FAILURE) {
1848        return;
1849    }
1850
1851    if (delimiter_str != NULL) {
1852        /* Make sure that there is at least one character in string */
1853        if (delimiter_str_len < 1) {
1854            php_error_docref(NULL, E_WARNING, "delimiter must be a character");
1855            RETURN_FALSE;
1856        } else if (delimiter_str_len > 1) {
1857            php_error_docref(NULL, E_NOTICE, "delimiter must be a single character");
1858        }
1859
1860        /* use first character from string */
1861        delimiter = *delimiter_str;
1862    }
1863
1864    if (enclosure_str != NULL) {
1865        if (enclosure_str_len < 1) {
1866            php_error_docref(NULL, E_WARNING, "enclosure must be a character");
1867            RETURN_FALSE;
1868        } else if (enclosure_str_len > 1) {
1869            php_error_docref(NULL, E_NOTICE, "enclosure must be a single character");
1870        }
1871        /* use first character from string */
1872        enclosure = *enclosure_str;
1873    }
1874
1875    if (escape_str != NULL) {
1876        if (escape_str_len < 1) {
1877            php_error_docref(NULL, E_WARNING, "escape must be a character");
1878            RETURN_FALSE;
1879        } else if (escape_str_len > 1) {
1880            php_error_docref(NULL, E_NOTICE, "escape must be a single character");
1881        }
1882        /* use first character from string */
1883        escape_char = *escape_str;
1884    }
1885
1886    PHP_STREAM_TO_ZVAL(stream, fp);
1887
1888    ret = php_fputcsv(stream, fields, delimiter, enclosure, escape_char);
1889    RETURN_LONG(ret);
1890}
1891/* }}} */
1892
1893/* {{{ PHPAPI size_t php_fputcsv(php_stream *stream, zval *fields, char delimiter, char enclosure, char escape_char) */
1894PHPAPI size_t php_fputcsv(php_stream *stream, zval *fields, char delimiter, char enclosure, char escape_char)
1895{
1896    int count, i = 0;
1897    size_t ret;
1898    zval *field_tmp;
1899    smart_str csvline = {0};
1900
1901    count = zend_hash_num_elements(Z_ARRVAL_P(fields));
1902    ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(fields), field_tmp) {
1903        zend_string *field_str = zval_get_string(field_tmp);
1904
1905        /* enclose a field that contains a delimiter, an enclosure character, or a newline */
1906        if (FPUTCSV_FLD_CHK(delimiter) ||
1907            FPUTCSV_FLD_CHK(enclosure) ||
1908            FPUTCSV_FLD_CHK(escape_char) ||
1909            FPUTCSV_FLD_CHK('\n') ||
1910            FPUTCSV_FLD_CHK('\r') ||
1911            FPUTCSV_FLD_CHK('\t') ||
1912            FPUTCSV_FLD_CHK(' ')
1913        ) {
1914            char *ch = field_str->val;
1915            char *end = ch + field_str->len;
1916            int escaped = 0;
1917
1918            smart_str_appendc(&csvline, enclosure);
1919            while (ch < end) {
1920                if (*ch == escape_char) {
1921                    escaped = 1;
1922                } else if (!escaped && *ch == enclosure) {
1923                    smart_str_appendc(&csvline, enclosure);
1924                } else {
1925                    escaped = 0;
1926                }
1927                smart_str_appendc(&csvline, *ch);
1928                ch++;
1929            }
1930            smart_str_appendc(&csvline, enclosure);
1931        } else {
1932            smart_str_append(&csvline, field_str);
1933        }
1934
1935        if (++i != count) {
1936            smart_str_appendl(&csvline, &delimiter, 1);
1937        }
1938        zend_string_release(field_str);
1939    } ZEND_HASH_FOREACH_END();
1940
1941    smart_str_appendc(&csvline, '\n');
1942    smart_str_0(&csvline);
1943
1944    ret = php_stream_write(stream, csvline.s->val, csvline.s->len);
1945
1946    smart_str_free(&csvline);
1947
1948    return ret;
1949}
1950/* }}} */
1951
1952/* {{{ proto array fgetcsv(resource fp [,int length [, string delimiter [, string enclosure [, string escape]]]])
1953   Get line from file pointer and parse for CSV fields */
1954PHP_FUNCTION(fgetcsv)
1955{
1956    char delimiter = ',';   /* allow this to be set as parameter */
1957    char enclosure = '"';   /* allow this to be set as parameter */
1958    char escape = '\\';
1959
1960    /* first section exactly as php_fgetss */
1961
1962    zend_long len = 0;
1963    size_t buf_len;
1964    char *buf;
1965    php_stream *stream;
1966
1967    {
1968        zval *fd, *len_zv = NULL;
1969        char *delimiter_str = NULL;
1970        size_t delimiter_str_len = 0;
1971        char *enclosure_str = NULL;
1972        size_t enclosure_str_len = 0;
1973        char *escape_str = NULL;
1974        size_t escape_str_len = 0;
1975
1976        if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|zsss",
1977            &fd, &len_zv, &delimiter_str, &delimiter_str_len,
1978            &enclosure_str, &enclosure_str_len,
1979            &escape_str, &escape_str_len) == FAILURE
1980        ) {
1981            return;
1982        }
1983
1984        if (delimiter_str != NULL) {
1985            /* Make sure that there is at least one character in string */
1986            if (delimiter_str_len < 1) {
1987                php_error_docref(NULL, E_WARNING, "delimiter must be a character");
1988                RETURN_FALSE;
1989            } else if (delimiter_str_len > 1) {
1990                php_error_docref(NULL, E_NOTICE, "delimiter must be a single character");
1991            }
1992
1993            /* use first character from string */
1994            delimiter = delimiter_str[0];
1995        }
1996
1997        if (enclosure_str != NULL) {
1998            if (enclosure_str_len < 1) {
1999                php_error_docref(NULL, E_WARNING, "enclosure must be a character");
2000                RETURN_FALSE;
2001            } else if (enclosure_str_len > 1) {
2002                php_error_docref(NULL, E_NOTICE, "enclosure must be a single character");
2003            }
2004
2005            /* use first character from string */
2006            enclosure = enclosure_str[0];
2007        }
2008
2009        if (escape_str != NULL) {
2010            if (escape_str_len < 1) {
2011                php_error_docref(NULL, E_WARNING, "escape must be character");
2012                RETURN_FALSE;
2013            } else if (escape_str_len > 1) {
2014                php_error_docref(NULL, E_NOTICE, "escape must be a single character");
2015            }
2016
2017            escape = escape_str[0];
2018        }
2019
2020        if (len_zv != NULL && Z_TYPE_P(len_zv) != IS_NULL) {
2021            len = zval_get_long(len_zv);
2022            if (len < 0) {
2023                php_error_docref(NULL, E_WARNING, "Length parameter may not be negative");
2024                RETURN_FALSE;
2025            } else if (len == 0) {
2026                len = -1;
2027            }
2028        } else {
2029            len = -1;
2030        }
2031
2032        PHP_STREAM_TO_ZVAL(stream, fd);
2033    }
2034
2035    if (len < 0) {
2036        if ((buf = php_stream_get_line(stream, NULL, 0, &buf_len)) == NULL) {
2037            RETURN_FALSE;
2038        }
2039    } else {
2040        buf = emalloc(len + 1);
2041        if (php_stream_get_line(stream, buf, len + 1, &buf_len) == NULL) {
2042            efree(buf);
2043            RETURN_FALSE;
2044        }
2045    }
2046
2047    php_fgetcsv(stream, delimiter, enclosure, escape, buf_len, buf, return_value);
2048}
2049/* }}} */
2050
2051PHPAPI void php_fgetcsv(php_stream *stream, char delimiter, char enclosure, char escape_char, size_t buf_len, char *buf, zval *return_value) /* {{{ */
2052{
2053    char *temp, *tptr, *bptr, *line_end, *limit;
2054    size_t temp_len, line_end_len;
2055    int inc_len;
2056    zend_bool first_field = 1;
2057
2058    /* initialize internal state */
2059    php_mb_reset();
2060
2061    /* Now into new section that parses buf for delimiter/enclosure fields */
2062
2063    /* Strip trailing space from buf, saving end of line in case required for enclosure field */
2064
2065    bptr = buf;
2066    tptr = (char *)php_fgetcsv_lookup_trailing_spaces(buf, buf_len, delimiter);
2067    line_end_len = buf_len - (size_t)(tptr - buf);
2068    line_end = limit = tptr;
2069
2070    /* reserve workspace for building each individual field */
2071    temp_len = buf_len;
2072    temp = emalloc(temp_len + line_end_len + 1);
2073
2074    /* Initialize return array */
2075    array_init(return_value);
2076
2077    /* Main loop to read CSV fields */
2078    /* NB this routine will return a single null entry for a blank line */
2079
2080    do {
2081        char *comp_end, *hunk_begin;
2082
2083        tptr = temp;
2084
2085        inc_len = (bptr < limit ? (*bptr == '\0' ? 1 : php_mblen(bptr, limit - bptr)): 0);
2086        if (inc_len == 1) {
2087            char *tmp = bptr;
2088            while ((*tmp != delimiter) && isspace((int)*(unsigned char *)tmp)) {
2089                tmp++;
2090            }
2091            if (*tmp == enclosure) {
2092                bptr = tmp;
2093            }
2094        }
2095
2096        if (first_field && bptr == line_end) {
2097            add_next_index_null(return_value);
2098            break;
2099        }
2100        first_field = 0;
2101        /* 2. Read field, leaving bptr pointing at start of next field */
2102        if (inc_len != 0 && *bptr == enclosure) {
2103            int state = 0;
2104
2105            bptr++; /* move on to first character in field */
2106            hunk_begin = bptr;
2107
2108            /* 2A. handle enclosure delimited field */
2109            for (;;) {
2110                switch (inc_len) {
2111                    case 0:
2112                        switch (state) {
2113                            case 2:
2114                                memcpy(tptr, hunk_begin, bptr - hunk_begin - 1);
2115                                tptr += (bptr - hunk_begin - 1);
2116                                hunk_begin = bptr;
2117                                goto quit_loop_2;
2118
2119                            case 1:
2120                                memcpy(tptr, hunk_begin, bptr - hunk_begin);
2121                                tptr += (bptr - hunk_begin);
2122                                hunk_begin = bptr;
2123                                /* break is omitted intentionally */
2124
2125                            case 0: {
2126                                char *new_buf;
2127                                size_t new_len;
2128                                char *new_temp;
2129
2130                                if (hunk_begin != line_end) {
2131                                    memcpy(tptr, hunk_begin, bptr - hunk_begin);
2132                                    tptr += (bptr - hunk_begin);
2133                                    hunk_begin = bptr;
2134                                }
2135
2136                                /* add the embedded line end to the field */
2137                                memcpy(tptr, line_end, line_end_len);
2138                                tptr += line_end_len;
2139
2140                                if (stream == NULL) {
2141                                    goto quit_loop_2;
2142                                } else if ((new_buf = php_stream_get_line(stream, NULL, 0, &new_len)) == NULL) {
2143                                    /* we've got an unterminated enclosure,
2144                                     * assign all the data from the start of
2145                                     * the enclosure to end of data to the
2146                                     * last element */
2147                                    if ((size_t)temp_len > (size_t)(limit - buf)) {
2148                                        goto quit_loop_2;
2149                                    }
2150                                    zval_dtor(return_value);
2151                                    RETVAL_FALSE;
2152                                    goto out;
2153                                }
2154                                temp_len += new_len;
2155                                new_temp = erealloc(temp, temp_len);
2156                                tptr = new_temp + (size_t)(tptr - temp);
2157                                temp = new_temp;
2158
2159                                efree(buf);
2160                                buf_len = new_len;
2161                                bptr = buf = new_buf;
2162                                hunk_begin = buf;
2163
2164                                line_end = limit = (char *)php_fgetcsv_lookup_trailing_spaces(buf, buf_len, delimiter);
2165                                line_end_len = buf_len - (size_t)(limit - buf);
2166
2167                                state = 0;
2168                            } break;
2169                        }
2170                        break;
2171
2172                    case -2:
2173                    case -1:
2174                        php_mb_reset();
2175                        /* break is omitted intentionally */
2176                    case 1:
2177                        /* we need to determine if the enclosure is
2178                         * 'real' or is it escaped */
2179                        switch (state) {
2180                            case 1: /* escaped */
2181                                bptr++;
2182                                state = 0;
2183                                break;
2184                            case 2: /* embedded enclosure ? let's check it */
2185                                if (*bptr != enclosure) {
2186                                    /* real enclosure */
2187                                    memcpy(tptr, hunk_begin, bptr - hunk_begin - 1);
2188                                    tptr += (bptr - hunk_begin - 1);
2189                                    hunk_begin = bptr;
2190                                    goto quit_loop_2;
2191                                }
2192                                memcpy(tptr, hunk_begin, bptr - hunk_begin);
2193                                tptr += (bptr - hunk_begin);
2194                                bptr++;
2195                                hunk_begin = bptr;
2196                                state = 0;
2197                                break;
2198                            default:
2199                                if (*bptr == enclosure) {
2200                                    state = 2;
2201                                } else if (*bptr == escape_char) {
2202                                    state = 1;
2203                                }
2204                                bptr++;
2205                                break;
2206                        }
2207                        break;
2208
2209                    default:
2210                        switch (state) {
2211                            case 2:
2212                                /* real enclosure */
2213                                memcpy(tptr, hunk_begin, bptr - hunk_begin - 1);
2214                                tptr += (bptr - hunk_begin - 1);
2215                                hunk_begin = bptr;
2216                                goto quit_loop_2;
2217                            case 1:
2218                                bptr += inc_len;
2219                                memcpy(tptr, hunk_begin, bptr - hunk_begin);
2220                                tptr += (bptr - hunk_begin);
2221                                hunk_begin = bptr;
2222                                break;
2223                            default:
2224                                bptr += inc_len;
2225                                break;
2226                        }
2227                        break;
2228                }
2229                inc_len = (bptr < limit ? (*bptr == '\0' ? 1 : php_mblen(bptr, limit - bptr)): 0);
2230            }
2231
2232        quit_loop_2:
2233            /* look up for a delimiter */
2234            for (;;) {
2235                switch (inc_len) {
2236                    case 0:
2237                        goto quit_loop_3;
2238
2239                    case -2:
2240                    case -1:
2241                        inc_len = 1;
2242                        php_mb_reset();
2243                        /* break is omitted intentionally */
2244                    case 1:
2245                        if (*bptr == delimiter) {
2246                            goto quit_loop_3;
2247                        }
2248                        break;
2249                    default:
2250                        break;
2251                }
2252                bptr += inc_len;
2253                inc_len = (bptr < limit ? (*bptr == '\0' ? 1 : php_mblen(bptr, limit - bptr)): 0);
2254            }
2255
2256        quit_loop_3:
2257            memcpy(tptr, hunk_begin, bptr - hunk_begin);
2258            tptr += (bptr - hunk_begin);
2259            bptr += inc_len;
2260            comp_end = tptr;
2261        } else {
2262            /* 2B. Handle non-enclosure field */
2263
2264            hunk_begin = bptr;
2265
2266            for (;;) {
2267                switch (inc_len) {
2268                    case 0:
2269                        goto quit_loop_4;
2270                    case -2:
2271                    case -1:
2272                        inc_len = 1;
2273                        php_mb_reset();
2274                        /* break is omitted intentionally */
2275                    case 1:
2276                        if (*bptr == delimiter) {
2277                            goto quit_loop_4;
2278                        }
2279                        break;
2280                    default:
2281                        break;
2282                }
2283                bptr += inc_len;
2284                inc_len = (bptr < limit ? (*bptr == '\0' ? 1 : php_mblen(bptr, limit - bptr)): 0);
2285            }
2286        quit_loop_4:
2287            memcpy(tptr, hunk_begin, bptr - hunk_begin);
2288            tptr += (bptr - hunk_begin);
2289
2290            comp_end = (char *)php_fgetcsv_lookup_trailing_spaces(temp, tptr - temp, delimiter);
2291            if (*bptr == delimiter) {
2292                bptr++;
2293            }
2294        }
2295
2296        /* 3. Now pass our field back to php */
2297        *comp_end = '\0';
2298        add_next_index_stringl(return_value, temp, comp_end - temp);
2299    } while (inc_len > 0);
2300
2301out:
2302    efree(temp);
2303    if (stream) {
2304        efree(buf);
2305    }
2306}
2307/* }}} */
2308
2309#if (!defined(__BEOS__) && !defined(NETWARE) && HAVE_REALPATH) || defined(ZTS)
2310/* {{{ proto string realpath(string path)
2311   Return the resolved path */
2312PHP_FUNCTION(realpath)
2313{
2314    char *filename;
2315    size_t filename_len;
2316    char resolved_path_buff[MAXPATHLEN];
2317
2318#ifndef FAST_ZPP
2319    if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &filename, &filename_len) == FAILURE) {
2320        return;
2321    }
2322#else
2323    ZEND_PARSE_PARAMETERS_START(1, 1)
2324        Z_PARAM_PATH(filename, filename_len)
2325    ZEND_PARSE_PARAMETERS_END();
2326#endif
2327
2328    if (VCWD_REALPATH(filename, resolved_path_buff)) {
2329        if (php_check_open_basedir(resolved_path_buff)) {
2330            RETURN_FALSE;
2331        }
2332
2333#ifdef ZTS
2334        if (VCWD_ACCESS(resolved_path_buff, F_OK)) {
2335            RETURN_FALSE;
2336        }
2337#endif
2338        RETURN_STRING(resolved_path_buff);
2339    } else {
2340        RETURN_FALSE;
2341    }
2342}
2343/* }}} */
2344#endif
2345
2346/* See http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.2 */
2347#define PHP_META_HTML401_CHARS "-_.:"
2348
2349/* {{{ php_next_meta_token
2350   Tokenizes an HTML file for get_meta_tags */
2351php_meta_tags_token php_next_meta_token(php_meta_tags_data *md)
2352{
2353    int ch = 0, compliment;
2354    char buff[META_DEF_BUFSIZE + 1];
2355
2356    memset((void *)buff, 0, META_DEF_BUFSIZE + 1);
2357
2358    while (md->ulc || (!php_stream_eof(md->stream) && (ch = php_stream_getc(md->stream)))) {
2359        if (php_stream_eof(md->stream)) {
2360            break;
2361        }
2362
2363        if (md->ulc) {
2364            ch = md->lc;
2365            md->ulc = 0;
2366        }
2367
2368        switch (ch) {
2369            case '<':
2370                return TOK_OPENTAG;
2371                break;
2372
2373            case '>':
2374                return TOK_CLOSETAG;
2375                break;
2376
2377            case '=':
2378                return TOK_EQUAL;
2379                break;
2380            case '/':
2381                return TOK_SLASH;
2382                break;
2383
2384            case '\'':
2385            case '"':
2386                compliment = ch;
2387                md->token_len = 0;
2388                while (!php_stream_eof(md->stream) && (ch = php_stream_getc(md->stream)) && ch != compliment && ch != '<' && ch != '>') {
2389                    buff[(md->token_len)++] = ch;
2390
2391                    if (md->token_len == META_DEF_BUFSIZE) {
2392                        break;
2393                    }
2394                }
2395
2396                if (ch == '<' || ch == '>') {
2397                    /* Was just an apostrohpe */
2398                    md->ulc = 1;
2399                    md->lc = ch;
2400                }
2401
2402                /* We don't need to alloc unless we are in a meta tag */
2403                if (md->in_meta) {
2404                    md->token_data = (char *) emalloc(md->token_len + 1);
2405                    memcpy(md->token_data, buff, md->token_len+1);
2406                }
2407
2408                return TOK_STRING;
2409                break;
2410
2411            case '\n':
2412            case '\r':
2413            case '\t':
2414                break;
2415
2416            case ' ':
2417                return TOK_SPACE;
2418                break;
2419
2420            default:
2421                if (isalnum(ch)) {
2422                    md->token_len = 0;
2423                    buff[(md->token_len)++] = ch;
2424                    while (!php_stream_eof(md->stream) && (ch = php_stream_getc(md->stream)) && (isalnum(ch) || strchr(PHP_META_HTML401_CHARS, ch))) {
2425                        buff[(md->token_len)++] = ch;
2426
2427                        if (md->token_len == META_DEF_BUFSIZE) {
2428                            break;
2429                        }
2430                    }
2431
2432                    /* This is ugly, but we have to replace ungetc */
2433                    if (!isalpha(ch) && ch != '-') {
2434                        md->ulc = 1;
2435                        md->lc = ch;
2436                    }
2437
2438                    md->token_data = (char *) emalloc(md->token_len + 1);
2439                    memcpy(md->token_data, buff, md->token_len+1);
2440
2441                    return TOK_ID;
2442                } else {
2443                    return TOK_OTHER;
2444                }
2445                break;
2446        }
2447    }
2448
2449    return TOK_EOF;
2450}
2451/* }}} */
2452
2453#ifdef HAVE_FNMATCH
2454/* {{{ proto bool fnmatch(string pattern, string filename [, int flags])
2455   Match filename against pattern */
2456PHP_FUNCTION(fnmatch)
2457{
2458    char *pattern, *filename;
2459    size_t pattern_len, filename_len;
2460    zend_long flags = 0;
2461
2462    if (zend_parse_parameters(ZEND_NUM_ARGS(), "pp|l", &pattern, &pattern_len, &filename, &filename_len, &flags) == FAILURE) {
2463        return;
2464    }
2465
2466    if (filename_len >= MAXPATHLEN) {
2467        php_error_docref(NULL, E_WARNING, "Filename exceeds the maximum allowed length of %d characters", MAXPATHLEN);
2468        RETURN_FALSE;
2469    }
2470    if (pattern_len >= MAXPATHLEN) {
2471        php_error_docref(NULL, E_WARNING, "Pattern exceeds the maximum allowed length of %d characters", MAXPATHLEN);
2472        RETURN_FALSE;
2473    }
2474
2475    RETURN_BOOL( ! fnmatch( pattern, filename, (int)flags ));
2476}
2477/* }}} */
2478#endif
2479
2480/* {{{ proto string sys_get_temp_dir()
2481   Returns directory path used for temporary files */
2482PHP_FUNCTION(sys_get_temp_dir)
2483{
2484    if (zend_parse_parameters_none() == FAILURE) {
2485        return;
2486    }
2487    RETURN_STRING((char *)php_get_temporary_directory());
2488}
2489/* }}} */
2490
2491/*
2492 * Local variables:
2493 * tab-width: 4
2494 * c-basic-offset: 4
2495 * End:
2496 * vim600: noet sw=4 ts=4 fdm=marker
2497 * vim<600: noet sw=4 ts=4
2498 */
2499