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