Compare commits

..
Author SHA1 Message Date
Jeroen van Wolffelaar d101bd33e9 Implement the proposal v2
Added PHPAPI php_drand, which returns a double in the range [0,1)

RAND_REDESIGN completed, prohibited some minor points. Ready to
be re-entered in MAIN branch
2001-09-03 00:29:54 +00:00
Jeroen van Wolffelaar 183cf93bca Fix the other 5% of the build - thanx to Zeev & Wez 2001-09-02 23:39:45 +00:00
Jeroen van Wolffelaar 736bdf7117 Fix linebreaks which were somehow converted to win32 2001-09-02 19:43:49 +00:00
Jeroen van Wolffelaar 36f6b63c05 Fix build for 95% 2001-09-02 19:42:29 +00:00
Jeroen van Wolffelaar a8aed3118d - Different approach to handling multiple random number generators,
now it is way more general, adding a new generator is way more
  easier. Also elimination the need for a lot of switches.
- Made rand() Thread Safe
- Made sure this doesn't compile anymore ;-)
- PHPAPI functions now behave (almost) as intended, this is not yet
  the case for PHP_FUNCTION functions.
2001-08-26 22:47:55 +00:00
Jeroen van Wolffelaar e6d996d41c Implement (not yet totally complete) INI-logic for rand.
Seed random generators on script execution start (was
already done in some configurations by crypt, removed that)
2001-08-24 23:47:27 +00:00
Jeroen van Wolffelaar 2235479111 Fixed the right version 2001-08-22 22:15:33 +00:00
Jeroen van Wolffelaar 8d6a9b0a17 Experimental beginning of a change in the way rand-functions work.
This is only a _move around_ of code into functions.
2001-08-22 21:53:21 +00:00
SVN Migration 6e8ad1f0d9 This commit was manufactured by cvs2svn to create branch 'RAND_REDESIGN'. 2001-08-22 05:47:12 +00:00
187 changed files with 37380 additions and 9011 deletions

No files matched your search

+664
View File
@@ -0,0 +1,664 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
| Jim Winstead <jimw@php.net> |
| Jaakko Hyvätti <jaakko@hyvatti.iki.fi> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include <stdio.h>
#include "php.h"
#include "php_string.h"
#include "reg.h"
#include "ext/standard/info.h"
#if 0
zend_module_entry regexp_module_entry = {
"Regular Expressions",
reg_functions,
PHP_MINIT(regex), PHP_MSHUTDOWN(regex),
NULL, NULL, PHP_MINFO(regex),
STANDARD_MODULE_PROPERTIES
};
#endif
#ifdef ZTS
int reg_globals_id;
#else
static php_reg_globals reg_globals;
#endif
typedef struct {
regex_t preg;
int cflags;
} reg_cache;
/* {{{ _php_regcomp
*/
static int _php_regcomp(regex_t *preg, const char *pattern, int cflags)
{
int r = 0;
int patlen = strlen(pattern);
reg_cache *rc = NULL;
TSRMLS_FETCH();
if(zend_hash_find(&REG(ht_rc), (char *) pattern, patlen+1, (void **) &rc) == FAILURE ||
rc->cflags != cflags) {
r = regcomp(preg, pattern, cflags);
if(!r) {
reg_cache rcp;
rcp.cflags = cflags;
memcpy(&rcp.preg, preg, sizeof(*preg));
zend_hash_update(&REG(ht_rc), (char *) pattern, patlen+1,
(void *) &rcp, sizeof(rcp), NULL);
}
} else {
memcpy(preg, &rc->preg, sizeof(*preg));
}
return r;
}
/* }}} */
static void _free_reg_cache(reg_cache *rc)
{
regfree(&rc->preg);
}
#undef regfree
#define regfree(a);
#undef regcomp
#define regcomp(a, b, c) _php_regcomp(a, b, c)
static void php_reg_init_globals(php_reg_globals *reg_globals TSRMLS_DC)
{
zend_hash_init(&reg_globals->ht_rc, 0, NULL, (void (*)(void *)) _free_reg_cache, 1);
}
PHP_MINIT_FUNCTION(regex)
{
#ifdef ZTS
ts_allocate_id(&reg_globals_id, sizeof(php_reg_globals), (ts_allocate_ctor) php_reg_init_globals, NULL);
#else
php_reg_init_globals(&reg_globals TSRMLS_CC);
#endif
return SUCCESS;
}
PHP_MSHUTDOWN_FUNCTION(regex)
{
zend_hash_destroy(&REG(ht_rc));
return SUCCESS;
}
PHP_MINFO_FUNCTION(regex)
{
#if HSREGEX
php_info_print_table_row(2, "Regex Library", "Bundled library enabled");
#else
php_info_print_table_row(2, "Regex Library", "System library enabled");
#endif
}
/* This is the maximum number of (..) constructs we'll generate from a
call to ereg() or eregi() with the optional third argument. */
#define NS 10
/* {{{ php_reg_eprint
* php_reg_eprint - convert error number to name
*/
static void php_reg_eprint(int err, regex_t *re) {
char *buf = NULL, *message = NULL;
size_t len;
size_t buf_len;
#ifdef REG_ITOA
/* get the length of the message */
buf_len = regerror(REG_ITOA | err, re, NULL, 0);
if (buf_len) {
buf = (char *)emalloc(buf_len * sizeof(char));
if (!buf) return; /* fail silently */
/* finally, get the error message */
regerror(REG_ITOA | err, re, buf, buf_len);
}
#else
buf_len = 0;
#endif
len = regerror(err, re, NULL, 0);
if (len) {
message = (char *)emalloc((buf_len + len + 2) * sizeof(char));
if (!message) {
return; /* fail silently */
}
if (buf_len) {
snprintf(message, buf_len, "%s: ", buf);
buf_len += 1; /* so pointer math below works */
}
/* drop the message into place */
regerror(err, re, message + buf_len, len);
php_error(E_WARNING, "%s", message);
}
STR_FREE(buf);
STR_FREE(message);
}
/* }}} */
/* {{{ php_ereg
*/
static void php_ereg(INTERNAL_FUNCTION_PARAMETERS, int icase)
{
pval **regex, /* Regular expression */
**findin, /* String to apply expression to */
**array = NULL; /* Optional register array */
regex_t re;
regmatch_t subs[NS];
int err, i, match_len, string_len;
int copts = 0;
off_t start, end;
char *buf = NULL;
char *string = NULL;
if (icase)
copts |= REG_ICASE;
switch(ZEND_NUM_ARGS()) {
case 2:
if (zend_get_parameters_ex(2, &regex, &findin) == FAILURE) {
WRONG_PARAM_COUNT;
}
/* don't bother doing substring matching if we're not going
to make use of the information */
copts |= REG_NOSUB;
break;
case 3:
if (zend_get_parameters_ex(3, &regex, &findin, &array) == FAILURE) {
WRONG_PARAM_COUNT;
}
break;
default:
WRONG_PARAM_COUNT;
}
/* compile the regular expression from the supplied regex */
if ((*regex)->type == IS_STRING) {
err = regcomp(&re, (*regex)->value.str.val, REG_EXTENDED | copts);
} else {
/* we convert numbers to integers and treat them as a string */
if ((*regex)->type == IS_DOUBLE)
convert_to_long_ex(regex); /* get rid of decimal places */
convert_to_string_ex(regex);
/* don't bother doing an extended regex with just a number */
err = regcomp(&re, (*regex)->value.str.val, copts);
}
if (err) {
php_reg_eprint(err, &re);
RETURN_FALSE;
}
/* make a copy of the string we're looking in */
convert_to_string_ex(findin);
string = estrndup((*findin)->value.str.val, (*findin)->value.str.len);
/* actually execute the regular expression */
err = regexec(&re, string, (size_t) NS, subs, 0);
if (err && err != REG_NOMATCH) {
php_reg_eprint(err, &re);
regfree(&re);
RETURN_FALSE;
}
match_len = 1;
if (array && err != REG_NOMATCH) {
match_len = (int) (subs[0].rm_eo - subs[0].rm_so);
string_len = strlen(string) + 1;
buf = emalloc(string_len);
if (!buf) {
php_error(E_WARNING, "Unable to allocate memory in php_ereg");
RETURN_FALSE;
}
pval_destructor(*array); /* start with clean array */
array_init(*array);
for (i = 0; i < NS; i++) {
start = subs[i].rm_so;
end = subs[i].rm_eo;
if (start != -1 && end > 0 && start < string_len && end < string_len && start < end) {
add_index_stringl(*array, i, string+start, end-start, 1);
} else {
add_index_bool(*array, i, 0);
}
}
efree(buf);
}
efree(string);
if (err == REG_NOMATCH) {
RETVAL_FALSE;
} else {
if (match_len == 0)
match_len = 1;
RETVAL_LONG(match_len);
}
regfree(&re);
}
/* }}} */
/* {{{ proto int ereg(string pattern, string string [, array registers])
Regular expression match */
PHP_FUNCTION(ereg)
{
php_ereg(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
/* }}} */
/* {{{ proto int eregi(string pattern, string string [, array registers])
Case-insensitive regular expression match */
PHP_FUNCTION(eregi)
{
php_ereg(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}
/* }}} */
/* {{{ php_reg_replace
* this is the meat and potatoes of regex replacement! */
char *php_reg_replace(const char *pattern, const char *replace, const char *string, int icase, int extended)
{
regex_t re;
regmatch_t subs[NS];
char *buf, /* buf is where we build the replaced string */
*nbuf, /* nbuf is used when we grow the buffer */
*walkbuf; /* used to walk buf when replacing backrefs */
const char *walk; /* used to walk replacement string for backrefs */
int buf_len;
int pos, tmp, string_len, new_l;
int err, copts = 0;
string_len = strlen(string);
if (icase)
copts = REG_ICASE;
if (extended)
copts |= REG_EXTENDED;
err = regcomp(&re, pattern, copts);
if (err) {
php_reg_eprint(err, &re);
return ((char *) -1);
}
/* start with a buffer that is twice the size of the stringo
we're doing replacements in */
buf_len = 2 * string_len + 1;
buf = emalloc(buf_len * sizeof(char));
if (!buf) {
php_error(E_WARNING, "Unable to allocate memory in php_reg_replace");
regfree(&re);
return ((char *) -1);
}
err = pos = 0;
buf[0] = '\0';
while (!err) {
err = regexec(&re, &string[pos], (size_t) NS, subs, (pos ? REG_NOTBOL : 0));
if (err && err != REG_NOMATCH) {
php_reg_eprint(err, &re);
regfree(&re);
return ((char *) -1);
}
if (!err) {
/* backref replacement is done in two passes:
1) find out how long the string will be, and allocate buf
2) copy the part before match, replacement and backrefs to buf
Jaakko Hyvätti <Jaakko.Hyvatti@iki.fi>
*/
new_l = strlen(buf) + subs[0].rm_so; /* part before the match */
walk = replace;
while (*walk)
if ('\\' == *walk
&& '0' <= walk[1] && '9' >= walk[1]
&& subs[walk[1] - '0'].rm_so > -1
&& subs[walk[1] - '0'].rm_eo > -1) {
new_l += subs[walk[1] - '0'].rm_eo
- subs[walk[1] - '0'].rm_so;
walk += 2;
} else {
new_l++;
walk++;
}
if (new_l + 1 > buf_len) {
buf_len = 1 + buf_len + 2 * new_l;
nbuf = emalloc(buf_len);
strcpy(nbuf, buf);
efree(buf);
buf = nbuf;
}
tmp = strlen(buf);
/* copy the part of the string before the match */
strncat(buf, &string[pos], subs[0].rm_so);
/* copy replacement and backrefs */
walkbuf = &buf[tmp + subs[0].rm_so];
walk = replace;
while (*walk)
if ('\\' == *walk
&& '0' <= walk[1] && '9' >= walk[1]
&& subs[walk[1] - '0'].rm_so > -1
&& subs[walk[1] - '0'].rm_eo > -1) {
tmp = subs[walk[1] - '0'].rm_eo
- subs[walk[1] - '0'].rm_so;
memcpy (walkbuf,
&string[pos + subs[walk[1] - '0'].rm_so],
tmp);
walkbuf += tmp;
walk += 2;
} else
*walkbuf++ = *walk++;
*walkbuf = '\0';
/* and get ready to keep looking for replacements */
if (subs[0].rm_so == subs[0].rm_eo) {
if (subs[0].rm_so + pos >= string_len)
break;
new_l = strlen (buf) + 1;
if (new_l + 1 > buf_len) {
buf_len = 1 + buf_len + 2 * new_l;
nbuf = emalloc(buf_len * sizeof(char));
strcpy(nbuf, buf);
efree(buf);
buf = nbuf;
}
pos += subs[0].rm_eo + 1;
buf [new_l-1] = string [pos-1];
buf [new_l] = '\0';
} else {
pos += subs[0].rm_eo;
}
} else { /* REG_NOMATCH */
new_l = strlen(buf) + strlen(&string[pos]);
if (new_l + 1 > buf_len) {
buf_len = new_l + 1; /* now we know exactly how long it is */
nbuf = emalloc(buf_len * sizeof(char));
strcpy(nbuf, buf);
efree(buf);
buf = nbuf;
}
/* stick that last bit of string on our output */
strcat(buf, &string[pos]);
}
}
/* don't want to leak memory .. */
regfree(&re);
/* whew. */
return (buf);
}
/* }}} */
/* {{{ php_ereg_replace
*/
static void php_ereg_replace(INTERNAL_FUNCTION_PARAMETERS, int icase)
{
pval **arg_pattern,
**arg_replace,
**arg_string;
char *pattern;
char *string;
char *replace;
char *ret;
if (ZEND_NUM_ARGS() != 3 || zend_get_parameters_ex(3, &arg_pattern, &arg_replace, &arg_string) == FAILURE) {
WRONG_PARAM_COUNT;
}
if ((*arg_pattern)->type == IS_STRING) {
if ((*arg_pattern)->value.str.val && (*arg_pattern)->value.str.len)
pattern = estrndup((*arg_pattern)->value.str.val, (*arg_pattern)->value.str.len);
else
pattern = empty_string;
} else {
convert_to_long_ex(arg_pattern);
pattern = emalloc(2);
pattern[0] = (char) (*arg_pattern)->value.lval;
pattern[1] = '\0';
}
if ((*arg_replace)->type == IS_STRING) {
if ((*arg_replace)->value.str.val && (*arg_replace)->value.str.len)
replace = estrndup((*arg_replace)->value.str.val, (*arg_replace)->value.str.len);
else
replace = empty_string;
} else {
convert_to_long_ex(arg_replace);
replace = emalloc(2);
replace[0] = (char) (*arg_replace)->value.lval;
replace[1] = '\0';
}
convert_to_string_ex(arg_string);
if ((*arg_string)->value.str.val && (*arg_string)->value.str.len)
string = estrndup((*arg_string)->value.str.val, (*arg_string)->value.str.len);
else
string = empty_string;
/* do the actual work */
ret = php_reg_replace(pattern, replace, string, icase, 1);
if (ret == (char *) -1) {
RETVAL_FALSE;
} else {
RETVAL_STRING(ret, 1);
STR_FREE(ret);
}
STR_FREE(string);
STR_FREE(replace);
STR_FREE(pattern);
}
/* }}} */
/* {{{ proto string ereg_replace(string pattern, string replacement, string string)
Replace regular expression */
PHP_FUNCTION(ereg_replace)
{
php_ereg_replace(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
/* }}} */
/* {{{ proto string eregi_replace(string pattern, string replacement, string string)
Case insensitive replace regular expression */
PHP_FUNCTION(eregi_replace)
{
php_ereg_replace(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}
/* }}} */
/* {{{ php_split
*/
static void php_split(INTERNAL_FUNCTION_PARAMETERS, int icase)
{
pval **spliton, **str, **arg_count = NULL;
regex_t re;
regmatch_t subs[1];
char *strp, *endp;
int err, size, count, copts = 0;
if (icase)
copts = REG_ICASE;
switch (ZEND_NUM_ARGS()) {
case 2:
if (zend_get_parameters_ex(2, &spliton, &str) == FAILURE)
WRONG_PARAM_COUNT;
count = -1;
break;
case 3:
if (zend_get_parameters_ex(3, &spliton, &str, &arg_count) == FAILURE)
WRONG_PARAM_COUNT;
convert_to_long_ex(arg_count);
count = (*arg_count)->value.lval;
break;
default:
WRONG_PARAM_COUNT;
}
convert_to_string_ex(spliton);
convert_to_string_ex(str);
strp = (*str)->value.str.val;
endp = (*str)->value.str.val + strlen((*str)->value.str.val);
err = regcomp(&re, (*spliton)->value.str.val, REG_EXTENDED | copts);
if (err) {
php_error(E_WARNING, "unexpected regex error (%d)", err);
RETURN_FALSE;
}
if (array_init(return_value) == FAILURE) {
regfree(&re);
RETURN_FALSE;
}
/* churn through str, generating array entries as we go */
while ((count == -1 || count > 1) && !(err = regexec(&re, strp, 1, subs, 0))) {
if (subs[0].rm_so == 0 && subs[0].rm_eo) {
/* match is at start of string, return empty string */
add_next_index_stringl(return_value, empty_string, 0, 1);
/* skip ahead the length of the regex match */
strp+=subs[0].rm_eo;
} else if (subs[0].rm_so==0 && subs[0].rm_eo==0) {
/* No more matches */
regfree(&re);
php_error(E_WARNING, "bad regular expression for split()");
zend_hash_destroy(return_value->value.ht);
efree(return_value->value.ht);
RETURN_FALSE;
} else {
/* On a real match */
/* make a copy of the substring */
size = subs[0].rm_so;
/* add it to the array */
add_next_index_stringl(return_value, strp, size, 1);
/* point at our new starting point */
strp = strp + subs[0].rm_eo;
}
/* if we're only looking for a certain number of points,
stop looking once we hit it */
if (count != -1) {
count--;
}
}
/* see if we encountered an error */
if (err && err != REG_NOMATCH) {
php_error(E_WARNING, "unexpected regex error (%d)", err);
regfree(&re);
zend_hash_destroy(return_value->value.ht);
efree(return_value->value.ht);
RETURN_FALSE;
}
/* otherwise we just have one last element to add to the array */
size = endp - strp;
add_next_index_stringl(return_value, strp, size, 1);
regfree(&re);
}
/* }}} */
/* ("root", "passwd", "uid", "gid", "other:stuff:like:/bin/sh")
= split(":", $passwd_file, 5); */
/* {{{ proto array split(string pattern, string string [, int limit])
Split string into array by regular expression */
PHP_FUNCTION(split)
{
php_split(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
/* }}} */
/* {{{ proto array spliti(string pattern, string string [, int limit])
Split string into array by regular expression case-insensitive */
PHP_FUNCTION(spliti)
{
php_split(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}
/* }}} */
/* {{{ proto string sql_regcase(string string)
Make regular expression for case insensitive match */
PHPAPI PHP_FUNCTION(sql_regcase)
{
pval **string;
char *tmp;
unsigned char c;
register int i, j;
if (ZEND_NUM_ARGS()!=1 || zend_get_parameters_ex(1, &string)==FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(string);
tmp = (char *) emalloc((*string)->value.str.len*4+1);
for (i=j=0; i<(*string)->value.str.len; i++) {
c = (unsigned char) (*string)->value.str.val[i];
if(isalpha(c)) {
tmp[j++] = '[';
tmp[j++] = toupper(c);
tmp[j++] = tolower(c);
tmp[j++] = ']';
} else {
tmp[j++] = c;
}
}
tmp[j]=0;
tmp = erealloc(tmp, j + 1);
RETVAL_STRINGL(tmp, j, 0);
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+50
View File
@@ -0,0 +1,50 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef REG_H
#define REG_H
char *php_reg_replace(const char *pattern, const char *replace, const char *string, int icase, int extended);
PHP_FUNCTION(ereg);
PHP_FUNCTION(eregi);
PHP_FUNCTION(eregi_replace);
PHP_FUNCTION(ereg_replace);
PHP_FUNCTION(split);
PHP_FUNCTION(spliti);
PHPAPI PHP_FUNCTION(sql_regcase);
typedef struct {
HashTable ht_rc;
} php_reg_globals;
PHP_MINIT_FUNCTION(regex);
PHP_MSHUTDOWN_FUNCTION(regex);
PHP_MINFO_FUNCTION(regex);
#ifdef ZTS
#define REG(v) TSRMG(reg_globals_id, php_reg_globals *, v)
#else
#define REG(v) (reg_globals.v)
#endif
#endif /* REG_H */
+9
View File
@@ -0,0 +1,9 @@
--TEST--
RegReplace test 1
--POST--
--GET--
--FILE--
<?php $a="abc123";
echo ereg_replace("123","def",$a)?>
--EXPECT--
abcdef
+9
View File
@@ -0,0 +1,9 @@
--TEST--
RegReplace test 2
--POST--
--GET--
--FILE--
<?php $a="abc123";
echo ereg_replace("123","",$a)?>
--EXPECT--
abc
+10
View File
@@ -0,0 +1,10 @@
--TEST--
ereg_replace single-quote test
--POST--
--GET--
--FILE--
<?php $a="\\'test";
echo ereg_replace("\\\\'","'",$a)
?>
--EXPECT--
'test
+16
View File
@@ -0,0 +1,16 @@
--TEST--
simple ereg test
--POST--
--GET--
--FILE--
<?php $a="This is a nice and simple string";
if (ereg(".*nice and simple.*",$a)) {
echo "ok\n";
}
if (!ereg(".*doesn't exist.*",$a)) {
echo "ok\n";
}
?>
--EXPECT--
ok
ok
+20
View File
@@ -0,0 +1,20 @@
--TEST--
Test Regular expression register support in ereg
--POST--
--GET--
--FILE--
<?php $a="This is a nice and simple string";
echo ereg(".*(is).*(is).*",$a,$registers);
echo "\n";
echo $registers[0];
echo "\n";
echo $registers[1];
echo "\n";
echo $registers[2];
echo "\n";
?>
--EXPECT--
32
This is a nice and simple string
is
is
+10
View File
@@ -0,0 +1,10 @@
--TEST--
Test ereg_replace of start-of-line
--POST--
--GET--
--FILE--
<?php $a="This is a nice and simple string";
echo ereg_replace("^This","That",$a);
?>
--EXPECT--
That is a nice and simple string
+12
View File
@@ -0,0 +1,12 @@
--TEST--
Test empty result buffer in reg_replace
--POST--
--GET--
--FILE--
<?php
$a="abcd";
$b=ereg_replace("abcd","",$a);
echo "strlen(\$b)=".strlen($b);
?>
--EXPECT--
strlen($b)=0
+10
View File
@@ -0,0 +1,10 @@
--TEST--
Test back-references in regular expressions
--POST--
--GET--
--FILE--
<?php
echo ereg_replace("([a-z]*)([-=+|]*)([0-9]+)","\\3 \\1 \\2\n","abc+-|=123");
?>
--EXPECT--
123 abc +-|=
+19
View File
@@ -0,0 +1,19 @@
--TEST--
Test split()
--POST--
--GET--
--FILE--
<?php
$a=split("[[:space:]]","this is a
test");
echo count($a) . "\n";
for ($i = 0; $i < count($a); $i++) {
echo $a[$i] . "\n";
}
?>
--EXPECT--
4
this
is
a
test
+9
View File
@@ -0,0 +1,9 @@
--TEST--
Long back references
--POST--
--GET--
--FILE--
<?php $a="abc122222222223";
echo ereg_replace("1(2*)3","\\1def\\1",$a)?>
--EXPECT--
abc2222222222def2222222222
+9
View File
@@ -0,0 +1,9 @@
--TEST--
\0 back reference
--POST--
--GET--
--FILE--
<?php $a="abc123";
echo ereg_replace("123","def\\0ghi",$a)?>
--EXPECT--
abcdef123ghi
+9
View File
@@ -0,0 +1,9 @@
--TEST--
nonexisting back reference
--POST--
--GET--
--FILE--
<?php $a="abc123";
echo ereg_replace("123",'def\1ghi',$a)?>
--EXPECT--
abcdef\1ghi
+9
View File
@@ -0,0 +1,9 @@
--TEST--
escapes in replace string
--POST--
--GET--
--FILE--
<?php $a="abc123";
echo ereg_replace("123","def\\g\\\\hi\\",$a)?>
--EXPECT--
abcdef\g\\hi\
+9
View File
@@ -0,0 +1,9 @@
--TEST--
backreferences not replaced recursively
--POST--
--GET--
--FILE--
<?php $a="a\\2bxc";
echo ereg_replace("a(.*)b(.*)c","\\1",$a)?>
--EXPECT--
\2
+8
View File
@@ -0,0 +1,8 @@
--TEST--
replace empty matches
--POST--
--GET--
--FILE--
<?php echo ereg_replace("^","z","abc123")?>
--EXPECT--
zabc123
+8
View File
@@ -0,0 +1,8 @@
--TEST--
test backslash handling in regular expressions
--POST--
--GET--
--FILE--
<?php echo ereg_replace('\?',"abc","?123?")?>
--EXPECT--
abc123abc
+3
View File
@@ -0,0 +1,3 @@
Assert
Thies C. Arntzen
+19
View File
@@ -0,0 +1,19 @@
LTLIBRARY_NAME = libstandard.la
LTLIBRARY_SOURCES=\
array.c base64.c basic_functions.c browscap.c crc32.c crypt.c cyr_convert.c datetime.c \
dir.c dl.c dns.c exec.c file.c filestat.c flock_compat.c \
formatted_print.c fsock.c head.c html.c image.c info.c iptc.c lcg.c \
link.c mail.c math.c md5.c metaphone.c microtime.c pack.c pageinfo.c \
parsedate.c quot_print.c rand.c rand_sys.c rand_mt.c reg.c \
soundex.c string.c scanf.c \
syslog.c type.c uniqid.c url.c url_scanner.c var.c assert.c \
strnatcmp.c levenshtein.c incomplete_class.c url_scanner_ex.c \
ftp_fopen_wrapper.c http_fopen_wrapper.c php_fopen_wrapper.c credits.c
include $(top_srcdir)/build/dynlib.mk
parsedate.c: $(srcdir)/parsedate.y
$(srcdir)/url_scanner_ex.c: $(srcdir)/url_scanner_ex.re
re2c -b $(srcdir)/url_scanner_ex.re > $@
+3158
View File
File diff suppressed because it is too large. Load diff
+301
View File
@@ -0,0 +1,301 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Thies C. Arntzen (thies@thieso.net) |
+----------------------------------------------------------------------+
*/
/* $Id$ */
/* {{{ includes/startup/misc */
#include "php.h"
#include "php_assert.h"
#include "php_ini.h"
typedef struct {
long active;
long bail;
long warning;
long quiet_eval;
zval *callback;
} php_assert_globals;
#ifdef ZTS
#define ASSERTG(v) TSRMG(assert_globals_id, php_assert_globals *, v)
int assert_globals_id;
#else
#define ASSERTG(v) (assert_globals.v)
php_assert_globals assert_globals;
#endif
#define SAFE_STRING(s) ((s)?(s):"")
enum {
ASSERT_ACTIVE=1,
ASSERT_CALLBACK,
ASSERT_BAIL,
ASSERT_WARNING,
ASSERT_QUIET_EVAL
};
static PHP_INI_MH(OnChangeCallback)
{
if (ASSERTG(callback)) {
zval_ptr_dtor(&ASSERTG(callback));
}
MAKE_STD_ZVAL(ASSERTG(callback));
if (new_value) {
ZVAL_STRINGL(ASSERTG(callback), new_value, new_value_length, 1);
} else {
ZVAL_EMPTY_STRING(ASSERTG(callback));
}
return SUCCESS;
}
PHP_INI_BEGIN()
STD_PHP_INI_ENTRY("assert.active", "1", PHP_INI_ALL, OnUpdateInt, active, php_assert_globals, assert_globals)
STD_PHP_INI_ENTRY("assert.bail", "0", PHP_INI_ALL, OnUpdateInt, bail, php_assert_globals, assert_globals)
STD_PHP_INI_ENTRY("assert.warning", "1", PHP_INI_ALL, OnUpdateInt, warning, php_assert_globals, assert_globals)
PHP_INI_ENTRY ("assert.callback", NULL, PHP_INI_ALL, OnChangeCallback)
STD_PHP_INI_ENTRY("assert.quiet_eval", "0", PHP_INI_ALL, OnUpdateInt, quiet_eval, php_assert_globals, assert_globals)
PHP_INI_END()
static void php_assert_init_globals(php_assert_globals *assert_globals_p TSRMLS_DC)
{
ASSERTG(callback) = NULL;
}
PHP_MINIT_FUNCTION(assert)
{
#ifdef ZTS
ts_allocate_id(&assert_globals_id, sizeof(php_assert_globals), (ts_allocate_ctor) php_assert_init_globals, NULL);
#else
php_assert_init_globals(&assert_globals TSRMLS_CC);
#endif
REGISTER_INI_ENTRIES();
REGISTER_LONG_CONSTANT("ASSERT_ACTIVE", ASSERT_ACTIVE, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("ASSERT_CALLBACK", ASSERT_CALLBACK, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("ASSERT_BAIL", ASSERT_BAIL, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("ASSERT_WARNING", ASSERT_WARNING, CONST_CS|CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("ASSERT_QUIET_EVAL", ASSERT_QUIET_EVAL, CONST_CS|CONST_PERSISTENT);
return SUCCESS;
}
PHP_MSHUTDOWN_FUNCTION(assert)
{
if (ASSERTG(callback)) {
zval_ptr_dtor(&ASSERTG(callback));
}
return SUCCESS;
}
PHP_RSHUTDOWN_FUNCTION(assert)
{
if (ASSERTG(callback)) {
zval_ptr_dtor(&ASSERTG(callback));
ASSERTG(callback) = NULL;
}
return SUCCESS;
}
PHP_MINFO_FUNCTION(assert)
{
DISPLAY_INI_ENTRIES();
}
/* }}} */
/* {{{ internal functions */
/* }}} */
/* {{{ proto int assert(string|bool assertion)
Checks if assertion is false */
PHP_FUNCTION(assert)
{
zval **assertion;
int val;
char *myeval = NULL;
char *compiled_string_description;
if (! ASSERTG(active)) {
RETURN_TRUE;
}
if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &assertion) == FAILURE) {
WRONG_PARAM_COUNT;
}
if ((*assertion)->type == IS_STRING) {
zval retval;
int old_error_reporting = 0; /* shut up gcc! */
myeval = Z_STRVAL_PP(assertion);
if (ASSERTG(quiet_eval)) {
old_error_reporting = EG(error_reporting);
EG(error_reporting) = 0;
}
compiled_string_description = zend_make_compiled_string_description("assert code" TSRMLS_CC);
if (zend_eval_string(myeval, &retval, compiled_string_description TSRMLS_CC) == FAILURE) {
efree(compiled_string_description);
zend_error(E_ERROR, "Failure evaluating code:\n%s\n", myeval);
/* zend_error() does not return in this case. */
}
efree(compiled_string_description);
if (ASSERTG(quiet_eval)) {
EG(error_reporting) = old_error_reporting;
}
convert_to_boolean(&retval);
val = Z_LVAL(retval);
} else {
convert_to_boolean_ex(assertion);
val = Z_LVAL_PP(assertion);
}
if (val) {
RETURN_TRUE;
}
if (ASSERTG(callback)) {
zval *args[4];
zval *retval;
int i;
uint lineno = zend_get_executed_lineno(TSRMLS_C);
char *filename = zend_get_executed_filename(TSRMLS_C);
MAKE_STD_ZVAL(args[0]);
MAKE_STD_ZVAL(args[1]);
MAKE_STD_ZVAL(args[2]);
ZVAL_STRING(args[0], SAFE_STRING(filename), 1);
ZVAL_LONG (args[1], lineno);
ZVAL_STRING(args[2], SAFE_STRING(myeval), 1);
MAKE_STD_ZVAL(retval);
ZVAL_FALSE(retval);
/* XXX do we want to check for error here? */
call_user_function(CG(function_table), NULL, ASSERTG(callback), retval, 3, args TSRMLS_CC);
for (i = 0; i <= 2; i++) {
zval_ptr_dtor(&(args[i]));
}
zval_ptr_dtor(&retval);
}
if (ASSERTG(warning)) {
if (myeval) {
php_error(E_WARNING, "Assertion \"%s\" failed", myeval);
} else {
php_error(E_WARNING, "Assertion failed");
}
}
if (ASSERTG(bail)) {
zend_bailout();
}
}
/* }}} */
/* {{{ proto mixed assert_options(int what [, mixed value])
Set/get the various assert flags */
PHP_FUNCTION(assert_options)
{
pval **what, **value;
int oldint;
int ac = ZEND_NUM_ARGS();
if (ac < 1 || ac > 2 || zend_get_parameters_ex(ac, &what, &value) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_long_ex(what);
switch ((*what)->value.lval) {
case ASSERT_ACTIVE:
oldint = ASSERTG(active);
if (ac == 2) {
convert_to_long_ex(value);
ASSERTG(active) = Z_LVAL_PP(value);
}
RETURN_LONG(oldint);
break;
case ASSERT_BAIL:
oldint = ASSERTG(bail);
if (ac == 2) {
convert_to_long_ex(value);
ASSERTG(bail) = Z_LVAL_PP(value);
}
RETURN_LONG(oldint);
break;
case ASSERT_QUIET_EVAL:
oldint = ASSERTG(quiet_eval);
if (ac == 2) {
convert_to_long_ex(value);
ASSERTG(quiet_eval) = Z_LVAL_PP(value);
}
RETURN_LONG(oldint);
break;
case ASSERT_WARNING:
oldint = ASSERTG(warning);
if (ac == 2) {
convert_to_long_ex(value);
ASSERTG(warning) = Z_LVAL_PP(value);
}
RETURN_LONG(oldint);
break;
case ASSERT_CALLBACK:
if (ac == 2) {
if (ASSERTG(callback)) {
zval_ptr_dtor(&ASSERTG(callback));
}
ASSERTG(callback) = *value;
zval_add_ref(value);
}
RETURN_TRUE;
break;
default:
php_error(E_WARNING, "Unknown value %d.", Z_LVAL_PP(what));
break;
}
RETURN_FALSE;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+203
View File
@@ -0,0 +1,203 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Jim Winstead (jimw@php.net) |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include <string.h>
#include "php.h"
#include "base64.h"
static char base64_table[] =
{ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', '\0'
};
static char base64_pad = '=';
unsigned char *php_base64_encode(const unsigned char *str, int length, int *ret_length) {
const unsigned char *current = str;
int i = 0;
unsigned char *result = (unsigned char *)emalloc(((length + 3 - length % 3) * 4 / 3 + 1) * sizeof(char));
while (length > 2) { /* keep going until we have less than 24 bits */
result[i++] = base64_table[current[0] >> 2];
result[i++] = base64_table[((current[0] & 0x03) << 4) + (current[1] >> 4)];
result[i++] = base64_table[((current[1] & 0x0f) << 2) + (current[2] >> 6)];
result[i++] = base64_table[current[2] & 0x3f];
current += 3;
length -= 3; /* we just handle 3 octets of data */
}
/* now deal with the tail end of things */
if (length != 0) {
result[i++] = base64_table[current[0] >> 2];
if (length > 1) {
result[i++] = base64_table[((current[0] & 0x03) << 4) + (current[1] >> 4)];
result[i++] = base64_table[(current[1] & 0x0f) << 2];
result[i++] = base64_pad;
}
else {
result[i++] = base64_table[(current[0] & 0x03) << 4];
result[i++] = base64_pad;
result[i++] = base64_pad;
}
}
if(ret_length) {
*ret_length = i;
}
result[i] = '\0';
return result;
}
/* as above, but backwards. :) */
unsigned char *php_base64_decode(const unsigned char *str, int length, int *ret_length) {
const unsigned char *current = str;
int ch, i = 0, j = 0, k;
/* this sucks for threaded environments */
static short reverse_table[256];
static int table_built;
unsigned char *result;
if (++table_built == 1) {
char *chp;
for(ch = 0; ch < 256; ch++) {
chp = strchr(base64_table, ch);
if(chp) {
reverse_table[ch] = chp - base64_table;
} else {
reverse_table[ch] = -1;
}
}
}
result = (unsigned char *)emalloc(length + 1);
if (result == NULL) {
return NULL;
}
/* run through the whole string, converting as we go */
while ((ch = *current++) != '\0') {
if (ch == base64_pad) break;
/* When Base64 gets POSTed, all pluses are interpreted as spaces.
This line changes them back. It's not exactly the Base64 spec,
but it is completely compatible with it (the spec says that
spaces are invalid). This will also save many people considerable
headache. - Turadg Aleahmad <turadg@wise.berkeley.edu>
*/
if (ch == ' ') ch = '+';
ch = reverse_table[ch];
if (ch < 0) continue;
switch(i % 4) {
case 0:
result[j] = ch << 2;
break;
case 1:
result[j++] |= ch >> 4;
result[j] = (ch & 0x0f) << 4;
break;
case 2:
result[j++] |= ch >>2;
result[j] = (ch & 0x03) << 6;
break;
case 3:
result[j++] |= ch;
break;
}
i++;
}
k = j;
/* mop things up if we ended on a boundary */
if (ch == base64_pad) {
switch(i % 4) {
case 0:
case 1:
efree(result);
return NULL;
case 2:
k++;
case 3:
result[k++] = 0;
}
}
if(ret_length) {
*ret_length = j;
}
result[k] = '\0';
return result;
}
/* {{{ proto string base64_encode(string str)
Encodes string using MIME base64 algorithm */
PHP_FUNCTION(base64_encode)
{
pval **str;
unsigned char *result;
int ret_length;
if (ZEND_NUM_ARGS()!=1 || zend_get_parameters_ex(1, &str) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(str);
result = php_base64_encode(Z_STRVAL_PP(str), Z_STRLEN_PP(str), &ret_length);
if (result != NULL) {
RETVAL_STRINGL(result, ret_length, 0);
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto string base64_decode(string str)
Decodes string using MIME base64 algorithm */
PHP_FUNCTION(base64_decode)
{
pval **str;
unsigned char *result;
int ret_length;
if (ZEND_NUM_ARGS()!=1 || zend_get_parameters_ex(1, &str) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(str);
result = php_base64_decode(Z_STRVAL_PP(str), Z_STRLEN_PP(str), &ret_length);
if (result != NULL) {
RETVAL_STRINGL(result, ret_length, 0);
} else {
RETURN_FALSE;
}
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vimo<600: sw=4 ts=4 tw=78
*/
+37
View File
@@ -0,0 +1,37 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Jim Winstead (jimw@php.net) |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef BASE64_H
#define BASE64_H
PHP_FUNCTION(base64_decode);
PHP_FUNCTION(base64_encode);
extern unsigned char *php_base64_encode(const unsigned char *, int, int *);
extern unsigned char *php_base64_decode(const unsigned char *, int, int *);
#endif /* BASE64_H */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
*/
File diff suppressed because it is too large. Load diff
+228
View File
@@ -0,0 +1,228 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Andi Gutmans <andi@zend.com> |
| Zeev Suraski <zeev@zend.com> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef BASIC_FUNCTIONS_H
#define BASIC_FUNCTIONS_H
#include <sys/stat.h>
#include "zend_highlight.h"
#ifdef TRANS_SID
# include "url_scanner.h"
# include "url_scanner_ex.h"
#endif
extern zend_module_entry basic_functions_module;
#define basic_functions_module_ptr &basic_functions_module
PHP_MINIT_FUNCTION(basic);
PHP_MSHUTDOWN_FUNCTION(basic);
PHP_RINIT_FUNCTION(basic);
PHP_RSHUTDOWN_FUNCTION(basic);
PHP_MINFO_FUNCTION(basic);
PHP_FUNCTION(constant);
PHP_FUNCTION(intval);
PHP_FUNCTION(doubleval);
PHP_FUNCTION(strval);
PHP_FUNCTION(toggle_short_open_tag);
PHP_FUNCTION(sleep);
PHP_FUNCTION(usleep);
PHP_FUNCTION(flush);
PHP_FUNCTION(gettype);
PHP_FUNCTION(settype);
PHP_FUNCTION(ip2long);
PHP_FUNCTION(long2ip);
/* system functions */
PHP_FUNCTION(getenv);
PHP_FUNCTION(putenv);
PHP_FUNCTION(get_current_user);
PHP_FUNCTION(set_time_limit);
PHP_FUNCTION(get_cfg_var);
PHP_FUNCTION(set_magic_quotes_runtime);
PHP_FUNCTION(get_magic_quotes_runtime);
PHP_FUNCTION(get_magic_quotes_gpc);
void php_is_type(INTERNAL_FUNCTION_PARAMETERS, int type);
PHP_FUNCTION(is_null);
PHP_FUNCTION(is_resource);
PHP_FUNCTION(is_bool);
PHP_FUNCTION(is_long);
PHP_FUNCTION(is_double);
PHP_FUNCTION(is_numeric);
PHP_FUNCTION(is_string);
PHP_FUNCTION(is_array);
PHP_FUNCTION(is_object);
PHP_FUNCTION(is_scalar);
PHP_FUNCTION(is_callable);
PHP_FUNCTION(import_request_variables);
PHP_FUNCTION(error_log);
PHP_FUNCTION(call_user_func);
PHP_FUNCTION(call_user_func_array);
PHP_FUNCTION(call_user_method);
PHP_FUNCTION(call_user_method_array);
PHP_FUNCTION(register_shutdown_function);
PHP_FUNCTION(highlight_file);
PHP_FUNCTION(highlight_string);
ZEND_API void php_get_highlight_struct(zend_syntax_highlighter_ini *syntax_highlighter_ini);
PHP_FUNCTION(ini_get);
PHP_FUNCTION(ini_set);
PHP_FUNCTION(ini_restore);
PHP_FUNCTION(print_r);
PHP_FUNCTION(connection_aborted);
PHP_FUNCTION(connection_status);
PHP_FUNCTION(ignore_user_abort);
PHP_FUNCTION(getservbyname);
PHP_FUNCTION(getservbyport);
PHP_FUNCTION(getprotobyname);
PHP_FUNCTION(getprotobynumber);
PHP_NAMED_FUNCTION(php_if_crc32);
PHP_FUNCTION(register_tick_function);
PHP_FUNCTION(unregister_tick_function);
PHP_FUNCTION(is_uploaded_file);
PHP_FUNCTION(move_uploaded_file);
/* From the INI parser */
PHP_FUNCTION(parse_ini_file);
#ifdef PHP_WIN32
typedef unsigned int php_stat_len;
#else
typedef int php_stat_len;
#endif
PHPAPI int _php_error_log(int opt_err, char *message, char *opt, char *headers TSRMLS_DC);
#if SIZEOF_INT == 4
/* Most 32-bit and 64-bit systems have 32-bit ints */
typedef unsigned int php_uint32;
typedef signed int php_int32;
#elif SIZEOF_LONG == 4
/* 16-bit systems? */
typedef unsigned long php_uint32;
typedef signed int php_int32;
#else
#error Need type which holds 32 bits
#endif
#define MT_N (624)
typedef struct {
HashTable *user_shutdown_function_names;
HashTable putenv_ht;
zval *strtok_zval;
char *strtok_string;
char *locale_string;
char *strtok_last;
char strtok_table[256];
ulong strtok_len;
char str_ebuf[40];
zval **array_walk_func_name;
zval **user_compare_func_name;
zend_llist *user_tick_functions;
zval *active_ini_file_section;
HashTable sm_protected_env_vars;
char *sm_allowed_env_vars;
/* pageinfo.c */
long page_uid;
long page_gid;
long page_inode;
long page_mtime;
/* filestat.c */
char *CurrentStatFile;
php_stat_len CurrentStatLength;
struct stat sb;
struct stat lsb;
/* rand.c */
int rand_generator; /* current ini-setting */
int rand_generator_current; /* current (by overriding by [mt_]srand) */
/* rand_sys.c */
unsigned int rand_sys_seed; /* Current seed for system-rand() (necessary for thread-safety) */
/* rand_mt.c */
php_uint32 state[MT_N+1]; /* state vector + 1 extra to not violate ANSI C */
php_uint32 *next; /* next random value is computed from here */
int left; /* can *next++ this many times before reloading */
/* syslog.c */
int syslog_started;
char *syslog_device;
/* var.c */
zend_class_entry *incomplete_class;
zend_bool use_trans_sid;
#ifdef TRANS_SID
/* url_scanner.c */
url_adapt_state_t url_adapt_state;
/* url_scanner_ex.re */
url_adapt_state_ex_t url_adapt_state_ex;
#endif
#ifdef HAVE_MMAP
void *mmap_file;
size_t mmap_len;
#endif
} php_basic_globals;
#ifdef ZTS
#define BG(v) TSRMG(basic_globals_id, php_basic_globals *, v)
extern int basic_globals_id;
#else
#define BG(v) (basic_globals.v)
extern php_basic_globals basic_globals;
#endif
#if HAVE_PUTENV
typedef struct {
char *putenv_string;
char *previous_value;
char *key;
int key_len;
} putenv_entry;
#endif
/* Values are comma-delimited
*/
#define SAFE_MODE_PROTECTED_ENV_VARS "LD_LIBRARY_PATH"
#define SAFE_MODE_ALLOWED_ENV_VARS "PHP_"
#endif /* BASIC_FUNCTIONS_H */
+269
View File
@@ -0,0 +1,269 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Zeev Suraski <zeev@zend.com> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "php_regex.h"
#include "php_browscap.h"
#include "php_ini.h"
#include "zend_globals.h"
static HashTable browser_hash;
static zval *current_section;
#define DEFAULT_SECTION_NAME "Default Browser Capability Settings"
/* OBJECTS_FIXME: This whole extension needs going through. The use of objects looks pretty broken here */
static void browscap_entry_dtor(zval *pvalue)
{
if (pvalue->type == IS_OBJECT) {
zend_hash_destroy(Z_OBJPROP_P(pvalue));
free(Z_OBJPROP_P(pvalue));
}
}
/* {{{ convert_browscap_pattern
*/
static void convert_browscap_pattern(zval *pattern)
{
register int i, j;
char *t;
for (i=0; i<pattern->value.str.len; i++) {
if (pattern->value.str.val[i]=='*' || pattern->value.str.val[i]=='?' || pattern->value.str.val[i]=='.') {
break;
}
}
if (i==pattern->value.str.len) { /* no wildcards */
pattern->value.str.val = zend_strndup(pattern->value.str.val, pattern->value.str.len);
return;
}
t = (char *) malloc(pattern->value.str.len*2);
for (i=0, j=0; i<pattern->value.str.len; i++, j++) {
switch (pattern->value.str.val[i]) {
case '?':
t[j] = '.';
break;
case '*':
t[j++] = '.';
t[j] = '*';
break;
case '.':
t[j++] = '\\';
t[j] = '.';
break;
default:
t[j] = pattern->value.str.val[i];
break;
}
}
t[j]=0;
pattern->value.str.val = t;
pattern->value.str.len = j;
}
/* }}} */
/* {{{ php_browscap_parser_cb
*/
static void php_browscap_parser_cb(zval *arg1, zval *arg2, int callback_type, void *arg)
{
switch (callback_type) {
case ZEND_INI_PARSER_ENTRY:
if (current_section) {
zval *new_property;
char *new_key;
new_property = (zval *) malloc(sizeof(zval));
INIT_PZVAL(new_property);
new_property->value.str.val = Z_STRLEN_P(arg2)?zend_strndup(Z_STRVAL_P(arg2), Z_STRLEN_P(arg2)):"";
new_property->value.str.len = Z_STRLEN_P(arg2);
new_property->type = IS_STRING;
new_key = zend_strndup(Z_STRVAL_P(arg1), Z_STRLEN_P(arg1));
zend_str_tolower(new_key, Z_STRLEN_P(arg1));
zend_hash_update(Z_OBJPROP_P(current_section), new_key, Z_STRLEN_P(arg1)+1, &new_property, sizeof(zval *), NULL);
free(new_key);
}
break;
case ZEND_INI_PARSER_SECTION: {
zval *processed;
/*printf("'%s' (%d)\n",$1.value.str.val,$1.value.str.len+1);*/
current_section = (zval *) malloc(sizeof(zval));
INIT_PZVAL(current_section);
processed = (zval *) malloc(sizeof(zval));
INIT_PZVAL(processed);
/* OBJECTS_FIXME */
Z_OBJCE_P(current_section) = &zend_standard_class_def;
Z_OBJPROP_P(current_section) = (HashTable *) malloc(sizeof(HashTable));
current_section->type = IS_OBJECT;
zend_hash_init(Z_OBJPROP_P(current_section), 0, NULL, (dtor_func_t) browscap_entry_dtor, 1);
zend_hash_update(&browser_hash, Z_STRVAL_P(arg1), Z_STRLEN_P(arg1)+1, (void *) &current_section, sizeof(zval *), NULL);
processed->value.str.val = Z_STRVAL_P(arg1);
processed->value.str.len = Z_STRLEN_P(arg1);
processed->type = IS_STRING;
convert_browscap_pattern(processed);
zend_hash_update(Z_OBJPROP_P(current_section), "browser_name_pattern", sizeof("browser_name_pattern"), (void *) &processed, sizeof(zval *), NULL);
}
break;
}
}
/* }}} */
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(browscap)
{
char *browscap = INI_STR("browscap");
if (browscap) {
zend_file_handle fh;
if (zend_hash_init(&browser_hash, 0, NULL, (dtor_func_t) browscap_entry_dtor, 1)==FAILURE) {
return FAILURE;
}
fh.handle.fp = VCWD_FOPEN(browscap, "r");
if (!fh.handle.fp) {
php_error(E_CORE_WARNING, "Cannot open '%s' for reading", browscap);
return FAILURE;
}
fh.filename = browscap;
fh.type = ZEND_HANDLE_FP;
zend_parse_ini_file(&fh, 1, (zend_ini_parser_cb_t) php_browscap_parser_cb, &browser_hash);
}
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(browscap)
{
if (INI_STR("browscap")) {
zend_hash_destroy(&browser_hash);
}
return SUCCESS;
}
/* }}} */
/* {{{ browser_reg_compare
*/
static int browser_reg_compare(zval **browser, int num_args, va_list args, zend_hash_key *key)
{
zval **browser_name;
regex_t r;
char *lookup_browser_name = va_arg(args, char *);
zval **found_browser_entry = va_arg(args, zval **);
if (*found_browser_entry) { /* already found */
return 0;
}
if(zend_hash_find(Z_OBJPROP_PP(browser), "browser_name_pattern", sizeof("browser_name_pattern"), (void **) &browser_name) == FAILURE) {
return 0;
}
if (!strchr((*browser_name)->value.str.val,'*')) {
return 0;
}
if (regcomp(&r, (*browser_name)->value.str.val, REG_NOSUB)!=0) {
return 0;
}
if (regexec(&r, lookup_browser_name, 0, NULL, 0)==0) {
*found_browser_entry = *browser;
}
regfree(&r);
return 0;
}
/* }}} */
/* {{{ proto object get_browser(string browser_name)
Get information about the capabilities of a browser */
PHP_FUNCTION(get_browser)
{
zval **agent_name, **agent;
zval *found_browser_entry, *tmp_copy;
char *lookup_browser_name;
if (!INI_STR("browscap")) {
RETURN_FALSE;
}
switch(ZEND_NUM_ARGS()) {
case 0:
if (!PG(http_globals)[TRACK_VARS_SERVER]
|| zend_hash_find(PG(http_globals)[TRACK_VARS_SERVER]->value.ht, "HTTP_USER_AGENT", sizeof("HTTP_USER_AGENT"), (void **) &agent_name)==FAILURE) {
zend_error(E_WARNING, "HTTP_USER_AGENT variable is not set, cannot determine user agent name");
RETURN_FALSE;
}
break;
case 1:
if (zend_get_parameters_ex(1, &agent_name)==FAILURE) {
RETURN_FALSE;
}
break;
default:
WRONG_PARAM_COUNT;
break;
}
convert_to_string_ex(agent_name);
if (zend_hash_find(&browser_hash, (*agent_name)->value.str.val, (*agent_name)->value.str.len+1, (void **) &agent)==FAILURE) {
lookup_browser_name = (*agent_name)->value.str.val;
found_browser_entry = NULL;
zend_hash_apply_with_arguments(&browser_hash, (apply_func_args_t) browser_reg_compare, 2, lookup_browser_name, &found_browser_entry);
if (found_browser_entry) {
agent = &found_browser_entry;
} else if (zend_hash_find(&browser_hash, DEFAULT_SECTION_NAME, sizeof(DEFAULT_SECTION_NAME), (void **) &agent)==FAILURE) {
RETURN_FALSE;
}
}
object_init(return_value);
zend_hash_copy(Z_OBJPROP_P(return_value), Z_OBJPROP_PP(agent), (copy_ctor_func_t) zval_add_ref, (void *) &tmp_copy, sizeof(zval *));
while (zend_hash_find(Z_OBJPROP_PP(agent), "parent", sizeof("parent"), (void **) &agent_name)==SUCCESS) {
if (zend_hash_find(&browser_hash, (*agent_name)->value.str.val, (*agent_name)->value.str.len+1, (void **)&agent)==FAILURE) {
break;
}
zend_hash_merge(Z_OBJPROP_P(return_value), Z_OBJPROP_PP(agent), (copy_ctor_func_t) zval_add_ref, (void *) &tmp_copy, sizeof(zval *), 0);
}
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+232
View File
@@ -0,0 +1,232 @@
dnl $Id$ -*- sh -*-
divert(3)dnl
dnl
dnl Check if flush should be called explicitly after buffered io
dnl
AC_DEFUN(AC_FLUSH_IO,[
AC_CACHE_CHECK([whether flush should be called explicitly after a bufferered io], ac_cv_flush_io,[
AC_TRY_RUN( [
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char *filename = tmpnam(NULL);
char buffer[64];
int result = 0;
FILE *fp = fopen(filename, "wb");
if (NULL == fp)
return 0;
fputs("line 1\n", fp);
fputs("line 2\n", fp);
fclose(fp);
fp = fopen(filename, "rb+");
if (NULL == fp)
return 0;
fgets(buffer, sizeof(buffer), fp);
fputs("line 3\n", fp);
rewind(fp);
fgets(buffer, sizeof(buffer), fp);
if (0 != strcmp(buffer, "line 1\n"))
result = 1;
fgets(buffer, sizeof(buffer), fp);
if (0 != strcmp(buffer, "line 3\n"))
result = 1;
fclose(fp);
unlink(filename);
exit(result);
}
],[
ac_cv_flush_io=no
],[
ac_cv_flush_io=yes
],[
ac_cv_flush_io=no
])])
if test "$ac_cv_flush_io" = "yes"; then
AC_DEFINE(HAVE_FLUSHIO, 1, [Define if flush should be called explicitly after a buffered io.])
fi
])
dnl
dnl Check for crypt() capabilities
dnl
AC_DEFUN(AC_CRYPT_CAP,[
AC_CACHE_CHECK(for standard DES crypt, ac_cv_crypt_des,[
AC_TRY_RUN([
#if HAVE_CRYPT_H
#include <crypt.h>
#endif
main() {
#if HAVE_CRYPT
exit (strcmp((char *)crypt("rasmuslerdorf","rl"),"rl.3StKT.4T8M"));
#else
exit(0);
#endif
}],[
ac_cv_crypt_des=yes
],[
ac_cv_crypt_des=no
],[
ac_cv_crypt_des=yes
])
])
if test "$ac_cv_crypt_des" = "yes"; then
ac_result=1
else
ac_result=0
fi
AC_DEFINE_UNQUOTED(PHP_STD_DES_CRYPT, $ac_result, [Whether the system supports standard DES salt])
AC_CACHE_CHECK(for extended DES crypt, ac_cv_crypt_ext_des,[
AC_TRY_RUN([
#if HAVE_CRYPT_H
#include <crypt.h>
#endif
main() {
#if HAVE_CRYPT
exit (strcmp((char *)crypt("rasmuslerdorf","_J9..rasm"),"_J9..rasmBYk8r9AiWNc"));
#else
exit(0);
#endif
}],[
ac_cv_crypt_ext_des=yes
],[
ac_cv_crypt_ext_des=no
],[
ac_cv_crypt_ext_des=no
])
])
if test "$ac_cv_crypt_ext_des" = "yes"; then
ac_result=1
else
ac_result=0
fi
AC_DEFINE_UNQUOTED(PHP_EXT_DES_CRYPT, $ac_result, [Whether the system supports extended DES salt])
AC_CACHE_CHECK(for MD5 crypt, ac_cv_crypt_md5,[
AC_TRY_RUN([
#if HAVE_CRYPT_H
#include <crypt.h>
#endif
main() {
#if HAVE_CRYPT
char salt[15], answer[40];
salt[0]='$'; salt[1]='1'; salt[2]='$';
salt[3]='r'; salt[4]='a'; salt[5]='s';
salt[6]='m'; salt[7]='u'; salt[8]='s';
salt[9]='l'; salt[10]='e'; salt[11]='$';
salt[12]='\0';
strcpy(answer,salt);
strcat(answer,"rISCgZzpwk3UhDidwXvin0");
exit (strcmp((char *)crypt("rasmuslerdorf",salt),answer));
#else
exit(0);
#endif
}],[
ac_cv_crypt_md5=yes
],[
ac_cv_crypt_md5=no
],[
ac_cv_crypt_md5=no
])
])
if test "$ac_cv_crypt_md5" = "yes"; then
ac_result=1
else
if test "$ac_cv_crypt_des" != "yes"; then
PHP_DEBUG_MACRO(debug.log)
fi
ac_result=0
fi
AC_DEFINE_UNQUOTED(PHP_MD5_CRYPT, $ac_result, [Whether the system supports MD5 salt])
AC_CACHE_CHECK(for Blowfish crypt, ac_cv_crypt_blowfish,[
AC_TRY_RUN([
#if HAVE_CRYPT_H
#include <crypt.h>
#endif
main() {
#if HAVE_CRYPT
char salt[30], answer[70];
salt[0]='$'; salt[1]='2'; salt[2]='a'; salt[3]='$'; salt[4]='0'; salt[5]='7'; salt[6]='$'; salt[7]='\0';
strcat(salt,"rasmuslerd............");
strcpy(answer,salt);
strcpy(&answer[29],"nIdrcHdxcUxWomQX9j6kvERCFjTg7Ra");
exit (strcmp((char *)crypt("rasmuslerdorf",salt),answer));
#else
exit(0);
#endif
}],[
ac_cv_crypt_blowfish=yes
],[
ac_cv_crypt_blowfish=no
],[
ac_cv_crypt_blowfish=no
])
])
if test "$ac_cv_crypt_blowfish" = "yes"; then
ac_result=1
else
ac_result=0
fi
AC_DEFINE_UNQUOTED(PHP_BLOWFISH_CRYPT, $ac_result, [Whether the system supports BlowFish salt])
])
AC_CHECK_FUNC(dlopen, [AC_DEFINE(HAVE_LIBDL,1,[ ])])
AC_CHECK_LIB(pam, pam_start, [
EXTRA_LIBS="$EXTRA_LIBS -lpam"
AC_DEFINE(HAVE_LIBPAM,1,[ ]) ], [])
AC_CHECK_FUNCS(getcwd getwd)
AC_CRYPT_CAP
AC_FLUSH_IO
divert(5)dnl
AC_ARG_WITH(regex,
[ --with-regex=TYPE regex library type: system, apache, php],
[
case $withval in
system)
REGEX_TYPE=system
;;
apache)
REGEX_TYPE=apache
;;
php)
REGEX_TYPE=php
;;
*)
REGEX_TYPE=php
AC_MSG_WARN(Invalid regex library type. Using default value: php)
;;
esac
],[
REGEX_TYPE=php
])
AC_ARG_WITH(system-regex,
[ --with-system-regex (deprecated) Use system regex library],[
if test "$withval" = "yes"; then
REGEX_TYPE=system
else
REGEX_TYPE=php
fi
])
PHP_EXTENSION(standard)
+136
View File
@@ -0,0 +1,136 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "basic_functions.h"
/*
* This code implements the AUTODIN II polynomial
* The variable corresponding to the macro argument "crc" should
* be an unsigned long.
* Oroginal code by Spencer Garrett <srg@quick.com>
*/
#define CRC32(crc, ch) (crc = (crc >> 8) ^ crc32tab[(crc ^ (ch)) & 0xff])
/* generated using the AUTODIN II polynomial
* x^32 + x^26 + x^23 + x^22 + x^16 +
* x^12 + x^11 + x^10 + x^8 + x^7 + x^5 + x^4 + x^2 + x^1 + 1
*/
static const unsigned int crc32tab[256] = {
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba,
0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec,
0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940,
0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116,
0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a,
0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818,
0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c,
0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086,
0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4,
0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe,
0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252,
0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60,
0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04,
0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a,
0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e,
0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0,
0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6,
0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,
};
/* {{{ proto string crc32(string str)
Calculate the crc32 polynomial of a string */
PHP_NAMED_FUNCTION(php_if_crc32)
{
pval **arg;
unsigned int crc = ~0;
char *p ;
int len, nr ;
if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &arg) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(arg);
len = 0 ;
nr=(*arg)->value.str.len;
p = (*arg)->value.str.val;
for (len += nr; nr--; ++p) {
CRC32(crc, *p);
}
RETVAL_LONG(~crc);
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+125
View File
@@ -0,0 +1,125 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
| Zeev Suraski <zeev@zend.com> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "info.h"
#define CREDIT_LINE(module, authors) php_info_print_table_row(2, module, authors)
/* {{{ php_print_credits
*/
PHPAPI void php_print_credits(int flag)
{
TSRMLS_FETCH();
if (flag & PHP_CREDITS_FULLPAGE) {
PUTS("<html><head><title>PHP Credits</title></head><body>\n");
}
php_info_print_style();
PUTS("<h1 align=\"center\">PHP 4.0 Credits</h1>\n");
if (flag & PHP_CREDITS_GROUP) {
/* Group */
php_info_print_table_start();
php_info_print_table_header(1, "PHP Group");
php_info_print_table_row(1, "Thies C. Arntzen, Stig Bakken, Andi Gutmans, Rasmus Lerdorf, Sam Ruby, Sascha Schumann, Zeev Suraski, Jim Winstead, Andrei Zmievski");
php_info_print_table_end();
}
if (flag & PHP_CREDITS_GENERAL) {
/* Design & Concept */
php_info_print_table_start();
php_info_print_table_header(1, "Language Design & Concept");
php_info_print_table_row(1, "Andi Gutmans, Rasmus Lerdorf, Zeev Suraski");
php_info_print_table_end();
/* PHP 4.0 Language */
php_info_print_table_start();
php_info_print_table_colspan_header(2, "PHP 4.0 Authors");
php_info_print_table_header(2, "Contribution", "Authors");
CREDIT_LINE("Zend Scripting Language Engine", "Andi Gutmans, Zeev Suraski");
CREDIT_LINE("Extension Module API", "Andi Gutmans, Zeev Suraski, Andrei Zmievski");
CREDIT_LINE("UNIX Build and Modularization", "Stig Bakken, Sascha Schumann");
CREDIT_LINE("Win32 Port", "Shane Caraveo, Zeev Suraski");
CREDIT_LINE("Server API (SAPI) Abstraction Layer", "Andi Gutmans, Shane Caraveo, Zeev Suraski");
php_info_print_table_end();
}
if (flag & PHP_CREDITS_SAPI) {
/* SAPI Modules */
php_info_print_table_start();
php_info_print_table_colspan_header(2, "SAPI Modules");
php_info_print_table_header(2, "Contribution", "Authors");
#include "credits_sapi.h"
php_info_print_table_end();
}
if (flag & PHP_CREDITS_MODULES) {
/* Modules */
php_info_print_table_start();
php_info_print_table_colspan_header(2, "Module Authors");
php_info_print_table_header(2, "Module", "Authors");
#include "credits_ext.h"
php_info_print_table_end();
}
if (flag & PHP_CREDITS_DOCS) {
php_info_print_table_start();
php_info_print_table_header(1, "PHP Documentation Team");
php_info_print_table_row(1, "Jouni Ahto, Alexander Aulbach, Stig Bakken, Rasmus Lerdorf, Egon Schmid, Zeev Suraski, Lars Torben Wilson, Jim Winstead");
php_info_print_table_row(1, "Edited by: Stig Bakken and Egon Schmid");
php_info_print_table_end();
}
if (flag & PHP_CREDITS_QA) {
php_info_print_table_start();
php_info_print_table_header(1, "PHP Quality Assurance Team");
php_info_print_table_row(1, "Andre Langhorst, Hellekin O. Wolf, Jalal Pushman, James Moore, Jani Taskinen, Joey Smith, Olivier Cahagne, Phil Driscoll, Sebastian Bergmann, Zak Greant");
php_info_print_table_end();
}
if (flag & PHP_CREDITS_WEB) {
/* Website Team */
php_info_print_table_start();
php_info_print_table_header(1, "PHP Website Team");
php_info_print_table_row(1, "Hojtsy Gabor, Colin Viebrock, Jim Winstead");
php_info_print_table_end();
}
if (flag & PHP_CREDITS_FULLPAGE) {
PUTS("</body></html>\n");
}
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+42
View File
@@ -0,0 +1,42 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
| Zeev Suraski <zeev@zend.com> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef CREDITS_H
#define CREDITS_H
#ifndef HAVE_CREDITS_DEFS
#define HAVE_CREDITS_DEFS
#define PHP_CREDITS_GROUP (1<<0)
#define PHP_CREDITS_GENERAL (1<<1)
#define PHP_CREDITS_SAPI (1<<2)
#define PHP_CREDITS_MODULES (1<<3)
#define PHP_CREDITS_DOCS (1<<4)
#define PHP_CREDITS_FULLPAGE (1<<5)
#define PHP_CREDITS_QA (1<<6)
#define PHP_CREDITS_WEB (1<<7)
#define PHP_CREDITS_ALL 0xFFFFFFFF
#endif /* HAVE_CREDITS_DEFS */
PHPAPI void php_print_credits(int flag);
#endif
+89
View File
@@ -0,0 +1,89 @@
/*
DO NOT EDIT THIS FILE!
it has been automaticaly created by php4/scripts/credits from
the information found in the various php4/ext/.../CREDITS and
php4/sapi/.../CREDITS files
if you want to change an entry you have to edit the appropriate
CREDITS file instead
*/
CREDIT_LINE("aspell", "Rasmus Lerdorf");
CREDIT_LINE("Assert", "Thies C. Arntzen");
CREDIT_LINE("BC Math", "Andi Gutmans");
CREDIT_LINE("bz2", "Sterling Hughes");
CREDIT_LINE("ccvs", "Brendan W. McAdams, Doug DeJulio");
CREDIT_LINE("cpdf", "Uwe Steinmann");
CREDIT_LINE("crack", "Alexander Feldman");
CREDIT_LINE("ctype", "Hartmut Holzgraefe");
CREDIT_LINE("CURL", "Sterling Hughes");
CREDIT_LINE("CyberCash", "Evan Klinger");
CREDIT_LINE("DBA", "Sascha Schumann");
CREDIT_LINE("dBase", "Jim Winstead");
CREDIT_LINE("DBM", "Rasmus Lerdorf, Jim Winstead");
CREDIT_LINE("domxml", "Uwe Steinmann");
CREDIT_LINE("dotnet", "Sam Ruby");
CREDIT_LINE("EXIF", "Rasmus Lerdorf");
CREDIT_LINE("FBSQL", "Frank M. Kromann");
CREDIT_LINE("FDF", "Uwe Steinmann");
CREDIT_LINE("FilePro", "Chad Robinson");
CREDIT_LINE("FTP", "Andrew Skalski");
CREDIT_LINE("GD imaging", "Rasmus Lerdorf, Stig Bakken, Jim Winstead, Jouni Ahto");
CREDIT_LINE("GetText", "Alex Plotnick");
CREDIT_LINE("HyperWave", "Uwe Steinmann");
CREDIT_LINE("icap", "Mark Musone");
CREDIT_LINE("iisfunc", "Frank M. Kromann");
CREDIT_LINE("IMAP", "Rex Logan, Mark Musone, Brian Wang, Kaj-Michael Lang, Antoni Pamies Olive, Rasmus Lerdorf, Andrew Skalski, Chuck Hagenbuch, Daniel R Kalowsky");
CREDIT_LINE("Informix", "Danny Heijl, Christian Cartus");
CREDIT_LINE("Ingres II", "David Hénot");
CREDIT_LINE("InterBase", "Jouni Ahto, Andrew Avdeev");
CREDIT_LINE("IRCG", "Sascha Schumann");
CREDIT_LINE("Java", "Sam Ruby");
CREDIT_LINE("LDAP", "Amitay Isaacs, Eric Warnke, Rasmus Lerdorf, Gerrit Thomson");
CREDIT_LINE("Mailparse MIME parsing and manipulation functions", "Wez Furlong");
CREDIT_LINE("MCAL", "Mark Musone, Chuck Hagenbuch");
CREDIT_LINE("mcrypt", "Sascha Schumann, Derick Rethans");
CREDIT_LINE("mhash", "Sascha Schumann");
CREDIT_LINE("MING", "Dave Hayden");
CREDIT_LINE("mnoGoSearch", "Alex Barkov, Ramil Kalimullin, Sergey Kartashoff");
CREDIT_LINE("MS SQL", "Frank M. Kromann");
CREDIT_LINE("mSQL", "Zeev Suraski");
CREDIT_LINE("Multibyte (Japanese) String Functions", "Tsukada Takuya");
CREDIT_LINE("MySQL", "Zeev Suraski");
CREDIT_LINE("OCI8", "Stig Bakken, Thies C. Arntzen, Andy Sautins, David Benson");
CREDIT_LINE("ODBC", "Stig Bakken, Andreas Karajannis, Frank M. Kromann, Daniel R. Kalowsky");
CREDIT_LINE("OpenSSL", "Stig Venaas, Wez Furlong, Sascha Kettler");
CREDIT_LINE("Oracle", "Stig Bakken, Mitch Golden, Rasmus Lerdorf, Andreas Karajannis, Thies C. Arntzen");
CREDIT_LINE("Ovrimos", "Nikos Mavroyanopoulos");
CREDIT_LINE("pcntl", "Jason Greene");
CREDIT_LINE("PDF", "Uwe Steinmann");
CREDIT_LINE("Perl Compatible Regexps", "Andrei Zmievski");
CREDIT_LINE("Posix", "Kristian Köhntopp");
CREDIT_LINE("PostgreSQL", "Jouni Ahto, Zeev Suraski");
CREDIT_LINE("PRINTER", "Daniel Beulshausen, Frank M. Kromann");
CREDIT_LINE("Pspell", "Vlad Krupin");
CREDIT_LINE("qtdom", "Jan Borsodi");
CREDIT_LINE("Readline", "Thies C. Arntzen");
CREDIT_LINE("Recode", "Kristian Köhntopp");
CREDIT_LINE("Sablotron XSLT", "Sterling Hughes");
CREDIT_LINE("Satellite (CORBA)", "David Eriksson");
CREDIT_LINE("Sessions", "Sascha Schumann, Andrei Zmievski");
CREDIT_LINE("Shared Memory Operations", "Slava Poliakov, Ilia Alshanetsky");
CREDIT_LINE("SNMP", "Rasmus Lerdorf");
CREDIT_LINE("Sockets", "Chris Vandomelen, Sterling Hughes, Daniel Beulshausen");
CREDIT_LINE("SWF", "Sterling Hughes");
CREDIT_LINE("Sybase-CT", "Zeev Suraski, Tom May");
CREDIT_LINE("Sybase-DB", "Zeev Suraski");
CREDIT_LINE("System V Semaphores", "Tom May");
CREDIT_LINE("System V Shared Memory", "Christian Cartus");
CREDIT_LINE("Verisign Payflow Pro", "John Donagher, David Croft");
CREDIT_LINE("Vpopmail", "David Croft, Boian Bonev");
CREDIT_LINE("WDDX", "Andrei Zmievski");
CREDIT_LINE("Win32 COM", "Zeev Suraski, Harald Radi");
CREDIT_LINE("XML", "Stig Bakken, Thies C. Arntzen");
CREDIT_LINE("YAZ", "Adam Dickmeiss");
CREDIT_LINE("Yellow Pages", "Stephanie Wehner, Fredrik Ohrn");
CREDIT_LINE("Zip", "Sterling Hughes");
CREDIT_LINE("Zlib", "Rasmus Lerdorf, Stefan Roehrich");
+24
View File
@@ -0,0 +1,24 @@
/*
DO NOT EDIT THIS FILE!
it has been automaticaly created by php4/scripts/credits from
the information found in the various php4/ext/.../CREDITS and
php4/sapi/.../CREDITS files
if you want to change an entry you have to edit the appropriate
CREDITS file instead
*/
CREDIT_LINE("AOLserver", "Sascha Schumann");
CREDIT_LINE("Apache 1.3", "Rasmus Lerdorf, Zeev Suraski, Stig Bakken, David Sklar");
CREDIT_LINE("Apache 2.0", "Sascha Schumann");
CREDIT_LINE("Caudium / Roxen", "David Hedbor");
CREDIT_LINE("CGI", "Rasmus Lerdorf, Stig Bakken");
CREDIT_LINE("fhttpd", "Alex Belits");
CREDIT_LINE("ISAPI", "Andi Gutmans, Zeev Suraski");
CREDIT_LINE("Java Servlet", "Sam Ruby");
CREDIT_LINE("NSAPI", "Jayakumar Muthukumarasamy");
CREDIT_LINE("phttpd", "Thies C. Arntzen");
CREDIT_LINE("pi3web", "Holger Zimmermann");
CREDIT_LINE("thttpd", "Sascha Schumann");
+169
View File
@@ -0,0 +1,169 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Stig Bakken <ssb@gaurdian.no> |
| Zeev Suraski <zeev@zend.com> |
| Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include <stdlib.h>
#include "php.h"
#if HAVE_CRYPT
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#if HAVE_CRYPT_H
#include <crypt.h>
#endif
#if TM_IN_SYS_TIME
#include <sys/time.h>
#else
#include <time.h>
#endif
#if HAVE_STRING_H
#include <string.h>
#else
#include <strings.h>
#endif
#ifdef PHP_WIN32
#include <process.h>
extern char *crypt(char *__key, char *__salt);
#endif
#include "php_lcg.h"
#include "php_crypt.h"
#include "php_rand.h"
/*
The capabilities of the crypt() function is determined by the test programs
run by configure from aclocal.m4. They will set PHP_STD_DES_CRYPT,
PHP_EXT_DES_CRYPT, PHP_MD5_CRYPT and PHP_BLOWFISH_CRYPT as appropriate
for the target platform
*/
#if PHP_STD_DES_CRYPT
#define PHP_MAX_SALT_LEN 2
#endif
#if PHP_EXT_DES_CRYPT
#undef PHP_MAX_SALT_LEN
#define PHP_MAX_SALT_LEN 9
#endif
#if PHP_MD5_CRYPT
#undef PHP_MAX_SALT_LEN
#define PHP_MAX_SALT_LEN 12
#endif
#if PHP_BLOWFISH_CRYPT
#undef PHP_MAX_SALT_LEN
#define PHP_MAX_SALT_LEN 60
#endif
/*
* If the configure-time checks fail, we provide DES.
* XXX: This is a hack. Fix the real problem
*/
#ifndef PHP_MAX_SALT_LEN
#define PHP_MAX_SALT_LEN 2
#undef PHP_STD_DES_CRYPT
#define PHP_STD_DES_CRYPT 1
#endif
#define PHP_CRYPT_RAND php_rand()
PHP_MINIT_FUNCTION(crypt)
{
REGISTER_LONG_CONSTANT("CRYPT_SALT_LENGTH", PHP_MAX_SALT_LEN, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CRYPT_STD_DES", PHP_STD_DES_CRYPT, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CRYPT_EXT_DES", PHP_EXT_DES_CRYPT, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CRYPT_MD5", PHP_MD5_CRYPT, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("CRYPT_BLOWFISH", PHP_BLOWFISH_CRYPT, CONST_CS | CONST_PERSISTENT);
return SUCCESS;
}
static unsigned char itoa64[] = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static void php_to64(char *s, long v, int n) {
while (--n >= 0) {
*s++ = itoa64[v&0x3f];
v >>= 6;
}
}
/* {{{ proto string crypt(string str [, string salt])
Encrypt a string */
PHP_FUNCTION(crypt)
{
char salt[PHP_MAX_SALT_LEN+1];
pval **arg1, **arg2;
salt[0]=salt[PHP_MAX_SALT_LEN]='\0';
/* This will produce suitable results if people depend on DES-encryption
available (passing always 2-character salt). At least for glibc6.1 */
memset(&salt[1], '$', PHP_MAX_SALT_LEN-1);
switch (ZEND_NUM_ARGS()) {
case 1:
if (zend_get_parameters_ex(1, &arg1)==FAILURE) {
RETURN_FALSE;
}
break;
case 2:
if (zend_get_parameters_ex(2, &arg1, &arg2)==FAILURE) {
RETURN_FALSE;
}
convert_to_string_ex(arg2);
memcpy(salt, Z_STRVAL_PP(arg2), MIN(PHP_MAX_SALT_LEN, Z_STRLEN_PP(arg2)));
break;
default:
WRONG_PARAM_COUNT;
break;
}
convert_to_string_ex(arg1);
/* The automatic salt generation only covers standard DES and md5-crypt */
if(!*salt) {
#if PHP_MD5_CRYPT
strcpy(salt, "$1$");
php_to64(&salt[3], PHP_CRYPT_RAND, 4);
php_to64(&salt[7], PHP_CRYPT_RAND, 4);
strcpy(&salt[11], "$");
#elif PHP_STD_DES_CRYPT
php_to64(&salt[0], PHP_CRYPT_RAND, 2);
salt[2] = '\0';
#endif
}
RETVAL_STRING(crypt(Z_STRVAL_PP(arg1), salt), 1);
}
/* }}} */
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+299
View File
@@ -0,0 +1,299 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Kirill Maximov <kir@rus.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <string.h>
#include <errno.h>
#include "php.h"
#include "cyr_convert.h"
#include <stdio.h>
/*****************************************************************************
* This is codetables for different Cyrillic charsets (relative to koi8-r).
* Each table contains data for 128-255 symbols from ASCII table.
* First 256 symbols are for conversion from koi8-r to corresponding charset,
* second 256 symbols are for reverse conversion, from charset to koi8-r.
*
* Here we have the following tables:
* _cyr_win1251 - for windows-1251 charset
* _cyr_iso88595 - for iso8859-5 charset
* _cyr_cp866 - for x-cp866 charset
* _cyr_mac - for x-mac-cyrillic charset
*
*****************************************************************************/
typedef unsigned char _cyr_charset_table[512];
/* {{{ const static _cyr_charset_table _cyr_win1251
*/
const static _cyr_charset_table _cyr_win1251 = {
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,
46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,
154,174,190,46,159,189,46,46,179,191,180,157,46,46,156,183,
46,46,182,166,173,46,46,158,163,152,164,155,46,46,46,167,
225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240,
242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241,
193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208,
210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,209,
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,184,186,32,179,191,32,32,32,32,32,180,162,32,
32,32,32,168,170,32,178,175,32,32,32,32,32,165,161,169,
254,224,225,246,228,229,244,227,245,232,233,234,235,236,237,238,
239,255,240,241,242,243,230,226,252,251,231,248,253,249,247,250,
222,192,193,214,196,197,212,195,213,200,201,202,203,204,205,206,
207,223,208,209,210,211,198,194,220,219,199,216,221,217,215,218,
},
_cyr_cp866 = {
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240,
242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241,
193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208,
35,35,35,124,124,124,124,43,43,124,124,43,43,43,43,43,
43,45,45,124,45,43,124,124,43,43,45,45,124,45,43,45,
45,45,45,43,43,43,43,43,43,43,43,35,35,124,124,35,
210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,209,
179,163,180,164,183,167,190,174,32,149,158,32,152,159,148,154,
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
205,186,213,241,243,201,32,245,187,212,211,200,190,32,247,198,
199,204,181,240,242,185,32,244,203,207,208,202,216,32,246,32,
238,160,161,230,164,165,228,163,229,168,169,170,171,172,173,174,
175,239,224,225,226,227,166,162,236,235,167,232,237,233,231,234,
158,128,129,150,132,133,148,131,149,136,137,138,139,140,141,142,
143,159,144,145,146,147,134,130,156,155,135,152,157,153,151,154,
},
_cyr_iso88595 = {
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,179,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240,
242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241,
193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208,
210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,209,
32,163,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,241,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,161,32,32,32,32,32,32,32,32,32,32,32,32,
238,208,209,230,212,213,228,211,229,216,217,218,219,220,221,222,
223,239,224,225,226,227,214,210,236,235,215,232,237,233,231,234,
206,176,177,198,180,181,196,179,197,184,185,186,187,188,189,190,
191,207,192,193,194,195,182,178,204,203,183,200,205,201,199,202,
},
_cyr_mac = {
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240,
242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241,
160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
144,145,146,147,148,149,150,151,152,153,154,155,156,179,163,209,
193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208,
210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,255,
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
160,161,162,222,164,165,166,167,168,169,170,171,172,173,174,175,
176,177,178,221,180,181,182,183,184,185,186,187,188,189,190,191,
254,224,225,246,228,229,244,227,245,232,233,234,235,236,237,238,
239,223,240,241,242,243,230,226,252,251,231,248,253,249,247,250,
158,128,129,150,132,133,148,131,149,136,137,138,139,140,141,142,
143,159,144,145,146,147,134,130,156,155,135,152,157,153,151,154,
};
/* }}} */
/* {{{ php_convert_cyr_string
* This is the function that performs real in-place conversion of the string
* between charsets.
* Parameters:
* str - string to be converted
* from,to - one-symbol label of source and destination charset
* The following symbols are used as labels:
* k - koi8-r
* w - windows-1251
* i - iso8859-5
* a - x-cp866
* d - x-cp866
* m - x-mac-cyrillic
*****************************************************************************/
static char * php_convert_cyr_string(unsigned char *str, int length, char from, char to)
{
const unsigned char *from_table, *to_table;
unsigned char tmp;
int i;
from_table = NULL;
to_table = NULL;
switch (toupper(from))
{
case 'W':
from_table = _cyr_win1251;
break;
case 'A':
case 'D':
from_table = _cyr_cp866;
break;
case 'I':
from_table = _cyr_iso88595;
break;
case 'M':
from_table = _cyr_mac;
break;
case 'K':
break;
default:
php_error(E_WARNING, "Unknown source charset: %c", from);
break;
}
switch (toupper(to))
{
case 'W':
to_table = _cyr_win1251;
break;
case 'A':
case 'D':
to_table = _cyr_cp866;
break;
case 'I':
to_table = _cyr_iso88595;
break;
case 'M':
to_table = _cyr_mac;
break;
case 'K':
break;
default:
php_error(E_WARNING, "Unknown destination charset: %c", to);
break;
}
if (!str)
return (char *)str;
for( i = 0; i<length; i++)
{
tmp = (from_table == NULL)? str[i] : from_table[ str[i] ];
str[i] = (to_table == NULL) ? tmp : to_table[tmp + 256];
}
return (char *)str;
}
/* }}} */
/* {{{ proto string convert_cyr_string(string str, string from, string to)
Convert from one Cyrillic character set to another */
PHP_FUNCTION(convert_cyr_string)
{
pval **str_arg, **fr_cs, **to_cs;
unsigned char *str;
if (ZEND_NUM_ARGS() != 3 || zend_get_parameters_ex(3,&str_arg,&fr_cs, &to_cs)==FAILURE)
{
WRONG_PARAM_COUNT;
}
convert_to_string_ex(str_arg);
convert_to_string_ex(fr_cs);
convert_to_string_ex(to_cs);
str = (unsigned char*) estrndup((*str_arg)->value.str.val, (*str_arg)->value.str.len);
php_convert_cyr_string(str, (*str_arg)->value.str.len, (*fr_cs)->value.str.val[0], (*to_cs)->value.str.val[0]);
RETVAL_STRING((char *)str, 0)
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+29
View File
@@ -0,0 +1,29 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Kirill Maximov (kir@rus.net) |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef CYR_CONVERT_H
#define CYR_CONVERT_H
PHP_FUNCTION(convert_cyr_string);
#endif /* CYR_CONVERT_H */
+832
View File
@@ -0,0 +1,832 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Andi Gutmans <andi@zend.com> |
| Zeev Suraski <zeev@zend.com> |
| Rasmus Lerdorf <rasmus@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "zend_operators.h"
#include "datetime.h"
#include "php_globals.h"
#include <time.h>
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
#include <stdio.h>
#include "php_parsedate.h"
char *mon_full_names[] =
{
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
};
char *mon_short_names[] =
{
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
char *day_full_names[] =
{
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
};
char *day_short_names[] =
{
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
#if !defined(HAVE_TM_ZONE) && !defined(_TIMEZONE) && !defined(HAVE_DECLARED_TIMEZONE)
extern time_t timezone;
extern int daylight;
#endif
static int phpday_tab[2][12] =
{
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
#define isleap(year) (((year%4) == 0 && (year%100)!=0) || (year%400)==0)
/* {{{ proto int time(void)
Return current UNIX timestamp */
PHP_FUNCTION(time)
{
RETURN_LONG((long)time(NULL));
}
/* }}} */
/* {{{ php_mktime
*/
void php_mktime(INTERNAL_FUNCTION_PARAMETERS, int gm)
{
pval **arguments[7];
struct tm *ta, tmbuf;
time_t t;
int i, gmadjust, seconds, arg_count = ZEND_NUM_ARGS();
int is_dst = -1;
if (arg_count > 7 || zend_get_parameters_array_ex(arg_count, arguments) == FAILURE) {
WRONG_PARAM_COUNT;
}
/* convert supplied arguments to longs */
for (i = 0; i < arg_count; i++) {
convert_to_long_ex(arguments[i]);
}
t = time(NULL);
#ifdef HAVE_TZSET
tzset();
#endif
/*
** Set default time parameters with local time values,
** EVEN when some GMT time parameters are specified!
** This may give strange result, with PHP gmmktime(0, 0, 0),
** which is assumed to return GMT midnight time
** for today (in localtime), so that the result time may be
** AFTER or BEFORE the current time.
** May be we should initialize tn using gmtime(), so that
** default parameters for PHP gmmktime would be the current
** GMT time values...
*/
ta = php_localtime_r(&t, &tmbuf);
/* Let DST be unknown. mktime() should compute the right value
** and behave correctly. Unless the user overrides this.
*/
ta->tm_isdst = -1;
/*
** Now change date values with supplied parameters.
*/
switch(arg_count) {
case 7:
ta->tm_isdst = is_dst = (*arguments[6])->value.lval;
/* fall-through */
case 6:
/* special case:
a zero in year, month and day is considered illegal
as it would be interpreted as 30.11.1999 otherwise
*/
if ( ( (*arguments[5])->value.lval==0)
&&((*arguments[4])->value.lval==0)
&&((*arguments[3])->value.lval==0)
) {
RETURN_LONG(-1);
}
/*
** Accept parameter in range 0..1000 interpreted as 1900..2900
** (if 100 is given, it means year 2000)
** or in range 1001..9999 interpreted as is (this will store
** negative tm_year for years in range 1001..1899)
** This function is then Y2K ready, and accepts a wide range of
** dates including the whole gregorian calendar.
** But it cannot represent ancestral dates prior to year 1001.
** Additionally, input parameters of 0..70 are mapped to 100..170
*/
if ((*arguments[5])->value.lval < 70)
ta->tm_year = (*arguments[5])->value.lval + 100;
else
ta->tm_year = (*arguments[5])->value.lval
- (((*arguments[5])->value.lval > 1000) ? 1900 : 0);
/* fall-through */
case 5:
ta->tm_mday = (*arguments[4])->value.lval;
/* fall-through */
case 4:
ta->tm_mon = (*arguments[3])->value.lval - 1;
/* fall-through */
case 3:
ta->tm_sec = (*arguments[2])->value.lval;
/* fall-through */
case 2:
ta->tm_min = (*arguments[1])->value.lval;
/* fall-through */
case 1:
ta->tm_hour = (*arguments[0])->value.lval;
/* fall-through */
case 0:
break;
}
seconds = mktime(ta);
if (is_dst == -1)
is_dst = ta->tm_isdst;
if (gm) {
#if HAVE_TM_GMTOFF
/*
** mktime(ta) very nicely just filled ta->tm_gmtoff with
** the exactly right value for adjustment if we want GMT.
*/
gmadjust = ta->tm_gmtoff;
#else
/*
** If correcting for daylight savings time, we set the adjustment to
** the value of timezone - 3600 seconds. Otherwise, we need to overcorrect and
** set the adjustment to the main timezone + 3600 seconds.
*/
gmadjust = -(is_dst ? timezone - 3600 : timezone + 3600);
#endif
seconds += gmadjust;
}
RETURN_LONG(seconds);
}
/* }}} */
/* {{{ proto int mktime(int hour, int min, int sec, int mon, int day, int year)
Get UNIX timestamp for a date */
PHP_FUNCTION(mktime)
{
php_mktime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
/* }}} */
/* {{{ proto int gmmktime(int hour, int min, int sec, int mon, int day, int year)
Get UNIX timestamp for a GMT date */
PHP_FUNCTION(gmmktime)
{
php_mktime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}
/* }}} */
/* {{{ php_date
*/
static void
php_date(INTERNAL_FUNCTION_PARAMETERS, int gm)
{
pval **format, **timestamp;
time_t the_time;
struct tm *ta, tmbuf;
int i, size = 0, length, h, beat, fd, wd, yd, wk;
char tmp_buff[32];
switch(ZEND_NUM_ARGS()) {
case 1:
if (zend_get_parameters_ex(1, &format) == FAILURE) {
WRONG_PARAM_COUNT;
}
the_time = time(NULL);
break;
case 2:
if (zend_get_parameters_ex(2, &format, &timestamp) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_long_ex(timestamp);
the_time = (*timestamp)->value.lval;
break;
default:
WRONG_PARAM_COUNT;
}
convert_to_string_ex(format);
if (gm) {
ta = php_gmtime_r(&the_time, &tmbuf);
} else {
ta = php_localtime_r(&the_time, &tmbuf);
}
if (!ta) { /* that really shouldn't happen... */
php_error(E_WARNING, "unexpected error in date()");
RETURN_FALSE;
}
for (i = 0; i < (*format)->value.str.len; i++) {
switch ((*format)->value.str.val[i]) {
case 'r': /* rfc822 format */
size += 31;
break;
case 'U': /* seconds since the epoch */
size += 10;
break;
case 'F': /* month, textual, full */
case 'l': /* day (of the week), textual */
size += 28;
break;
case 'T': /* timezone name */
#if HAVE_TM_ZONE
size += strlen(ta->tm_zone);
#elif HAVE_TZNAME
size += strlen(tzname[0]);
#endif
break;
case 'Z': /* timezone offset in seconds */
size += 6;
break;
case 'O': /* GMT offset in [+-]HHMM format */
size += 5;
break;
case 'Y': /* year, numeric, 4 digits */
size += 4;
break;
case 'M': /* month, textual, 3 letters */
case 'D': /* day, textual, 3 letters */
case 'z': /* day of the year, 1 to 366 */
case 'B': /* Swatch Beat, 3 digits */
size += 3;
break;
case 'y': /* year, numeric, 2 digits */
case 'm': /* month, numeric */
case 'n': /* month, numeric, no leading zeroes */
case 'd': /* day of the month, numeric */
case 'j': /* day of the month, numeric, no leading zeros */
case 'H': /* hour, numeric, 24 hour format */
case 'h': /* hour, numeric, 12 hour format */
case 'G': /* hour, numeric, 24 hour format, no leading zeroes */
case 'g': /* hour, numeric, 12 hour format, no leading zeroes */
case 'i': /* minutes, numeric */
case 's': /* seconds, numeric */
case 'A': /* AM/PM */
case 'a': /* am/pm */
case 'S': /* standard english suffix for the day of the month (e.g. 3rd, 2nd, etc) */
case 't': /* days in current month */
case 'W': /* ISO-8601 week number of year, weeks starting on Monday */
size += 2;
break;
case '\\':
if(i < (*format)->value.str.len-1) {
i++;
}
size ++;
break;
case 'L': /* boolean for leap year */
case 'w': /* day of the week, numeric */
case 'I': /* DST? */
default:
size++;
break;
}
}
return_value->value.str.val = (char *) emalloc(size + 1);
return_value->value.str.val[0] = '\0';
for (i = 0; i < (*format)->value.str.len; i++) {
switch ((*format)->value.str.val[i]) {
case '\\':
if(i < (*format)->value.str.len-1) {
char ch[2];
ch[0]=(*format)->value.str.val[i+1];
ch[1]='\0';
strcat(return_value->value.str.val, ch);
i++;
}
break;
case 'U': /* seconds since the epoch */
sprintf(tmp_buff, "%ld", (long)the_time); /* SAFE */
strcat(return_value->value.str.val, tmp_buff);
break;
case 'F': /* month, textual, full */
strcat(return_value->value.str.val, mon_full_names[ta->tm_mon]);
break;
case 'l': /* day (of the week), textual, full */
strcat(return_value->value.str.val, day_full_names[ta->tm_wday]);
break;
case 'Y': /* year, numeric, 4 digits */
sprintf(tmp_buff, "%d", ta->tm_year + 1900); /* SAFE */
strcat(return_value->value.str.val, tmp_buff);
break;
case 'M': /* month, textual, 3 letters */
strcat(return_value->value.str.val, mon_short_names[ta->tm_mon]);
break;
case 'D': /* day (of the week), textual, 3 letters */
strcat(return_value->value.str.val, day_short_names[ta->tm_wday]);
break;
case 'z': /* day (of the year) */
sprintf(tmp_buff, "%d", ta->tm_yday); /* SAFE */
strcat(return_value->value.str.val, tmp_buff);
break;
case 'y': /* year, numeric, 2 digits */
sprintf(tmp_buff, "%02d", ((ta->tm_year)%100)); /* SAFE */
strcat(return_value->value.str.val, tmp_buff);
break;
case 'm': /* month, numeric */
sprintf(tmp_buff, "%02d", ta->tm_mon + 1); /* SAFE */
strcat(return_value->value.str.val, tmp_buff);
break;
case 'n': /* month, numeric, no leading zeros */
sprintf(tmp_buff, "%d", ta->tm_mon + 1); /* SAFE */
strcat(return_value->value.str.val, tmp_buff);
break;
case 'd': /* day of the month, numeric */
sprintf(tmp_buff, "%02d", ta->tm_mday); /* SAFE */
strcat(return_value->value.str.val, tmp_buff);
break;
case 'j':
sprintf(tmp_buff, "%d", ta->tm_mday); /* SAFE */
strcat(return_value->value.str.val, tmp_buff);
break;
case 'H': /* hour, numeric, 24 hour format */
sprintf(tmp_buff, "%02d", ta->tm_hour); /* SAFE */
strcat(return_value->value.str.val, tmp_buff);
break;
case 'h': /* hour, numeric, 12 hour format */
h = ta->tm_hour % 12; if (h==0) h = 12;
sprintf(tmp_buff, "%02d", h); /* SAFE */
strcat(return_value->value.str.val, tmp_buff);
break;
case 'G': /* hour, numeric, 24 hour format, no leading zeros */
sprintf(tmp_buff, "%d", ta->tm_hour); /* SAFE */
strcat(return_value->value.str.val, tmp_buff);
break;
case 'g': /* hour, numeric, 12 hour format, no leading zeros */
h = ta->tm_hour % 12; if (h==0) h = 12;
sprintf(tmp_buff, "%d", h); /* SAFE */
strcat(return_value->value.str.val, tmp_buff);
break;
case 'i': /* minutes, numeric */
sprintf(tmp_buff, "%02d", ta->tm_min); /* SAFE */
strcat(return_value->value.str.val, tmp_buff);
break;
case 's': /* seconds, numeric */
sprintf(tmp_buff, "%02d", ta->tm_sec); /* SAFE */
strcat(return_value->value.str.val, tmp_buff);
break;
case 'A': /* AM/PM */
strcat(return_value->value.str.val, (ta->tm_hour >= 12 ? "PM" : "AM"));
break;
case 'a': /* am/pm */
strcat(return_value->value.str.val, (ta->tm_hour >= 12 ? "pm" : "am"));
break;
case 'S': /* standard english suffix, e.g. 2nd/3rd for the day of the month */
if (ta->tm_mday >= 10 && ta->tm_mday <= 19) {
strcat(return_value->value.str.val, "th");
} else {
switch (ta->tm_mday % 10) {
case 1:
strcat(return_value->value.str.val, "st");
break;
case 2:
strcat(return_value->value.str.val, "nd");
break;
case 3:
strcat(return_value->value.str.val, "rd");
break;
default:
strcat(return_value->value.str.val, "th");
break;
}
}
break;
case 't': /* days in current month */
sprintf(tmp_buff, "%2d", phpday_tab[isleap((ta->tm_year+1900))][ta->tm_mon] );
strcat(return_value->value.str.val, tmp_buff);
break;
case 'w': /* day of the week, numeric EXTENSION */
sprintf(tmp_buff, "%01d", ta->tm_wday); /* SAFE */
strcat(return_value->value.str.val, tmp_buff);
break;
case 'O': /* GMT offset in [+-]HHMM format */
#if HAVE_TM_GMTOFF
sprintf(tmp_buff, "%c%02d%02d", (ta->tm_gmtoff < 0) ? '-' : '+', abs(ta->tm_gmtoff / 3600), abs( ta->tm_gmtoff % 3600));
#else
sprintf(tmp_buff, "%c%02d%02d", ((ta->tm_isdst ? timezone - 3600:timezone)>0)?'-':'+', abs((ta->tm_isdst ? timezone - 3600 : timezone) / 3600), abs((ta->tm_isdst ? timezone - 3600 : timezone) % 3600));
#endif
strcat(return_value->value.str.val, tmp_buff);
break;
case 'Z': /* timezone offset in seconds */
#if HAVE_TM_GMTOFF
sprintf(tmp_buff, "%ld", ta->tm_gmtoff);
#else
sprintf(tmp_buff, "%ld", ta->tm_isdst ? -(timezone - 3600) : -timezone);
#endif
strcat(return_value->value.str.val, tmp_buff);
break;
case 'L': /* boolean for leapyear */
sprintf(tmp_buff, "%d", (isleap((ta->tm_year+1900)) ? 1 : 0 ) );
strcat(return_value->value.str.val, tmp_buff);
break;
case 'T': /* timezone name */
#if HAVE_TM_ZONE
strcat(return_value->value.str.val, ta->tm_zone);
#elif HAVE_TZNAME
strcat(return_value->value.str.val, tzname[0]);
#endif
break;
case 'B': /* Swatch Beat a.k.a. Internet Time */
beat = (((((long)the_time)-(((long)the_time) -
((((long)the_time) % 86400) + 3600))) * 10) / 864);
while (beat < 0) {
beat += 1000;
}
beat = beat % 1000;
sprintf(tmp_buff, "%03d", beat); /* SAFE */
strcat(return_value->value.str.val, tmp_buff);
break;
case 'I':
sprintf(tmp_buff, "%d", ta->tm_isdst);
strcat(return_value->value.str.val, tmp_buff);
break;
case 'r':
#if HAVE_TM_GMTOFF
sprintf(tmp_buff, "%3s, %2d %3s %04d %02d:%02d:%02d %c%02d%02d",
day_short_names[ta->tm_wday],
ta->tm_mday,
mon_short_names[ta->tm_mon],
ta->tm_year + 1900,
ta->tm_hour,
ta->tm_min,
ta->tm_sec,
(ta->tm_gmtoff < 0) ? '-' : '+',
abs(ta->tm_gmtoff / 3600),
abs( ta->tm_gmtoff % 3600)
);
#else
sprintf(tmp_buff, "%3s, %2d %3s %04d %02d:%02d:%02d %c%02d%02d",
day_short_names[ta->tm_wday],
ta->tm_mday,
mon_short_names[ta->tm_mon],
ta->tm_year + 1900,
ta->tm_hour,
ta->tm_min,
ta->tm_sec,
((ta->tm_isdst ? timezone - 3600 : timezone) > 0) ? '-' : '+',
abs((ta->tm_isdst ? timezone - 3600 : timezone) / 3600),
abs((ta->tm_isdst ? timezone - 3600 : timezone) % 3600)
);
#endif
strcat(return_value->value.str.val, tmp_buff);
break;
case 'W': /* ISO-8601 week number of year, weeks starting on Monday */
wd = ta->tm_wday==0 ? 7 : ta->tm_wday;
yd = ta->tm_yday + 1;
fd = (7 + (wd - yd) % 7 ) % 7;
wk = ( (yd + fd - 1) / 7 ) + 1;
if (fd>3) {
wk--;
}
sprintf(tmp_buff, "%d", wk); /* SAFE */
strcat(return_value->value.str.val, tmp_buff);
break;
default:
length = strlen(return_value->value.str.val);
return_value->value.str.val[length] = (*format)->value.str.val[i];
return_value->value.str.val[length + 1] = '\0';
break;
}
}
return_value->value.str.len = strlen(return_value->value.str.val);
return_value->type = IS_STRING;
}
/* }}} */
/* {{{ proto string date(string format [, int timestamp])
Format a local time/date */
PHP_FUNCTION(date)
{
php_date(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
/* }}} */
/* {{{ proto string gmdate(string format [, int timestamp])
Format a GMT/UTC date/time */
PHP_FUNCTION(gmdate)
{
php_date(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}
/* }}} */
/* {{{ proto array localtime([int timestamp [, bool associative_array]])
Returns the results of the C system call localtime as an associative array if the associative_array argument is set to 1 other wise it is a regular array */
PHP_FUNCTION(localtime)
{
zval **timestamp_arg, **assoc_array_arg;
struct tm *ta, tmbuf;
time_t timestamp;
int assoc_array = 0;
int arg_count = ZEND_NUM_ARGS();
if (arg_count < 0 || arg_count > 2 ||
zend_get_parameters_ex(arg_count, &timestamp_arg, &assoc_array_arg) == FAILURE) {
WRONG_PARAM_COUNT;
}
switch (arg_count) {
case 0:
timestamp = (long)time(NULL);
break;
case 1:
convert_to_long_ex(timestamp_arg);
timestamp = (*timestamp_arg)->value.lval;
break;
case 2:
convert_to_long_ex(timestamp_arg);
convert_to_long_ex(assoc_array_arg);
timestamp = (*timestamp_arg)->value.lval;
assoc_array = (*assoc_array_arg)->value.lval;
break;
}
ta = php_localtime_r(&timestamp, &tmbuf);
if (array_init(return_value) == FAILURE) {
php_error(E_ERROR, "Cannot prepare return array from localtime");
RETURN_FALSE;
}
if (assoc_array) {
add_assoc_long(return_value, "tm_sec", ta->tm_sec);
add_assoc_long(return_value, "tm_min", ta->tm_min);
add_assoc_long(return_value, "tm_hour", ta->tm_hour);
add_assoc_long(return_value, "tm_mday", ta->tm_mday);
add_assoc_long(return_value, "tm_mon", ta->tm_mon);
add_assoc_long(return_value, "tm_year", ta->tm_year);
add_assoc_long(return_value, "tm_wday", ta->tm_wday);
add_assoc_long(return_value, "tm_yday", ta->tm_yday);
add_assoc_long(return_value, "tm_isdst", ta->tm_isdst);
} else {
add_next_index_long(return_value, ta->tm_sec);
add_next_index_long(return_value, ta->tm_min);
add_next_index_long(return_value, ta->tm_hour);
add_next_index_long(return_value, ta->tm_mday);
add_next_index_long(return_value, ta->tm_mon);
add_next_index_long(return_value, ta->tm_year);
add_next_index_long(return_value, ta->tm_wday);
add_next_index_long(return_value, ta->tm_yday);
add_next_index_long(return_value, ta->tm_isdst);
}
}
/* }}} */
/* {{{ proto array getdate([int timestamp])
Get date/time information */
PHP_FUNCTION(getdate)
{
pval **timestamp_arg;
struct tm *ta, tmbuf;
time_t timestamp;
if (ZEND_NUM_ARGS() == 0) {
timestamp = time(NULL);
} else if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &timestamp_arg) == FAILURE) {
WRONG_PARAM_COUNT;
} else {
convert_to_long_ex(timestamp_arg);
timestamp = (*timestamp_arg)->value.lval;
}
ta = php_localtime_r(&timestamp, &tmbuf);
if (!ta) {
php_error(E_WARNING, "Cannot perform date calculation");
return;
}
if (array_init(return_value) == FAILURE) {
php_error(E_ERROR, "Unable to initialize array");
return;
}
add_assoc_long(return_value, "seconds", ta->tm_sec);
add_assoc_long(return_value, "minutes", ta->tm_min);
add_assoc_long(return_value, "hours", ta->tm_hour);
add_assoc_long(return_value, "mday", ta->tm_mday);
add_assoc_long(return_value, "wday", ta->tm_wday);
add_assoc_long(return_value, "mon", ta->tm_mon + 1);
add_assoc_long(return_value, "year", ta->tm_year + 1900);
add_assoc_long(return_value, "yday", ta->tm_yday);
add_assoc_string(return_value, "weekday", day_full_names[ta->tm_wday], 1);
add_assoc_string(return_value, "month", mon_full_names[ta->tm_mon], 1);
add_index_long(return_value, 0, timestamp);
}
/* }}} */
/* {{{ php_std_date
Return date string in standard format for http headers */
char *php_std_date(time_t t)
{
struct tm *tm1, tmbuf;
char *str;
TSRMLS_FETCH();
tm1 = php_gmtime_r(&t, &tmbuf);
str = emalloc(81);
if (PG(y2k_compliance)) {
snprintf(str, 80, "%s, %02d-%s-%04d %02d:%02d:%02d GMT",
day_short_names[tm1->tm_wday],
tm1->tm_mday,
mon_short_names[tm1->tm_mon],
tm1->tm_year+1900,
tm1->tm_hour, tm1->tm_min, tm1->tm_sec);
} else {
snprintf(str, 80, "%s, %02d-%s-%02d %02d:%02d:%02d GMT",
day_short_names[tm1->tm_wday],
tm1->tm_mday,
mon_short_names[tm1->tm_mon],
((tm1->tm_year)%100),
tm1->tm_hour, tm1->tm_min, tm1->tm_sec);
}
str[79]=0;
return (str);
}
/* }}} */
/* {{{ proto bool checkdate(int month, int day, int year)
Returns true(1) if it is a valid date in gregorian calendar */
PHP_FUNCTION(checkdate)
{
pval **month, **day, **year;
int m, d, y, res=0;
if (ZEND_NUM_ARGS() != 3 ||
zend_get_parameters_ex(3, &month, &day, &year) == FAILURE) {
WRONG_PARAM_COUNT;
}
if((*year)->type == IS_STRING) {
res = is_numeric_string((*year)->value.str.val, (*year)->value.str.len, NULL, NULL, 0);
if(res!=IS_LONG && res !=IS_DOUBLE) {
RETURN_FALSE;
}
}
convert_to_long_ex(day);
convert_to_long_ex(month);
convert_to_long_ex(year);
y = (*year)->value.lval;
m = (*month)->value.lval;
d = (*day)->value.lval;
if (y < 1 || y > 32767) {
RETURN_FALSE;
}
if (m < 1 || m > 12) {
RETURN_FALSE;
}
if (d < 1 || d > phpday_tab[isleap(y)][m - 1]) {
RETURN_FALSE;
}
RETURN_TRUE; /* True : This month, day, year arguments are valid */
}
/* }}} */
#if HAVE_STRFTIME
/* {{{ _php_strftime
*/
void _php_strftime(INTERNAL_FUNCTION_PARAMETERS, int gm)
{
pval **format_arg, **timestamp_arg;
char *format, *buf;
time_t timestamp;
struct tm *ta, tmbuf;
int max_reallocs = 5;
size_t buf_len=64, real_len;
switch (ZEND_NUM_ARGS()) {
case 1:
if (zend_get_parameters_ex(1, &format_arg)==FAILURE) {
RETURN_FALSE;
}
time(&timestamp);
break;
case 2:
if (zend_get_parameters_ex(2, &format_arg, &timestamp_arg)==FAILURE) {
RETURN_FALSE;
}
convert_to_long_ex(timestamp_arg);
timestamp = (*timestamp_arg)->value.lval;
break;
default:
WRONG_PARAM_COUNT;
break;
}
convert_to_string_ex(format_arg);
if ((*format_arg)->value.str.len==0) {
RETURN_FALSE;
}
if (timestamp < 0) {
RETURN_FALSE;
}
format = (*format_arg)->value.str.val;
if (gm) {
ta = php_gmtime_r(&timestamp, &tmbuf);
} else {
ta = php_localtime_r(&timestamp, &tmbuf);
}
buf = (char *) emalloc(buf_len);
while ((real_len=strftime(buf, buf_len, format, ta))==buf_len || real_len==0) {
buf_len *= 2;
buf = (char *) erealloc(buf, buf_len);
if(!--max_reallocs) break;
}
if(real_len && real_len != buf_len) {
buf = (char *) erealloc(buf, real_len+1);
RETURN_STRINGL(buf, real_len, 0);
}
efree(buf);
RETURN_FALSE;
}
/* }}} */
/* {{{ proto string strftime(string format [, int timestamp])
Format a local time/date according to locale settings */
PHP_FUNCTION(strftime)
{
_php_strftime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
/* }}} */
/* {{{ proto string gmstrftime(string format [, int timestamp])
Format a GMT/UCT time/date according to locale settings */
PHP_FUNCTION(gmstrftime)
{
_php_strftime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}
/* }}} */
#endif
/* {{{ proto int strtotime(string time, int now)
Convert string representation of date and time to a timestamp */
PHP_FUNCTION(strtotime)
{
zval **z_time, **z_now;
int argc;
time_t now;
argc = ZEND_NUM_ARGS();
if (argc < 1 || argc > 2 || zend_get_parameters_ex(argc, &z_time, &z_now)==FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(z_time);
if (Z_STRLEN_PP(z_time) == 0)
php_error (E_NOTICE, "strtotime() called with empty time parameter");
if (argc == 2) {
convert_to_long_ex(z_now);
now = Z_LVAL_PP(z_now);
RETURN_LONG(php_parse_date(Z_STRVAL_PP(z_time), &now));
} else {
RETURN_LONG(php_parse_date(Z_STRVAL_PP(z_time), NULL));
}
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+45
View File
@@ -0,0 +1,45 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Andi Gutmans <andi@zend.com> |
| Zeev Suraski <zeev@zend.com> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef DATETIME_H
#define DATETIME_H
PHP_FUNCTION(time);
PHP_FUNCTION(mktime);
PHP_FUNCTION(gmmktime);
PHP_FUNCTION(date);
PHP_FUNCTION(gmdate);
PHP_FUNCTION(localtime);
PHP_FUNCTION(getdate);
PHP_FUNCTION(checkdate);
#if HAVE_STRFTIME
PHP_FUNCTION(strftime);
PHP_FUNCTION(gmstrftime);
#endif
PHP_FUNCTION(strtotime);
extern char *php_std_date(time_t t);
void php_mktime(INTERNAL_FUNCTION_PARAMETERS, int gm);
#if HAVE_STRFTIME
void _php_strftime(INTERNAL_FUNCTION_PARAMETERS, int gm);
#endif
#endif /* DATETIME_H */
+357
View File
@@ -0,0 +1,357 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: |
| PHP 4.0 patches by Thies C. Arntzen (thies@thieso.net) |
+----------------------------------------------------------------------+
*/
/* $Id$ */
/* {{{ includes/startup/misc */
#include "php.h"
#include "fopen_wrappers.h"
#include "php_dir.h"
#ifdef HAVE_DIRENT_H
# include <dirent.h>
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <errno.h>
#ifdef PHP_WIN32
#include "win32/readdir.h"
#endif
typedef struct {
int default_dir;
} php_dir_globals;
#ifdef ZTS
#define DIRG(v) TSRMG(dir_globals_id, php_dir_globals *, v)
int dir_globals_id;
#else
#define DIRG(v) (dir_globals.v)
php_dir_globals dir_globals;
#endif
typedef struct {
int id;
DIR *dir;
} php_dir;
static int le_dirp;
static zend_class_entry *dir_class_entry_ptr;
#define FETCH_DIRP() \
if (ZEND_NUM_ARGS() == 0) { \
myself = getThis(); \
if (myself) { \
if (zend_hash_find(Z_OBJPROP_P(myself), "handle", sizeof("handle"), (void **)&tmp) == FAILURE) { \
php_error(E_WARNING, "unable to find my handle property"); \
RETURN_FALSE; \
} \
ZEND_FETCH_RESOURCE(dirp, php_dir *, tmp, -1, "Directory", le_dirp); \
} else { \
ZEND_FETCH_RESOURCE(dirp, php_dir *, 0, DIRG(default_dir), "Directory", le_dirp); \
} \
} else if ((ZEND_NUM_ARGS() != 1) || zend_get_parameters_ex(1, &id) == FAILURE) { \
WRONG_PARAM_COUNT; \
} else { \
ZEND_FETCH_RESOURCE(dirp, php_dir *, id,-1, "Directory", le_dirp); \
}
static zend_function_entry php_dir_class_functions[] = {
PHP_FALIAS(close, closedir, NULL)
PHP_FALIAS(rewind, rewinddir, NULL)
PHP_STATIC_FE("read", php_if_readdir, NULL)
{NULL, NULL, NULL}
};
static void php_set_default_dir(int id TSRMLS_DC)
{
if (DIRG(default_dir)!=-1) {
zend_list_delete(DIRG(default_dir));
}
if (id != -1) {
zend_list_addref(id);
}
DIRG(default_dir) = id;
}
static void _dir_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
php_dir *dirp = (php_dir *)rsrc->ptr;
closedir(dirp->dir);
efree(dirp);
}
PHP_RINIT_FUNCTION(dir)
{
DIRG(default_dir) = -1;
return SUCCESS;
}
PHP_MINIT_FUNCTION(dir)
{
static char tmpstr[2];
zend_class_entry dir_class_entry;
le_dirp = zend_register_list_destructors_ex(_dir_dtor, NULL, "dir", module_number);
INIT_CLASS_ENTRY(dir_class_entry, "Directory", php_dir_class_functions);
dir_class_entry_ptr = zend_register_internal_class(&dir_class_entry TSRMLS_CC);
#ifdef ZTS
ts_allocate_id(&dir_globals_id, sizeof(php_dir_globals), NULL, NULL);
#endif
tmpstr[0] = DEFAULT_SLASH;
tmpstr[1] = '\0';
REGISTER_STRING_CONSTANT("DIRECTORY_SEPARATOR", tmpstr, CONST_CS|CONST_PERSISTENT);
return SUCCESS;
}
/* }}} */
/* {{{ internal functions */
static void _php_do_opendir(INTERNAL_FUNCTION_PARAMETERS, int createobject)
{
pval **arg;
php_dir *dirp;
if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &arg) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(arg);
if (php_check_open_basedir((*arg)->value.str.val TSRMLS_CC)) {
RETURN_FALSE;
}
dirp = emalloc(sizeof(php_dir));
dirp->dir = VCWD_OPENDIR((*arg)->value.str.val);
#ifdef PHP_WIN32
if (!dirp->dir || dirp->dir->finished) {
if (dirp->dir) {
closedir(dirp->dir);
}
#else
if (!dirp->dir) {
#endif
efree(dirp);
php_error(E_WARNING, "OpenDir: %s (errno %d)", strerror(errno), errno);
RETURN_FALSE;
}
dirp->id = zend_list_insert(dirp, le_dirp);
php_set_default_dir(dirp->id TSRMLS_CC);
if (createobject) {
object_init_ex(return_value, dir_class_entry_ptr);
add_property_stringl(return_value, "path", (*arg)->value.str.val, (*arg)->value.str.len, 1);
add_property_resource(return_value, "handle", dirp->id);
zend_list_addref(dirp->id);
} else {
RETURN_RESOURCE(dirp->id);
}
}
/* }}} */
/* {{{ proto int opendir(string path)
Open a directory and return a dir_handle */
PHP_FUNCTION(opendir)
{
_php_do_opendir(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
/* }}} */
/* {{{ proto class dir(string directory)
Directory class with properties, handle and class and methods read, rewind and close */
PHP_FUNCTION(getdir)
{
_php_do_opendir(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}
/* }}} */
/* {{{ proto void closedir([int dir_handle])
Close directory connection identified by the dir_handle */
PHP_FUNCTION(closedir)
{
pval **id, **tmp, *myself;
php_dir *dirp;
FETCH_DIRP();
zend_list_delete(dirp->id);
if (dirp->id == DIRG(default_dir)) {
php_set_default_dir(-1 TSRMLS_CC);
}
}
/* }}} */
#if defined(HAVE_CHROOT) && !defined(ZTS)
/* {{{ proto int chroot(string directory)
Change root directory */
PHP_FUNCTION(chroot)
{
pval **arg;
int ret;
if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &arg) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(arg);
ret = chroot((*arg)->value.str.val);
if (ret != 0) {
php_error(E_WARNING, "chroot: %s (errno %d)", strerror(errno), errno);
RETURN_FALSE;
}
ret = chdir("/");
if (ret != 0) {
php_error(E_WARNING, "chdir: %s (errno %d)", strerror(errno), errno);
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
#endif
/* {{{ proto int chdir(string directory)
Change the current directory */
PHP_FUNCTION(chdir)
{
pval **arg;
int ret;
if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &arg) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(arg);
if (PG(safe_mode) && !php_checkuid((*arg)->value.str.val, NULL, CHECKUID_ALLOW_ONLY_FILE)) {
RETURN_FALSE;
}
ret = VCWD_CHDIR((*arg)->value.str.val);
if (ret != 0) {
php_error(E_WARNING, "ChDir: %s (errno %d)", strerror(errno), errno);
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto string getcwd(void)
Gets the current directory */
PHP_FUNCTION(getcwd)
{
char path[MAXPATHLEN];
char *ret=NULL;
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
#if HAVE_GETCWD
ret = VCWD_GETCWD(path, MAXPATHLEN);
#elif HAVE_GETWD
ret = VCWD_GETWD(path);
/*
* #warning is not ANSI C
* #else
* #warning no proper getcwd support for your site
*/
#endif
if (ret) {
RETURN_STRING(path, 1);
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto void rewinddir([int dir_handle])
Rewind dir_handle back to the start */
PHP_FUNCTION(rewinddir)
{
pval **id, **tmp, *myself;
php_dir *dirp;
FETCH_DIRP();
rewinddir(dirp->dir);
}
/* }}} */
/* {{{ proto string readdir([int dir_handle])
Read directory entry from dir_handle */
PHP_NAMED_FUNCTION(php_if_readdir)
{
pval **id, **tmp, *myself;
php_dir *dirp;
char entry[sizeof(struct dirent)+MAXPATHLEN];
struct dirent *result = (struct dirent *)&entry; /* patch for libc5 readdir problems */
FETCH_DIRP();
if (php_readdir_r(dirp->dir, (struct dirent *) entry, &result) == 0 && result) {
RETURN_STRINGL(result->d_name, strlen(result->d_name), 1);
}
RETURN_FALSE;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+230
View File
@@ -0,0 +1,230 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Brian Schaffner <brian@tool.net> |
| Shane Caraveo <shane@caraveo.com> |
| Zeev Suraski <zeev@zend.com> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "dl.h"
#include "php_globals.h"
#include "ext/standard/info.h"
#include "SAPI.h"
#ifndef PHP_WIN32
#include "build-defs.h"
#endif
#ifdef HAVE_LIBDL
#include <stdlib.h>
#include <stdio.h>
#if HAVE_STRING_H
#include <string.h>
#else
#include <strings.h>
#endif
#ifdef PHP_WIN32
#include "win32/param.h"
#include "win32/winutil.h"
#define GET_DL_ERROR() php_win_err()
#else
#include <sys/param.h>
#define GET_DL_ERROR() dlerror()
#endif
#endif
/* {{{ proto int dl(string extension_filename)
Load a PHP extension at runtime */
PHP_FUNCTION(dl)
{
pval **file;
#ifdef ZTS
if (strcmp(sapi_module.name, "cgi")!=0) {
php_error(E_ERROR, "dl() is not supported in multithreaded Web servers - use extension statements in your php.ini");
}
#endif
/* obtain arguments */
if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &file) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(file);
if (!PG(enable_dl)) {
php_error(E_ERROR, "Dynamically loaded extentions aren't enabled.");
} else if (PG(safe_mode)) {
php_error(E_ERROR, "Dynamically loaded extensions aren't allowed when running in SAFE MODE.");
} else {
php_dl(*file, MODULE_TEMPORARY, return_value TSRMLS_CC);
}
}
/* }}} */
#ifdef HAVE_LIBDL
#ifdef ZTS
#define USING_ZTS 1
#else
#define USING_ZTS 0
#endif
/* {{{ php_dl
*/
void php_dl(pval *file, int type, pval *return_value TSRMLS_DC)
{
void *handle;
char *libpath;
zend_module_entry *module_entry, *tmp;
zend_module_entry *(*get_module)(void);
int error_type;
char *extension_dir;
if (type==MODULE_PERSISTENT) {
/* Use the configuration hash directly, the INI mechanism is not yet initialized */
if (cfg_get_string("extension_dir", &extension_dir)==FAILURE) {
extension_dir = PHP_EXTENSION_DIR;
}
} else {
extension_dir = PG(extension_dir);
}
if (type==MODULE_TEMPORARY) {
error_type = E_WARNING;
} else {
error_type = E_CORE_WARNING;
}
if (extension_dir && extension_dir[0]){
int extension_dir_len = strlen(extension_dir);
libpath = emalloc(extension_dir_len+file->value.str.len+2);
if (IS_SLASH(extension_dir[extension_dir_len-1])) {
sprintf(libpath, "%s%s", extension_dir, file->value.str.val); /* SAFE */
} else {
sprintf(libpath, "%s/%s", extension_dir, file->value.str.val); /* SAFE */
}
} else {
libpath = estrndup(file->value.str.val, file->value.str.len);
}
/* load dynamic symbol */
handle = DL_LOAD(libpath);
if (!handle) {
php_error(error_type, "Unable to load dynamic library '%s' - %s", libpath, GET_DL_ERROR());
efree(libpath);
RETURN_FALSE;
}
efree(libpath);
get_module = (zend_module_entry *(*)(void)) DL_FETCH_SYMBOL(handle, "get_module");
/*
* some OS prepend _ to symbol names while their dynamic linker
* does not do that automatically. Thus we check manually for
* _get_module.
*/
if (!get_module)
get_module = (zend_module_entry *(*)(void)) DL_FETCH_SYMBOL(handle, "_get_module");
if (!get_module) {
DL_UNLOAD(handle);
php_error(error_type, "Invalid library (maybe not a PHP library) '%s' ", file->value.str.val);
RETURN_FALSE;
}
module_entry = get_module();
if ((module_entry->zend_debug != ZEND_DEBUG) || (module_entry->zts != USING_ZTS)
|| (module_entry->zend_api != ZEND_MODULE_API_NO)) {
php_error(error_type,
"%s: Unable to initialize module\n"
"Module compiled with debug=%d, thread-safety=%d module API=%d\n"
"PHP compiled with debug=%d, thread-safety=%d module API=%d\n"
"These options need to match\n",
module_entry->name, module_entry->zend_debug, module_entry->zts, module_entry->zend_api,
ZEND_DEBUG, USING_ZTS, ZEND_MODULE_API_NO);
DL_UNLOAD(handle);
RETURN_FALSE;
}
module_entry->type = type;
module_entry->module_number = zend_next_free_module();
if (module_entry->module_startup_func) {
if (module_entry->module_startup_func(type, module_entry->module_number TSRMLS_CC)==FAILURE) {
php_error(error_type, "%s: Unable to initialize module", module_entry->name);
DL_UNLOAD(handle);
RETURN_FALSE;
}
}
zend_register_module(module_entry);
if ((type == MODULE_TEMPORARY) && module_entry->request_startup_func) {
if (module_entry->request_startup_func(type, module_entry->module_number TSRMLS_CC)) {
php_error(error_type, "%s: Unable to initialize module", module_entry->name);
DL_UNLOAD(handle);
RETURN_FALSE;
}
}
/* update the .request_started property... */
if (zend_hash_find(&module_registry, module_entry->name, strlen(module_entry->name)+1, (void **) &tmp)==FAILURE) {
php_error(error_type, "%s: Loaded module got lost", module_entry->name);
RETURN_FALSE;
}
tmp->handle = handle;
RETURN_TRUE;
}
/* }}} */
PHP_MINFO_FUNCTION(dl)
{
php_info_print_table_row(2, "Dynamic Library Support", "enabled");
}
#else
void php_dl(pval *file, int type, pval *return_value)
{
php_error(E_WARNING, "Cannot dynamically load %s - dynamic modules are not supported", file->value.str.val);
RETURN_FALSE;
}
PHP_MINFO_FUNCTION(dl)
{
PUTS("Dynamic Library support not available<br>.\n");
}
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+34
View File
@@ -0,0 +1,34 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Brian Schaffner <brian@tool.net> |
| Shane Caraveo <shane@caraveo.com> |
| Zeev Suraski <zeev@zend.com> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef DL_H
#define DL_H
void php_dl(pval *file,int type,pval *return_value TSRMLS_DC);
/* dynamic loading functions */
PHP_FUNCTION(dl);
PHP_MINFO_FUNCTION(dl);
#endif /* DL_H */
+332
View File
@@ -0,0 +1,332 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: |
+----------------------------------------------------------------------+
*/
/* $Id$ */
/* {{{ includes
*/
#include "php.h"
#if HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef PHP_WIN32
#if HAVE_LIBBIND
#ifndef WINNT
#define WINNT 1
#endif
/* located in www.php.net/extra/bindlib.zip */
#if HAVE_ARPA_INET_H
#include "arpa/inet.h"
#endif
#include "netdb.h"
#if HAVE_ARPA_NAMESERV_H
#include "arpa/nameser.h"
#endif
#if HAVE_RESOLV_H
#include "resolv.h"
#endif
#endif
#include <winsock.h>
#else
#include <netinet/in.h>
#if HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#include <netdb.h>
#ifdef _OSD_POSIX
#undef STATUS
#undef T_UNSPEC
#endif
#if HAVE_ARPA_NAMESER_H
#include <arpa/nameser.h>
#endif
#if HAVE_RESOLV_H
#include <resolv.h>
#endif
#endif
#include "dns.h"
/* }}} */
static char *php_gethostbyaddr(char *ip);
static char *php_gethostbyname(char *name);
/* {{{ proto string gethostbyaddr(string ip_address)
Get the Internet host name corresponding to a given IP address */
PHP_FUNCTION(gethostbyaddr)
{
zval **arg;
char *addr;
if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &arg) == FAILURE) {
ZEND_WRONG_PARAM_COUNT();
}
convert_to_string_ex(arg);
addr = php_gethostbyaddr(Z_STRVAL_PP(arg));
if(addr == NULL) {
php_error(E_WARNING, "Address is not in a.b.c.d form");
RETVAL_FALSE;
} else {
RETVAL_STRING(addr, 0);
}
}
/* }}} */
/* {{{ php_gethostbyaddr
*/
static char *php_gethostbyaddr(char *ip)
{
struct in_addr addr;
struct hostent *hp;
addr.s_addr = inet_addr(ip);
if (addr.s_addr == -1) {
return NULL;
}
hp = gethostbyaddr((char *) &addr, sizeof(addr), AF_INET);
if (!hp) {
return estrdup(ip);
}
return estrdup(hp->h_name);
}
/* }}} */
/* {{{ proto string gethostbyname(string hostname)
Get the IP address corresponding to a given Internet host name */
PHP_FUNCTION(gethostbyname)
{
zval **arg;
if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &arg) == FAILURE) {
ZEND_WRONG_PARAM_COUNT();
}
convert_to_string_ex(arg);
RETVAL_STRING(php_gethostbyname(Z_STRVAL_PP(arg)), 0);
}
/* }}} */
/* {{{ proto array gethostbynamel(string hostname)
Return a list of IP addresses that a given hostname resolves to. */
PHP_FUNCTION(gethostbynamel)
{
zval **arg;
struct hostent *hp;
struct in_addr in;
int i;
if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &arg) == FAILURE) {
ZEND_WRONG_PARAM_COUNT();
}
convert_to_string_ex(arg);
if (array_init(return_value) == FAILURE) {
RETURN_FALSE;
}
hp = gethostbyname(Z_STRVAL_PP(arg));
if (hp == NULL || hp->h_addr_list == NULL) {
RETURN_FALSE;
}
for (i = 0 ; hp->h_addr_list[i] != 0 ; i++) {
in = *(struct in_addr *) hp->h_addr_list[i];
add_next_index_string(return_value, inet_ntoa(in), 1);
}
}
/* }}} */
/* {{{ php_gethostbyname
*/
static char *php_gethostbyname(char *name)
{
struct hostent *hp;
struct in_addr in;
hp = gethostbyname(name);
if (!hp || !hp->h_addr_list) {
return estrdup(name);
}
memcpy(&in.s_addr, *(hp->h_addr_list), sizeof(in.s_addr));
return estrdup(inet_ntoa(in));
}
/* }}} */
#if HAVE_RES_SEARCH && !(defined(__BEOS__)||defined(PHP_WIN32))
/* {{{ proto int checkdnsrr(string host [, string type])
Check DNS records corresponding to a given Internet host name or IP address */
PHP_FUNCTION(checkdnsrr)
{
zval **arg1, **arg2;
int type, i;
#ifndef MAXPACKET
#define MAXPACKET 8192 /* max packet size used internally by BIND */
#endif
u_char ans[MAXPACKET];
switch (ZEND_NUM_ARGS()) {
case 1:
if (zend_get_parameters_ex(1, &arg1) == FAILURE) {
WRONG_PARAM_COUNT;
}
type = T_MX;
convert_to_string_ex(arg1);
break;
case 2:
if (zend_get_parameters_ex(2, &arg1, &arg2) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(arg1);
convert_to_string_ex(arg2);
if ( !strcasecmp("A", Z_STRVAL_PP(arg2)) ) type = T_A;
else if ( !strcasecmp("NS", Z_STRVAL_PP(arg2)) ) type = T_NS;
else if ( !strcasecmp("MX", Z_STRVAL_PP(arg2)) ) type = T_MX;
else if ( !strcasecmp("PTR", Z_STRVAL_PP(arg2)) ) type = T_PTR;
else if ( !strcasecmp("ANY", Z_STRVAL_PP(arg2)) ) type = T_ANY;
else if ( !strcasecmp("SOA", Z_STRVAL_PP(arg2)) ) type = T_SOA;
else if ( !strcasecmp("CNAME", Z_STRVAL_PP(arg2)) ) type = T_CNAME;
else {
php_error(E_WARNING, "Type '%s' not supported", Z_STRVAL_PP(arg2));
RETURN_FALSE;
}
break;
default:
WRONG_PARAM_COUNT;
}
i = res_search(Z_STRVAL_PP(arg1), C_IN, type, ans, sizeof(ans));
if ( i < 0 ) {
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
#ifndef HFIXEDSZ
#define HFIXEDSZ 12 /* fixed data in header <arpa/nameser.h> */
#endif /* HFIXEDSZ */
#ifndef QFIXEDSZ
#define QFIXEDSZ 4 /* fixed data in query <arpa/nameser.h> */
#endif /* QFIXEDSZ */
#ifndef MAXHOSTNAMELEN
#define MAXHOSTNAMELEN 256
#endif /* MAXHOSTNAMELEN */
/* {{{ proto int getmxrr(string hostname, array mxhosts [, array weight])
Get MX records corresponding to a given Internet host name */
PHP_FUNCTION(getmxrr)
{
pval *host, *mx_list, *weight_list;
int need_weight = 0;
int count, qdc;
u_short type, weight;
u_char ans[MAXPACKET];
char buf[MAXHOSTNAMELEN];
HEADER *hp;
u_char *cp, *end;
int i;
switch(ZEND_NUM_ARGS()) {
case 2:
if (zend_get_parameters(ht, 2, &host, &mx_list) == FAILURE) {
WRONG_PARAM_COUNT;
}
break;
case 3:
if (zend_get_parameters(ht, 3, &host, &mx_list, &weight_list) == FAILURE) {
WRONG_PARAM_COUNT;
}
need_weight = 1;
pval_destructor(weight_list); /* start with clean array */
if ( array_init(weight_list) == FAILURE ) {
RETURN_FALSE;
}
break;
default:
WRONG_PARAM_COUNT;
}
convert_to_string( host );
pval_destructor(mx_list); /* start with clean array */
if ( array_init(mx_list) == FAILURE ) {
RETURN_FALSE;
}
/* Go! */
i = res_search(Z_STRVAL_P(host), C_IN, T_MX, (u_char *)&ans, sizeof(ans));
if ( i < 0 ) {
RETURN_FALSE;
}
if ( i > sizeof(ans) ) i = sizeof(ans);
hp = (HEADER *)&ans;
cp = (u_char *)&ans + HFIXEDSZ;
end = (u_char *)&ans +i;
for ( qdc = ntohs((unsigned short)hp->qdcount); qdc--; cp += i + QFIXEDSZ) {
if ( (i = dn_skipname(cp, end)) < 0 ) {
RETURN_FALSE;
}
}
count = ntohs((unsigned short)hp->ancount);
while ( --count >= 0 && cp < end ) {
if ( (i = dn_skipname(cp, end)) < 0 ) {
RETURN_FALSE;
}
cp += i;
GETSHORT(type, cp);
cp += INT16SZ + INT32SZ;
GETSHORT(i, cp);
if ( type != T_MX ) {
cp += i;
continue;
}
GETSHORT(weight, cp);
if ( (i = dn_expand(ans, end, cp, buf, sizeof(buf)-1)) < 0 ) {
RETURN_FALSE;
}
cp += i;
add_next_index_string(mx_list, buf, 1);
if ( need_weight ) {
add_next_index_long(weight_list, weight);
}
}
RETURN_TRUE;
}
/* }}} */
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+42
View File
@@ -0,0 +1,42 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: |
| |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef DNS_H
#define DNS_H
PHP_FUNCTION(gethostbyaddr);
PHP_FUNCTION(gethostbyname);
PHP_FUNCTION(gethostbynamel);
#if HAVE_RES_SEARCH && !(defined(__BEOS__)||defined(PHP_WIN32))
PHP_FUNCTION(checkdnsrr);
PHP_FUNCTION(getmxrr);
#endif
#ifndef INT16SZ
#define INT16SZ 2
#endif
#ifndef INT32SZ
#define INT32SZ 4
#endif
#endif /* DNS_H */
+487
View File
@@ -0,0 +1,487 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Rasmus Lerdorf |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include <stdio.h>
#include "php.h"
#include <ctype.h>
#include "php_string.h"
#include "safe_mode.h"
#include "ext/standard/head.h"
#include "ext/standard/file.h"
#include "exec.h"
#include "php_globals.h"
#include "SAPI.h"
#if HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#if HAVE_SIGNAL_H
#include <signal.h>
#endif
/* {{{ php_Exec
* If type==0, only last line of output is returned (exec)
* If type==1, all lines will be printed and last lined returned (system)
* If type==2, all lines will be saved to given array (exec with &$array)
* If type==3, output will be printed binary, no lines will be saved or returned (passthru)
*
*/
int php_Exec(int type, char *cmd, pval *array, pval *return_value TSRMLS_DC)
{
FILE *fp;
char *buf, *tmp=NULL;
int buflen = 0;
int t, l, output=1;
int overflow_limit, lcmd, ldir;
int rsrc_id;
char *b, *c, *d=NULL;
#if PHP_SIGCHILD
void (*sig_handler)();
#endif
buf = (char*) emalloc(EXEC_INPUT_BUF);
if (!buf) {
php_error(E_WARNING, "Unable to emalloc %d bytes for exec buffer", EXEC_INPUT_BUF);
return -1;
}
buflen = EXEC_INPUT_BUF;
if (PG(safe_mode)) {
lcmd = strlen(cmd);
ldir = strlen(PG(safe_mode_exec_dir));
l = lcmd + ldir + 2;
overflow_limit = l;
c = strchr(cmd, ' ');
if (c) *c = '\0';
if (strstr(cmd, "..")) {
php_error(E_WARNING, "No '..' components allowed in path");
efree(buf);
return -1;
}
d = emalloc(l);
strcpy(d, PG(safe_mode_exec_dir));
overflow_limit -= ldir;
b = strrchr(cmd, PHP_DIR_SEPARATOR);
if (b) {
strcat(d, b);
overflow_limit -= strlen(b);
} else {
strcat(d, "/");
strcat(d, cmd);
overflow_limit-=(strlen(cmd)+1);
}
if (c) {
*c = ' ';
strncat(d, c, overflow_limit);
}
tmp = php_escape_shell_cmd(d);
efree(d);
d = tmp;
#if PHP_SIGCHILD
sig_handler = signal (SIGCHLD, SIG_DFL);
#endif
#ifdef PHP_WIN32
fp = VCWD_POPEN(d, "rb");
#else
fp = VCWD_POPEN(d, "r");
#endif
if (!fp) {
php_error(E_WARNING, "Unable to fork [%s]", d);
efree(d);
efree(buf);
#if PHP_SIGCHILD
signal (SIGCHLD, sig_handler);
#endif
return -1;
}
} else { /* not safe_mode */
#if PHP_SIGCHILD
sig_handler = signal (SIGCHLD, SIG_DFL);
#endif
#ifdef PHP_WIN32
fp = VCWD_POPEN(cmd, "rb");
#else
fp = VCWD_POPEN(cmd, "r");
#endif
if (!fp) {
php_error(E_WARNING, "Unable to fork [%s]", cmd);
efree(buf);
#if PHP_SIGCHILD
signal (SIGCHLD, sig_handler);
#endif
return -1;
}
}
buf[0] = '\0';
if (type==2) {
if (Z_TYPE_P(array) != IS_ARRAY) {
pval_destructor(array);
array_init(array);
}
}
/* we register the resource so that case of an aborted connection the
* fd gets pclosed
*/
rsrc_id = ZEND_REGISTER_RESOURCE(NULL, fp, php_file_le_popen());
if (type != 3) {
l=0;
while ( !feof(fp) || l != 0 ) {
l = 0;
/* Read a line or fill the buffer, whichever comes first */
do {
if ( buflen <= (l+1) ) {
buf = erealloc(buf, buflen + EXEC_INPUT_BUF);
if ( buf == NULL ) {
php_error(E_WARNING, "Unable to erealloc %d bytes for exec buffer",
buflen + EXEC_INPUT_BUF);
#if PHP_SIGCHILD
signal (SIGCHLD, sig_handler);
#endif
return -1;
}
buflen += EXEC_INPUT_BUF;
}
if ( fgets(&(buf[l]), buflen - l, fp) == NULL ) {
/* eof */
break;
}
l += strlen(&(buf[l]));
} while ( (l > 0) && (buf[l-1] != '\n') );
if ( feof(fp) && (l == 0) ) {
break;
}
if (type == 1) {
if (output) PUTS(buf);
sapi_flush(TSRMLS_C);
}
else if (type == 2) {
/* strip trailing whitespaces */
l = strlen(buf);
t = l;
while (l-- && isspace((int)buf[l]));
if (l < t) {
buf[l + 1] = '\0';
}
add_next_index_string(array, buf, 1);
}
}
/* strip trailing spaces */
l = strlen(buf);
t = l;
while (l && isspace((int)buf[l - 1])) {
l--;
}
if (l < t) buf[l] = '\0';
/* Return last line from the shell command */
if (PG(magic_quotes_runtime)) {
int len;
tmp = php_addslashes(buf, 0, &len, 0 TSRMLS_CC);
RETVAL_STRINGL(tmp, len, 0);
} else {
RETVAL_STRINGL(buf, l, 1);
}
} else {
int b, i;
while ((b = fread(buf, 1, buflen, fp)) > 0) {
for (i = 0; i < b; i++)
if (output) (void)PUTC(buf[i]);
}
}
/* the zend_list_delete will pclose our popen'ed process */
zend_list_delete(rsrc_id);
#if HAVE_SYS_WAIT_H
if (WIFEXITED(FG(pclose_ret))) {
FG(pclose_ret) = WEXITSTATUS(FG(pclose_ret));
}
#endif
#if PHP_SIGCHILD
signal (SIGCHLD, sig_handler);
#endif
if (d) {
efree(d);
}
efree(buf);
return FG(pclose_ret);
}
/* }}} */
/* {{{ proto string exec(string command [, array output [, int return_value]])
Execute an external program */
PHP_FUNCTION(exec)
{
pval **arg1, **arg2, **arg3;
int arg_count = ZEND_NUM_ARGS();
int ret;
if (arg_count > 3 || zend_get_parameters_ex(arg_count, &arg1, &arg2, &arg3) == FAILURE) {
WRONG_PARAM_COUNT;
}
switch (arg_count) {
case 1:
ret = php_Exec(0, Z_STRVAL_PP(arg1), NULL, return_value TSRMLS_CC);
break;
case 2:
ret = php_Exec(2, Z_STRVAL_PP(arg1), *arg2, return_value TSRMLS_CC);
break;
case 3:
ret = php_Exec(2, Z_STRVAL_PP(arg1), *arg2, return_value TSRMLS_CC);
Z_TYPE_PP(arg3) = IS_LONG;
Z_LVAL_PP(arg3)=ret;
break;
}
}
/* }}} */
/* {{{ proto int system(string command [, int return_value])
Execute an external program and display output */
PHP_FUNCTION(system)
{
pval **arg1, **arg2;
int arg_count = ZEND_NUM_ARGS();
int ret;
if (arg_count > 2 || zend_get_parameters_ex(arg_count, &arg1, &arg2) == FAILURE) {
WRONG_PARAM_COUNT;
}
switch (arg_count) {
case 1:
ret = php_Exec(1, Z_STRVAL_PP(arg1), NULL, return_value TSRMLS_CC);
break;
case 2:
ret = php_Exec(1, Z_STRVAL_PP(arg1), NULL, return_value TSRMLS_CC);
Z_TYPE_PP(arg2) = IS_LONG;
Z_LVAL_PP(arg2)=ret;
break;
}
}
/* }}} */
/* {{{ proto void passthru(string command [, int return_value])
Execute an external program and display raw output */
PHP_FUNCTION(passthru)
{
pval **arg1, **arg2;
int arg_count = ZEND_NUM_ARGS();
int ret;
if (arg_count > 2 || zend_get_parameters_ex(arg_count, &arg1, &arg2) == FAILURE) {
WRONG_PARAM_COUNT;
}
switch (arg_count) {
case 1:
ret = php_Exec(3, Z_STRVAL_PP(arg1), NULL, return_value TSRMLS_CC);
break;
case 2:
ret = php_Exec(3, Z_STRVAL_PP(arg1), NULL, return_value TSRMLS_CC);
Z_TYPE_PP(arg2) = IS_LONG;
Z_LVAL_PP(arg2)=ret;
break;
}
}
/* }}} */
/* {{{ php_escape_shell_cmd
Escape all chars that could possibly be used to
break out of a shell command
This function emalloc's a string and returns the pointer.
Remember to efree it when done with it.
*NOT* safe for binary strings
*/
char *php_escape_shell_cmd(char *str) {
register int x, y, l;
char *cmd;
l = strlen(str);
cmd = emalloc(2 * l + 1);
for (x = 0, y = 0; x < l; x++) {
switch (str[x]) {
case '#': /* This is character-set independent */
case '&':
case ';':
case '`':
case '\'':
case '"':
case '|':
case '*':
case '?':
case '~':
case '<':
case '>':
case '^':
case '(':
case ')':
case '[':
case ']':
case '{':
case '}':
case '$':
case '\\':
case '\x0A': /* excluding these two */
case '\xFF':
cmd[y++] = '\\';
/* fall-through */
default:
cmd[y++] = str[x];
}
}
cmd[y] = '\0';
return cmd;
}
/* }}} */
/* {{{ php_escape_shell_arg
*/
char *php_escape_shell_arg(char *str) {
int x, y, l;
char *cmd;
y = 0;
l = strlen(str);
cmd = emalloc(4 * l + 3); /* worst case */
cmd[y++] = '\'';
for (x = 0; x < l; x++) {
switch (str[x]) {
case '\'':
cmd[y++] = '\'';
cmd[y++] = '\\';
cmd[y++] = '\'';
/* fall-through */
default:
cmd[y++] = str[x];
}
}
cmd[y++] = '\'';
cmd[y] = '\0';
return cmd;
}
/* }}} */
/* {{{ proto string escapeshellcmd(string command)
Escape shell metacharacters */
PHP_FUNCTION(escapeshellcmd)
{
pval **arg1;
char *cmd = NULL;
if (zend_get_parameters_ex(1, &arg1) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(arg1);
if (Z_STRLEN_PP(arg1)) {
cmd = php_escape_shell_cmd(Z_STRVAL_PP(arg1));
RETVAL_STRING(cmd, 1);
efree(cmd);
}
}
/* }}} */
/* {{{ proto string escapeshellarg(string arg)
Quote and escape an argument for use in a shell command */
PHP_FUNCTION(escapeshellarg)
{
pval **arg1;
char *cmd = NULL;
if (zend_get_parameters_ex(1, &arg1) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(arg1);
if (Z_STRLEN_PP(arg1)) {
cmd = php_escape_shell_arg(Z_STRVAL_PP(arg1));
RETVAL_STRING(cmd, 1);
efree(cmd);
}
}
/* }}} */
/* {{{ proto string shell_exec(string cmd)
Use pclose() for FILE* that has been opened via popen() */
PHP_FUNCTION(shell_exec)
{
FILE *in;
int readbytes, total_readbytes=0, allocated_space;
pval **cmd;
char *ret;
if (ZEND_NUM_ARGS()!=1 || zend_get_parameters_ex(1, &cmd)==FAILURE) {
WRONG_PARAM_COUNT;
}
if (PG(safe_mode)) {
php_error(E_WARNING, "Cannot execute using backquotes in safe mode");
RETURN_FALSE;
}
convert_to_string_ex(cmd);
#ifdef PHP_WIN32
if ((in=VCWD_POPEN(Z_STRVAL_PP(cmd), "rt"))==NULL) {
#else
if ((in=VCWD_POPEN(Z_STRVAL_PP(cmd), "r"))==NULL) {
#endif
php_error(E_WARNING, "Unable to execute '%s'", Z_STRVAL_PP(cmd));
}
allocated_space = EXEC_INPUT_BUF;
ret = (char *) emalloc(allocated_space);
while (1) {
readbytes = fread(ret+total_readbytes, 1, EXEC_INPUT_BUF, in);
if (readbytes<=0) {
break;
}
total_readbytes += readbytes;
allocated_space = total_readbytes+EXEC_INPUT_BUF;
ret = (char *) erealloc(ret, allocated_space);
}
pclose(in);
RETVAL_STRINGL(ret, total_readbytes, 0);
Z_STRVAL_P(return_value)[total_readbytes] = '\0';
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+35
View File
@@ -0,0 +1,35 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef EXEC_H
#define EXEC_H
PHP_FUNCTION(system);
PHP_FUNCTION(exec);
PHP_FUNCTION(escapeshellcmd);
PHP_FUNCTION(escapeshellarg);
PHP_FUNCTION(passthru);
PHP_FUNCTION(shell_exec);
char *php_escape_shell_cmd(char *);
char *php_escape_shell_arg(char *);
int php_Exec(int type, char *cmd, pval *array, pval *return_value TSRMLS_DC);
#endif /* EXEC_H */
+2357
View File
File diff suppressed because it is too large. Load diff
+127
View File
@@ -0,0 +1,127 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
/* Synced with php 3.0 revision 1.30 1999-06-16 [ssb] */
#ifndef FILE_H
#define FILE_H
PHP_MINIT_FUNCTION(file);
PHP_MSHUTDOWN_FUNCTION(file);
PHP_FUNCTION(tempnam);
PHP_NAMED_FUNCTION(php_if_tmpfile);
PHP_NAMED_FUNCTION(php_if_fopen);
PHP_FUNCTION(fclose);
PHP_FUNCTION(popen);
PHP_FUNCTION(pclose);
PHP_FUNCTION(feof);
PHP_FUNCTION(fread);
PHP_FUNCTION(fgetc);
PHP_FUNCTION(fgets);
PHP_FUNCTION(fscanf);
PHP_FUNCTION(fgetss);
PHP_FUNCTION(fgetcsv);
PHP_FUNCTION(fwrite);
PHP_FUNCTION(fflush);
PHP_FUNCTION(rewind);
PHP_FUNCTION(ftell);
PHP_FUNCTION(fseek);
PHP_FUNCTION(mkdir);
PHP_FUNCTION(rmdir);
PHP_FUNCTION(fpassthru);
PHP_FUNCTION(readfile);
PHP_FUNCTION(umask);
PHP_FUNCTION(rename);
PHP_FUNCTION(unlink);
PHP_FUNCTION(copy);
PHP_FUNCTION(file);
PHP_FUNCTION(set_socket_blocking); /* deprecated */
PHP_FUNCTION(socket_set_blocking);
PHP_FUNCTION(socket_set_timeout);
PHP_FUNCTION(socket_get_status);
PHP_FUNCTION(set_file_buffer);
PHP_FUNCTION(get_meta_tags);
PHP_FUNCTION(flock);
PHP_FUNCTION(fd_set);
PHP_FUNCTION(fd_isset);
PHP_FUNCTION(select);
PHP_FUNCTION(realpath);
PHP_NAMED_FUNCTION(php_if_ftruncate);
PHP_NAMED_FUNCTION(php_if_fstat);
/* temporary function for testing streams */
PHP_FUNCTION(fopenstream);
PHPAPI int php_set_sock_blocking(int socketd, int block);
PHPAPI int php_file_le_fopen(void);
PHPAPI int php_file_le_stream(void);
PHPAPI int php_file_le_popen(void);
PHPAPI int php_file_le_socket(void);
PHPAPI int php_copy_file(char *src, char *dest TSRMLS_DC);
#define META_DEF_BUFSIZE 8192
typedef enum _php_meta_tags_token {
TOK_EOF = 0,
TOK_OPENTAG,
TOK_CLOSETAG,
TOK_SLASH,
TOK_EQUAL,
TOK_SPACE,
TOK_ID,
TOK_STRING,
TOK_OTHER
} php_meta_tags_token;
typedef struct _php_meta_tags_data {
FILE *fp;
int socketd;
int issock;
int ulc;
int lc;
char *input_buffer;
char *token_data;
int token_len;
int in_meta;
} php_meta_tags_data;
php_meta_tags_token php_next_meta_token(php_meta_tags_data *);
typedef struct {
int fgetss_state;
int pclose_ret;
HashTable ht_fsock_keys;
HashTable ht_fsock_socks;
struct php_sockbuf *phpsockbuf;
size_t def_chunk_size;
} php_file_globals;
#ifdef ZTS
#define FG(v) TSRMG(file_globals_id, php_file_globals *, v)
extern int file_globals_id;
#else
#define FG(v) (file_globals.v)
extern php_file_globals file_globals;
#endif
#endif /* FILE_H */
+875
View File
@@ -0,0 +1,875 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Jim Winstead <jimw@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "safe_mode.h"
#include "fopen_wrappers.h"
#include "php_globals.h"
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <time.h>
#if HAVE_UNISTD_H
# include <unistd.h>
#endif
#if HAVE_SYS_VFS_H
# include <sys/vfs.h>
#endif
#ifdef OS2
# define INCL_DOS
# include <os2.h>
#endif
#if defined(HAVE_SYS_STATVFS_H) && defined(HAVE_STATVFS)
# include <sys/statvfs.h>
#elif defined(HAVE_SYS_STATFS_H) && defined(HAVE_STATFS)
# include <sys/statfs.h>
#elif defined(HAVE_SYS_MOUNT_H) && defined(HAVE_STATFS)
# include <sys/mount.h>
#endif
#if HAVE_PWD_H
# ifdef PHP_WIN32
# include "win32/pwd.h"
# else
# include <pwd.h>
# endif
#endif
#if HAVE_GRP_H
# ifdef PHP_WIN32
# include "win32/grp.h"
# else
# include <grp.h>
# endif
#endif
#if HAVE_UTIME
# ifdef PHP_WIN32
# include <sys/utime.h>
# else
# include <utime.h>
# endif
#endif
#include "basic_functions.h"
#include "php_filestat.h"
#ifndef S_ISDIR
#define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR)
#endif
#ifndef S_ISREG
#define S_ISREG(mode) (((mode)&S_IFMT) == S_IFREG)
#endif
#ifndef S_ISLNK
#define S_ISLNK(mode) (((mode)&S_IFMT) == S_IFLNK)
#endif
#define S_IXROOT ( S_IXUSR | S_IXGRP | S_IXOTH )
/* Switches for various filestat functions: */
#define FS_PERMS 0
#define FS_INODE 1
#define FS_SIZE 2
#define FS_OWNER 3
#define FS_GROUP 4
#define FS_ATIME 5
#define FS_MTIME 6
#define FS_CTIME 7
#define FS_TYPE 8
#define FS_IS_W 9
#define FS_IS_R 10
#define FS_IS_X 11
#define FS_IS_FILE 12
#define FS_IS_DIR 13
#define FS_IS_LINK 14
#define FS_EXISTS 15
#define FS_LSTAT 16
#define FS_STAT 17
PHP_RINIT_FUNCTION(filestat)
{
BG(CurrentStatFile)=NULL;
BG(CurrentStatLength)=0;
return SUCCESS;
}
PHP_RSHUTDOWN_FUNCTION(filestat) {
if (BG(CurrentStatFile)) {
efree (BG(CurrentStatFile));
}
return SUCCESS;
}
/* {{{ proto double disk_total_space(string path)
Get total disk space for filesystem that path is on */
PHP_FUNCTION(disk_total_space)
{
pval **path;
#ifdef WINDOWS
double bytestotal;
HINSTANCE kernel32;
FARPROC gdfse;
typedef BOOL (WINAPI *gdfse_func)(LPCTSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
gdfse_func func;
/* These are used by GetDiskFreeSpaceEx, if available. */
ULARGE_INTEGER FreeBytesAvailableToCaller;
ULARGE_INTEGER TotalNumberOfBytes;
ULARGE_INTEGER TotalNumberOfFreeBytes;
/* These are used by GetDiskFreeSpace otherwise. */
DWORD SectorsPerCluster;
DWORD BytesPerSector;
DWORD NumberOfFreeClusters;
DWORD TotalNumberOfClusters;
#else /* not - WINDOWS */
#if defined(HAVE_SYS_STATVFS_H) && defined(HAVE_STATVFS)
struct statvfs buf;
#elif (defined(HAVE_SYS_STATFS_H) || defined(HAVE_SYS_MOUNT_H)) && defined(HAVE_STATFS)
struct statfs buf;
#endif
double bytestotal = 0;
#endif /* WINDOWS */
if (ZEND_NUM_ARGS()!=1 || zend_get_parameters_ex(1, &path)==FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(path);
if (php_check_open_basedir((*path)->value.str.val TSRMLS_CC)) {
RETURN_FALSE;
}
#ifdef WINDOWS
/* GetDiskFreeSpaceEx is only available in NT and Win95 post-OSR2,
so we have to jump through some hoops to see if the function
exists. */
kernel32 = LoadLibrary("kernel32.dll");
if (kernel32) {
gdfse = GetProcAddress(kernel32, "GetDiskFreeSpaceExA");
/* It's available, so we can call it. */
if (gdfse) {
func = (gdfse_func)gdfse;
if (func((*path)->value.str.val,
&FreeBytesAvailableToCaller,
&TotalNumberOfBytes,
&TotalNumberOfFreeBytes) == 0) RETURN_FALSE;
/* i know - this is ugly, but i works (thies@thieso.net) */
bytestotal = TotalNumberOfBytes.HighPart *
(double) (((unsigned long)1) << 31) * 2.0 +
TotalNumberOfBytes.LowPart;
}
/* If it's not available, we just use GetDiskFreeSpace */
else {
if (GetDiskFreeSpace((*path)->value.str.val,
&SectorsPerCluster, &BytesPerSector,
&NumberOfFreeClusters, &TotalNumberOfClusters) == 0) RETURN_FALSE;
bytestotal = (double)TotalNumberOfClusters * (double)SectorsPerCluster * (double)BytesPerSector;
}
}
else {
php_error(E_WARNING, "Unable to load kernel32.dll");
RETURN_FALSE;
}
#elif defined(OS2)
{
FSALLOCATE fsinfo;
char drive = (*path)->value.str.val[0] & 95;
if (DosQueryFSInfo( drive ? drive - 64 : 0, FSIL_ALLOC, &fsinfo, sizeof( fsinfo ) ) == 0)
bytestotal = (double)fsinfo.cbSector * fsinfo.cSectorUnit * fsinfo.cUnit;
}
#else /* WINDOWS, OS/2 */
#if defined(HAVE_SYS_STATVFS_H) && defined(HAVE_STATVFS)
if (statvfs((*path)->value.str.val, &buf)) RETURN_FALSE;
if (buf.f_frsize) {
bytestotal = (((double)buf.f_blocks) * ((double)buf.f_frsize));
} else {
bytestotal = (((double)buf.f_blocks) * ((double)buf.f_bsize));
}
#elif (defined(HAVE_SYS_STATFS_H) || defined(HAVE_SYS_MOUNT_H)) && defined(HAVE_STATFS)
if (statfs((*path)->value.str.val, &buf)) RETURN_FALSE;
bytestotal = (((double)buf.f_bsize) * ((double)buf.f_blocks));
#endif
#endif /* WINDOWS */
RETURN_DOUBLE(bytestotal);
}
/* }}} */
/* {{{ proto double disk_free_space(string path)
Get free disk space for filesystem that path is on */
PHP_FUNCTION(disk_free_space)
{
pval **path;
#ifdef WINDOWS
double bytesfree;
HINSTANCE kernel32;
FARPROC gdfse;
typedef BOOL (WINAPI *gdfse_func)(LPCTSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
gdfse_func func;
/* These are used by GetDiskFreeSpaceEx, if available. */
ULARGE_INTEGER FreeBytesAvailableToCaller;
ULARGE_INTEGER TotalNumberOfBytes;
ULARGE_INTEGER TotalNumberOfFreeBytes;
/* These are used by GetDiskFreeSpace otherwise. */
DWORD SectorsPerCluster;
DWORD BytesPerSector;
DWORD NumberOfFreeClusters;
DWORD TotalNumberOfClusters;
#else /* not - WINDOWS */
#if defined(HAVE_SYS_STATVFS_H) && defined(HAVE_STATVFS)
struct statvfs buf;
#elif (defined(HAVE_SYS_STATFS_H) || defined(HAVE_SYS_MOUNT_H)) && defined(HAVE_STATFS)
struct statfs buf;
#endif
double bytesfree = 0;
#endif /* WINDOWS */
if (ZEND_NUM_ARGS()!=1 || zend_get_parameters_ex(1, &path)==FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(path);
if (php_check_open_basedir((*path)->value.str.val TSRMLS_CC)) {
RETURN_FALSE;
}
#ifdef WINDOWS
/* GetDiskFreeSpaceEx is only available in NT and Win95 post-OSR2,
so we have to jump through some hoops to see if the function
exists. */
kernel32 = LoadLibrary("kernel32.dll");
if (kernel32) {
gdfse = GetProcAddress(kernel32, "GetDiskFreeSpaceExA");
/* It's available, so we can call it. */
if (gdfse) {
func = (gdfse_func)gdfse;
if (func((*path)->value.str.val,
&FreeBytesAvailableToCaller,
&TotalNumberOfBytes,
&TotalNumberOfFreeBytes) == 0) RETURN_FALSE;
/* i know - this is ugly, but i works (thies@thieso.net) */
bytesfree = FreeBytesAvailableToCaller.HighPart *
(double) (((unsigned long)1) << 31) * 2.0 +
FreeBytesAvailableToCaller.LowPart;
}
/* If it's not available, we just use GetDiskFreeSpace */
else {
if (GetDiskFreeSpace((*path)->value.str.val,
&SectorsPerCluster, &BytesPerSector,
&NumberOfFreeClusters, &TotalNumberOfClusters) == 0) RETURN_FALSE;
bytesfree = (double)NumberOfFreeClusters * (double)SectorsPerCluster * (double)BytesPerSector;
}
}
else {
php_error(E_WARNING, "Unable to load kernel32.dll");
RETURN_FALSE;
}
#elif defined(OS2)
{
FSALLOCATE fsinfo;
char drive = (*path)->value.str.val[0] & 95;
if (DosQueryFSInfo( drive ? drive - 64 : 0, FSIL_ALLOC, &fsinfo, sizeof( fsinfo ) ) == 0)
bytesfree = (double)fsinfo.cbSector * fsinfo.cSectorUnit * fsinfo.cUnitAvail;
}
#else /* WINDOWS, OS/2 */
#if defined(HAVE_SYS_STATVFS_H) && defined(HAVE_STATVFS)
if (statvfs((*path)->value.str.val, &buf)) RETURN_FALSE;
if (buf.f_frsize) {
bytesfree = (((double)buf.f_bavail) * ((double)buf.f_frsize));
} else {
bytesfree = (((double)buf.f_bavail) * ((double)buf.f_bsize));
}
#elif (defined(HAVE_SYS_STATFS_H) || defined(HAVE_SYS_MOUNT_H)) && defined(HAVE_STATFS)
if (statfs((*path)->value.str.val, &buf)) RETURN_FALSE;
bytesfree = (((double)buf.f_bsize) * ((double)buf.f_bavail));
#endif
#endif /* WINDOWS */
RETURN_DOUBLE(bytesfree);
}
/* }}} */
/* {{{ proto bool chgrp(string filename, mixed group)
Change file group */
PHP_FUNCTION(chgrp)
{
#ifndef WINDOWS
pval **filename, **group;
gid_t gid;
struct group *gr=NULL;
int ret;
if (ZEND_NUM_ARGS()!=2 || zend_get_parameters_ex(2, &filename, &group)==FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(filename);
if ((*group)->type == IS_STRING) {
gr = getgrnam((*group)->value.str.val);
if (!gr) {
php_error(E_WARNING, "unable to find gid for %s",
(*group)->value.str.val);
RETURN_FALSE;
}
gid = gr->gr_gid;
} else {
convert_to_long_ex(group);
gid = (*group)->value.lval;
}
if (PG(safe_mode) &&(!php_checkuid((*filename)->value.str.val, NULL, CHECKUID_ALLOW_FILE_NOT_EXISTS))) {
RETURN_FALSE;
}
/* Check the basedir */
if (php_check_open_basedir((*filename)->value.str.val TSRMLS_CC)) {
RETURN_FALSE;
}
ret = VCWD_CHOWN((*filename)->value.str.val, -1, gid);
if (ret == -1) {
php_error(E_WARNING, "chgrp failed: %s", strerror(errno));
RETURN_FALSE;
}
RETURN_TRUE;
#else
RETURN_FALSE;
#endif
}
/* }}} */
/* {{{ proto bool chown (string filename, mixed user)
Change file owner */
PHP_FUNCTION(chown)
{
#ifndef WINDOWS
pval **filename, **user;
int ret;
uid_t uid;
struct passwd *pw = NULL;
if (ZEND_NUM_ARGS()!=2 || zend_get_parameters_ex(2, &filename, &user)==FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(filename);
if ((*user)->type == IS_STRING) {
pw = getpwnam((*user)->value.str.val);
if (!pw) {
php_error(E_WARNING, "unable to find uid for %s",
(*user)->value.str.val);
RETURN_FALSE;
}
uid = pw->pw_uid;
} else {
convert_to_long_ex(user);
uid = (*user)->value.lval;
}
if (PG(safe_mode) &&(!php_checkuid((*filename)->value.str.val, NULL, CHECKUID_ALLOW_FILE_NOT_EXISTS))) {
RETURN_FALSE;
}
/* Check the basedir */
if (php_check_open_basedir((*filename)->value.str.val TSRMLS_CC)) {
RETURN_FALSE;
}
ret = VCWD_CHOWN((*filename)->value.str.val, uid, -1);
if (ret == -1) {
php_error(E_WARNING, "chown failed: %s", strerror(errno));
RETURN_FALSE;
}
#endif
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool chmod(string filename, int mode)
Change file mode */
PHP_FUNCTION(chmod)
{
pval **filename, **mode;
int ret;
mode_t imode;
if (ZEND_NUM_ARGS()!=2 || zend_get_parameters_ex(2, &filename, &mode)==FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(filename);
convert_to_long_ex(mode);
if (PG(safe_mode) &&(!php_checkuid((*filename)->value.str.val, NULL, CHECKUID_ALLOW_FILE_NOT_EXISTS))) {
RETURN_FALSE;
}
/* Check the basedir */
if (php_check_open_basedir((*filename)->value.str.val TSRMLS_CC)) {
RETURN_FALSE;
}
imode = (mode_t) (*mode)->value.lval;
/* in safe mode, do not allow to setuid files.
Setuiding files could allow users to gain privileges
that safe mode doesn't give them.
*/
if(PG(safe_mode))
imode &= 0777;
ret = VCWD_CHMOD((*filename)->value.str.val, imode);
if (ret == -1) {
php_error(E_WARNING, "chmod failed: %s", strerror(errno));
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool touch(string filename [, int time])
Set modification time of file */
PHP_FUNCTION(touch)
{
#if HAVE_UTIME
pval **filename, **filetime;
int ret;
struct stat sb;
FILE *file;
struct utimbuf *newtime = NULL;
int ac = ZEND_NUM_ARGS();
if (ac == 1 && zend_get_parameters_ex(1, &filename) != FAILURE) {
#ifndef HAVE_UTIME_NULL
newtime = (struct utimbuf *)emalloc(sizeof(struct utimbuf));
if (!newtime) {
php_error(E_WARNING, "unable to emalloc memory for changing time");
return;
}
newtime->actime = time(NULL);
newtime->modtime = newtime->actime;
#endif
} else if (ac == 2 && zend_get_parameters_ex(2, &filename, &filetime) != FAILURE) {
newtime = (struct utimbuf *)emalloc(sizeof(struct utimbuf));
if (!newtime) {
php_error(E_WARNING, "unable to emalloc memory for changing time");
return;
}
convert_to_long_ex(filetime);
newtime->actime = (*filetime)->value.lval;
newtime->modtime = (*filetime)->value.lval;
} else {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(filename);
if (PG(safe_mode) &&(!php_checkuid((*filename)->value.str.val, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {
if (newtime) efree(newtime);
RETURN_FALSE;
}
/* Check the basedir */
if (php_check_open_basedir((*filename)->value.str.val TSRMLS_CC)) {
if (newtime) {
efree(newtime);
}
RETURN_FALSE;
}
/* create the file if it doesn't exist already */
ret = VCWD_STAT((*filename)->value.str.val, &sb);
if (ret == -1) {
file = VCWD_FOPEN((*filename)->value.str.val, "w");
if (file == NULL) {
php_error(E_WARNING, "unable to create file %s because %s", (*filename)->value.str.val, strerror(errno));
if (newtime) efree(newtime);
RETURN_FALSE;
}
fclose(file);
}
ret = VCWD_UTIME((*filename)->value.str.val, newtime);
if (newtime) efree(newtime);
if (ret == -1) {
php_error(E_WARNING, "utime failed: %s", strerror(errno));
RETURN_FALSE;
} else {
RETURN_TRUE;
}
#endif
}
/* }}} */
/* {{{ proto void clearstatcache(void)
Clear file stat cache */
PHP_FUNCTION(clearstatcache)
{
if (BG(CurrentStatFile)) {
efree(BG(CurrentStatFile));
BG(CurrentStatFile) = NULL;
}
}
/* }}} */
#define IS_LINK_OPERATION() (type == 8 /* filetype */ || type == 14 /* is_link */ || type == 16 /* lstat */)
/* {{{ php_stat
*/
static void php_stat(const char *filename, php_stat_len filename_length, int type, pval *return_value)
{
zval *stat_dev, *stat_ino, *stat_mode, *stat_nlink, *stat_uid, *stat_gid, *stat_rdev,
*stat_size, *stat_atime, *stat_mtime, *stat_ctime, *stat_blksize, *stat_blocks;
struct stat *stat_sb;
int rmask=S_IROTH, wmask=S_IWOTH, xmask=S_IXOTH; /* access rights defaults to other */
char *stat_sb_names[13]={"dev", "ino", "mode", "nlink", "uid", "gid", "rdev",
"size", "atime", "mtime", "ctime", "blksize", "blocks"};
TSRMLS_FETCH();
stat_sb = &BG(sb);
if (!BG(CurrentStatFile) || strcmp(filename, BG(CurrentStatFile))) {
if (!BG(CurrentStatFile) || filename_length > BG(CurrentStatLength)) {
if (BG(CurrentStatFile)) {
efree(BG(CurrentStatFile));
}
BG(CurrentStatLength) = filename_length;
BG(CurrentStatFile) = estrndup(filename, filename_length);
} else {
memcpy(BG(CurrentStatFile), filename, filename_length+1);
}
#if HAVE_SYMLINK
BG(lsb).st_mode = 0; /* mark lstat buf invalid */
#endif
if (VCWD_STAT(BG(CurrentStatFile), &BG(sb)) == -1) {
if (!IS_LINK_OPERATION() && (type != FS_EXISTS || errno != ENOENT)) { /* fileexists() test must print no error */
php_error(E_WARNING, "stat failed for %s (errno=%d - %s)", BG(CurrentStatFile), errno, strerror(errno));
}
efree(BG(CurrentStatFile));
BG(CurrentStatFile) = NULL;
if (!IS_LINK_OPERATION()) { /* Don't require success for link operation */
RETURN_FALSE;
}
}
}
#if HAVE_SYMLINK
if (IS_LINK_OPERATION() && !BG(lsb).st_mode) {
/* do lstat if the buffer is empty */
if (VCWD_LSTAT(filename, &BG(lsb)) == -1) {
php_error(E_WARNING, "lstat failed for %s (errno=%d - %s)", filename, errno, strerror(errno));
RETURN_FALSE;
}
}
#endif
if (type >= FS_IS_W && type <= FS_IS_X) {
if(BG(sb).st_uid==getuid()) {
rmask=S_IRUSR;
wmask=S_IWUSR;
xmask=S_IXUSR;
} else if(BG(sb).st_gid==getgid()) {
rmask=S_IRGRP;
wmask=S_IWGRP;
xmask=S_IXGRP;
} else {
int groups, n, i;
gid_t *gids;
groups = getgroups(0, NULL);
if(groups) {
gids=(gid_t *)emalloc(groups*sizeof(gid_t));
n=getgroups(groups, gids);
for(i=0;i<n;i++){
if(BG(sb).st_gid==gids[i]) {
rmask=S_IRGRP;
wmask=S_IWGRP;
xmask=S_IXGRP;
break;
}
}
efree(gids);
}
}
}
switch (type) {
case FS_PERMS:
RETURN_LONG((long)BG(sb).st_mode);
case FS_INODE:
RETURN_LONG((long)BG(sb).st_ino);
case FS_SIZE:
RETURN_LONG((long)BG(sb).st_size);
case FS_OWNER:
RETURN_LONG((long)BG(sb).st_uid);
case FS_GROUP:
RETURN_LONG((long)BG(sb).st_gid);
case FS_ATIME:
RETURN_LONG((long)BG(sb).st_atime);
case FS_MTIME:
RETURN_LONG((long)BG(sb).st_mtime);
case FS_CTIME:
RETURN_LONG((long)BG(sb).st_ctime);
case FS_TYPE:
#if HAVE_SYMLINK
if (S_ISLNK(BG(lsb).st_mode)) {
RETURN_STRING("link", 1);
}
#endif
switch(BG(sb).st_mode&S_IFMT) {
case S_IFIFO: RETURN_STRING("fifo", 1);
case S_IFCHR: RETURN_STRING("char", 1);
case S_IFDIR: RETURN_STRING("dir", 1);
case S_IFBLK: RETURN_STRING("block", 1);
case S_IFREG: RETURN_STRING("file", 1);
#if defined(S_IFSOCK) && !defined(ZEND_WIN32)&&!defined(__BEOS__)
case S_IFSOCK: RETURN_STRING("socket", 1);
#endif
}
php_error(E_WARNING, "Unknown file type (%d)", BG(sb).st_mode&S_IFMT);
RETURN_STRING("unknown", 1);
case FS_IS_W:
if (getuid()==0) {
RETURN_LONG(1); /* root */
}
RETURN_LONG((BG(sb).st_mode & wmask) != 0);
case FS_IS_R:
if (getuid()==0) {
RETURN_LONG(1); /* root */
}
RETURN_LONG((BG(sb).st_mode&rmask)!=0);
case FS_IS_X:
if (getuid()==0) {
xmask = S_IXROOT; /* root */
}
RETURN_LONG((BG(sb).st_mode&xmask)!=0 && !S_ISDIR(BG(sb).st_mode));
case FS_IS_FILE:
RETURN_LONG(S_ISREG(BG(sb).st_mode));
case FS_IS_DIR:
RETURN_LONG(S_ISDIR(BG(sb).st_mode));
case FS_IS_LINK:
#if HAVE_SYMLINK
RETURN_LONG(S_ISLNK(BG(lsb).st_mode));
#else
RETURN_FALSE;
#endif
case FS_EXISTS:
RETURN_TRUE; /* the false case was done earlier */
case FS_LSTAT:
#if HAVE_SYMLINK
stat_sb = &BG(lsb);
#endif
/* FALLTHROUGH */
case FS_STAT:
if (array_init(return_value) == FAILURE) {
RETURN_FALSE;
}
MAKE_LONG_ZVAL_INCREF(stat_dev, stat_sb->st_dev);
MAKE_LONG_ZVAL_INCREF(stat_ino, stat_sb->st_ino);
MAKE_LONG_ZVAL_INCREF(stat_mode, stat_sb->st_mode);
MAKE_LONG_ZVAL_INCREF(stat_nlink, stat_sb->st_nlink);
MAKE_LONG_ZVAL_INCREF(stat_uid, stat_sb->st_uid);
MAKE_LONG_ZVAL_INCREF(stat_gid, stat_sb->st_gid);
#ifdef HAVE_ST_RDEV
MAKE_LONG_ZVAL_INCREF(stat_rdev, stat_sb->st_rdev);
#else
MAKE_LONG_ZVAL_INCREF(stat_rdev, -1);
#endif
MAKE_LONG_ZVAL_INCREF(stat_size, stat_sb->st_size);
MAKE_LONG_ZVAL_INCREF(stat_atime, stat_sb->st_atime);
MAKE_LONG_ZVAL_INCREF(stat_mtime, stat_sb->st_mtime);
MAKE_LONG_ZVAL_INCREF(stat_ctime, stat_sb->st_ctime);
#ifdef HAVE_ST_BLKSIZE
MAKE_LONG_ZVAL_INCREF(stat_blksize, stat_sb->st_blksize);
#else
MAKE_LONG_ZVAL_INCREF(stat_blksize,-1);
#endif
#ifdef HAVE_ST_BLOCKS
MAKE_LONG_ZVAL_INCREF(stat_blocks, stat_sb->st_blocks);
#else
MAKE_LONG_ZVAL_INCREF(stat_blocks,-1);
#endif
/* Store numeric indexes in propper order */
zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_dev, sizeof(zval *), NULL);
zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_ino, sizeof(zval *), NULL);
zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_mode, sizeof(zval *), NULL);
zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_nlink, sizeof(zval *), NULL);
zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_uid, sizeof(zval *), NULL);
zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_gid, sizeof(zval *), NULL);
zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_rdev, sizeof(zval *), NULL);
zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_size, sizeof(zval *), NULL);
zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_atime, sizeof(zval *), NULL);
zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_mtime, sizeof(zval *), NULL);
zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_ctime, sizeof(zval *), NULL);
zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_blksize, sizeof(zval *), NULL);
zend_hash_next_index_insert(HASH_OF(return_value), (void *)&stat_blocks, sizeof(zval *), NULL);
/* Store string indexes referencing the same zval*/
zend_hash_update(HASH_OF(return_value), stat_sb_names[0], strlen(stat_sb_names[0])+1, (void *) &stat_dev, sizeof(zval *), NULL);
zend_hash_update(HASH_OF(return_value), stat_sb_names[1], strlen(stat_sb_names[1])+1, (void *) &stat_ino, sizeof(zval *), NULL);
zend_hash_update(HASH_OF(return_value), stat_sb_names[2], strlen(stat_sb_names[2])+1, (void *) &stat_mode, sizeof(zval *), NULL);
zend_hash_update(HASH_OF(return_value), stat_sb_names[3], strlen(stat_sb_names[3])+1, (void *) &stat_nlink, sizeof(zval *), NULL);
zend_hash_update(HASH_OF(return_value), stat_sb_names[4], strlen(stat_sb_names[4])+1, (void *) &stat_uid, sizeof(zval *), NULL);
zend_hash_update(HASH_OF(return_value), stat_sb_names[5], strlen(stat_sb_names[5])+1, (void *) &stat_gid, sizeof(zval *), NULL);
zend_hash_update(HASH_OF(return_value), stat_sb_names[6], strlen(stat_sb_names[6])+1, (void *) &stat_rdev, sizeof(zval *), NULL);
zend_hash_update(HASH_OF(return_value), stat_sb_names[7], strlen(stat_sb_names[7])+1, (void *) &stat_size, sizeof(zval *), NULL);
zend_hash_update(HASH_OF(return_value), stat_sb_names[8], strlen(stat_sb_names[8])+1, (void *) &stat_atime, sizeof(zval *), NULL);
zend_hash_update(HASH_OF(return_value), stat_sb_names[9], strlen(stat_sb_names[9])+1, (void *) &stat_mtime, sizeof(zval *), NULL);
zend_hash_update(HASH_OF(return_value), stat_sb_names[10], strlen(stat_sb_names[10])+1, (void *) &stat_ctime, sizeof(zval *), NULL);
zend_hash_update(HASH_OF(return_value), stat_sb_names[11], strlen(stat_sb_names[11])+1, (void *) &stat_blksize, sizeof(zval *), NULL);
zend_hash_update(HASH_OF(return_value), stat_sb_names[12], strlen(stat_sb_names[12])+1, (void *) &stat_blocks, sizeof(zval *), NULL);
return;
}
php_error(E_WARNING, "didn't understand stat call");
RETURN_FALSE;
}
/* }}} */
/* another quickie macro to make defining similar functions easier */
#define FileFunction(name, funcnum) \
void name(INTERNAL_FUNCTION_PARAMETERS) { \
pval **filename; \
if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &filename) == FAILURE) { \
WRONG_PARAM_COUNT; \
} \
convert_to_string_ex(filename); \
php_stat(Z_STRVAL_PP(filename), (php_stat_len) Z_STRLEN_PP(filename), funcnum, return_value); \
}
/* {{{ proto int fileperms(string filename)
Get file permissions */
FileFunction(PHP_FN(fileperms), FS_PERMS)
/* }}} */
/* {{{ proto int fileinode(string filename)
Get file inode */
FileFunction(PHP_FN(fileinode), FS_INODE)
/* }}} */
/* {{{ proto int filesize(string filename)
Get file size */
FileFunction(PHP_FN(filesize), FS_SIZE)
/* }}} */
/* {{{ proto int fileowner(string filename)
Get file owner */
FileFunction(PHP_FN(fileowner), FS_OWNER)
/* }}} */
/* {{{ proto int filegroup(string filename)
Get file group */
FileFunction(PHP_FN(filegroup), FS_GROUP)
/* }}} */
/* {{{ proto int fileatime(string filename)
Get last access time of file */
FileFunction(PHP_FN(fileatime), FS_ATIME)
/* }}} */
/* {{{ proto int filemtime(string filename)
Get last modification time of file */
FileFunction(PHP_FN(filemtime), FS_MTIME)
/* }}} */
/* {{{ proto int filectime(string filename)
Get inode modification time of file */
FileFunction(PHP_FN(filectime), FS_CTIME)
/* }}} */
/* {{{ proto string filetype(string filename)
Get file type */
FileFunction(PHP_FN(filetype), FS_TYPE)
/* }}} */
/* {{{ proto int is_writable(string filename)
Returns true if file can be written */
FileFunction(PHP_FN(is_writable), FS_IS_W)
/* }}} */
/* {{{ proto int is_readable(string filename)
Returns true if file can be read */
FileFunction(PHP_FN(is_readable), FS_IS_R)
/* }}} */
/* {{{ proto int is_executable(string filename)
Returns true if file is executable */
FileFunction(PHP_FN(is_executable), FS_IS_X)
/* }}} */
/* {{{ proto int is_file(string filename)
Returns true if file is a regular file */
FileFunction(PHP_FN(is_file), FS_IS_FILE)
/* }}} */
/* {{{ proto int is_dir(string filename)
Returns true if file is directory */
FileFunction(PHP_FN(is_dir), FS_IS_DIR)
/* }}} */
/* {{{ proto int is_link(string filename)
Returns true if file is symbolic link */
FileFunction(PHP_FN(is_link), FS_IS_LINK)
/* }}} */
/* {{{ proto bool file_exists(string filename)
Returns true if filename exists */
FileFunction(PHP_FN(file_exists), FS_EXISTS)
/* }}} */
/* {{{ proto array lstat(string filename)
Give information about a file or symbolic link */
FileFunction(php_if_lstat, FS_LSTAT)
/* }}} */
/* {{{ proto array stat(string filename)
Give information about a file */
FileFunction(php_if_stat, FS_STAT)
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+225
View File
@@ -0,0 +1,225 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Sascha Schumann <sascha@schumann.cx> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include <php.h>
#include <errno.h>
#include "ext/standard/flock_compat.h"
#if HAVE_STRUCT_FLOCK
#include <unistd.h>
#include <fcntl.h>
#endif
#ifdef PHP_WIN32
#include <windows.h>
#include <io.h>
#endif
#ifndef HAVE_FLOCK
int flock(int fd, int operation)
#if HAVE_STRUCT_FLOCK
{
struct flock flck;
int ret;
flck.l_start = flck.l_len = 0;
flck.l_whence = SEEK_SET;
if (operation & LOCK_SH)
flck.l_type = F_RDLCK;
else if (operation & LOCK_EX)
flck.l_type = F_WRLCK;
else if (operation & LOCK_UN)
flck.l_type = F_UNLCK;
else {
errno = EINVAL;
return -1;
}
ret = fcntl(fd, operation & LOCK_NB ? F_SETLK : F_SETLKW, &flck);
if (operation & LOCK_NB && ret == -1 &&
(errno == EACCES || errno == EAGAIN))
errno = EWOULDBLOCK;
if (ret != -1) ret = 0;
return ret;
}
#elif defined(PHP_WIN32)
/*
* Program: Unix compatibility routines
*
* Author: Mark Crispin
* Networks and Distributed Computing
* Computing & Communications
* University of Washington
* Administration Building, AG-44
* Seattle, WA 98195
* Internet: MRC@CAC.Washington.EDU
*
* Date: 14 September 1996
* Last Edited: 14 August 1997
*
* Copyright 1997 by the University of Washington
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted, provided
* that the above copyright notice appears in all copies and that both the
* above copyright notice and this permission notice appear in supporting
* documentation, and that the name of the University of Washington not be
* used in advertising or publicity pertaining to distribution of the software
* without specific, written prior permission. This software is made available
* "as is", and
* THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
* WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND IN
* NO EVENT SHALL THE UNIVERSITY OF WASHINGTON BE LIABLE FOR ANY SPECIAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT
* (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
/* DEDICATION
* This file is dedicated to my dog, Unix, also known as Yun-chan and
* Unix J. Terwilliker Jehosophat Aloysius Monstrosity Animal Beast. Unix
* passed away at the age of 11 1/2 on September 14, 1996, 12:18 PM PDT, after
* a two-month bout with cirrhosis of the liver.
*
* He was a dear friend, and I miss him terribly.
*
* Lift a leg, Yunie. Luv ya forever!!!!
*/
{
HANDLE hdl = (HANDLE) _get_osfhandle(fd);
DWORD low = 1, high = 0;
OVERLAPPED offset =
{0, 0, 0, 0, NULL};
if (hdl < 0)
return -1; /* error in file descriptor */
/* bug for bug compatible with Unix */
UnlockFileEx(hdl, 0, low, high, &offset);
switch (operation & ~LOCK_NB) { /* translate to LockFileEx() op */
case LOCK_EX: /* exclusive */
if (LockFileEx(hdl, LOCKFILE_EXCLUSIVE_LOCK +
((operation & LOCK_NB) ? LOCKFILE_FAIL_IMMEDIATELY : 0),
0, low, high, &offset))
return 0;
break;
case LOCK_SH: /* shared */
if (LockFileEx(hdl, ((operation & LOCK_NB) ? LOCKFILE_FAIL_IMMEDIATELY : 0),
0, low, high, &offset))
return 0;
break;
case LOCK_UN: /* unlock */
return 0; /* always succeeds */
default: /* default */
break;
}
/* Under Win32 MT library, errno is not a variable but a function call,
* which cannot be assigned to.
*/
#if !defined(PHP_WIN32)
errno = EINVAL; /* bad call */
#endif
return -1;
}
#else
#warning no proper flock support for your site
{
errno = 0;
return 0;
}
#endif
#endif /* !defined(HAVE_FLOCK) */
#if !(HAVE_INET_ATON)
/* {{{ inet_aton
* Check whether "cp" is a valid ascii representation
* of an Internet address and convert to a binary address.
* Returns 1 if the address is valid, 0 if not.
* This replaces inet_addr, the return value from which
* cannot distinguish between failure and a local broadcast address.
*/
int inet_aton(const char *cp, struct in_addr *ap)
{
int dots = 0;
register unsigned long acc = 0, addr = 0;
do {
register char cc = *cp;
switch (cc) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
acc = acc * 10 + (cc - '0');
break;
case '.':
if (++dots > 3) {
return 0;
}
/* Fall through */
case '\0':
if (acc > 255) {
return 0;
}
addr = addr << 8 | acc;
acc = 0;
break;
default:
return 0;
}
} while (*cp++) ;
/* Normalize the address */
if (dots < 3) {
addr <<= 8 * (3 - dots) ;
}
/* Store it if requested */
if (ap) {
ap->s_addr = htonl(addr);
}
return 1;
}
/* }}} */
#endif /* !HAVE_INET_ATON */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+49
View File
@@ -0,0 +1,49 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Sascha Schumann <sascha@schumann.cx> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef FLOCK_COMPAT_H
#define FLOCK_COMPAT_H
#ifndef HAVE_FLOCK
# define LOCK_SH 1
# define LOCK_EX 2
# define LOCK_NB 4
# define LOCK_UN 8
int flock(int fd, int operation);
#endif
#ifdef PHP_WIN32
#define EWOULDBLOCK WSAEWOULDBLOCK
# define fsync _commit
# define ftruncate(a, b) chsize(a, b)
#endif /* defined(PHP_WIN32) */
#if !HAVE_INET_ATON
#if HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#if HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
extern int inet_aton(const char *, struct in_addr *);
#endif
#endif /* FLOCK_COMPAT_H */
+712
View File
@@ -0,0 +1,712 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Stig Sæther Bakken <ssb@guardian.no> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include <math.h> /* modf() */
#include "php.h"
#include "ext/standard/head.h"
#include "php_string.h"
#include "zend_execute.h"
#include <stdio.h>
#define ALIGN_LEFT 0
#define ALIGN_RIGHT 1
#define ADJ_WIDTH 1
#define ADJ_PRECISION 2
#define NUM_BUF_SIZE 500
#define NDIG 80
#define FLOAT_DIGITS 6
#define FLOAT_PRECISION 6
#define MAX_FLOAT_DIGITS 38
#define MAX_FLOAT_PRECISION 40
#if 0
/* trick to control varargs functions through cpp */
# define PRINTF_DEBUG(arg) php_printf arg
#else
# define PRINTF_DEBUG(arg)
#endif
static char hexchars[] = "0123456789abcdef";
static char HEXCHARS[] = "0123456789ABCDEF";
/*
* cvt.c - IEEE floating point formatting routines for FreeBSD
* from GNU libc-4.6.27
*/
/*
* php_convert_to_decimal converts to decimal
* the number of digits is specified by ndigit
* decpt is set to the position of the decimal point
* sign is set to 0 for positive, 1 for negative
*/
static char *php_convert_to_decimal(double arg, int ndigits, int *decpt, int *sign, int eflag)
{
register int r2;
double fi, fj;
register char *p, *p1;
/*THREADX*/
#ifndef THREAD_SAFE
static char cvt_buf[NDIG];
#endif
if (ndigits >= NDIG - 1)
ndigits = NDIG - 2;
r2 = 0;
*sign = 0;
p = &cvt_buf[0];
if (arg < 0) {
*sign = 1;
arg = -arg;
}
arg = modf(arg, &fi);
p1 = &cvt_buf[NDIG];
/*
* Do integer part
*/
if (fi != 0) {
p1 = &cvt_buf[NDIG];
while (fi != 0) {
fj = modf(fi / 10, &fi);
*--p1 = (int) ((fj + .03) * 10) + '0';
r2++;
}
while (p1 < &cvt_buf[NDIG])
*p++ = *p1++;
} else if (arg > 0) {
while ((fj = arg * 10.0) < 0.9999999) {
arg = fj;
r2--;
}
}
p1 = &cvt_buf[ndigits];
if (eflag == 0)
p1 += r2;
*decpt = r2;
if (p1 < &cvt_buf[0]) {
cvt_buf[0] = '\0';
return (cvt_buf);
}
while (p <= p1 && p < &cvt_buf[NDIG]) {
arg *= 10;
arg = modf(arg, &fj);
*p++ = (int) fj + '0';
}
if (p1 >= &cvt_buf[NDIG]) {
cvt_buf[NDIG - 1] = '\0';
return (cvt_buf);
}
p = p1;
*p1 += 5;
while (*p1 > '9') {
*p1 = '0';
if (p1 > cvt_buf)
++ * --p1;
else {
*p1 = '1';
(*decpt)++;
if (eflag == 0) {
if (p > cvt_buf)
*p = '0';
p++;
}
}
}
*p = '\0';
return (cvt_buf);
}
inline static void
php_sprintf_appendchar(char **buffer, int *pos, int *size, char add TSRMLS_DC)
{
if ((*pos + 1) >= *size) {
*size <<= 1;
PRINTF_DEBUG(("%s: ereallocing buffer to %d bytes\n", get_active_function_name(TSRMLS_C), *size));
*buffer = erealloc(*buffer, *size);
}
PRINTF_DEBUG(("sprintf: appending '%c', pos=\n", add, *pos));
(*buffer)[(*pos)++] = add;
}
inline static void
php_sprintf_appendstring(char **buffer, int *pos, int *size, char *add,
int min_width, int max_width, char padding,
int alignment, int len, int sign, int expprec)
{
register int npad;
npad = min_width - MIN(len, (expprec ? max_width : len));
if (npad < 0) {
npad = 0;
}
PRINTF_DEBUG(("sprintf: appendstring(%x, %d, %d, \"%s\", %d, '%c', %d)\n",
*buffer, *pos, *size, add, min_width, padding, alignment));
if ((max_width == 0) && (! expprec)) {
max_width = MAX(min_width, len);
}
if ((*pos + max_width) >= *size) {
while ((*pos + max_width) >= *size) {
*size <<= 1;
}
PRINTF_DEBUG(("sprintf ereallocing buffer to %d bytes\n", *size));
*buffer = erealloc(*buffer, *size);
}
if (alignment == ALIGN_RIGHT) {
if (sign && padding=='0') {
(*buffer)[(*pos)++] = '-';
add++;
len--;
}
while (npad-- > 0) {
(*buffer)[(*pos)++] = padding;
}
}
PRINTF_DEBUG(("sprintf: appending \"%s\"\n", add));
memcpy(&(*buffer)[*pos], add, MIN(max_width, len)+1);
*pos += MIN(max_width, len);
if (alignment == ALIGN_LEFT) {
while (npad--) {
(*buffer)[(*pos)++] = padding;
}
}
}
inline static void
php_sprintf_appendint(char **buffer, int *pos, int *size, long number,
int width, char padding, int alignment)
{
char numbuf[NUM_BUF_SIZE];
register unsigned long magn, nmagn;
register unsigned int i = NUM_BUF_SIZE - 1, neg = 0;
PRINTF_DEBUG(("sprintf: appendint(%x, %x, %x, %d, %d, '%c', %d)\n",
*buffer, pos, size, number, width, padding, alignment));
if (number < 0) {
neg = 1;
magn = ((unsigned long) -(number + 1)) + 1;
} else {
magn = (unsigned long) number;
}
/* Can't right-pad 0's on integers */
if(alignment==0 && padding=='0') padding=' ';
numbuf[i] = '\0';
do {
nmagn = magn / 10;
numbuf[--i] = (unsigned char)(magn - (nmagn * 10)) + '0';
magn = nmagn;
}
while (magn > 0 && i > 0);
if (neg) {
numbuf[--i] = '-';
}
PRINTF_DEBUG(("sprintf: appending %d as \"%s\", i=%d\n",
number, &numbuf[i], i));
php_sprintf_appendstring(buffer, pos, size, &numbuf[i], width, 0,
padding, alignment, (NUM_BUF_SIZE - 1) - i,
neg, 0);
}
inline static void
php_sprintf_appenduint(char **buffer, int *pos, int *size,
unsigned long number,
int width, char padding, int alignment)
{
char numbuf[NUM_BUF_SIZE];
register unsigned long magn, nmagn;
register unsigned int i = NUM_BUF_SIZE - 1;
PRINTF_DEBUG(("sprintf: appenduint(%x, %x, %x, %d, %d, '%c', %d)\n",
*buffer, pos, size, number, width, padding, alignment));
magn = (unsigned int) number;
/* Can't right-pad 0's on integers */
if (alignment == 0 && padding == '0') padding = ' ';
numbuf[i] = '\0';
do {
nmagn = magn / 10;
numbuf[--i] = (unsigned char)(magn - (nmagn * 10)) + '0';
magn = nmagn;
}
while (magn > 0 && i > 0);
PRINTF_DEBUG(("sprintf: appending %d as \"%s\", i=%d\n", number, &numbuf[i], i));
php_sprintf_appendstring(buffer, pos, size, &numbuf[i], width, 0,
padding, alignment, (NUM_BUF_SIZE - 1) - i, 0, 0);
}
inline static void
php_sprintf_appenddouble(char **buffer, int *pos,
int *size, double number,
int width, char padding,
int alignment, int precision,
int adjust, char fmt)
{
char numbuf[NUM_BUF_SIZE];
char *cvt;
register int i = 0, j = 0;
int sign, decpt;
PRINTF_DEBUG(("sprintf: appenddouble(%x, %x, %x, %f, %d, '%c', %d, %c)\n",
*buffer, pos, size, number, width, padding, alignment, fmt));
if ((adjust & ADJ_PRECISION) == 0) {
precision = FLOAT_PRECISION;
} else if (precision > MAX_FLOAT_PRECISION) {
precision = MAX_FLOAT_PRECISION;
}
if (zend_isnan(number)) {
sign = (number<0);
php_sprintf_appendstring(buffer, pos, size, "NaN", 3, 0, padding,
alignment, precision, sign, 0);
return;
}
if (zend_isinf(number)) {
sign = (number<0);
php_sprintf_appendstring(buffer, pos, size, "INF", 3, 0, padding,
alignment, precision, sign, 0);
return;
}
cvt = php_convert_to_decimal(number, precision, &decpt, &sign, (fmt == 'e'));
if (sign) {
numbuf[i++] = '-';
}
if (fmt == 'f') {
if (decpt <= 0) {
numbuf[i++] = '0';
if (precision > 0) {
int k = precision;
numbuf[i++] = '.';
while ((decpt++ < 0) && k--) {
numbuf[i++] = '0';
}
}
} else {
while (decpt-- > 0)
numbuf[i++] = cvt[j++];
if (precision > 0)
numbuf[i++] = '.';
}
} else {
numbuf[i++] = cvt[j++];
if (precision > 0)
numbuf[i++] = '.';
}
while (cvt[j]) {
numbuf[i++] = cvt[j++];
}
numbuf[i] = '\0';
if (precision > 0) {
width += (precision + 1);
}
php_sprintf_appendstring(buffer, pos, size, numbuf, width, 0, padding,
alignment, i, sign, 0);
}
inline static void
php_sprintf_append2n(char **buffer, int *pos, int *size, long number,
int width, char padding, int alignment, int n,
char *chartable, int expprec)
{
char numbuf[NUM_BUF_SIZE];
register unsigned long num;
register unsigned int i = NUM_BUF_SIZE - 1;
register int andbits = (1 << n) - 1;
PRINTF_DEBUG(("sprintf: append2n(%x, %x, %x, %d, %d, '%c', %d, %d, %x)\n",
*buffer, pos, size, number, width, padding, alignment, n,
chartable));
PRINTF_DEBUG(("sprintf: append2n 2^%d andbits=%x\n", n, andbits));
num = (unsigned long) number;
numbuf[i] = '\0';
do {
numbuf[--i] = chartable[(num & andbits)];
num >>= n;
}
while (num > 0);
php_sprintf_appendstring(buffer, pos, size, &numbuf[i], width, 0,
padding, alignment, (NUM_BUF_SIZE - 1) - i,
0, expprec);
}
inline static long
php_sprintf_getnumber(char *buffer, int *pos)
{
char *endptr;
register long num = strtol(&buffer[*pos], &endptr, 10);
register int i = 0;
if (endptr != NULL) {
i = (endptr - &buffer[*pos]);
}
PRINTF_DEBUG(("sprintf_getnumber: number was %d bytes long\n", i));
*pos += i;
return num;
}
/* {{{ php_formatted_print
* New sprintf implementation for PHP.
*
* Modifiers:
*
* " " pad integers with spaces
* "-" left adjusted field
* n field size
* "."n precision (floats only)
*
* Type specifiers:
*
* "%" literal "%", modifiers are ignored.
* "b" integer argument is printed as binary
* "c" integer argument is printed as a single character
* "d" argument is an integer
* "f" the argument is a float
* "o" integer argument is printed as octal
* "s" argument is a string
* "x" integer argument is printed as lowercase hexadecimal
* "X" integer argument is printed as uppercase hexadecimal
*
*/
static char *
php_formatted_print(int ht, int *len, int use_array TSRMLS_DC)
{
zval ***args, **z_format, **array;
int argc, size = 240, inpos = 0, outpos = 0, temppos;
int alignment, width, precision, currarg, adjusting, argnum;
char *format, *result, padding;
argc = ZEND_NUM_ARGS();
if (use_array) {
int i = 1;
if (ZEND_NUM_ARGS() != 2 || zend_get_parameters_ex(argc, &z_format, &array) == FAILURE) {
WRONG_PARAM_COUNT_WITH_RETVAL(NULL);
}
SEPARATE_ZVAL(array);
convert_to_array_ex(array);
argc = 1 + zend_hash_num_elements(Z_ARRVAL_PP(array));
args = (zval ***)emalloc(argc * sizeof(zval *));
args[0] = z_format;
for (zend_hash_internal_pointer_reset(Z_ARRVAL_PP(array));
zend_hash_get_current_data(Z_ARRVAL_PP(array), (void **)&args[i++]) == SUCCESS;
zend_hash_move_forward(Z_ARRVAL_PP(array)));
} else {
if (argc < 1) {
WRONG_PARAM_COUNT_WITH_RETVAL(NULL);
}
args = (zval ***)emalloc(argc * sizeof(zval *));
if (zend_get_parameters_array_ex(argc, args) == FAILURE) {
efree(args);
WRONG_PARAM_COUNT_WITH_RETVAL(NULL);
}
}
convert_to_string_ex(args[0]);
format = (*args[0])->value.str.val;
result = emalloc(size);
currarg = 1;
while (inpos<(*args[0])->value.str.len) {
int expprec = 0;
PRINTF_DEBUG(("sprintf: format[%d]='%c'\n", inpos, format[inpos]));
PRINTF_DEBUG(("sprintf: outpos=%d\n", outpos));
if (format[inpos] != '%') {
php_sprintf_appendchar(&result, &outpos, &size, format[inpos++] TSRMLS_CC);
} else if (format[inpos + 1] == '%') {
php_sprintf_appendchar(&result, &outpos, &size, '%' TSRMLS_CC);
inpos += 2;
} else {
if (currarg >= argc && format[inpos + 1] != '%') {
efree(result);
efree(args);
php_error(E_WARNING, "%s(): too few arguments", get_active_function_name(TSRMLS_C));
return NULL;
}
/* starting a new format specifier, reset variables */
alignment = ALIGN_RIGHT;
adjusting = 0;
padding = ' ';
inpos++; /* skip the '%' */
PRINTF_DEBUG(("sprintf: first looking at '%c', inpos=%d\n",
format[inpos], inpos));
if (isascii((int)format[inpos]) && !isalpha((int)format[inpos])) {
/* first look for argnum */
temppos = inpos;
while (isdigit((int)format[temppos])) temppos++;
if (format[temppos] == '$') {
argnum = php_sprintf_getnumber(format, &inpos);
inpos++; /* skip the '$' */
} else {
argnum = currarg++;
}
if (argnum >= argc) {
efree(result);
efree(args);
php_error(E_WARNING, "%s(): too few arguments", get_active_function_name(TSRMLS_C));
return NULL;
}
/* after argnum comes modifiers */
PRINTF_DEBUG(("sprintf: looking for modifiers\n"
"sprintf: now looking at '%c', inpos=%d\n",
format[inpos], inpos));
for (;; inpos++) {
if (format[inpos] == ' ' || format[inpos] == '0') {
padding = format[inpos];
} else if (format[inpos] == '-') {
alignment = ALIGN_LEFT;
/* space padding, the default */
} else if (format[inpos] == '\'') {
padding = format[++inpos];
} else {
PRINTF_DEBUG(("sprintf: end of modifiers\n"));
break;
}
}
PRINTF_DEBUG(("sprintf: padding='%c'\n", padding));
PRINTF_DEBUG(("sprintf: alignment=%s\n",
(alignment == ALIGN_LEFT) ? "left" : "right"));
/* after modifiers comes width */
if (isdigit((int)format[inpos])) {
PRINTF_DEBUG(("sprintf: getting width\n"));
width = php_sprintf_getnumber(format, &inpos);
adjusting |= ADJ_WIDTH;
} else {
width = 0;
}
PRINTF_DEBUG(("sprintf: width=%d\n", width));
/* after width and argnum comes precision */
if (format[inpos] == '.') {
inpos++;
PRINTF_DEBUG(("sprintf: getting precision\n"));
if (isdigit((int)format[inpos])) {
precision = php_sprintf_getnumber(format, &inpos);
adjusting |= ADJ_PRECISION;
expprec = 1;
} else {
precision = 0;
}
} else {
precision = 0;
}
PRINTF_DEBUG(("sprintf: precision=%d\n", precision));
} else {
width = precision = 0;
argnum = currarg++;
}
if (format[inpos] == 'l') {
inpos++;
}
PRINTF_DEBUG(("sprintf: format character='%c'\n", format[inpos]));
/* now we expect to find a type specifier */
switch (format[inpos]) {
case 's':
convert_to_string_ex(args[argnum]);
php_sprintf_appendstring(&result, &outpos, &size,
(*args[argnum])->value.str.val,
width, precision, padding,
alignment,
(*args[argnum])->value.str.len,
0, expprec);
break;
case 'd':
convert_to_long_ex(args[argnum]);
php_sprintf_appendint(&result, &outpos, &size,
(*args[argnum])->value.lval,
width, padding, alignment);
break;
case 'u':
convert_to_long_ex(args[argnum]);
php_sprintf_appenduint(&result, &outpos, &size,
(*args[argnum])->value.lval,
width, padding, alignment);
break;
case 'e':
case 'f':
/* XXX not done */
convert_to_double_ex(args[argnum]);
php_sprintf_appenddouble(&result, &outpos, &size,
(*args[argnum])->value.dval,
width, padding, alignment,
precision, adjusting,
format[inpos]);
break;
case 'c':
convert_to_long_ex(args[argnum]);
php_sprintf_appendchar(&result, &outpos, &size,
(char) (*args[argnum])->value.lval TSRMLS_CC);
break;
case 'o':
convert_to_long_ex(args[argnum]);
php_sprintf_append2n(&result, &outpos, &size,
(*args[argnum])->value.lval,
width, padding, alignment, 3,
hexchars, expprec);
break;
case 'x':
convert_to_long_ex(args[argnum]);
php_sprintf_append2n(&result, &outpos, &size,
(*args[argnum])->value.lval,
width, padding, alignment, 4,
hexchars, expprec);
break;
case 'X':
convert_to_long_ex(args[argnum]);
php_sprintf_append2n(&result, &outpos, &size,
(*args[argnum])->value.lval,
width, padding, alignment, 4,
HEXCHARS, expprec);
break;
case 'b':
convert_to_long_ex(args[argnum]);
php_sprintf_append2n(&result, &outpos, &size,
(*args[argnum])->value.lval,
width, padding, alignment, 1,
hexchars, expprec);
break;
case '%':
php_sprintf_appendchar(&result, &outpos, &size, '%' TSRMLS_CC);
break;
default:
break;
}
inpos++;
}
}
efree(args);
/* possibly, we have to make sure we have room for the terminating null? */
result[outpos]=0;
*len = outpos;
return result;
}
/* }}} */
/* {{{ proto string sprintf(string format [, mixed arg1 [, mixed ...]])
Return a formatted string */
PHP_FUNCTION(user_sprintf)
{
char *result;
int len;
if ((result=php_formatted_print(ht, &len, 0 TSRMLS_CC))==NULL) {
RETURN_FALSE;
}
RETVAL_STRINGL(result, len, 1);
efree(result);
}
/* }}} */
/* {{{ proto string vsprintf(string format, array args)
Return a formatted string */
PHP_FUNCTION(vsprintf)
{
char *result;
int len;
if ((result=php_formatted_print(ht, &len, 1 TSRMLS_CC))==NULL) {
RETURN_FALSE;
}
RETVAL_STRINGL(result, len, 1);
efree(result);
}
/* }}} */
/* {{{ proto int printf(string format [, mixed arg1 [, mixed ...]])
Output a formatted string */
PHP_FUNCTION(user_printf)
{
char *result;
int len;
if ((result=php_formatted_print(ht, &len, 0 TSRMLS_CC))==NULL) {
RETURN_FALSE;
}
PHPWRITE(result, len);
efree(result);
}
/* }}} */
/* {{{ proto int printf(string format, array args)
Output a formatted string */
PHP_FUNCTION(vprintf)
{
char *result;
int len;
if ((result=php_formatted_print(ht, &len, 1 TSRMLS_CC))==NULL) {
RETURN_FALSE;
}
PHPWRITE(result, len);
efree(result);
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+771
View File
@@ -0,0 +1,771 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Paul Panotzki - Bunyip Information Systems |
| Jim Winstead <jimw@php.net> |
| Sascha Schumann <sascha@schumann.cx> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
/* Synced with php 3.0 revision 1.121 1999-06-18 [ssb] */
/* Synced with php 3.0 revision 1.133 1999-07-21 [sas] */
#include "php.h"
#include "php_globals.h"
#include <stdlib.h>
#include <stddef.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_FCNTL_H
# include <fcntl.h>
#endif
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
#include <sys/types.h>
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef PHP_WIN32
#include <winsock.h>
#else
#include <netinet/in.h>
#include <netdb.h>
#if HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#endif
#ifdef PHP_WIN32
#undef AF_UNIX
#endif
#if defined(AF_UNIX)
#include <sys/un.h>
#endif
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#ifndef PF_INET
#define PF_INET AF_INET
#endif
#ifndef PF_UNIX
#define PF_UNIX AF_UNIX
#endif
#include <string.h>
#include <errno.h>
#include "base64.h"
#include "file.h"
#include "url.h"
#include "fsock.h"
#include "php_network.h"
#ifdef ZTS
static int fsock_globals_id;
#else
extern int le_fp;
#endif
#define CLOSE_SOCK(free_sock) \
if(socketd >= 0) { \
close(socketd); \
} \
if (free_sock) { \
efree(sock); \
} \
if (key) { \
efree(key); \
}
#define SEARCHCR() do { \
if (TOREAD(sock)) { \
for (p = READPTR(sock), pe = p + MIN(TOREAD(sock), maxlen); \
*p != '\n'; ) \
if (++p >= pe) { \
p = NULL; \
break; \
} \
} else \
p = NULL; \
} while (0)
#ifdef PHP_WIN32
#define EWOULDBLOCK WSAEWOULDBLOCK
#else
#include "build-defs.h"
#endif
/* {{{ php_lookup_hostname */
/*
* Converts a host name to an IP address.
*/
PHPAPI int php_lookup_hostname(const char *addr, struct in_addr *in)
{
struct hostent *host_info;
if (!inet_aton(addr, in)) {
/* XXX NOT THREAD SAFE */
host_info = gethostbyname(addr);
if (host_info == 0) {
/* Error: unknown host */
return -1;
}
*in = *((struct in_addr *) host_info->h_addr);
}
return 0;
}
/* }}} */
/* {{{ php_is_persistent_sock */
PHPAPI int php_is_persistent_sock(int sock)
{
char *key;
TSRMLS_FETCH();
if (zend_hash_find(&FG(ht_fsock_socks), (char *) &sock, sizeof(sock),
(void **) &key) == SUCCESS) {
return 1;
}
return 0;
}
/* }}} */
/* {{{ php_fsockopen() */
/*
This function takes an optional third argument which should be
passed by reference. The error code from the connect call is written
to this variable.
*/
static void php_fsockopen(INTERNAL_FUNCTION_PARAMETERS, int persistent) {
pval **args[5];
int *sock=emalloc(sizeof(int));
int *sockp;
int arg_count=ZEND_NUM_ARGS();
int socketd = -1;
unsigned char udp = 0;
struct timeval timeout = { 60, 0 };
unsigned short portno;
unsigned long conv;
char *key = NULL;
if (arg_count > 5 || arg_count < 2 || zend_get_parameters_array_ex(arg_count, args)==FAILURE) {
CLOSE_SOCK(1);
WRONG_PARAM_COUNT;
}
switch(arg_count) {
case 5:
convert_to_double_ex(args[4]);
conv = (unsigned long) (Z_DVAL_PP(args[4]) * 1000000.0);
timeout.tv_sec = conv / 1000000;
timeout.tv_usec = conv % 1000000;
/* fall-through */
case 4:
zval_ptr_dtor(args[3]);
ZVAL_STRING(*args[3], "", 1);
/* fall-through */
case 3:
zval_ptr_dtor(args[2]);
ZVAL_LONG(*args[2], 0);
break;
}
convert_to_string_ex(args[0]);
convert_to_long_ex(args[1]);
portno = (unsigned short) Z_LVAL_PP(args[1]);
key = emalloc(Z_STRLEN_PP(args[0]) + 10);
sprintf(key, "%s:%d", Z_STRVAL_PP(args[0]), portno);
if (persistent && zend_hash_find(&FG(ht_fsock_keys), key, strlen(key) + 1,
(void *) &sockp) == SUCCESS) {
CLOSE_SOCK(0);
*sock = *sockp;
ZEND_REGISTER_RESOURCE(return_value, sock, php_file_le_socket());
return;
}
if (portno) {
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
if(Z_STRLEN_PP(args[0]) >= 6 && !memcmp(Z_STRVAL_PP(args[0]), "udp://", sizeof("udp://")-1)) {
udp = 1;
}
socketd = socket(PF_INET, udp ? SOCK_DGRAM : SOCK_STREAM, 0);
if (socketd == SOCK_ERR) {
CLOSE_SOCK(1);
RETURN_FALSE;
}
server.sin_family = AF_INET;
if(php_lookup_hostname(udp ? &Z_STRVAL_PP(args[0])[6] : Z_STRVAL_PP(args[0]), &server.sin_addr)) {
CLOSE_SOCK(1);
RETURN_FALSE;
}
server.sin_port = htons(portno);
if (php_connect_nonb(socketd, (struct sockaddr *) &server, sizeof(server), &timeout) == SOCK_CONN_ERR) {
CLOSE_SOCK(1);
if (arg_count>2) {
zval_ptr_dtor(args[2]);
ZVAL_LONG(*args[2], errno);
}
if (arg_count>3) {
zval_ptr_dtor(args[3]);
ZVAL_STRING(*args[3], strerror(errno), 1);
}
RETURN_FALSE;
}
#if defined(AF_UNIX)
} else {
/* Unix domain socket. s->strval is socket name. */
struct sockaddr_un unix_addr;
socketd = socket(PF_UNIX, SOCK_STREAM, 0);
if (socketd == SOCK_ERR) {
CLOSE_SOCK(1);
RETURN_FALSE;
}
memset(&unix_addr, 0, sizeof(unix_addr));
unix_addr.sun_family = AF_UNIX;
strlcpy(unix_addr.sun_path, Z_STRVAL_PP(args[0]), sizeof(unix_addr.sun_path));
if (php_connect_nonb(socketd, (struct sockaddr *) &unix_addr, sizeof(unix_addr), &timeout) == SOCK_CONN_ERR) {
CLOSE_SOCK(1);
if (arg_count>2) {
zval_ptr_dtor(args[2]);
ZVAL_LONG(*args[2], errno);
}
if (arg_count>3) {
zval_ptr_dtor(args[3]);
ZVAL_STRING(*args[3], strerror(errno), 1);
}
RETURN_FALSE;
}
#endif /* AF_UNIX */
}
*sock = socketd;
if (persistent) {
zend_hash_update(&FG(ht_fsock_keys), key, strlen(key) + 1,
sock, sizeof(*sock), NULL);
zend_hash_update(&FG(ht_fsock_socks), (char *) sock, sizeof(*sock),
key, strlen(key) + 1, NULL);
}
if (key)
efree(key);
ZEND_REGISTER_RESOURCE(return_value, sock, php_file_le_socket());
}
/* }}} */
/* {{{ proto int fsockopen(string hostname, int port [, int errno [, string errstr [, double timeout]]])
Open Internet or Unix domain socket connection */
PHP_FUNCTION(fsockopen)
{
php_fsockopen(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
/* }}} */
/* {{{ proto int pfsockopen(string hostname, int port [, int errno [, string errstr [, double timeout]]])
Open persistent Internet or Unix domain socket connection */
PHP_FUNCTION(pfsockopen)
{
php_fsockopen(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}
/* }}} */
#define SOCK_DESTROY(sock) \
if(sock->readbuf) pefree(sock->readbuf, sock->persistent); \
if(sock->prev) sock->prev->next = sock->next; \
if(sock->next) sock->next->prev = sock->prev; \
if(sock == FG(phpsockbuf)) \
FG(phpsockbuf) = sock->next; \
pefree(sock, sock->persistent)
PHPAPI void php_cleanup_sockbuf(int persistent TSRMLS_DC)
{
php_sockbuf *now, *next;
for(now = FG(phpsockbuf); now; now = next) {
next = now->next;
if(now->persistent == persistent) {
SOCK_DESTROY(now);
}
}
}
#define TOREAD(sock) ((sock)->writepos - (sock)->readpos)
#define READPTR(sock) ((sock)->readbuf + (sock)->readpos)
#define WRITEPTR(sock) ((sock)->readbuf + (sock)->writepos)
#define SOCK_FIND(sock, socket) \
php_sockbuf *sock; \
TSRMLS_FETCH(); \
sock = php_sockfind(socket TSRMLS_CC); \
if(!sock) sock = php_sockcreate(socket TSRMLS_CC)
static php_sockbuf *php_sockfind(int socket TSRMLS_DC)
{
php_sockbuf *buf = NULL, *tmp;
for(tmp = FG(phpsockbuf); tmp; tmp = tmp->next)
if(tmp->socket == socket) {
buf = tmp;
break;
}
return buf;
}
static php_sockbuf *php_sockcreate(int socket TSRMLS_DC)
{
php_sockbuf *sock;
int persistent = php_is_persistent_sock(socket);
sock = pecalloc(sizeof(*sock), 1, persistent);
sock->socket = socket;
if((sock->next = FG(phpsockbuf)))
FG(phpsockbuf)->prev = sock;
sock->persistent = persistent;
sock->is_blocked = 1;
sock->chunk_size = FG(def_chunk_size);
sock->timeout.tv_sec = -1;
FG(phpsockbuf) = sock;
return sock;
}
PHPAPI php_sockbuf *php_get_socket(int socket)
{
SOCK_FIND(sock, socket);
return sock;
}
PHPAPI size_t php_sock_set_def_chunk_size(size_t size)
{
size_t old;
TSRMLS_FETCH();
old = FG(def_chunk_size);
if(size <= PHP_FSOCK_CHUNK_SIZE || size > 0)
FG(def_chunk_size) = size;
return old;
}
PHPAPI int php_sockdestroy(int socket)
{
int ret = 0;
php_sockbuf *sock;
TSRMLS_FETCH();
sock = php_sockfind(socket TSRMLS_CC);
if(sock) {
ret = 1;
SOCK_DESTROY(sock);
}
return ret;
}
#if !defined(PHP_WIN32)
#undef closesocket
#define closesocket close
#endif
#ifndef HAVE_SHUTDOWN
#undef shutdown
#define shutdown
#endif
#define SOCK_CLOSE(s) shutdown(s, 0); closesocket(s)
PHPAPI int php_sock_close(int socket)
{
int ret = 0;
php_sockbuf *sock;
TSRMLS_FETCH();
sock = php_sockfind(socket TSRMLS_CC);
if(sock) {
if(!sock->persistent) {
SOCK_CLOSE(sock->socket);
SOCK_DESTROY(sock);
}
} else {
SOCK_CLOSE(socket);
}
return ret;
}
#define MAX_CHUNKS_PER_READ 10
static void php_sockwait_for_data(php_sockbuf *sock)
{
fd_set fdr, tfdr;
int retval;
struct timeval timeout, *ptimeout;
FD_ZERO(&fdr);
FD_SET(sock->socket, &fdr);
sock->timeout_event = 0;
if (sock->timeout.tv_sec == -1)
ptimeout = NULL;
else
ptimeout = &timeout;
while(1) {
tfdr = fdr;
timeout = sock->timeout;
retval = select(sock->socket + 1, &tfdr, NULL, NULL, ptimeout);
if (retval == 0)
sock->timeout_event = 1;
if (retval >= 0)
break;
}
}
static size_t php_sockread_internal(php_sockbuf *sock)
{
char buf[PHP_FSOCK_CHUNK_SIZE];
int nr_bytes;
size_t nr_read = 0;
/* For blocking sockets, we wait until there is some
data to read (real data or EOF)
Otherwise, recv() may time out and return 0 and
therefore sock->eof would be set errornously.
*/
if(sock->is_blocked) {
php_sockwait_for_data(sock);
if (sock->timeout_event)
return 0;
}
/* read at a maximum sock->chunk_size */
nr_bytes = recv(sock->socket, buf, sock->chunk_size, 0);
if(nr_bytes > 0) {
if(sock->writepos + nr_bytes > sock->readbuflen) {
sock->readbuflen += sock->chunk_size;
sock->readbuf = perealloc(sock->readbuf, sock->readbuflen,
sock->persistent);
}
memcpy(WRITEPTR(sock), buf, nr_bytes);
sock->writepos += nr_bytes;
nr_read = nr_bytes;
} else if(nr_bytes == 0 || (nr_bytes < 0 && errno != EWOULDBLOCK)) {
sock->eof = 1;
}
return nr_read;
}
static void php_sockread_total(php_sockbuf *sock, size_t maxread)
{
while(!sock->eof && TOREAD(sock) < maxread && !sock->timeout_event) {
php_sockread_internal(sock);
}
}
static size_t php_sockread(php_sockbuf *sock)
{
size_t nr_bytes;
size_t nr_read = 0;
int i;
for(i = 0; !sock->eof && i < MAX_CHUNKS_PER_READ; i++) {
nr_bytes = php_sockread_internal(sock);
if(nr_bytes == 0) break;
nr_read += nr_bytes;
}
return nr_read;
}
PHPAPI int php_sockset_blocking(int socket, int mode)
{
int old;
SOCK_FIND(sock, socket);
old = sock->is_blocked;
sock->is_blocked = mode;
return old;
}
PHPAPI void php_sockset_timeout(int socket, struct timeval *timeout)
{
SOCK_FIND(sock, socket);
sock->timeout = *timeout;
sock->timeout_event = 0;
}
#define SOCK_FIND_AND_READ_MAX(max) \
SOCK_FIND(sock, socket); \
if(sock->is_blocked) php_sockread_total(sock, max); else php_sockread(sock)
/* {{{ php_sock_fgets() */
/*
* FIXME: fgets depends on '\n' as line delimiter
*/
static char * php_sock_fgets_internal(char * buf, size_t maxlen, php_sockbuf * sock)
{
char *p = NULL, *pe;
char *ret = NULL;
size_t amount = 0;
if (maxlen==0) {
buf[0] = 0;
return buf;
}
SEARCHCR();
if(!p) {
if(sock->is_blocked) {
while(!p && !sock->eof && !sock->timeout_event && TOREAD(sock) < maxlen) {
php_sockread_internal(sock);
SEARCHCR();
}
} else {
php_sockread(sock);
SEARCHCR();
}
}
if(p) {
amount = (ptrdiff_t) p - (ptrdiff_t) READPTR(sock) + 1;
} else {
amount = TOREAD(sock);
}
amount = MIN(amount, maxlen);
if(amount > 0) {
memcpy(buf, READPTR(sock), amount);
sock->readpos += amount;
}
buf[amount] = '\0';
/* signal error only, if we don't return data from this call and
if there is no data to read and if the eof flag is set */
if(amount || TOREAD(sock) || !sock->eof) {
ret = buf;
}
return ret;
}
PHPAPI char *php_sock_fgets(char *buf, size_t maxlen, int socket)
{
SOCK_FIND(sock, socket);
return php_sock_fgets_internal(buf, maxlen, sock);
}
/* }}} */
/*
* FIXME: fgetc returns EOF, if no data is available on a nonblocking socket.
* I don't have any documentation on the semantics of fgetc in this case.
*
* ss@2ns.de 19990528
*/
PHPAPI int php_sock_fgetc(int socket)
{
int ret = EOF;
SOCK_FIND_AND_READ_MAX(1);
if(TOREAD(sock) > 0) {
ret = *READPTR(sock);
sock->readpos++;
}
return ret;
}
PHPAPI int php_sock_feof(int socket)
{
int ret = 0;
SOCK_FIND(sock, socket);
if(!sock->is_blocked)
php_sockread(sock);
if(!TOREAD(sock) && sock->eof)
ret = 1;
return ret;
}
/* {{{ stream abstraction */
#if HAVE_PHP_STREAM
static size_t php_sockop_write(php_stream * stream, const char * buf, size_t count)
{
php_sockbuf * sock = (php_sockbuf*)stream->abstract;
return send(sock->socket, buf, count, 0);
}
static size_t php_sockop_read(php_stream * stream, char * buf, size_t count)
{
php_sockbuf * sock = (php_sockbuf*)stream->abstract;
size_t ret = 0;
if (sock->is_blocked)
php_sockread_total(sock, count);
else
php_sockread(sock);
if(count < 0)
return ret;
ret = MIN(TOREAD(sock), count);
if (ret) {
memcpy(buf, READPTR(sock), ret);
sock->readpos += ret;
}
return ret;
}
static int php_sockop_close(php_stream * stream)
{
php_sockbuf * sock = (php_sockbuf*)stream->abstract;
SOCK_CLOSE(sock->socket);
SOCK_DESTROY(sock);
return 0;
}
static int php_sockop_flush(php_stream * stream)
{
php_sockbuf * sock = (php_sockbuf*)stream->abstract;
return fsync(sock->socket);
}
static int php_sockop_cast(php_stream * stream, int castas, void ** ret)
{
php_sockbuf * sock = (php_sockbuf*)stream->abstract;
TSRMLS_FETCH();
switch(castas) {
case PHP_STREAM_AS_STDIO:
if (ret) {
/* DANGER!: data buffered in stream->readbuf will be forgotten! */
if (TOREAD(sock) > 0)
zend_error(E_WARNING, "%s(): buffered data lost during conversion to FILE*!", get_active_function_name(TSRMLS_C));
*ret = fdopen(sock->socket, stream->mode);
if (*ret)
return SUCCESS;
return FAILURE;
}
return SUCCESS;
case PHP_STREAM_AS_FD:
case PHP_STREAM_AS_SOCKETD:
if (ret)
*ret = (void*)sock->socket;
return SUCCESS;
default:
return FAILURE;
}
}
static char * php_sockop_gets(php_stream * stream, char *buf, size_t size)
{
php_sockbuf * sock = (php_sockbuf*)stream->abstract;
return php_sock_fgets_internal(buf, size, sock);
}
php_stream_ops php_stream_socket_ops = {
php_sockop_write, php_sockop_read,
php_sockop_close, php_sockop_flush,
NULL, php_sockop_gets,
php_sockop_cast,
"socket"
};
#endif
/* }}} */
/* {{{ php_sock_fread() */
PHPAPI size_t php_sock_fread(char *ptr, size_t size, int socket)
{
size_t ret = 0;
SOCK_FIND_AND_READ_MAX(size);
if(size < 0)
return ret;
ret = MIN(TOREAD(sock), size);
if(ret) {
memcpy(ptr, READPTR(sock), ret);
sock->readpos += ret;
}
return ret;
}
/* }}} */
/* {{{ module start/shutdown functions */
/* {{{ php_msock_destroy */
PHPAPI void php_msock_destroy(int *data)
{
close(*data);
}
/* }}} */
PHP_RSHUTDOWN_FUNCTION(fsock)
{
php_cleanup_sockbuf(0 TSRMLS_CC);
return SUCCESS;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+88
View File
@@ -0,0 +1,88 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Paul Panotzki - Bunyip Information Systems |
| Jim Winstead (jimw@php.net) |
| Wez Furlong |
+----------------------------------------------------------------------+
*/
/* $Id$ */
/* Synced with php 3.0 revision 1.24 1999-06-18 [ssb] */
#ifndef FSOCK_H
#define FSOCK_H
#include "file.h"
#define PHP_FSOCK_CHUNK_SIZE 8192
#include "php_network.h"
#if HAVE_PHP_STREAM
extern php_stream_ops php_stream_socket_ops;
#endif
/* stream->abstract points to an instance of this */
struct php_sockbuf {
int socket;
unsigned char *readbuf;
size_t readbuflen;
size_t readpos;
size_t writepos;
struct php_sockbuf *next;
struct php_sockbuf *prev;
char eof;
char persistent;
char is_blocked;
size_t chunk_size;
struct timeval timeout;
char timeout_event;
#if HAVE_PHP_STREAM
php_stream * stream;
#endif
};
typedef struct php_sockbuf php_sockbuf;
PHP_FUNCTION(fsockopen);
PHP_FUNCTION(pfsockopen);
PHPAPI int php_lookup_hostname(const char *addr, struct in_addr *in);
PHPAPI char *php_sock_fgets(char *buf, size_t maxlen, int socket);
PHPAPI size_t php_sock_fread(char *buf, size_t maxlen, int socket);
PHPAPI int php_sock_feof(int socket);
PHPAPI int php_sock_fgetc(int socket);
PHPAPI int php_is_persistent_sock(int);
PHPAPI int php_sockset_blocking(int socket, int mode);
PHPAPI void php_sockset_timeout(int socket, struct timeval *timeout);
PHPAPI int php_sockdestroy(int socket);
PHPAPI int php_sock_close(int socket);
PHPAPI size_t php_sock_set_def_chunk_size(size_t size);
PHPAPI void php_msock_destroy(int *data);
PHPAPI void php_cleanup_sockbuf(int persistent TSRMLS_DC);
PHPAPI struct php_sockbuf *php_get_socket(int socket);
PHP_RSHUTDOWN_FUNCTION(fsock);
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim: sw=4 ts=4 tw=78
*/
#endif /* FSOCK_H */
+324
View File
@@ -0,0 +1,324 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
| Jim Winstead <jimw@php.net> |
| Hartmut Holzgraefe <hholzgra@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "php_globals.h"
#include "php_network.h"
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef PHP_WIN32
#include <windows.h>
#include <winsock.h>
#define O_RDONLY _O_RDONLY
#include "win32/param.h"
#else
#include <sys/param.h>
#endif
#include "php_standard.h"
#include <sys/types.h>
#if HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef PHP_WIN32
#include <winsock.h>
#else
#include <netinet/in.h>
#include <netdb.h>
#if HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#endif
#ifdef PHP_WIN32
#undef AF_UNIX
#endif
#if defined(AF_UNIX)
#include <sys/un.h>
#endif
#include "php_fopen_wrappers.h"
static int php_get_ftp_result(int socketd)
{
char tmp_line[513];
while (SOCK_FGETS(tmp_line, sizeof(tmp_line)-1, socketd) &&
!(isdigit((int) tmp_line[0]) && isdigit((int) tmp_line[1]) &&
isdigit((int) tmp_line[2]) && tmp_line[3] == ' '));
return strtol(tmp_line, NULL, 10);
}
/* {{{ php_fopen_url_wrap_ftp
*/
FILE *php_fopen_url_wrap_ftp(const char *path, char *mode, int options, int *issock, int *socketd, char **opened_path TSRMLS_DC)
{
FILE *fp=NULL;
php_url *resource=NULL;
char tmp_line[512];
unsigned short portno;
char *scratch;
int result;
int i;
char *tpath, *ttpath;
resource = php_url_parse((char *) path);
if (resource == NULL) {
php_error(E_WARNING, "Invalid URL specified, %s", path);
*issock = BAD_URL;
return NULL;
} else if (resource->path == NULL) {
php_error(E_WARNING, "No file-path specified");
php_url_free(resource);
*issock = BAD_URL;
return NULL;
}
/* use port 21 if one wasn't specified */
if (resource->port == 0)
resource->port = 21;
*socketd = php_hostconnect(resource->host, resource->port, SOCK_STREAM, 0);
if (*socketd == -1)
goto errexit;
#if 0
if ((fpc = fdopen(*socketd, "r+")) == NULL) {
php_url_free(resource);
return NULL;
}
#ifdef HAVE_SETVBUF
if ((setvbuf(fpc, NULL, _IONBF, 0)) != 0) {
php_url_free(resource);
fclose(fpc);
return NULL;
}
#endif
#endif
/* Start talking to ftp server */
result = php_get_ftp_result(*socketd);
if (result > 299 || result < 200)
goto errexit;
/* send the user name */
SOCK_WRITE("USER ", *socketd);
if (resource->user != NULL) {
php_raw_url_decode(resource->user, strlen(resource->user));
SOCK_WRITE(resource->user, *socketd);
} else {
SOCK_WRITE("anonymous", *socketd);
}
SOCK_WRITE("\r\n", *socketd);
/* get the response */
result = php_get_ftp_result(*socketd);
/* if a password is required, send it */
if (result >= 300 && result <= 399) {
SOCK_WRITE("PASS ", *socketd);
if (resource->pass != NULL) {
php_raw_url_decode(resource->pass, strlen(resource->pass));
SOCK_WRITE(resource->pass, *socketd);
} else {
/* if the user has configured who they are,
send that as the password */
if (cfg_get_string("from", &scratch) == SUCCESS) {
SOCK_WRITE(scratch, *socketd);
} else {
SOCK_WRITE("anonymous", *socketd);
}
}
SOCK_WRITE("\r\n", *socketd);
/* read the response */
result = php_get_ftp_result(*socketd);
}
if (result > 299 || result < 200)
goto errexit;
/* set the connection to be binary */
SOCK_WRITE("TYPE I\r\n", *socketd);
result = php_get_ftp_result(*socketd);
if (result > 299 || result < 200)
goto errexit;
/* find out the size of the file (verifying it exists) */
SOCK_WRITE("SIZE ", *socketd);
SOCK_WRITE(resource->path, *socketd);
SOCK_WRITE("\r\n", *socketd);
/* read the response */
result = php_get_ftp_result(*socketd);
if (mode[0] == 'r') {
/* when reading file, it must exist */
if (result > 299 || result < 200) {
php_error(E_WARNING, "File not found");
php_url_free(resource);
SOCK_FCLOSE(*socketd);
*socketd = 0;
errno = ENOENT;
return NULL;
}
} else {
/* when writing file, it must NOT exist */
if (result <= 299 && result >= 200) {
php_error(E_WARNING, "File already exists");
php_url_free(resource);
SOCK_FCLOSE(*socketd);
*socketd = 0;
errno = EEXIST;
return NULL;
}
}
/* set up the passive connection */
/* We try EPSV first, needed for IPv6 and works on some IPv4 servers */
SOCK_WRITE("EPSV\r\n", *socketd);
while (SOCK_FGETS(tmp_line, sizeof(tmp_line)-1, *socketd) &&
!(isdigit((int) tmp_line[0]) && isdigit((int) tmp_line[1]) &&
isdigit((int) tmp_line[2]) && tmp_line[3] == ' '));
/* check if we got a 229 response */
if (strncmp(tmp_line, "229", 3)) {
/* EPSV failed, let's try PASV */
SOCK_WRITE("PASV\r\n", *socketd);
while (SOCK_FGETS(tmp_line, sizeof(tmp_line)-1, *socketd) &&
!(isdigit((int) tmp_line[0]) && isdigit((int) tmp_line[1]) &&
isdigit((int) tmp_line[2]) && tmp_line[3] == ' '));
/* make sure we got a 227 response */
if (strncmp(tmp_line, "227", 3))
goto errexit;
/* parse pasv command (129, 80, 95, 25, 13, 221) */
tpath = tmp_line;
/* skip over the "227 Some message " part */
for (tpath += 4; *tpath && !isdigit((int) *tpath); tpath++);
if (!*tpath)
goto errexit;
/* skip over the host ip, we just assume it's the same */
for (i = 0; i < 4; i++) {
for (; isdigit((int) *tpath); tpath++);
if (*tpath != ',')
goto errexit;
tpath++;
}
/* pull out the MSB of the port */
portno = (unsigned short) strtol(tpath, &ttpath, 10) * 256;
if (ttpath == NULL) {
/* didn't get correct response from PASV */
goto errexit;
}
tpath = ttpath;
if (*tpath != ',')
goto errexit;
tpath++;
/* pull out the LSB of the port */
portno += (unsigned short) strtol(tpath, &ttpath, 10);
} else {
/* parse epsv command (|||6446|) */
for (i = 0, tpath = tmp_line + 4; *tpath; tpath++) {
if (*tpath == '|') {
i++;
if (i == 3)
break;
}
}
if (i < 3)
goto errexit;
/* pull out the port */
portno = (unsigned short) strtol(tpath + 1, &ttpath, 10);
}
if (ttpath == NULL) {
/* didn't get correct response from EPSV/PASV */
goto errexit;
}
if (mode[0] == 'r') {
/* retrieve file */
SOCK_WRITE("RETR ", *socketd);
} else {
/* store file */
SOCK_WRITE("STOR ", *socketd);
}
if (resource->path != NULL) {
SOCK_WRITE(resource->path, *socketd);
} else {
SOCK_WRITE("/", *socketd);
}
/* close control connection */
SOCK_WRITE("\r\nQUIT\r\n", *socketd);
SOCK_FCLOSE(*socketd);
/* open the data channel */
*socketd = php_hostconnect(resource->host, portno, SOCK_STREAM, 0);
if (*socketd == -1)
goto errexit;
#if 0
if (mode[0] == 'r') {
if ((fp = fdopen(*socketd, "r+")) == NULL) {
php_url_free(resource);
return NULL;
}
} else {
if ((fp = fdopen(*socketd, "w+")) == NULL) {
php_url_free(resource);
return NULL;
}
}
#ifdef HAVE_SETVBUF
if ((setvbuf(fp, NULL, _IONBF, 0)) != 0) {
php_url_free(resource);
fclose(fp);
return NULL;
}
#endif
#endif
php_url_free(resource);
*issock = 1;
return (fp);
errexit:
php_url_free(resource);
SOCK_FCLOSE(*socketd);
*socketd = 0;
return NULL;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+201
View File
@@ -0,0 +1,201 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include <stdio.h>
#include "php.h"
#include "ext/standard/php_standard.h"
#include "SAPI.h"
#include "php_main.h"
#include "head.h"
#include "SAPI.h"
#ifdef TM_IN_SYS_TIME
#include <sys/time.h>
#else
#include <time.h>
#endif
#include "php_globals.h"
#include "safe_mode.h"
/* Implementation of the language Header() function */
/* {{{ proto void header(string header[, bool replace])
Send a raw HTTP header */
PHP_FUNCTION(header)
{
pval **arg1, **arg2;
zend_bool replace = 1;
if (ZEND_NUM_ARGS() < 1 || ZEND_NUM_ARGS() > 2
|| zend_get_parameters_ex(ZEND_NUM_ARGS(), &arg1, &arg2) == FAILURE) {
WRONG_PARAM_COUNT;
}
switch (ZEND_NUM_ARGS()) {
case 2:
convert_to_boolean_ex(arg2);
replace = Z_BVAL_PP(arg2);
case 1:
convert_to_string_ex(arg1);
}
sapi_add_header_ex(Z_STRVAL_PP(arg1), Z_STRLEN_PP(arg1), 1, replace TSRMLS_CC);
}
/* }}} */
PHPAPI int php_header()
{
TSRMLS_FETCH();
if (sapi_send_headers(TSRMLS_C)==FAILURE || SG(request_info).headers_only) {
return 0; /* don't allow output */
} else {
return 1; /* allow output */
}
}
/* php_set_cookie(name, value, expires, path, domain, secure) */
/* {{{ proto void setcookie(string name [, string value [, int expires [, string path [, string domain [, string secure]]]]])
Send a cookie */
PHP_FUNCTION(setcookie)
{
char *cookie, *encoded_value = NULL;
int len=sizeof("Set-Cookie: ");
time_t t;
char *dt;
time_t expires = 0;
int secure = 0;
pval **arg[6];
int arg_count;
zval **z_name=NULL, **z_value=NULL, **z_path=NULL, **z_domain=NULL;
arg_count = ZEND_NUM_ARGS();
if (arg_count < 1 || arg_count > 6 || zend_get_parameters_array_ex(arg_count, arg) == FAILURE) {
WRONG_PARAM_COUNT;
}
switch (arg_count) {
case 6:
convert_to_boolean_ex(arg[5]);
secure = Z_LVAL_PP(arg[5]);
/* break missing intentionally */
case 5:
convert_to_string_ex(arg[4]);
z_domain = arg[4];
/* break missing intentionally */
case 4:
convert_to_string_ex(arg[3]);
z_path = arg[3];
/* break missing intentionally */
case 3:
convert_to_long_ex(arg[2]);
expires = Z_LVAL_PP(arg[2]);
/* break missing intentionally */
case 2:
convert_to_string_ex(arg[1]);
z_value = arg[1];
/* break missing intentionally */
case 1:
convert_to_string_ex(arg[0]);
z_name = arg[0];
break;
}
if (z_name) {
len += Z_STRLEN_PP(z_name);
}
if (z_value) {
int encoded_value_len;
encoded_value = php_url_encode(Z_STRVAL_PP(z_value), Z_STRLEN_PP(z_value), &encoded_value_len);
len += encoded_value_len;
}
if (z_path) {
len += Z_STRLEN_PP(z_path);
}
if (z_domain) {
len += Z_STRLEN_PP(z_domain);
}
cookie = emalloc(len + 100);
if (z_value && Z_STRLEN_PP(z_value)==0) {
/*
* MSIE doesn't delete a cookie when you set it to a null value
* so in order to force cookies to be deleted, even on MSIE, we
* pick an expiry date 1 year and 1 second in the past
*/
t = time(NULL) - 31536001;
dt = php_std_date(t);
sprintf(cookie, "Set-Cookie: %s=deleted; expires=%s", Z_STRVAL_PP(z_name), dt);
efree(dt);
} else {
sprintf(cookie, "Set-Cookie: %s=%s", Z_STRVAL_PP(z_name), (z_value && Z_STRVAL_PP(z_value)) ? encoded_value : "");
if (expires > 0) {
strcat(cookie, "; expires=");
dt = php_std_date(expires);
strcat(cookie, dt);
efree(dt);
}
}
if (encoded_value) {
efree(encoded_value);
}
if (z_path && Z_STRLEN_PP(z_path)>0) {
strcat(cookie, "; path=");
strcat(cookie, Z_STRVAL_PP(z_path));
}
if (z_domain && Z_STRLEN_PP(z_domain)>0) {
strcat(cookie, "; domain=");
strcat(cookie, Z_STRVAL_PP(z_domain));
}
if (secure) {
strcat(cookie, "; secure");
}
if (sapi_add_header(cookie, strlen(cookie), 0)==SUCCESS) {
RETVAL_TRUE;
} else {
RETVAL_FALSE;
}
}
/* }}} */
/* {{{ proto int headers_sent(void)
Return true if headers have already been sent, false otherwise */
PHP_FUNCTION(headers_sent)
{
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
if (SG(headers_sent)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78 * End:
*/
+31
View File
@@ -0,0 +1,31 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef HEAD_H
#define HEAD_H
extern PHP_RINIT_FUNCTION(head);
PHP_FUNCTION(header);
PHP_FUNCTION(setcookie);
PHP_FUNCTION(headers_sent);
PHPAPI int php_header(void);
#endif
+502
View File
@@ -0,0 +1,502 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
| Jaakko Hyvätti <jaakko.hyvatti@iki.fi> |
| Wez Furlong <wez@thebrainroom.com> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "reg.h"
#include "html.h"
#if HAVE_LOCALE_H
#include <locale.h>
#endif
#if HAVE_LANGINFO_H
#include <langinfo.h>
#endif
/* This must be fixed to handle the input string according to LC_CTYPE.
Defaults to ISO-8859-1 for now. */
enum entity_charset { cs_terminator, cs_8859_1, cs_cp1252,
cs_8859_15, cs_utf_8 };
typedef const char * entity_table_t;
/* codepage 1252 is a Windows extension to iso-8859-1. */
static entity_table_t ent_cp_1252[] = {
NULL, NULL, "sbquo", "fnof", "bdquo", "hellip", "dagger",
"Dagger", "circ", "permil", "Scaron", "lsaquo", "OElig",
NULL, NULL, NULL, NULL, "lsquo", "rsquo", "ldquo", "rdquo",
"bull", "ndash", "mdash", "tilde", "trade", "scaron", "rsaquo",
"oelig", NULL, NULL, "Yuml"
};
static entity_table_t ent_iso_8859_1[] = {
"nbsp", "iexcl", "cent", "pound", "curren", "yen", "brvbar",
"sect", "uml", "copy", "ordf", "laquo", "not", "shy", "reg",
"macr", "deg", "plusmn", "sup2", "sup3", "acute", "micro",
"para", "middot", "cedil", "sup1", "ordm", "raquo", "frac14",
"frac12", "frac34", "iquest", "Agrave", "Aacute", "Acirc",
"Atilde", "Auml", "Aring", "AElig", "Ccedil", "Egrave",
"Eacute", "Ecirc", "Euml", "Igrave", "Iacute", "Icirc",
"Iuml", "ETH", "Ntilde", "Ograve", "Oacute", "Ocirc", "Otilde",
"Ouml", "times", "Oslash", "Ugrave", "Uacute", "Ucirc", "Uuml",
"Yacute", "THORN", "szlig", "agrave", "aacute", "acirc",
"atilde", "auml", "aring", "aelig", "ccedil", "egrave",
"eacute", "ecirc", "euml", "igrave", "iacute", "icirc",
"iuml", "eth", "ntilde", "ograve", "oacute", "ocirc", "otilde",
"ouml", "divide", "oslash", "ugrave", "uacute", "ucirc",
"uuml", "yacute", "thorn", "yuml"
};
static entity_table_t ent_iso_8859_15[] = {
"nbsp", "iexcl", "cent", "pound", "euro", "yen", "Scaron",
"sect", "scaron", "copy", "ordf", "laquo", "not", "shy", "reg",
"macr", "deg", "plusmn", "sup2", "sup3", NULL, /* Zcaron */
"micro", "para", "middot", NULL, /* zcaron */ "sup1", "ordm",
"raquo", "OElig", "oelig", "Yuml", "iquest", "Agrave", "Aacute",
"Acirc", "Atilde", "Auml", "Aring", "AElig", "Ccedil", "Egrave",
"Eacute", "Ecirc", "Euml", "Igrave", "Iacute", "Icirc",
"Iuml", "ETH", "Ntilde", "Ograve", "Oacute", "Ocirc", "Otilde",
"Ouml", "times", "Oslash", "Ugrave", "Uacute", "Ucirc", "Uuml",
"Yacute", "THORN", "szlig", "agrave", "aacute", "acirc",
"atilde", "auml", "aring", "aelig", "ccedil", "egrave",
"eacute", "ecirc", "euml", "igrave", "iacute", "icirc",
"iuml", "eth", "ntilde", "ograve", "oacute", "ocirc", "otilde",
"ouml", "divide", "oslash", "ugrave", "uacute", "ucirc",
"uuml", "yacute", "thorn", "yuml"
};
struct html_entity_map {
enum entity_charset charset; /* charset identifier */
unsigned short basechar; /* char code at start of table */
unsigned short endchar; /* last char code in the table */
entity_table_t * table; /* the table of mappings */
};
static const struct html_entity_map entity_map[] = {
{ cs_cp1252, 0x80, 0x9f, ent_cp_1252 },
{ cs_cp1252, 0xa0, 0xff, ent_iso_8859_1 },
{ cs_8859_1, 0xa0, 0xff, ent_iso_8859_1 },
{ cs_8859_15, 0xa0, 0xff, ent_iso_8859_15 },
{ cs_utf_8, 0xa0, 0xff, ent_iso_8859_1 },
{ cs_terminator }
};
static const struct {
const char * codeset;
enum entity_charset charset;
} charset_map[] = {
{ "ISO-8859-1", cs_8859_1 },
{ "ISO-8859-15", cs_8859_15 },
{ "utf-8", cs_utf_8 },
{ "cp1252", cs_cp1252 },
{ NULL }
};
/* {{{ get_next_char
*/
inline static unsigned short get_next_char(enum entity_charset charset,
unsigned char * str,
int * newpos,
unsigned char * mbseq,
int * mbseqlen
)
{
int pos = *newpos;
int mbpos = 0;
unsigned short this_char = str[pos++];
mbseq[mbpos++] = (unsigned char)this_char;
if (charset == cs_utf_8) {
unsigned long utf = 0;
int stat = 0;
int more = 1;
/* unpack utf-8 encoding into a wide char.
* Code stolen from the mbstring extension */
do {
if (this_char < 0x80) {
more = 0;
break;
}
else if (this_char < 0xc0) {
switch(stat) {
case 0x10: /* 2, 2nd */
case 0x21: /* 3, 3rd */
case 0x32: /* 4, 4th */
case 0x43: /* 5, 5th */
case 0x54: /* 6, 6th */
/* last byte in sequence */
more = 0;
utf |= (this_char & 0x3f);
this_char = (unsigned short)utf;
break;
case 0x20: /* 3, 2nd */
case 0x31: /* 4, 3rd */
case 0x42: /* 5, 4th */
case 0x53: /* 6, 5th */
/* penultimate char */
utf |= ((this_char & 0x3f) << 6);
stat++;
break;
case 0x30: /* 4, 2nd */
case 0x41: /* 5, 3rd */
case 0x52: /* 6, 4th */
utf |= ((this_char & 0x3f) << 12);
stat++;
break;
case 0x40: /* 5, 2nd */
case 0x51:
utf |= ((this_char & 0x3f) << 18);
stat++;
break;
case 0x50: /* 6, 2nd */
utf |= ((this_char & 0x3f) << 24);
stat++;
default:
/* invalid */
more = 0;
}
}
/* lead byte */
else if (this_char < 0xe0) {
stat = 0x10; /* 2 byte */
utf = (this_char & 0x1f) << 6;
} else if (this_char < 0xf0) {
stat = 0x20; /* 3 byte */
utf = (this_char & 0xf) << 12;
} else if (this_char < 0xf8) {
stat = 0x30; /* 4 byte */
utf = (this_char & 0x7) << 18;
} else if (this_char < 0xfc) {
stat = 0x40; /* 5 byte */
utf = (this_char & 0x3) << 24;
} else if (this_char < 0xfe) {
stat = 0x50; /* 6 byte */
utf = (this_char & 0x1) << 30;
}
else {
/* invalid; bail */
more = 0;
break;
}
if (more)
{
this_char = str[pos++];
mbseq[mbpos++] = (unsigned char)this_char;
}
} while(more);
}
*newpos = pos;
mbseq[mbpos] = '\0';
*mbseqlen = mbpos;
return this_char;
}
/* }}} */
/* {{{ entity_charset determine_charset
* returns the charset identifier based on current locale or a hint.
* defaults to iso-8859-1 */
static enum entity_charset determine_charset(char * charset_hint)
{
int i;
enum entity_charset charset = cs_8859_1;
int len;
/* Guarantee default behaviour */
if (charset_hint == NULL)
return cs_8859_1;
if (strlen(charset_hint) == 0) {
/* try to detect the charset for the locale */
#if HAVE_NL_LANGINFO && HAVE_LOCALE_H && defined(CODESET)
charset_hint = nl_langinfo(CODESET);
#endif
#if HAVE_LOCALE_H
if (charset_hint == NULL)
{
/* try to figure out the charset from the locale */
char * localename;
char * dot, * at;
/* lang[_territory][.codeset][@modifier] */
localename = setlocale(LC_CTYPE, NULL);
dot = strchr(localename, '.');
if (dot) {
dot++;
/* locale specifies a codeset */
at = strchr(dot, '@');
if (at)
len = at - dot;
else
len = strlen(dot);
charset_hint = dot;
}
else {
/* no explicit name; see if the name itself
* is the charset */
charset_hint = localename;
len = strlen(charset_hint);
}
}
else
len = strlen(charset_hint);
#else
if (charset_hint)
len = strlen(charset_hint);
#endif
}
if (charset_hint) {
/* now walk the charset map and look for the codeset */
for (i = 0; charset_map[i].codeset; i++) {
if (strncasecmp(charset_hint, charset_map[i].codeset, len) == 0) {
charset = charset_map[i].charset;
break;
}
}
}
return charset;
}
/* }}} */
/* {{{ php_escape_html_entities
*/
PHPAPI char *php_escape_html_entities(unsigned char *old, int oldlen, int *newlen, int all, int quote_style, char * hint_charset)
{
int i, maxlen, len;
char *new;
enum entity_charset charset = determine_charset(hint_charset);
maxlen = 2 * oldlen;
if (maxlen < 128)
maxlen = 128;
new = emalloc (maxlen);
len = 0;
i = 0;
while (i < oldlen) {
int mbseqlen;
unsigned char mbsequence[16]; /* allow up to 15 characters
in a multibyte sequence
it should be more than enough.. */
unsigned short this_char = get_next_char(charset, old, &i, mbsequence, &mbseqlen);
int matches_map = 0;
if (len + 9 > maxlen)
new = erealloc (new, maxlen += 128);
if (all) {
/* look for a match in the maps for this charset */
int j;
unsigned char * rep;
for (j=0; entity_map[j].charset != cs_terminator; j++) {
if (entity_map[j].charset == charset
&& this_char >= entity_map[j].basechar
&& this_char <= entity_map[j].endchar)
{
rep = (unsigned char*)entity_map[j].table[this_char - entity_map[j].basechar];
if (rep == NULL) {
/* there is no entity for this position; fall through and
* just output the character itself */
break;
}
matches_map = 1;
break;
}
}
if (matches_map) {
new[len++] = '&';
strcpy(new + len, rep);
len += strlen(rep);
new[len++] = ';';
}
}
if (!matches_map) {
if (38 == this_char) {
memcpy (new + len, "&amp;", 5);
len += 5;
} else if (34 == this_char && !(quote_style&ENT_NOQUOTES)) {
memcpy (new + len, "&quot;", 6);
len += 6;
} else if (39 == this_char && (quote_style&ENT_QUOTES)) {
memcpy (new + len, "&#039;", 6);
len += 6;
} else if (60 == this_char) {
memcpy (new + len, "&lt;", 4);
len += 4;
} else if (62 == this_char) {
memcpy (new + len, "&gt;", 4);
len += 4;
} else if (this_char > 0xff) {
/* a wide char without a named entity; pass through the original sequence */
memcpy(new + len, mbsequence, mbseqlen);
len += mbseqlen;
} else {
new [len++] = (unsigned char)this_char;
}
}
}
new [len] = '\0';
*newlen = len;
return new;
}
/* }}} */
/* {{{ php_html_entities
*/
static void php_html_entities(INTERNAL_FUNCTION_PARAMETERS, int all)
{
zval **arg, **quotes, **charset;
int len, quote_style = ENT_COMPAT;
int ac = ZEND_NUM_ARGS();
char *hint_charset = NULL;
char *new;
if (ac < 1 || ac > 3 || zend_get_parameters_ex(ac, &arg, &quotes, &charset) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(arg);
if(ac==2) {
convert_to_long_ex(quotes);
quote_style = (*quotes)->value.lval;
}
if (ac == 3) {
convert_to_string_ex(charset);
hint_charset = Z_STRVAL_PP(charset);
}
new = php_escape_html_entities((*arg)->value.str.val, (*arg)->value.str.len, &len, all, quote_style, hint_charset);
RETVAL_STRINGL(new, len, 0);
}
/* }}} */
#define HTML_SPECIALCHARS 0
#define HTML_ENTITIES 1
/* {{{ register_html_constants
*/
void register_html_constants(INIT_FUNC_ARGS)
{
REGISTER_LONG_CONSTANT("HTML_SPECIALCHARS", HTML_SPECIALCHARS, CONST_PERSISTENT|CONST_CS);
REGISTER_LONG_CONSTANT("HTML_ENTITIES", HTML_ENTITIES, CONST_PERSISTENT|CONST_CS);
REGISTER_LONG_CONSTANT("ENT_COMPAT", ENT_COMPAT, CONST_PERSISTENT|CONST_CS);
REGISTER_LONG_CONSTANT("ENT_QUOTES", ENT_QUOTES, CONST_PERSISTENT|CONST_CS);
REGISTER_LONG_CONSTANT("ENT_NOQUOTES", ENT_NOQUOTES, CONST_PERSISTENT|CONST_CS);
}
/* }}} */
/* {{{ proto string htmlspecialchars(string string [, int quote_style][, string charset])
Convert special characters to HTML entities */
PHP_FUNCTION(htmlspecialchars)
{
php_html_entities(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
/* }}} */
/* {{{ proto string htmlentities(string string [, int quote_style][, string charset])
Convert all applicable characters to HTML entities */
PHP_FUNCTION(htmlentities)
{
php_html_entities(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}
/* }}} */
/* {{{ proto array get_html_translation_table([int table [, int quote_style][, string charset]])
Returns the internal translation table used by htmlspecialchars and htmlentities */
PHP_FUNCTION(get_html_translation_table)
{
zval **whichone, **quotes;
int which = HTML_SPECIALCHARS, quote_style = ENT_COMPAT;
int ac = ZEND_NUM_ARGS();
int i, j;
char ind[ 2 ];
enum entity_charset charset = determine_charset(NULL);
if (ac < 0 || ac > 2 || zend_get_parameters_ex(ac, &whichone, &quotes) == FAILURE) {
WRONG_PARAM_COUNT;
}
if (ac > 0) {
convert_to_long_ex(whichone);
which = (*whichone)->value.lval;
}
if (ac == 2) {
convert_to_long_ex(quotes);
quote_style = (*quotes)->value.lval;
}
array_init(return_value);
ind[1] = 0;
switch (which) {
case HTML_ENTITIES:
for (j=0; entity_map[j].charset != cs_terminator; j++) {
if (entity_map[j].charset != charset)
continue;
for (i = 0; i < entity_map[j].endchar - entity_map[j].basechar; i++)
{
char buffer[16];
if (entity_map[j].table[i] == NULL)
continue;
/* what about wide chars here ?? */
ind[0] = i + entity_map[j].basechar;
sprintf(buffer, "&%s;", entity_map[j].table[i]);
add_assoc_string(return_value, ind, buffer, 1);
}
}
/* break thru */
case HTML_SPECIALCHARS:
ind[0]=38; add_assoc_string(return_value, ind, "&amp;", 1);
if(quote_style&ENT_QUOTES) {
ind[0]=39; add_assoc_string(return_value, ind, "&#039;", 1);
}
if(!(quote_style&ENT_NOQUOTES)) {
ind[0]=34; add_assoc_string(return_value, ind, "&quot;", 1);
}
ind[0]=60; add_assoc_string(return_value, ind, "&lt;", 1);
ind[0]=62; add_assoc_string(return_value, ind, "&gt;", 1);
break;
}
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+36
View File
@@ -0,0 +1,36 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef HTML_H
#define HTML_H
#define ENT_COMPAT 1
#define ENT_QUOTES 2
#define ENT_NOQUOTES 4
void register_html_constants(INIT_FUNC_ARGS);
PHP_FUNCTION(htmlspecialchars);
PHP_FUNCTION(htmlentities);
PHP_FUNCTION(get_html_translation_table);
PHPAPI char *php_escape_html_entities(unsigned char *old, int oldlen, int *newlen, int all, int quote_style, char * hint_charset);
#endif /* HTML_H */
+314
View File
@@ -0,0 +1,314 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
| Jim Winstead <jimw@php.net> |
| Hartmut Holzgraefe <hholzgra@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "php_globals.h"
#include "php_network.h"
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef PHP_WIN32
#include <windows.h>
#include <winsock.h>
#define O_RDONLY _O_RDONLY
#include "win32/param.h"
#else
#include <sys/param.h>
#endif
#include "php_standard.h"
#include <sys/types.h>
#if HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef PHP_WIN32
#include <winsock.h>
#else
#include <netinet/in.h>
#include <netdb.h>
#if HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#endif
#ifdef PHP_WIN32
#undef AF_UNIX
#endif
#if defined(AF_UNIX)
#include <sys/un.h>
#endif
#include "php_fopen_wrappers.h"
#define HTTP_HEADER_BLOCK_SIZE 128
/* {{{ php_fopen_url_wrap_http
*/
FILE *php_fopen_url_wrap_http(const char *path, char *mode, int options, int *issock, int *socketd, char **opened_path TSRMLS_DC)
{
FILE *fp=NULL;
php_url *resource=NULL;
char tmp_line[128];
char location[512];
char hdr_line[8192];
int body = 0;
char *scratch;
unsigned char *tmp;
int len;
int reqok = 0;
zval *response_header;
char *http_header_line;
int http_header_line_length, http_header_line_size;
resource = php_url_parse((char *) path);
if (resource == NULL) {
php_error(E_WARNING, "Invalid URL specified, %s", path);
*issock = BAD_URL;
return NULL;
}
/* use port 80 if one wasn't specified */
if (resource->port == 0) {
resource->port = 80;
}
*socketd = php_hostconnect(resource->host, resource->port, SOCK_STREAM, 0);
if (*socketd == -1) {
SOCK_FCLOSE(*socketd);
*socketd = 0;
php_url_free(resource);
return NULL;
}
#if 0
if ((fp = fdopen(*socketd, "r+")) == NULL) {
php_url_free(resource);
return NULL;
}
#ifdef HAVE_SETVBUF
if ((setvbuf(fp, NULL, _IONBF, 0)) != 0) {
php_url_free(resource);
return NULL;
}
#endif
#endif /*win32 */
strcpy(hdr_line, "GET ");
/* tell remote http which file to get */
if (resource->path != NULL && *resource->path) {
strlcat(hdr_line, resource->path, sizeof(hdr_line));
} else {
strlcat(hdr_line, "/", sizeof(hdr_line));
}
/* append the query string, if any */
if (resource->query != NULL) {
strlcat(hdr_line, "?", sizeof(hdr_line));
strlcat(hdr_line, resource->query, sizeof(hdr_line));
}
strlcat(hdr_line, " HTTP/1.0\r\n", sizeof(hdr_line));
SOCK_WRITE(hdr_line, *socketd);
/* send authorization header if we have user/pass */
if (resource->user != NULL && resource->pass != NULL) {
scratch = (char *) emalloc(strlen(resource->user) + strlen(resource->pass) + 2);
if (!scratch) {
php_url_free(resource);
return NULL;
}
strcpy(scratch, resource->user);
strcat(scratch, ":");
strcat(scratch, resource->pass);
tmp = php_base64_encode((unsigned char *)scratch, strlen(scratch), NULL);
if (snprintf(hdr_line, sizeof(hdr_line),
"Authorization: Basic %s\r\n", tmp) > 0) {
SOCK_WRITE(hdr_line, *socketd);
}
efree(scratch);
efree(tmp);
}
/* if the user has configured who they are, send a From: line */
if (cfg_get_string("from", &scratch) == SUCCESS) {
if (snprintf(hdr_line, sizeof(hdr_line),
"From: %s\r\n", scratch) > 0) {
SOCK_WRITE(hdr_line, *socketd);
}
}
/* send a Host: header so name-based virtual hosts work */
if (resource->port != 80) {
len = snprintf(hdr_line, sizeof(hdr_line),
"Host: %s:%i\r\n", resource->host, resource->port);
} else {
len = snprintf(hdr_line, sizeof(hdr_line),
"Host: %s\r\n", resource->host);
}
if(len > sizeof(hdr_line) - 1) {
len = sizeof(hdr_line) - 1;
}
if (len > 0) {
SOCK_WRITE(hdr_line, *socketd);
}
/* identify ourselves and end the headers */
SOCK_WRITE("User-Agent: PHP/" PHP_VERSION "\r\n\r\n", *socketd);
body = 0;
location[0] = '\0';
MAKE_STD_ZVAL(response_header);
array_init(response_header);
if (!SOCK_FEOF(*socketd)) {
/* get response header */
if (SOCK_FGETS(tmp_line, sizeof(tmp_line)-1, *socketd) != NULL) {
zval *http_response;
MAKE_STD_ZVAL(http_response);
if (strncmp(tmp_line + 8, " 200 ", 5) == 0) {
reqok = 1;
}
Z_STRLEN_P(http_response) = strlen(tmp_line);
Z_STRVAL_P(http_response) = estrndup(tmp_line, Z_STRLEN_P(http_response));
if (Z_STRVAL_P(http_response)[Z_STRLEN_P(http_response)-1]=='\n') {
Z_STRVAL_P(http_response)[Z_STRLEN_P(http_response)-1]=0;
Z_STRLEN_P(http_response)--;
if (Z_STRVAL_P(http_response)[Z_STRLEN_P(http_response)-1]=='\r') {
Z_STRVAL_P(http_response)[Z_STRLEN_P(http_response)-1]=0;
Z_STRLEN_P(http_response)--;
}
}
Z_TYPE_P(http_response) = IS_STRING;
zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_response, sizeof(zval *), NULL);
}
}
/* Read past HTTP headers */
while (!body && !SOCK_FEOF(*socketd)) {
http_header_line = emalloc(HTTP_HEADER_BLOCK_SIZE);
http_header_line_size = HTTP_HEADER_BLOCK_SIZE;
http_header_line_length = 0;
if (SOCK_FGETS(http_header_line, HTTP_HEADER_BLOCK_SIZE-1, *socketd) != NULL) {
char *p;
zend_bool found_eol=0;
zval *http_header;
http_header_line[HTTP_HEADER_BLOCK_SIZE-1] = '\0';
do {
p = http_header_line+http_header_line_length;
while (*p) {
while (*p == '\n' || *p == '\r') {
*p = '\0';
p--;
found_eol=1;
}
if (found_eol) {
break;
}
p++;
}
if (!found_eol) {
http_header_line_size += HTTP_HEADER_BLOCK_SIZE;
http_header_line_length += HTTP_HEADER_BLOCK_SIZE-1;
http_header_line = erealloc(http_header_line, http_header_line_size);
if (SOCK_FGETS(http_header_line+http_header_line_length, HTTP_HEADER_BLOCK_SIZE-1, *socketd)==NULL) {
http_header_line[http_header_line_length] = 0;
break;
}
} else {
http_header_line_length = p-http_header_line+1;
}
} while (!found_eol);
if (!strncasecmp(http_header_line, "Location: ", 10)) {
strlcpy(location, http_header_line + 10, sizeof(location));
}
if (http_header_line[0] == '\0') {
body = 1;
}
if (http_header_line_length>0) {
MAKE_STD_ZVAL(http_header);
Z_STRVAL_P(http_header) = http_header_line;
Z_STRLEN_P(http_header) = http_header_line_length;
Z_TYPE_P(http_header) = IS_STRING;
zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header, sizeof(zval *), NULL);
} else {
efree(http_header_line);
}
}
}
if (!reqok) {
SOCK_FCLOSE(*socketd);
*socketd = 0;
php_url_free(resource);
if (location[0] != '\0') {
zval **response_header_new, *entry, **entryp;
fp = php_fopen_url_wrap_http(location, mode, options, issock, socketd, opened_path TSRMLS_CC);
if (zend_hash_find(EG(active_symbol_table), "http_response_header", sizeof("http_response_header"), (void **) &response_header_new) == SUCCESS) {
entryp = &entry;
MAKE_STD_ZVAL(entry);
ZVAL_EMPTY_STRING(entry);
zend_hash_next_index_insert(Z_ARRVAL_P(response_header), entryp, sizeof(zval *), NULL);
zend_hash_internal_pointer_reset(Z_ARRVAL_PP(response_header_new));
while (zend_hash_get_current_data(Z_ARRVAL_PP(response_header_new), (void **)&entryp) == SUCCESS) {
zval_add_ref(entryp);
zend_hash_next_index_insert(Z_ARRVAL_P(response_header), entryp, sizeof(zval *), NULL);
zend_hash_move_forward(Z_ARRVAL_PP(response_header_new));
}
}
goto out;
} else {
fp = NULL;
goto out;
}
}
php_url_free(resource);
*issock = 1;
out:
{
ZEND_SET_SYMBOL(EG(active_symbol_table), "http_response_header", response_header);
}
return (fp);
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+525
View File
@@ -0,0 +1,525 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf |
+----------------------------------------------------------------------+
*/
/* $Id$ */
/*
* Based on Daniel Schmitt's imageinfo.c which carried the following
* Copyright notice.
*/
/*
* imageinfo.c
*
* Simple routines to extract image width/height data from GIF/JPEG files.
*
* Copyright (c) 1997 Daniel Schmitt, opal online publishing, Bonn, Germany.
*
* Includes code snippets from rdjpgcom.c,
* Copyright (c) 1994-1995 Thomas G. Lane
* from release 6a of the Independent JPEG Group's software.
*
* Legal status: see GNU General Public License version 2 or later.
*
*/
#include "php.h"
#include <stdio.h>
#if HAVE_FCNTL_H
#include <fcntl.h>
#endif
#include "fopen_wrappers.h"
#include "ext/standard/fsock.h"
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "php_image.h"
/* file type markers */
PHPAPI const char php_sig_gif[3] = {'G', 'I', 'F'};
PHPAPI const char php_sig_psd[4] = {'8', 'B', 'P', 'S'};
PHPAPI const char php_sig_bmp[2] = {'B', 'M'};
PHPAPI const char php_sig_swf[3] = {'F', 'W', 'S'};
PHPAPI const char php_sig_jpg[3] = {(char) 0xff, (char) 0xd8, (char) 0xff};
PHPAPI const char php_sig_png[8] = {(char) 0x89, (char) 0x50, (char) 0x4e, (char) 0x47,
(char) 0x0d, (char) 0x0a, (char) 0x1a, (char) 0x0a};
/* return info as a struct, to make expansion easier */
struct gfxinfo {
unsigned int width;
unsigned int height;
unsigned int bits;
unsigned int channels;
};
/* {{{ php_handle_gif
* routine to handle GIF files. If only everything were that easy... ;} */
static struct gfxinfo *php_handle_gif (int socketd, FILE *fp, int issock)
{
struct gfxinfo *result = NULL;
unsigned char a[2];
char temp[3];
result = (struct gfxinfo *) ecalloc(1, sizeof(struct gfxinfo));
FP_FREAD(temp, 3, socketd, fp, issock); /* fseek(fp, 6L, SEEK_SET); */
FP_FREAD(a, sizeof(a), socketd, fp, issock); /* fread(a, sizeof(a), 1, fp); */
result->width = (unsigned short)a[0] | (((unsigned short)a[1])<<8);
FP_FREAD(a, sizeof(a), socketd, fp, issock); /* fread(a, sizeof(a), 1, fp); */
result->height = (unsigned short)a[0] | (((unsigned short)a[1])<<8);
return result;
}
/* }}} */
/* {{{ php_handle_psd
*/
static struct gfxinfo *php_handle_psd (int socketd, FILE *fp, int issock)
{
struct gfxinfo *result = NULL;
unsigned char a[8];
char temp[11];
unsigned long in_width, in_height;
result = (struct gfxinfo *) ecalloc(1, sizeof(struct gfxinfo));
FP_FREAD(temp, sizeof(temp), socketd, fp, issock);
if((FP_FREAD(a, sizeof(a), socketd, fp, issock)) <= 0) {
in_height = 0;
in_width = 0;
} else {
in_height = (((unsigned long) a[ 0 ]) << 24) + (((unsigned long) a[ 1 ]) << 16) + (((unsigned long) a[ 2 ]) << 8) + ((unsigned long) a[ 3 ]);
in_width = (((unsigned long) a[ 4 ]) << 24) + (((unsigned long) a[ 5 ]) << 16) + (((unsigned long) a[ 6 ]) << 8) + ((unsigned long) a[ 7 ]);
}
result->width = (unsigned int) in_width;
result->height = (unsigned int) in_height;
return result;
}
/* }}} */
/* {{{ php_handle_bmp
*/
static struct gfxinfo *php_handle_bmp (int socketd, FILE *fp, int issock)
{
struct gfxinfo *result = NULL;
char temp[15];
struct {
unsigned long in_width, in_height;
} dim;
result = (struct gfxinfo *) ecalloc (1, sizeof(struct gfxinfo));
FP_FREAD(temp, sizeof(temp), socketd, fp, issock);
FP_FREAD((char*) &dim, sizeof(dim), socketd, fp, issock);
result->width = dim.in_width;
result->height = dim.in_height;
return result;
}
/* }}} */
/* {{{ php_swf_get_bits
* routines to handle SWF files. */
static unsigned long int php_swf_get_bits (unsigned char* buffer, unsigned int pos, unsigned int count)
{
unsigned int loop;
unsigned long int result = 0;
for (loop = pos; loop < pos + count; loop++)
{
result = result +
((((buffer[loop / 8]) >> (7 - (loop % 8))) & 0x01) << (count - (loop - pos) - 1));
}
return result;
}
/* }}} */
/* {{{ php_handle_swf
*/
static struct gfxinfo *php_handle_swf (int socketd, FILE *fp, int issock)
{
struct gfxinfo *result = NULL;
long bits;
unsigned char a[32];
char temp[5];
result = (struct gfxinfo *) ecalloc (1, sizeof (struct gfxinfo));
FP_FREAD(temp, 5, socketd, fp, issock); /* fseek(fp, 8L, SEEK_SET); */
FP_FREAD(a, sizeof(a), socketd, fp, issock); /* fread(a, sizeof(a), 1, fp); */
bits = php_swf_get_bits (a, 0, 5);
result->width = (php_swf_get_bits (a, 5 + bits, bits) -
php_swf_get_bits (a, 5, bits)) / 20;
result->height = (php_swf_get_bits (a, 5 + (3 * bits), bits) -
php_swf_get_bits (a, 5 + (2 * bits), bits)) / 20;
return result;
}
/* }}} */
/* {{{ php_handle_png
* routine to handle PNG files */
static struct gfxinfo *php_handle_png (int socketd, FILE *fp, int issock)
{
struct gfxinfo *result = NULL;
unsigned long in_width, in_height;
char temp[8];
unsigned char a[8];
result = (struct gfxinfo *) ecalloc(1, sizeof(struct gfxinfo));
FP_FREAD(temp, sizeof(temp), socketd, fp, issock); /* fseek(fp, 16L, SEEK_SET); */
if((FP_FREAD(a, sizeof(a), socketd, fp, issock)) <= 0) {
in_width = 0;
in_height = 0;
} else {
in_width = (((unsigned long) a[ 0 ]) << 24) + (((unsigned long) a[ 1 ]) << 16) + (((unsigned long) a[ 2 ]) << 8) + ((unsigned long) a[ 3 ]);
in_height = (((unsigned long) a[ 4 ]) << 24) + (((unsigned long) a[ 5 ]) << 16) + (((unsigned long) a[ 6 ]) << 8) + ((unsigned long) a[ 7 ]);
}
result->width = (unsigned int) in_width;
result->height = (unsigned int) in_height;
return result;
}
/* }}} */
/* routines to handle JPEG data */
/* some defines for the different JPEG block types */
#define M_SOF0 0xC0 /* Start Of Frame N */
#define M_SOF1 0xC1 /* N indicates which compression process */
#define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */
#define M_SOF3 0xC3
#define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */
#define M_SOF6 0xC6
#define M_SOF7 0xC7
#define M_SOF9 0xC9
#define M_SOF10 0xCA
#define M_SOF11 0xCB
#define M_SOF13 0xCD
#define M_SOF14 0xCE
#define M_SOF15 0xCF
#define M_SOI 0xD8
#define M_EOI 0xD9 /* End Of Image (end of datastream) */
#define M_SOS 0xDA /* Start Of Scan (begins compressed data) */
#define M_APP0 0xe0
#define M_APP1 0xe1
#define M_APP2 0xe2
#define M_APP3 0xe3
#define M_APP4 0xe4
#define M_APP5 0xe5
#define M_APP6 0xe6
#define M_APP7 0xe7
#define M_APP8 0xe8
#define M_APP9 0xe9
#define M_APP10 0xea
#define M_APP11 0xeb
#define M_APP12 0xec
#define M_APP13 0xed
#define M_APP14 0xee
#define M_APP15 0xef
/* {{{ php_read2
*/
static unsigned short php_read2(int socketd, FILE *fp, int issock)
{
unsigned char a[2];
/* just return 0 if we hit the end-of-file */
if((FP_FREAD(a, sizeof(a), socketd, fp, issock)) <= 0) return 0;
return (((unsigned short) a[ 0 ]) << 8) + ((unsigned short) a[ 1 ]);
}
/* }}} */
/* {{{ php_next_marker
*/
static unsigned int php_next_marker(int socketd, FILE *fp, int issock)
/* get next marker byte from file */
{
int c;
/* get marker byte, swallowing possible padding */
do {
if ((c = FP_FGETC(socketd, fp, issock)) == EOF)
return M_EOI; /* we hit EOF */
} while (c == 0xff);
return (unsigned int) c;
}
/* }}} */
/* {{{ php_skip_variable
*/
static void php_skip_variable(int socketd, FILE *fp, int issock)
/* skip over a variable-length block; assumes proper length marker */
{
unsigned short length;
char *tmp;
length = php_read2(socketd, fp, issock);
length -= 2; /* length includes itself */
tmp = emalloc(length);
FP_FREAD(tmp, (long) length, socketd, fp, issock); /* skip the header */
efree(tmp);
}
/* }}} */
/* {{{ php_read_APP
*/
static void php_read_APP(int socketd, FILE *fp, int issock, unsigned int marker, pval *info)
{
unsigned short length;
unsigned char *buffer;
unsigned char markername[ 16 ];
zval *tmp;
length = php_read2(socketd, fp, issock);
length -= 2; /* length includes itself */
buffer = emalloc(length);
if (FP_FREAD(buffer, (long) length, socketd, fp, issock) <= 0) {
efree(buffer);
return;
}
sprintf(markername, "APP%d", marker - M_APP0);
if (zend_hash_find(info->value.ht, markername, strlen(markername)+1, (void **) &tmp) == FAILURE) {
/* XXX we onyl catch the 1st tag of it's kind! */
add_assoc_stringl(info, markername, buffer, length, 1);
}
efree(buffer);
}
/* }}} */
/* {{{ php_handle_jpeg
main loop to parse JPEG structure */
static struct gfxinfo *php_handle_jpeg (int socketd, FILE *fp, int issock, pval *info)
{
struct gfxinfo *result = NULL;
unsigned int marker;
char tmp[2];
unsigned char a[4];
for (;;) {
marker = php_next_marker(socketd, fp, issock);
switch (marker) {
case M_SOF0:
case M_SOF1:
case M_SOF2:
case M_SOF3:
case M_SOF5:
case M_SOF6:
case M_SOF7:
case M_SOF9:
case M_SOF10:
case M_SOF11:
case M_SOF13:
case M_SOF14:
case M_SOF15:
if (result == NULL) {
/* handle SOFn block */
result = (struct gfxinfo *) ecalloc(1, sizeof(struct gfxinfo));
FP_FREAD(tmp, sizeof(tmp), socketd, fp, issock);
result->bits = FP_FGETC(socketd, fp, issock);
FP_FREAD(a, sizeof(a), socketd, fp, issock);
result->height = (((unsigned short) a[ 0 ]) << 8) + ((unsigned short) a[ 1 ]);
result->width = (((unsigned short) a[ 2 ]) << 8) + ((unsigned short) a[ 3 ]);
result->channels = FP_FGETC(socketd, fp, issock);
if (! info) /* if we don't want an extanded info -> return */
return result;
} else {
php_skip_variable(socketd, fp, issock);
}
break;
case M_APP0:
case M_APP1:
case M_APP2:
case M_APP3:
case M_APP4:
case M_APP5:
case M_APP6:
case M_APP7:
case M_APP8:
case M_APP9:
case M_APP10:
case M_APP11:
case M_APP12:
case M_APP13:
case M_APP14:
case M_APP15:
if (info) {
php_read_APP(socketd, fp, issock, marker, info); /* read all the app markes... */
} else {
php_skip_variable(socketd, fp, issock);
}
break;
case M_SOS:
case M_EOI:
return result; /* we're about to hit image data, or are at EOF. stop processing. */
break;
default:
php_skip_variable(socketd, fp, issock); /* anything else isn't interesting */
break;
}
}
return NULL;
}
/* }}} */
/* main function */
/* {{{ proto array getimagesize(string imagefile [, array info])
Get the size of an image as 4-element array */
PHP_FUNCTION(getimagesize)
{
pval **arg1, **info = 0;
FILE *fp;
int issock=0, socketd=0, rsrc_id;
int itype = 0;
char filetype[8];
char temp[64];
struct gfxinfo *result = NULL;
switch(ZEND_NUM_ARGS()) {
case 1:
if (zend_get_parameters_ex(1, &arg1) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(arg1);
break;
case 2:
if (zend_get_parameters_ex(2, &arg1, &info) == FAILURE) {
WRONG_PARAM_COUNT;
}
zval_dtor(*info);
if (array_init(*info) == FAILURE) {
return;
}
convert_to_string_ex(arg1);
break;
default:
WRONG_PARAM_COUNT;
break;
}
fp = php_fopen_wrapper(Z_STRVAL_PP(arg1), "rb", IGNORE_PATH|ENFORCE_SAFE_MODE, &issock, &socketd, NULL TSRMLS_CC);
if (!fp && !socketd) {
if (issock != BAD_URL) {
char *tmp = estrndup(Z_STRVAL_PP(arg1), Z_STRLEN_PP(arg1));
php_strip_url_passwd(tmp);
php_error(E_WARNING, "getimagesize: Unable to open '%s' for reading.", tmp);
efree(tmp);
}
RETURN_FALSE;
}
if (issock) {
int *sock=emalloc(sizeof(int));
*sock = socketd;
rsrc_id = ZEND_REGISTER_RESOURCE(NULL, sock, php_file_le_socket());
} else {
rsrc_id = ZEND_REGISTER_RESOURCE(NULL, fp, php_file_le_fopen());
}
if((FP_FREAD(filetype, 3, socketd, fp, issock)) <= 0) {
php_error(E_WARNING, "getimagesize: Read error!");
RETURN_FALSE;
}
if (!memcmp(filetype, php_sig_gif, 3)) {
result = php_handle_gif (socketd, fp, issock);
itype = 1;
} else if (!memcmp(filetype, php_sig_jpg, 3)) {
if (info) {
result = php_handle_jpeg(socketd, fp, issock, *info);
} else {
result = php_handle_jpeg(socketd, fp, issock, NULL);
}
itype = 2;
} else if (!memcmp(filetype, php_sig_png, 3)) {
FP_FREAD(filetype+3, 5, socketd, fp, issock);
if (!memcmp(filetype, php_sig_png, 8)) {
result = php_handle_png(socketd, fp, issock);
itype = 3;
} else {
php_error(E_WARNING, "PNG file corrupted by ASCII conversion");
}
} else if (!memcmp(filetype, php_sig_swf, 3)) {
result = php_handle_swf(socketd, fp, issock);
itype = 4;
} else if (!memcmp(filetype, php_sig_psd, 3)) {
result = php_handle_psd(socketd, fp, issock);
itype = 5;
} else if (!memcmp(filetype, php_sig_bmp, 2)) {
result = php_handle_bmp(socketd, fp, issock);
itype = 6;
}
zend_list_delete(rsrc_id);
if (result) {
if (array_init(return_value) == FAILURE) {
php_error(E_ERROR, "Unable to initialize array");
efree(result);
return;
}
add_index_long(return_value, 0, result->width);
add_index_long(return_value, 1, result->height);
add_index_long(return_value, 2, itype);
sprintf(temp, "width=\"%d\" height=\"%d\"", result->width, result->height); /* safe */
add_index_string(return_value, 3, temp, 1);
if (result->bits != 0) {
add_assoc_long(return_value, "bits", result->bits);
}
if (result->channels != 0) {
add_assoc_long(return_value, "channels", result->channels);
}
efree(result);
}
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+151
View File
@@ -0,0 +1,151 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Sascha Schumann <sascha@schumann.cx> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "basic_functions.h"
#include "php_incomplete_class.h"
#define INCOMPLETE_CLASS_MSG \
"The script tried to execute a method or " \
"access a property of an incomplete object. " \
"Please ensure that the class definition <b>%s</b> of the object " \
"you are trying to operate on was loaded _before_ " \
"the session was started"
#define INCOMPLETE_CLASS "__PHP_Incomplete_Class"
#define MAGIC_MEMBER "__PHP_Incomplete_Class_Name"
/* {{{ incomplete_class_message
*/
static void incomplete_class_message(zend_property_reference *ref)
{
char buf[1024];
char *class_name;
class_name = php_lookup_class_name(ref->object, NULL, 0);
if (!class_name)
class_name = estrdup("unknown");
snprintf(buf, 1023, INCOMPLETE_CLASS_MSG, class_name);
efree(class_name);
php_error(E_ERROR, "%s", buf);
}
/* }}} */
/* {{{ incomplete_class_call_func
*/
static void incomplete_class_call_func(INTERNAL_FUNCTION_PARAMETERS, zend_property_reference *property_reference)
{
incomplete_class_message(property_reference);
}
/* }}} */
/* {{{ incomplete_class_set_property
*/
static int incomplete_class_set_property(zend_property_reference *property_reference, zval *value)
{
incomplete_class_message(property_reference);
/* does not reach this point */
return (0);
}
/* }}} */
/* {{{ incomplete_class_get_property
*/
static zval incomplete_class_get_property(zend_property_reference *property_reference)
{
zval foo;
incomplete_class_message(property_reference);
/* does not reach this point */
memset(&foo, 0, sizeof(zval)); /* shut warnings up */
return (foo);
}
/* }}} */
/* {{{ php_create_incomplete_class
*/
zend_class_entry *php_create_incomplete_class(TSRMLS_D)
{
zend_class_entry incomplete_class;
INIT_OVERLOADED_CLASS_ENTRY(incomplete_class, INCOMPLETE_CLASS, NULL,
incomplete_class_call_func,
incomplete_class_get_property,
incomplete_class_set_property);
return zend_register_internal_class(&incomplete_class TSRMLS_CC);
}
/* }}} */
/* {{{ php_lookup_class_name
*/
char *php_lookup_class_name(zval *object, size_t *nlen, zend_bool del)
{
zval **val;
char *retval = NULL;
HashTable *object_properties;
object_properties = Z_OBJPROP_P(object);
if (zend_hash_find(object_properties, MAGIC_MEMBER, sizeof(MAGIC_MEMBER), (void **) &val) == SUCCESS) {
retval = estrndup(Z_STRVAL_PP(val), Z_STRLEN_PP(val));
if (nlen)
*nlen = Z_STRLEN_PP(val);
if (del)
zend_hash_del(object_properties, MAGIC_MEMBER, sizeof(MAGIC_MEMBER));
}
return (retval);
}
/* }}} */
/* {{{ php_store_class_name
*/
void php_store_class_name(zval *object, const char *name, size_t len)
{
zval *val;
MAKE_STD_ZVAL(val);
Z_TYPE_P(val) = IS_STRING;
Z_STRVAL_P(val) = estrndup(name, len);
Z_STRLEN_P(val) = len;
zend_hash_update(Z_OBJPROP_P(object), MAGIC_MEMBER, sizeof(MAGIC_MEMBER), &val, sizeof(val), NULL);
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+581
View File
@@ -0,0 +1,581 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
| Zeev Suraski <zeev@zend.com> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "php_ini.h"
#include "php_globals.h"
#include "ext/standard/head.h"
#include "info.h"
#include "credits.h"
#include "SAPI.h"
#include <time.h>
#if !defined(PHP_WIN32)
#include "build-defs.h"
#endif
#include "zend_globals.h" /* needs ELS */
#include "zend_highlight.h"
#define SECTION(name) PUTS("<h2 align=\"center\">" name "</h2>\n")
PHPAPI extern char *php_ini_opened_path;
/* {{{ _display_module_info
*/
static int _display_module_info(zend_module_entry *module, void *arg TSRMLS_DC)
{
int show_info_func = *((int *) arg);
if (show_info_func && module->info_func) {
php_printf("<h2 align=\"center\"><a name=\"module_%s\">%s</a></h2>\n", module->name, module->name);
module->info_func(module TSRMLS_CC);
} else if (!show_info_func && !module->info_func) {
php_printf("<tr valign=\"baseline\" bgcolor=\"" PHP_CONTENTS_COLOR "\">");
php_printf("<td>");
php_printf("%s", module->name);
php_printf("</td></tr>\n");
}
return 0;
}
/* }}} */
/* {{{ php_print_gpcse_array
*/
static void php_print_gpcse_array(char *name, uint name_length TSRMLS_DC)
{
zval **data, **tmp, tmp2;
char *string_key;
ulong num_key;
if (zend_hash_find(&EG(symbol_table), name, name_length+1, (void **) &data)!=FAILURE
&& ((*data)->type==IS_ARRAY)) {
zend_hash_internal_pointer_reset((*data)->value.ht);
while (zend_hash_get_current_data((*data)->value.ht, (void **) &tmp) == SUCCESS) {
PUTS("<tr valign=\"baseline\" bgcolor=\"" PHP_CONTENTS_COLOR "\">");
PUTS("<td bgcolor=\"" PHP_ENTRY_NAME_COLOR "\"><b>");
PUTS(name);
PUTS("[\"");
switch (zend_hash_get_current_key((*data)->value.ht, &string_key, &num_key, 0)) {
case HASH_KEY_IS_STRING:
zend_html_puts(string_key, strlen(string_key));
break;
case HASH_KEY_IS_LONG:
php_printf("%ld", num_key);
break;
}
PUTS("\"]</b></td><td>");
if ((*tmp)->type == IS_ARRAY) {
PUTS("<pre>");
zend_print_zval_r(*tmp, 0);
PUTS("</pre>");
} else if ((*tmp)->type != IS_STRING) {
tmp2 = **tmp;
zval_copy_ctor(&tmp2);
convert_to_string(&tmp2);
zend_html_puts(tmp2.value.str.val, tmp2.value.str.len);
zval_dtor(&tmp2);
} else {
zend_html_puts((*tmp)->value.str.val, (*tmp)->value.str.len);
}
PUTS("&nbsp;</td></tr>\n");
zend_hash_move_forward((*data)->value.ht);
}
}
}
/* }}} */
/* {{{ php_info_print_style
*/
void php_info_print_style(void)
{
php_printf("<style type=\"text/css\"><!--\n");
php_printf("a { text-decoration: none; }\n");
php_printf("a:hover { text-decoration: underline; }\n");
php_printf("h1 { font-family: arial, helvetica, sans-serif; font-size: 18pt; font-weight: bold;}\n");
php_printf("h2 { font-family: arial, helvetica, sans-serif; font-size: 14pt; font-weight: bold;}\n");
php_printf("body, td { font-family: arial, helvetica, sans-serif; font-size: 10pt; }\n");
php_printf("th { font-family: arial, helvetica, sans-serif; font-size: 11pt; font-weight: bold; }\n");
php_printf("//--></style>\n");
}
/* }}} */
/* {{{ php_get_uname
*/
PHPAPI char *php_get_uname()
{
char *php_uname;
#ifdef PHP_WIN32
char php_windows_uname[256];
DWORD dwBuild=0;
DWORD dwVersion = GetVersion();
DWORD dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
DWORD dwWindowsMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
/* Get build numbers for Windows NT or Win95 */
if (dwVersion < 0x80000000){
dwBuild = (DWORD)(HIWORD(dwVersion));
snprintf(php_windows_uname, 255, "%s %d.%d build %d", "Windows NT", dwWindowsMajorVersion, dwWindowsMinorVersion, dwBuild);
} else {
snprintf(php_windows_uname, 255, "%s %d.%d", "Windows 95/98", dwWindowsMajorVersion, dwWindowsMinorVersion);
}
php_uname = php_windows_uname;
#else
php_uname=PHP_UNAME;
#endif
return estrdup(php_uname);
}
/* }}} */
/* {{{ php_print_info
*/
PHPAPI void php_print_info(int flag TSRMLS_DC)
{
char **env, *tmp1, *tmp2;
char *php_uname;
int expose_php = INI_INT("expose_php");
time_t the_time;
struct tm *ta, tmbuf;
the_time = time(NULL);
ta = php_localtime_r(&the_time, &tmbuf);
PUTS("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<html>\n");
if (flag & PHP_INFO_GENERAL) {
char *zend_version = get_zend_version();
php_uname = php_get_uname();
PUTS("<head>");
php_info_print_style();
PUTS("<title>phpinfo()</title></head><body>");
php_info_print_box_start(1);
if (expose_php) {
PUTS("<a href=\"http://www.php.net/\"><img src=\"");
if (SG(request_info).request_uri) {
PUTS(SG(request_info).request_uri);
}
if ((ta->tm_mon==3) && (ta->tm_mday==1)) {
PUTS("?="PHP_EGG_LOGO_GUID"\" border=0 align=\"right\" alt=\"Thies!\"></a>");
} else {
PUTS("?="PHP_LOGO_GUID"\" border=0 align=\"right\" alt=\"PHP Logo\"></a>");
}
}
php_printf("<h1>PHP Version %s</h1>\n", PHP_VERSION);
php_info_print_box_end();
php_info_print_table_start();
php_info_print_table_row(2, "System", php_uname );
php_info_print_table_row(2, "Build Date", __DATE__ " " __TIME__ );
#ifdef CONFIGURE_COMMAND
php_info_print_table_row(2, "Configure Command", CONFIGURE_COMMAND );
#endif
if (sapi_module.pretty_name) {
php_info_print_table_row(2, "Server API", sapi_module.pretty_name );
}
#ifdef VIRTUAL_DIR
php_info_print_table_row(2, "Virtual Directory Support", "enabled" );
#else
php_info_print_table_row(2, "Virtual Directory Support", "disabled" );
#endif
php_info_print_table_row(2, "Configuration File (php.ini) Path", php_ini_opened_path?php_ini_opened_path:PHP_CONFIG_FILE_PATH);
#if ZEND_DEBUG
php_info_print_table_row(2, "ZEND_DEBUG", "enabled" );
#else
php_info_print_table_row(2, "ZEND_DEBUG", "disabled" );
#endif
#ifdef ZTS
php_info_print_table_row(2, "Thread Safety", "enabled" );
#else
php_info_print_table_row(2, "Thread Safety", "disabled" );
#endif
#if HAVE_PHP_STREAM
php_info_print_table_row(2, "Experimental PHP Streams", "enabled");
#endif
php_info_print_table_end();
/* Zend Engine */
php_info_print_box_start(0);
if (expose_php) {
PUTS("<a href=\"http://www.zend.com/\"><img src=\"");
if (SG(request_info).request_uri) {
PUTS(SG(request_info).request_uri);
}
PUTS("?="ZEND_LOGO_GUID"\" border=\"0\" align=\"right\" alt=\"Zend logo\"></a>\n");
}
php_printf("This program makes use of the Zend Scripting Language Engine:<br>");
zend_html_puts(zend_version, strlen(zend_version));
php_info_print_box_end();
efree(php_uname);
}
if ((flag & PHP_INFO_CREDITS) && expose_php) {
php_info_print_hr();
PUTS("<h1 align=\"center\"><a href=\"");
if (SG(request_info).request_uri) {
PUTS(SG(request_info).request_uri);
}
PUTS("?=PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000\">");
PUTS("PHP 4.0 Credits");
PUTS("</a></h1>\n");
}
zend_ini_sort_entries(TSRMLS_C);
if (flag & PHP_INFO_CONFIGURATION) {
php_info_print_hr();
PUTS("<h1 align=\"center\">Configuration</h1>\n");
SECTION("PHP Core\n");
display_ini_entries(NULL);
}
if (flag & PHP_INFO_MODULES) {
int show_info_func;
show_info_func = 1;
zend_hash_apply_with_argument(&module_registry, (apply_func_arg_t) _display_module_info, &show_info_func TSRMLS_CC);
SECTION("Additional Modules");
php_info_print_table_start();
show_info_func = 0;
zend_hash_apply_with_argument(&module_registry, (apply_func_arg_t) _display_module_info, &show_info_func TSRMLS_CC);
php_info_print_table_end();
}
if (flag & PHP_INFO_ENVIRONMENT) {
SECTION("Environment");
php_info_print_table_start();
php_info_print_table_header(2, "Variable", "Value");
for (env=environ; env!=NULL && *env !=NULL; env++) {
tmp1 = estrdup(*env);
if (!(tmp2=strchr(tmp1,'='))) { /* malformed entry? */
efree(tmp1);
continue;
}
*tmp2 = 0;
tmp2++;
php_info_print_table_row(2, tmp1, tmp2);
efree(tmp1);
}
php_info_print_table_end();
}
if (flag & PHP_INFO_VARIABLES) {
pval **data;
SECTION("PHP Variables");
php_info_print_table_start();
php_info_print_table_header(2, "Variable", "Value");
if (zend_hash_find(&EG(symbol_table), "PHP_SELF", sizeof("PHP_SELF"), (void **) &data) != FAILURE) {
php_info_print_table_row(2, "PHP_SELF", (*data)->value.str.val);
}
if (zend_hash_find(&EG(symbol_table), "PHP_AUTH_TYPE", sizeof("PHP_AUTH_TYPE"), (void **) &data) != FAILURE) {
php_info_print_table_row(2, "PHP_AUTH_TYPE", (*data)->value.str.val);
}
if (zend_hash_find(&EG(symbol_table), "PHP_AUTH_USER", sizeof("PHP_AUTH_USER"), (void **) &data) != FAILURE) {
php_info_print_table_row(2, "PHP_AUTH_USER", (*data)->value.str.val);
}
if (zend_hash_find(&EG(symbol_table), "PHP_AUTH_PW", sizeof("PHP_AUTH_PW"), (void **) &data) != FAILURE) {
php_info_print_table_row(2, "PHP_AUTH_PW", (*data)->value.str.val);
}
php_print_gpcse_array("_FORM", sizeof("_FORM")-1 TSRMLS_CC);
php_print_gpcse_array("_GET", sizeof("_GET")-1 TSRMLS_CC);
php_print_gpcse_array("_POST", sizeof("_POST")-1 TSRMLS_CC);
php_print_gpcse_array("_FILES", sizeof("_FILES")-1 TSRMLS_CC);
php_print_gpcse_array("_COOKIE", sizeof("_COOKIE")-1 TSRMLS_CC);
php_print_gpcse_array("_SERVER", sizeof("_SERVER")-1 TSRMLS_CC);
php_print_gpcse_array("_ENV", sizeof("_ENV")-1 TSRMLS_CC);
php_info_print_table_end();
}
if (flag & PHP_INFO_LICENSE) {
SECTION("PHP License");
php_info_print_box_start(0);
PUTS("<p>\n");
PUTS("This program is free software; you can redistribute it and/or modify ");
PUTS("it under the terms of the PHP License as published by the PHP Group ");
PUTS("and included in the distribution in the file: LICENSE\n");
PUTS("</p>\n");
PUTS("<p>");
PUTS("This program is distributed in the hope that it will be useful, ");
PUTS("but WITHOUT ANY WARRANTY; without even the implied warranty of ");
PUTS("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
PUTS("</p>\n");
PUTS("<p>");
PUTS("If you did not receive a copy of the PHP license, or have any questions about ");
PUTS("PHP licensing, please contact license@php.net.\n");
PUTS("</p>\n");
php_info_print_box_end();
}
PUTS("</body></html>");
}
/* }}} */
PHPAPI void php_info_print_table_start()
{
php_printf("<table border=\"0\" cellpadding=\"3\" cellspacing=\"1\" width=\"600\" bgcolor=\"#000000\" align=\"center\">\n");
}
PHPAPI void php_info_print_table_end()
{
php_printf("</table><br>\n");
}
PHPAPI void php_info_print_box_start(int flag)
{
php_info_print_table_start();
if (flag) {
php_printf("<tr valign=\"middle\" bgcolor=\"" PHP_HEADER_COLOR "\"><td align=\"left\">\n");
} else {
php_printf("<tr valign=\"top\" bgcolor=\"" PHP_CONTENTS_COLOR "\"><td align=\"left\">\n");
}
}
PHPAPI void php_info_print_box_end()
{
php_printf("</td></tr>\n");
php_info_print_table_end();
}
PHPAPI void php_info_print_hr()
{
php_printf("<hr noshade size=\"1\" width=\"600\">\n");
}
PHPAPI void php_info_print_table_colspan_header(int num_cols, char *header)
{
php_printf("<tr bgcolor=\"" PHP_HEADER_COLOR "\"><th colspan=\"%d\">%s</th></tr>\n", num_cols, header );
}
/* {{{ php_info_print_table_header
*/
PHPAPI void php_info_print_table_header(int num_cols, ...)
{
int i;
va_list row_elements;
char *row_element;
va_start(row_elements, num_cols);
php_printf("<tr valign=\"middle\" bgcolor=\"" PHP_HEADER_COLOR "\">");
for (i=0; i<num_cols; i++) {
row_element = va_arg(row_elements, char *);
if (!row_element || !*row_element) {
row_element = "&nbsp;";
}
php_printf("<th>%s</th>", row_element);
}
php_printf("</tr>\n");
va_end(row_elements);
}
/* }}} */
/* {{{ php_info_print_table_row
*/
PHPAPI void php_info_print_table_row(int num_cols, ...)
{
int i;
va_list row_elements;
char *row_element;
va_start(row_elements, num_cols);
php_printf("<tr valign=\"baseline\" bgcolor=\"" PHP_CONTENTS_COLOR "\">");
for (i=0; i<num_cols; i++) {
php_printf("<td %s>%s",
(i==0?"bgcolor=\"" PHP_ENTRY_NAME_COLOR "\" ":"align=\"left\""),
(i==0?"<b>":""));
row_element = va_arg(row_elements, char *);
if (!row_element || !*row_element) {
php_printf("&nbsp;");
} else {
zend_html_puts(row_element, strlen(row_element));
}
php_printf("%s</td>", (i==0?"</b>":""));
}
php_printf("</tr>\n");
va_end(row_elements);
}
/* }}} */
/* {{{ register_phpinfo_constants
*/
void register_phpinfo_constants(INIT_FUNC_ARGS)
{
REGISTER_LONG_CONSTANT("INFO_GENERAL", PHP_INFO_GENERAL, CONST_PERSISTENT|CONST_CS);
REGISTER_LONG_CONSTANT("INFO_CREDITS", PHP_INFO_CREDITS, CONST_PERSISTENT|CONST_CS);
REGISTER_LONG_CONSTANT("INFO_CONFIGURATION", PHP_INFO_CONFIGURATION, CONST_PERSISTENT|CONST_CS);
REGISTER_LONG_CONSTANT("INFO_MODULES", PHP_INFO_MODULES, CONST_PERSISTENT|CONST_CS);
REGISTER_LONG_CONSTANT("INFO_ENVIRONMENT", PHP_INFO_ENVIRONMENT, CONST_PERSISTENT|CONST_CS);
REGISTER_LONG_CONSTANT("INFO_VARIABLES", PHP_INFO_VARIABLES, CONST_PERSISTENT|CONST_CS);
REGISTER_LONG_CONSTANT("INFO_LICENSE", PHP_INFO_LICENSE, CONST_PERSISTENT|CONST_CS);
REGISTER_LONG_CONSTANT("INFO_ALL", PHP_INFO_ALL, CONST_PERSISTENT|CONST_CS);
REGISTER_LONG_CONSTANT("CREDITS_GROUP", PHP_CREDITS_GROUP, CONST_PERSISTENT|CONST_CS);
REGISTER_LONG_CONSTANT("CREDITS_GENERAL", PHP_CREDITS_GENERAL, CONST_PERSISTENT|CONST_CS);
REGISTER_LONG_CONSTANT("CREDITS_SAPI", PHP_CREDITS_SAPI, CONST_PERSISTENT|CONST_CS);
REGISTER_LONG_CONSTANT("CREDITS_MODULES", PHP_CREDITS_MODULES, CONST_PERSISTENT|CONST_CS);
REGISTER_LONG_CONSTANT("CREDITS_DOCS", PHP_CREDITS_DOCS, CONST_PERSISTENT|CONST_CS);
REGISTER_LONG_CONSTANT("CREDITS_FULLPAGE", PHP_CREDITS_FULLPAGE, CONST_PERSISTENT|CONST_CS);
REGISTER_LONG_CONSTANT("CREDITS_QA", PHP_CREDITS_QA, CONST_PERSISTENT|CONST_CS);
REGISTER_LONG_CONSTANT("CREDITS_ALL", PHP_CREDITS_ALL, CONST_PERSISTENT|CONST_CS);
}
/* }}} */
/* {{{ proto void phpinfo([int what])
Output a page of useful information about PHP and the current request */
PHP_FUNCTION(phpinfo)
{
int argc = ZEND_NUM_ARGS();
long flag;
if (zend_parse_parameters(argc TSRMLS_CC, "|l", &flag) == FAILURE) {
return;
}
if(!argc) {
flag = 0xFFFFFFFF;
}
php_print_info(flag TSRMLS_CC);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto string phpversion(void)
Return the current PHP version */
PHP_FUNCTION(phpversion)
{
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
RETURN_STRING(PHP_VERSION, 1);
}
/* }}} */
/* {{{ proto void phpcredits([int flag])
Prints the list of people who've contributed to the PHP project */
PHP_FUNCTION(phpcredits)
{
int argc = ZEND_NUM_ARGS();
long flag;
if (zend_parse_parameters(argc TSRMLS_CC, "|l", &flag) == FAILURE) {
return;
}
if(!argc) {
flag = 0xFFFFFFFF;
}
php_print_credits(flag);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto string php_logo_guid(void)
Return the special ID used to request the PHP logo in phpinfo screens*/
PHP_FUNCTION(php_logo_guid)
{
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
RETURN_STRINGL(PHP_LOGO_GUID, sizeof(PHP_LOGO_GUID)-1, 1);
}
/* }}} */
/* {{{ proto string php_egg_logo_guid(void)
Return the special ID used to request the PHP logo in phpinfo screens*/
PHP_FUNCTION(php_egg_logo_guid)
{
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
RETURN_STRINGL(PHP_EGG_LOGO_GUID, sizeof(PHP_EGG_LOGO_GUID)-1, 1);
}
/* }}} */
/* {{{ proto string zend_logo_guid(void)
Return the special ID used to request the Zend logo in phpinfo screens*/
PHP_FUNCTION(zend_logo_guid)
{
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
RETURN_STRINGL(ZEND_LOGO_GUID, sizeof(ZEND_LOGO_GUID)-1, 1);
}
/* }}} */
/* {{{ proto string php_sapi_name(void)
Return the current SAPI module name */
PHP_FUNCTION(php_sapi_name)
{
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
if (sapi_module.name) {
RETURN_STRING(sapi_module.name, 1);
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto string php_uname(void)
Return information about the system PHP was built on */
PHP_FUNCTION(php_uname)
{
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
RETURN_STRING(php_get_uname(), 0);
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+80
View File
@@ -0,0 +1,80 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
| Zeev Suraski <zeev@zend.com> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef INFO_H
#define INFO_H
#define PHP_ENTRY_NAME_COLOR "#ccccff"
#define PHP_CONTENTS_COLOR "#cccccc"
#define PHP_HEADER_COLOR "#9999cc"
#define PHP_INFO_GENERAL (1<<0)
#define PHP_INFO_CREDITS (1<<1)
#define PHP_INFO_CONFIGURATION (1<<2)
#define PHP_INFO_MODULES (1<<3)
#define PHP_INFO_ENVIRONMENT (1<<4)
#define PHP_INFO_VARIABLES (1<<5)
#define PHP_INFO_LICENSE (1<<6)
#define PHP_INFO_ALL 0xFFFFFFFF
#ifndef HAVE_CREDITS_DEFS
#define HAVE_CREDITS_DEFS
#define PHP_CREDITS_GROUP (1<<0)
#define PHP_CREDITS_GENERAL (1<<1)
#define PHP_CREDITS_SAPI (1<<2)
#define PHP_CREDITS_MODULES (1<<3)
#define PHP_CREDITS_DOCS (1<<4)
#define PHP_CREDITS_FULLPAGE (1<<5)
#define PHP_CREDITS_QA (1<<6)
#define PHP_CREDITS_WEB (1<<7)
#define PHP_CREDITS_ALL 0xFFFFFFFF
#endif /* HAVE_CREDITS_DEFS */
#define PHP_LOGO_GUID "PHPE9568F34-D428-11d2-A769-00AA001ACF42"
#define PHP_EGG_LOGO_GUID "PHPE9568F36-D428-11d2-A769-00AA001ACF42"
#define ZEND_LOGO_GUID "PHPE9568F35-D428-11d2-A769-00AA001ACF42"
#define PHP_CREDITS_GUID "PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000"
PHP_FUNCTION(phpversion);
PHP_FUNCTION(phpinfo);
PHP_FUNCTION(phpcredits);
PHP_FUNCTION(php_logo_guid);
PHP_FUNCTION(zend_logo_guid);
PHP_FUNCTION(php_egg_logo_guid);
PHP_FUNCTION(php_sapi_name);
PHP_FUNCTION(php_uname);
PHPAPI void php_print_info(int flag TSRMLS_DC);
PHPAPI void php_print_style(void);
PHPAPI void php_info_print_style(void);
PHPAPI void php_info_print_table_colspan_header(int num_cols, char *header);
PHPAPI void php_info_print_table_header(int num_cols, ...);
PHPAPI void php_info_print_table_row(int num_cols, ...);
PHPAPI void php_info_print_table_start(void);
PHPAPI void php_info_print_table_end(void);
PHPAPI void php_info_print_box_start(int bg);
PHPAPI void php_info_print_box_end(void);
PHPAPI void php_info_print_hr(void);
void register_phpinfo_constants(INIT_FUNC_ARGS);
#endif /* INFO_H */
+396
View File
@@ -0,0 +1,396 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Thies C. Arntzen (thies@thieso.net) |
+----------------------------------------------------------------------+
*/
/* $Id$ */
/*
* Functions to parse & compse IPTC data.
* PhotoShop >= 3.0 can read and write textual data to JPEG files.
* ... more to come .....
*
* i know, parts of this is now duplicated in image.c
* but in this case i think it's okay!
*/
/*
* TODO:
* - add IPTC translation table
*/
#include "php.h"
#include "php_iptc.h"
#include "ext/standard/head.h"
#include <sys/stat.h>
/* some defines for the different JPEG block types */
#define M_SOF0 0xC0 /* Start Of Frame N */
#define M_SOF1 0xC1 /* N indicates which compression process */
#define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */
#define M_SOF3 0xC3
#define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */
#define M_SOF6 0xC6
#define M_SOF7 0xC7
#define M_SOF9 0xC9
#define M_SOF10 0xCA
#define M_SOF11 0xCB
#define M_SOF13 0xCD
#define M_SOF14 0xCE
#define M_SOF15 0xCF
#define M_SOI 0xD8
#define M_EOI 0xD9 /* End Of Image (end of datastream) */
#define M_SOS 0xDA /* Start Of Scan (begins compressed data) */
#define M_APP0 0xe0
#define M_APP1 0xe1
#define M_APP2 0xe2
#define M_APP3 0xe3
#define M_APP4 0xe4
#define M_APP5 0xe5
#define M_APP6 0xe6
#define M_APP7 0xe7
#define M_APP8 0xe8
#define M_APP9 0xe9
#define M_APP10 0xea
#define M_APP11 0xeb
#define M_APP12 0xec
#define M_APP13 0xed
#define M_APP14 0xee
#define M_APP15 0xef
/* {{{ php_iptc_put1
*/
static int php_iptc_put1(FILE *fp, int spool, unsigned char c, unsigned char **spoolbuf TSRMLS_DC)
{
if (spool > 0)
PUTC(c);
if (spoolbuf) *(*spoolbuf)++ = c;
return c;
}
/* }}} */
/* {{{ php_iptc_get1
*/
static int php_iptc_get1(FILE *fp, int spool, unsigned char **spoolbuf TSRMLS_DC)
{
int c;
char cc;
c = getc(fp);
if (c == EOF) return EOF;
if (spool > 0) {
cc = c;
PUTC(cc);
}
if (spoolbuf) *(*spoolbuf)++ = c;
return c;
}
/* }}} */
/* {{{ php_iptc_read_remaining
*/
static int php_iptc_read_remaining(FILE *fp, int spool, unsigned char **spoolbuf TSRMLS_DC)
{
int c;
while ((c = php_iptc_get1(fp, spool, spoolbuf TSRMLS_CC)) != EOF) continue;
return M_EOI;
}
/* }}} */
/* {{{ php_iptc_skip_variable
*/
static int php_iptc_skip_variable(FILE *fp, int spool, unsigned char **spoolbuf TSRMLS_DC)
{
unsigned int length;
int c1, c2;
if ((c1 = php_iptc_get1(fp, spool, spoolbuf TSRMLS_CC)) == EOF) return M_EOI;
if ((c2 = php_iptc_get1(fp, spool, spoolbuf TSRMLS_CC)) == EOF) return M_EOI;
length = (((unsigned char) c1) << 8) + ((unsigned char) c2);
length -= 2;
while (length--)
if (php_iptc_get1(fp, spool, spoolbuf TSRMLS_CC) == EOF) return M_EOI;
return 0;
}
/* }}} */
/* {{{ php_iptc_next_marker
*/
static int php_iptc_next_marker(FILE *fp, int spool, unsigned char **spoolbuf TSRMLS_DC)
{
int c;
/* skip unimportant stuff */
c = php_iptc_get1(fp, spool, spoolbuf TSRMLS_CC);
if (c == EOF) return M_EOI;
while (c != 0xff) {
if ((c = php_iptc_get1(fp, spool, spoolbuf TSRMLS_CC)) == EOF)
return M_EOI; /* we hit EOF */
}
/* get marker byte, swallowing possible padding */
do {
c = php_iptc_get1(fp, 0, 0 TSRMLS_CC);
if (c == EOF)
return M_EOI; /* we hit EOF */
else
if (c == 0xff)
php_iptc_put1(fp, spool, (unsigned char)c, spoolbuf TSRMLS_CC);
} while (c == 0xff);
return (unsigned int) c;
}
/* }}} */
static char psheader[] = "\xFF\xED\0\0Photoshop 3.0\08BIM\x04\x04\0\0\0\0";
/* {{{ proto array iptcembed(string iptcdata, string jpeg_file_name [, int spool])
Embed binary IPTC data into a JPEG image. */
PHP_FUNCTION(iptcembed)
{
zval **iptcdata, **jpeg_file, **spool_flag;
FILE *fp;
unsigned int marker;
unsigned int spool = 0, done = 0, inx, len;
unsigned char *spoolbuf=0, *poi=0;
struct stat sb;
switch(ZEND_NUM_ARGS()){
case 3:
if (zend_get_parameters_ex(3, &iptcdata, &jpeg_file, &spool_flag) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(iptcdata);
convert_to_string_ex(jpeg_file);
convert_to_long_ex(spool_flag);
spool = (*spool_flag)->value.lval;
break;
case 2:
if (zend_get_parameters_ex(2, &iptcdata, &jpeg_file) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(iptcdata);
convert_to_string_ex(jpeg_file);
break;
default:
WRONG_PARAM_COUNT;
break;
}
if (php_check_open_basedir((*jpeg_file)->value.str.val TSRMLS_CC)) {
RETURN_FALSE;
}
if ((fp = VCWD_FOPEN((*jpeg_file)->value.str.val, "rb")) == 0) {
php_error(E_WARNING, "Unable to open %s", (*jpeg_file)->value.str.val);
RETURN_FALSE;
}
len = (*iptcdata)->value.str.len;
if (spool < 2) {
fstat(fileno(fp), &sb);
poi = spoolbuf = emalloc(len + sizeof(psheader) + sb.st_size + 1024);
if (! spoolbuf) {
fclose(fp);
RETURN_FALSE;
}
}
if (php_iptc_get1(fp, spool, poi?&poi:0 TSRMLS_CC) != 0xFF) {
fclose(fp);
RETURN_FALSE;
}
if (php_iptc_get1(fp, spool, poi?&poi:0 TSRMLS_CC) != 0xD8) {
fclose(fp);
RETURN_FALSE;
}
while (!done) {
marker = php_iptc_next_marker(fp, spool, poi?&poi:0 TSRMLS_CC);
if (marker == M_EOI) { /* EOF */
break;
} else if (marker != M_APP13) {
php_iptc_put1(fp, spool, (unsigned char)marker, poi?&poi:0 TSRMLS_CC);
}
switch (marker) {
case M_APP13:
/* we are going to write a new APP13 marker, so don't output the old one */
php_iptc_skip_variable(fp, 0, 0 TSRMLS_CC);
php_iptc_read_remaining(fp, spool, poi?&poi:0 TSRMLS_CC);
done = 1;
break;
case M_APP0:
/* APP0 is in each and every JPEG, so when we hit APP0 we insert our new APP13! */
php_iptc_skip_variable(fp, spool, poi?&poi:0 TSRMLS_CC);
if (len & 1) len++; /* make the length even */
psheader[ 2 ] = (len+28)>>8;
psheader[ 3 ] = (len+28)&0xff;
for (inx = 0; inx < 28; inx++)
php_iptc_put1(fp, spool, psheader[inx], poi?&poi:0 TSRMLS_CC);
php_iptc_put1(fp, spool, (unsigned char)(len>>8), poi?&poi:0 TSRMLS_CC);
php_iptc_put1(fp, spool, (unsigned char)(len&0xff), poi?&poi:0 TSRMLS_CC);
for (inx = 0; inx < len; inx++)
php_iptc_put1(fp, spool, (*iptcdata)->value.str.val[inx], poi?&poi:0 TSRMLS_CC);
break;
case M_SOS:
/* we hit data, no more marker-inserting can be done! */
php_iptc_read_remaining(fp, spool, poi?&poi:0 TSRMLS_CC);
done = 1;
break;
default:
php_iptc_skip_variable(fp, spool, poi?&poi:0 TSRMLS_CC);
break;
}
}
fclose(fp);
if (spool < 2) {
RETVAL_STRINGL(spoolbuf, poi - spoolbuf, 0);
} else {
RETURN_TRUE;
}
}
/* }}} */
/* {{{ proto array iptcparse(string iptcdata)
Parse binary IPTC-data into associative array */
PHP_FUNCTION(iptcparse)
{
unsigned int length, inx, len, inheader, tagsfound;
unsigned char *buffer;
unsigned char recnum, dataset;
unsigned char key[ 16 ];
zval *values, **str, **element;
if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &str) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(str);
inx = 0;
length = (*str)->value.str.len;
buffer = (*str)->value.str.val;
inheader = 0; /* have we already found the IPTC-Header??? */
tagsfound = 0; /* number of tags already found */
while (inx < length) { /* find 1st tag */
if ((buffer[inx] == 0x1c) && (buffer[inx+1] == 0x02)){
break;
} else {
inx++;
}
}
while (inx < length) {
if (buffer[ inx++ ] != 0x1c) {
break; /* we ran against some data which does not conform to IPTC - stop parsing! */
}
if ((inx + 4) >= length)
break;
dataset = buffer[ inx++ ];
recnum = buffer[ inx++ ];
if (buffer[ inx ] & (unsigned char) 0x80) { /* long tag */
len = (((long) buffer[ inx + 2 ]) << 24) + (((long) buffer[ inx + 3 ]) << 16) +
(((long) buffer[ inx + 4 ]) << 8) + (((long) buffer[ inx + 5 ]));
inx += 6;
} else { /* short tag */
len = (((unsigned short) buffer[ inx ])<<8) | (unsigned short)buffer[ inx+1 ];
inx += 2;
}
sprintf(key, "%d#%03d", (unsigned int) dataset, (unsigned int) recnum);
if ((len > length) || (inx + len) > length)
break;
if (tagsfound == 0) { /* found the 1st tag - initialize the return array */
if (array_init(return_value) == FAILURE) {
php_error(E_ERROR, "Unable to initialize array");
RETURN_FALSE;
}
}
if (zend_hash_find(return_value->value.ht, key, strlen(key) + 1, (void **) &element) == FAILURE) {
ALLOC_ZVAL(values);
INIT_PZVAL(values);
if (array_init(values) == FAILURE) {
php_error(E_ERROR, "Unable to initialize array");
RETURN_FALSE;
}
zend_hash_update(return_value->value.ht, key, strlen(key)+1, (void *) &values, sizeof(pval*), (void **) &element);
}
add_next_index_stringl(*element, buffer+inx, len, 1);
inx += len;
tagsfound++;
}
if (! tagsfound) {
RETURN_FALSE;
}
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+112
View File
@@ -0,0 +1,112 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Sascha Schumann <sascha@schumann.cx> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "php_lcg.h"
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef ZTS
int lcg_globals_id;
#else
static php_lcg_globals lcg_globals;
static int php_lcg_initialized = 0;
#endif
#ifdef PHP_WIN32
#include <process.h>
#endif
/*
* combinedLCG() returns a pseudo random number in the range of (0, 1).
* The function combines two CGs with periods of
* 2^31 - 85 and 2^31 - 249. The period of this function
* is equal to the product of both primes.
*
* There are only about 65k distinct starting values, that's
* not much... If PHP is running as CGI, randomness is quite bad.
* If it is run as a module, it's long-livin', so no problem in that
* case.
*/
#define MODMULT(a, b, c, m, s) q = s/a;s=b*(s-a*q)-c*q;if(s<0)s+=m
double php_combined_lcg(TSRMLS_D)
{
php_int32 q;
php_int32 z;
MODMULT(53668, 40014, 12211, 2147483563L, LCG(s1));
MODMULT(52774, 40692, 3791, 2147483399L, LCG(s2));
z = LCG(s1) - LCG(s2);
if(z < 1) {
z += 2147483562;
}
return z * 4.656613e-10;
}
static void lcg_init_globals(php_lcg_globals *lcg_globals_p TSRMLS_DC)
{
LCG(s1) = 1;
#ifdef ZTS
LCG(s2) = (long) tsrm_thread_id();
#else
LCG(s2) = (long) getpid();
#endif
}
#ifdef ZTS
PHP_MINIT_FUNCTION(lcg)
{
ts_allocate_id(&lcg_globals_id, sizeof(php_lcg_globals), (ts_allocate_ctor) lcg_init_globals, NULL);
return SUCCESS;
}
#else
PHP_RINIT_FUNCTION(lcg)
{
if (!php_lcg_initialized) {
lcg_init_globals(&lcg_globals TSRMLS_CC);
php_lcg_initialized = 1;
}
return SUCCESS;
}
#endif
/* {{{ proto double lcg_value()
Returns a value from the combined linear congruential generator */
PHP_FUNCTION(lcg_value)
{
RETURN_DOUBLE(php_combined_lcg(TSRMLS_C));
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=8 ts=8 tw=78
*/
+162
View File
@@ -0,0 +1,162 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Hartmut Holzgraefe <hartmut@six.de> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include "php_string.h"
#define LEVENSHTEIN_MAX_LENTH 255
/* {{{ reference_levdist
* reference implementation, only optimized for memory usage, not speed */
static int reference_levdist(const char *s1, int l1,
const char *s2, int l2,
int cost_ins, int cost_rep, int cost_del )
{
int *p1, *p2, *tmp;
int i1, i2, c0, c1, c2;
if(l1==0) return l2*cost_ins;
if(l2==0) return l1*cost_del;
if((l1>LEVENSHTEIN_MAX_LENTH)||(l2>LEVENSHTEIN_MAX_LENTH))
return -1;
if(!(p1=emalloc(l2*sizeof(int)))) {
return -2;
}
if(!(p2=emalloc(l2*sizeof(int)))) {
free(p1);
return -2;
}
p1[0]=(s1[0]==s2[0])?0:cost_rep;
for(i2=1;i2<l2;i2++)
p1[i2]=i2*cost_ins;
for(i1=1;i1<l1;i1++)
{
p2[0]=i1*cost_del;
for(i2=1;i2<l2;i2++)
{
c0=p1[i2-1]+((s1[i1]==s2[i2])?0:cost_rep);
c1=p1[i2]+cost_del; if(c1<c0) c0=c1;
c2=p2[i2-1]+cost_ins; if(c2<c0) c0=c2;
p2[i2]=c0;
}
tmp=p1; p1=p2; p2=tmp;
}
c0=p1[l2-1];
efree(p1);
efree(p2);
return c0;
}
/* }}} */
/* {{{ custom_levdist
*/
static int custom_levdist(char *str1, char *str2, char *callback_name)
{
php_error(E_WARNING, "the general Levenshtein support is not there yet");
/* not there yet */
return -1;
}
/* }}} */
/* {{{ proto int levenshtein(string str1, string str2)
Calculate Levenshtein distance between two strings */
PHP_FUNCTION(levenshtein)
{
zval **str1, **str2, **cost_ins, **cost_rep, **cost_del, **callback_name;
int distance=-1;
switch(ZEND_NUM_ARGS()) {
case 2: /* just two string: use maximum performance version */
if (zend_get_parameters_ex(2, &str1, &str2) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(str1);
convert_to_string_ex(str2);
distance = reference_levdist((*str1)->value.str.val, (*str1)->value.str.len,
(*str2)->value.str.val, (*str2)->value.str.len,
1, 1, 1);
break;
case 5: /* more general version: calc cost by ins/rep/del weights */
if (zend_get_parameters_ex(5, &str1, &str2, &cost_ins, &cost_rep, &cost_del) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(str1);
convert_to_string_ex(str2);
convert_to_long_ex(cost_ins);
convert_to_long_ex(cost_rep);
convert_to_long_ex(cost_del);
distance = reference_levdist((*str1)->value.str.val, (*str1)->value.str.len,
(*str2)->value.str.val, (*str2)->value.str.len,
(*cost_ins)->value.lval,
(*cost_rep)->value.lval,
(*cost_del)->value.lval
);
break;
case 3: /* most general version: calc cost by user-supplied function */
if (zend_get_parameters_ex(3, &str1, &str2, &callback_name) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(str1);
convert_to_string_ex(str2);
convert_to_string_ex(callback_name);
distance = custom_levdist((*str1)->value.str.val
, (*str2)->value.str.val
, (*callback_name)->value.str.val
);
break;
default:
WRONG_PARAM_COUNT;
}
if(distance<0) {
php_error(E_WARNING, "levenshtein(): argument string(s) too long");
}
RETURN_LONG(distance);
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+168
View File
@@ -0,0 +1,168 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "php_filestat.h"
#include "php_globals.h"
#ifdef HAVE_SYMLINK
#include <stdlib.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <sys/stat.h>
#include <string.h>
#if HAVE_PWD_H
#ifdef PHP_WIN32
#include "win32/pwd.h"
#else
#include <pwd.h>
#endif
#endif
#if HAVE_GRP_H
#ifdef PHP_WIN32
#include "win32/grp.h"
#else
#include <grp.h>
#endif
#endif
#include <errno.h>
#include <ctype.h>
#include "safe_mode.h"
#include "php_link.h"
/* {{{ proto string readlink(string filename)
Return the target of a symbolic link */
PHP_FUNCTION(readlink)
{
pval **filename;
char buff[256];
int ret;
if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &filename) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(filename);
ret = readlink((*filename)->value.str.val, buff, 255);
if (ret == -1) {
php_error(E_WARNING, "readlink failed (%s)", strerror(errno));
RETURN_FALSE;
}
/* Append NULL to the end of the string */
buff[ret] = '\0';
RETURN_STRING(buff, 1);
}
/* }}} */
/* {{{ proto int linkinfo(string filename)
Returns the st_dev field of the UNIX C stat structure describing the link */
PHP_FUNCTION(linkinfo)
{
pval **filename;
struct stat sb;
int ret;
if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &filename) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(filename);
ret = VCWD_LSTAT((*filename)->value.str.val, &sb);
if (ret == -1) {
php_error(E_WARNING, "LinkInfo failed (%s)", strerror(errno));
RETURN_LONG(-1L);
}
RETURN_LONG((long) sb.st_dev);
}
/* }}} */
/* {{{ proto int symlink(string target, string link)
Create a symbolic link */
PHP_FUNCTION(symlink)
{
pval **topath, **frompath;
int ret;
if (ZEND_NUM_ARGS() != 2 || zend_get_parameters_ex(2, &topath, &frompath) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(topath);
convert_to_string_ex(frompath);
if (PG(safe_mode) && !php_checkuid((*topath)->value.str.val, NULL, CHECKUID_CHECK_FILE_AND_DIR)) {
RETURN_FALSE;
}
if (!strncasecmp((*topath)->value.str.val, "http://", 7) || !strncasecmp((*topath)->value.str.val, "ftp://", 6)) {
php_error(E_WARNING, "Unable to symlink to a URL");
RETURN_FALSE;
}
ret = symlink((*topath)->value.str.val, (*frompath)->value.str.val);
if (ret == -1) {
php_error(E_WARNING, "SymLink failed (%s)", strerror(errno));
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto int link(string target, string link)
Create a hard link */
PHP_FUNCTION(link)
{
pval **topath, **frompath;
int ret;
if (ZEND_NUM_ARGS() != 2 || zend_get_parameters_ex(2, &topath, &frompath) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(topath);
convert_to_string_ex(frompath);
if (PG(safe_mode) && !php_checkuid((*topath)->value.str.val, NULL, CHECKUID_CHECK_FILE_AND_DIR)) {
RETURN_FALSE;
}
if (!strncasecmp((*topath)->value.str.val, "http://", 7) || !strncasecmp((*topath)->value.str.val, "ftp://", 6)) {
php_error(E_WARNING, "Unable to link to a URL");
RETURN_FALSE;
}
ret = link((*topath)->value.str.val, (*frompath)->value.str.val);
if (ret == -1) {
php_error(E_WARNING, "Link failed (%s)", strerror(errno));
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+239
View File
@@ -0,0 +1,239 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
#include "php.h"
#include "ext/standard/info.h"
#if !defined(PHP_WIN32)
#include "build-defs.h"
#if HAVE_SYSEXITS_H
#include <sysexits.h>
#endif
#if HAVE_SYS_SYSEXITS_H
#include <sys/sysexits.h>
#endif
#endif
#include "php_mail.h"
#include "php_ini.h"
#include "safe_mode.h"
#include "exec.h"
#if HAVE_SENDMAIL
#ifdef PHP_WIN32
#include "win32/sendmail.h"
#endif
/* {{{ proto int ezmlm_hash(string addr)
Calculate EZMLM list hash value. */
PHP_FUNCTION(ezmlm_hash)
{
pval **pstr = NULL;
char *str=NULL;
unsigned long h = 5381L;
int j, l;
if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &pstr) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(pstr);
if ((*pstr)->value.str.val) {
str = (*pstr)->value.str.val;
} else {
php_error(E_WARNING, "Must give string parameter to ezmlm_hash()");
RETURN_FALSE;
}
l = strlen(str);
for (j=0; j<l; j++) {
h = (h + (h<<5)) ^ (unsigned long) (unsigned char) tolower(str[j]);
}
h = (h%53);
RETURN_LONG((int) h);
}
/* }}} */
/* {{{ proto int mail(string to, string subject, string message [, string additional_headers [, string additional_parameters]])
Send an email message */
PHP_FUNCTION(mail)
{
pval **argv[5];
char *to=NULL, *message=NULL, *headers=NULL, *subject=NULL, *extra_cmd=NULL;
int argc;
argc = ZEND_NUM_ARGS();
if (argc < 3 || argc > 5 || zend_get_parameters_array_ex(argc, argv) == FAILURE) {
WRONG_PARAM_COUNT;
}
/* To: */
convert_to_string_ex(argv[0]);
if ((*argv[0])->value.str.val) {
to = (*argv[0])->value.str.val;
} else {
php_error(E_WARNING, "No to field in mail command");
RETURN_FALSE;
}
/* Subject: */
convert_to_string_ex(argv[1]);
if ((*argv[1])->value.str.val) {
subject = Z_STRVAL_PP(argv[1]);
} else {
php_error(E_WARNING, "No subject field in mail command");
RETURN_FALSE;
}
/* message body */
convert_to_string_ex(argv[2]);
if ((*argv[2])->value.str.val) {
message = Z_STRVAL_PP(argv[2]);
} else {
/* this is not really an error, so it is allowed. */
php_error(E_WARNING, "No message string in mail command");
message = NULL;
}
if (argc >= 4) { /* other headers */
convert_to_string_ex(argv[3]);
headers = Z_STRVAL_PP(argv[3]);
}
if (argc == 5) { /* extra options that get passed to the mailer */
convert_to_string_ex(argv[4]);
extra_cmd = php_escape_shell_arg(Z_STRVAL_PP(argv[4]));
}
if (php_mail(to, subject, message, headers, extra_cmd)) {
RETVAL_TRUE;
} else {
RETVAL_FALSE;
}
if (extra_cmd) efree (extra_cmd);
}
/* }}} */
/* {{{ php_mail
*/
PHPAPI int php_mail(char *to, char *subject, char *message, char *headers, char *extra_cmd)
{
#ifdef PHP_WIN32
int tsm_err;
#endif
FILE *sendmail;
int ret;
char *sendmail_path = INI_STR("sendmail_path");
char *sendmail_cmd = NULL;
if (!sendmail_path) {
#ifdef PHP_WIN32
/* handle old style win smtp sending */
if (TSendMail(INI_STR("SMTP"), &tsm_err, headers, subject, to, message) != SUCCESS){
php_error(E_WARNING, GetSMErrorText(tsm_err));
return 0;
}
return 1;
#else
return 0;
#endif
}
if (extra_cmd != NULL) {
sendmail_cmd = emalloc (strlen (sendmail_path) + strlen (extra_cmd) + 2);
strcpy (sendmail_cmd, sendmail_path);
strcat (sendmail_cmd, " ");
strcat (sendmail_cmd, extra_cmd);
} else {
sendmail_cmd = sendmail_path;
}
#ifdef PHP_WIN32
sendmail = popen(sendmail_cmd, "wb");
#else
sendmail = popen(sendmail_cmd, "w");
#endif
if (extra_cmd != NULL)
efree (sendmail_cmd);
if (sendmail) {
fprintf(sendmail, "To: %s\n", to);
fprintf(sendmail, "Subject: %s\n", subject);
if (headers != NULL) {
fprintf(sendmail, "%s\n", headers);
}
fprintf(sendmail, "\n%s\n", message);
ret = pclose(sendmail);
#ifdef PHP_WIN32
if (ret == -1)
#else
#if defined(EX_TEMPFAIL)
if ((ret != EX_OK)&&(ret != EX_TEMPFAIL))
#else
if (ret != EX_OK)
#endif
#endif
{
return 0;
} else {
return 1;
}
} else {
php_error(E_WARNING, "Could not execute mail delivery program");
return 0;
}
return 1;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(mail)
{
char *sendmail_path = INI_STR("sendmail_path");
#ifdef PHP_WIN32
if (!sendmail_path) {
php_info_print_table_row(2, "Internal Sendmail Support for Windows", "enabled");
} else {
php_info_print_table_row(2, "Path to sendmail", sendmail_path);
}
#else
php_info_print_table_row(2, "Path to sendmail", sendmail_path);
#endif
}
/* }}} */
#else
PHP_FUNCTION(mail) {}
PHP_MINFO_FUNCTION(mail) {}
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+1005
View File
File diff suppressed because it is too large. Load diff
+377
View File
@@ -0,0 +1,377 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Lachlan Roche |
+----------------------------------------------------------------------+
*/
/* $Id$ */
/*
* md5.c - Copyright 1997 Lachlan Roche
*/
#include <stdio.h>
#include "php.h"
#include "md5.h"
/* {{{ proto string md5(string str)
Calculate the md5 hash of a string */
PHP_NAMED_FUNCTION(php_if_md5)
{
pval **arg;
char md5str[33];
PHP_MD5_CTX context;
unsigned char digest[16];
int i;
char *r;
if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &arg) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(arg);
md5str[0] = '\0';
PHP_MD5Init(&context);
PHP_MD5Update(&context, (*arg)->value.str.val, (*arg)->value.str.len);
PHP_MD5Final(digest, &context);
for (i = 0, r = md5str; i < 16; i++, r += 2) {
sprintf(r, "%02x", digest[i]);
}
*r = '\0';
RETVAL_STRING(md5str, 1);
}
/* }}} */
/*
* The remaining code is the reference MD5 code (md5c.c) from rfc1321
*/
/* MD5C.C - RSA Data Security, Inc., MD5 message-digest algorithm
*/
/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
rights reserved.
License to copy and use this software is granted provided that it
is identified as the "RSA Data Security, Inc. MD5 Message-Digest
Algorithm" in all material mentioning or referencing this software
or this function.
License is also granted to make and use derivative works provided
that such works are identified as "derived from the RSA Data
Security, Inc. MD5 Message-Digest Algorithm" in all material
mentioning or referencing the derived work.
RSA Data Security, Inc. makes no representations concerning either
the merchantability of this software or the suitability of this
software for any particular purpose. It is provided "as is"
without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this
documentation and/or software.
*/
/* Constants for MD5Transform routine.
*/
#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21
static void MD5Transform(php_uint32[4], const unsigned char[64]);
static void Encode(unsigned char *, php_uint32 *, unsigned int);
static void Decode(php_uint32 *, const unsigned char *, unsigned int);
static unsigned char PADDING[64] =
{
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/* F, G, H and I are basic MD5 functions.
*/
#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define I(x, y, z) ((y) ^ ((x) | (~z)))
/* ROTATE_LEFT rotates x left n bits.
*/
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
Rotation is separate from addition to prevent recomputation.
*/
#define FF(a, b, c, d, x, s, ac) { \
(a) += F ((b), (c), (d)) + (x) + (php_uint32)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define GG(a, b, c, d, x, s, ac) { \
(a) += G ((b), (c), (d)) + (x) + (php_uint32)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define HH(a, b, c, d, x, s, ac) { \
(a) += H ((b), (c), (d)) + (x) + (php_uint32)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
#define II(a, b, c, d, x, s, ac) { \
(a) += I ((b), (c), (d)) + (x) + (php_uint32)(ac); \
(a) = ROTATE_LEFT ((a), (s)); \
(a) += (b); \
}
/* {{{ PHP_MD5Init
* MD5 initialization. Begins an MD5 operation, writing a new context.
*/
void PHP_MD5Init(PHP_MD5_CTX * context)
{
context->count[0] = context->count[1] = 0;
/* Load magic initialization constants.
*/
context->state[0] = 0x67452301;
context->state[1] = 0xefcdab89;
context->state[2] = 0x98badcfe;
context->state[3] = 0x10325476;
}
/* }}} */
/* {{{ PHP_MD5Update
MD5 block update operation. Continues an MD5 message-digest
operation, processing another message block, and updating the
context.
*/
void PHP_MD5Update(PHP_MD5_CTX * context, const unsigned char *input,
unsigned int inputLen)
{
unsigned int i, index, partLen;
/* Compute number of bytes mod 64 */
index = (unsigned int) ((context->count[0] >> 3) & 0x3F);
/* Update number of bits */
if ((context->count[0] += ((php_uint32) inputLen << 3))
< ((php_uint32) inputLen << 3))
context->count[1]++;
context->count[1] += ((php_uint32) inputLen >> 29);
partLen = 64 - index;
/* Transform as many times as possible.
*/
if (inputLen >= partLen) {
memcpy
((unsigned char*) & context->buffer[index], (unsigned char*) input, partLen);
MD5Transform(context->state, context->buffer);
for (i = partLen; i + 63 < inputLen; i += 64)
MD5Transform(context->state, &input[i]);
index = 0;
} else
i = 0;
/* Buffer remaining input */
memcpy
((unsigned char*) & context->buffer[index], (unsigned char*) & input[i],
inputLen - i);
}
/* }}} */
/* {{{ PHP_MD5Final
MD5 finalization. Ends an MD5 message-digest operation, writing the
the message digest and zeroizing the context.
*/
void PHP_MD5Final(unsigned char digest[16], PHP_MD5_CTX * context)
{
unsigned char bits[8];
unsigned int index, padLen;
/* Save number of bits */
Encode(bits, context->count, 8);
/* Pad out to 56 mod 64.
*/
index = (unsigned int) ((context->count[0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
PHP_MD5Update(context, PADDING, padLen);
/* Append length (before padding) */
PHP_MD5Update(context, bits, 8);
/* Store state in digest */
Encode(digest, context->state, 16);
/* Zeroize sensitive information.
*/
memset((unsigned char*) context, 0, sizeof(*context));
}
/* }}} */
/* {{{ MD5Transform
* MD5 basic transformation. Transforms state based on block.
*/
static void MD5Transform(state, block)
php_uint32 state[4];
const unsigned char block[64];
{
php_uint32 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
Decode(x, block, 64);
/* Round 1 */
FF(a, b, c, d, x[0], S11, 0xd76aa478); /* 1 */
FF(d, a, b, c, x[1], S12, 0xe8c7b756); /* 2 */
FF(c, d, a, b, x[2], S13, 0x242070db); /* 3 */
FF(b, c, d, a, x[3], S14, 0xc1bdceee); /* 4 */
FF(a, b, c, d, x[4], S11, 0xf57c0faf); /* 5 */
FF(d, a, b, c, x[5], S12, 0x4787c62a); /* 6 */
FF(c, d, a, b, x[6], S13, 0xa8304613); /* 7 */
FF(b, c, d, a, x[7], S14, 0xfd469501); /* 8 */
FF(a, b, c, d, x[8], S11, 0x698098d8); /* 9 */
FF(d, a, b, c, x[9], S12, 0x8b44f7af); /* 10 */
FF(c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
FF(b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
FF(a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
FF(d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
FF(c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
FF(b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
/* Round 2 */
GG(a, b, c, d, x[1], S21, 0xf61e2562); /* 17 */
GG(d, a, b, c, x[6], S22, 0xc040b340); /* 18 */
GG(c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
GG(b, c, d, a, x[0], S24, 0xe9b6c7aa); /* 20 */
GG(a, b, c, d, x[5], S21, 0xd62f105d); /* 21 */
GG(d, a, b, c, x[10], S22, 0x2441453); /* 22 */
GG(c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
GG(b, c, d, a, x[4], S24, 0xe7d3fbc8); /* 24 */
GG(a, b, c, d, x[9], S21, 0x21e1cde6); /* 25 */
GG(d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
GG(c, d, a, b, x[3], S23, 0xf4d50d87); /* 27 */
GG(b, c, d, a, x[8], S24, 0x455a14ed); /* 28 */
GG(a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
GG(d, a, b, c, x[2], S22, 0xfcefa3f8); /* 30 */
GG(c, d, a, b, x[7], S23, 0x676f02d9); /* 31 */
GG(b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
/* Round 3 */
HH(a, b, c, d, x[5], S31, 0xfffa3942); /* 33 */
HH(d, a, b, c, x[8], S32, 0x8771f681); /* 34 */
HH(c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
HH(b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
HH(a, b, c, d, x[1], S31, 0xa4beea44); /* 37 */
HH(d, a, b, c, x[4], S32, 0x4bdecfa9); /* 38 */
HH(c, d, a, b, x[7], S33, 0xf6bb4b60); /* 39 */
HH(b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
HH(a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
HH(d, a, b, c, x[0], S32, 0xeaa127fa); /* 42 */
HH(c, d, a, b, x[3], S33, 0xd4ef3085); /* 43 */
HH(b, c, d, a, x[6], S34, 0x4881d05); /* 44 */
HH(a, b, c, d, x[9], S31, 0xd9d4d039); /* 45 */
HH(d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
HH(c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
HH(b, c, d, a, x[2], S34, 0xc4ac5665); /* 48 */
/* Round 4 */
II(a, b, c, d, x[0], S41, 0xf4292244); /* 49 */
II(d, a, b, c, x[7], S42, 0x432aff97); /* 50 */
II(c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
II(b, c, d, a, x[5], S44, 0xfc93a039); /* 52 */
II(a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
II(d, a, b, c, x[3], S42, 0x8f0ccc92); /* 54 */
II(c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
II(b, c, d, a, x[1], S44, 0x85845dd1); /* 56 */
II(a, b, c, d, x[8], S41, 0x6fa87e4f); /* 57 */
II(d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
II(c, d, a, b, x[6], S43, 0xa3014314); /* 59 */
II(b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
II(a, b, c, d, x[4], S41, 0xf7537e82); /* 61 */
II(d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
II(c, d, a, b, x[2], S43, 0x2ad7d2bb); /* 63 */
II(b, c, d, a, x[9], S44, 0xeb86d391); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
/* Zeroize sensitive information. */
memset((unsigned char*) x, 0, sizeof(x));
}
/* }}} */
/* {{{ Encode
Encodes input (php_uint32) into output (unsigned char). Assumes len is
a multiple of 4.
*/
static void Encode(output, input, len)
unsigned char *output;
php_uint32 *input;
unsigned int len;
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4) {
output[j] = (unsigned char) (input[i] & 0xff);
output[j + 1] = (unsigned char) ((input[i] >> 8) & 0xff);
output[j + 2] = (unsigned char) ((input[i] >> 16) & 0xff);
output[j + 3] = (unsigned char) ((input[i] >> 24) & 0xff);
}
}
/* }}} */
/* {{{ Decode
Decodes input (unsigned char) into output (php_uint32). Assumes len is
a multiple of 4.
*/
static void Decode(output, input, len)
php_uint32 *output;
const unsigned char *input;
unsigned int len;
{
unsigned int i, j;
for (i = 0, j = 0; j < len; i++, j += 4)
output[i] = ((php_uint32) input[j]) | (((php_uint32) input[j + 1]) << 8) |
(((php_uint32) input[j + 2]) << 16) | (((php_uint32) input[j + 3]) << 24);
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+63
View File
@@ -0,0 +1,63 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef MD5_H
#define MD5_H
/* MD5.H - header file for MD5C.C
*/
/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
rights reserved.
License to copy and use this software is granted provided that it
is identified as the "RSA Data Security, Inc. MD5 Message-Digest
Algorithm" in all material mentioning or referencing this software
or this function.
License is also granted to make and use derivative works provided
that such works are identified as "derived from the RSA Data
Security, Inc. MD5 Message-Digest Algorithm" in all material
mentioning or referencing the derived work.
RSA Data Security, Inc. makes no representations concerning either
the merchantability of this software or the suitability of this
software for any particular purpose. It is provided "as is"
without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this
documentation and/or software.
*/
#include "ext/standard/basic_functions.h"
/* MD5 context. */
typedef struct {
php_uint32 state[4]; /* state (ABCD) */
php_uint32 count[2]; /* number of bits, modulo 2^64 (lsb first) */
unsigned char buffer[64]; /* input buffer */
} PHP_MD5_CTX;
void PHP_MD5Init(PHP_MD5_CTX *);
void PHP_MD5Update(PHP_MD5_CTX *, const unsigned char *, unsigned int);
void PHP_MD5Final(unsigned char[16], PHP_MD5_CTX *);
PHP_NAMED_FUNCTION(php_if_md5);
#endif
+473
View File
@@ -0,0 +1,473 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Thies C. Arntzen <thies@thieso.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
/*
Based on CPANs "Text-Metaphone-1.96" by Michael G Schwern <schwern@pobox.com>
*/
#include "php.h"
#include "php_metaphone.h"
static int metaphone(char *word, int max_phonemes, char **phoned_word, int traditional);
PHP_FUNCTION(metaphone);
/* {{{ proto string metaphone(string text, int phones)
Break english phrases down into their phonemes */
PHP_FUNCTION(metaphone)
{
pval **pstr, **pphones;
char *result = 0;
int phones = 0;
if (zend_get_parameters_ex(2, &pstr, &pphones) == SUCCESS) {
convert_to_long_ex(pphones);
phones = (*pphones)->value.lval;
} else if (zend_get_parameters_ex(1, &pstr) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(pstr);
if (metaphone((*pstr)->value.str.val, phones, &result, 1) == 0) {
RETVAL_STRING(result, 0);
} else {
if (result) {
efree(result);
}
RETURN_FALSE;
}
}
/* }}} */
/*
this is now the original code by Michael G Schwern:
i've changed it just a slightly bit (use emalloc,
get rid of includes etc)
- thies - 13.09.1999
*/
/*----------------------------- */
/* this used to be "metaphone.h" */
/*----------------------------- */
/* Special encodings */
#define SH 'X'
#define TH '0'
/*----------------------------- */
/* end of "metaphone.h" */
/*----------------------------- */
/*----------------------------- */
/* this used to be "metachar.h" */
/*----------------------------- */
/* Metachar.h ... little bits about characters for metaphone */
/*-- Character encoding array & accessing macros --*/
/* Stolen directly out of the book... */
char _codes[26] =
{
1, 16, 4, 16, 9, 2, 4, 16, 9, 2, 0, 2, 2, 2, 1, 4, 0, 2, 4, 4, 1, 0, 0, 0, 8, 0
/* a b c d e f g h i j k l m n o p q r s t u v w x y z */
};
#define ENCODE(c) (isalpha(c) ? _codes[((toupper(c)) - 'A')] : 0)
#define isvowel(c) (ENCODE(c) & 1) /* AEIOU */
/* These letters are passed through unchanged */
#define NOCHANGE(c) (ENCODE(c) & 2) /* FJMNR */
/* These form dipthongs when preceding H */
#define AFFECTH(c) (ENCODE(c) & 4) /* CGPST */
/* These make C and G soft */
#define MAKESOFT(c) (ENCODE(c) & 8) /* EIY */
/* These prevent GH from becoming F */
#define NOGHTOF(c) (ENCODE(c) & 16) /* BDH */
/*----------------------------- */
/* end of "metachar.h" */
/*----------------------------- */
/* I suppose I could have been using a character pointer instead of
* accesssing the array directly... */
/* Look at the next letter in the word */
#define Next_Letter (toupper(word[w_idx+1]))
/* Look at the current letter in the word */
#define Curr_Letter (toupper(word[w_idx]))
/* Go N letters back. */
#define Look_Back_Letter(n) (w_idx >= n ? toupper(word[w_idx-n]) : '\0')
/* Previous letter. I dunno, should this return null on failure? */
#define Prev_Letter (Look_Back_Letter(1))
/* Look two letters down. It makes sure you don't walk off the string. */
#define After_Next_Letter (Next_Letter != '\0' ? toupper(word[w_idx+2]) \
: '\0')
#define Look_Ahead_Letter(n) (toupper(Lookahead(word+w_idx, n)))
/* Allows us to safely look ahead an arbitrary # of letters */
/* I probably could have just used strlen... */
static char Lookahead(char *word, int how_far)
{
char letter_ahead = '\0'; /* null by default */
int idx;
for (idx = 0; word[idx] != '\0' && idx < how_far; idx++);
/* Edge forward in the string... */
letter_ahead = word[idx]; /* idx will be either == to how_far or
* at the end of the string
*/
return letter_ahead;
}
/* phonize one letter */
#define Phonize(c) {(*phoned_word)[p_idx++] = c;}
/* Slap a null character on the end of the phoned word */
#define End_Phoned_Word {(*phoned_word)[p_idx] = '\0';}
/* How long is the phoned word? */
#define Phone_Len (p_idx)
/* Note is a letter is a 'break' in the word */
#define Isbreak(c) (!isalpha(c))
/* {{{ metaphone
*/
static int metaphone(char *word, int max_phonemes, char **phoned_word, int traditional)
{
int w_idx = 0; /* point in the phonization we're at. */
int p_idx = 0; /* end of the phoned phrase */
/*-- Parameter checks --*/
/* Negative phoneme length is meaningless */
if (max_phonemes < 0)
return -1;
/* Empty/null string is meaningless */
/* Overly paranoid */
/* assert(word != NULL && word[0] != '\0'); */
if (word == NULL)
return -1;
/*-- Allocate memory for our phoned_phrase --*/
if (max_phonemes == 0) { /* Assume largest possible */
*phoned_word = emalloc(sizeof(char) * strlen(word) + 1);
if (!*phoned_word)
return -1;
} else {
*phoned_word = emalloc(sizeof(char) * max_phonemes + 1);
if (!*phoned_word)
return -1;
}
/*-- The first phoneme has to be processed specially. --*/
/* Find our first letter */
for (; !isalpha(Curr_Letter); w_idx++) {
/* On the off chance we were given nothing but crap... */
if (Curr_Letter == '\0') {
End_Phoned_Word
return SUCCESS; /* For testing */
}
}
switch (Curr_Letter) {
/* AE becomes E */
case 'A':
if (Next_Letter == 'E') {
Phonize('E');
w_idx += 2;
}
/* Remember, preserve vowels at the beginning */
else {
Phonize('A');
w_idx++;
}
break;
/* [GKP]N becomes N */
case 'G':
case 'K':
case 'P':
if (Next_Letter == 'N') {
Phonize('N');
w_idx += 2;
}
break;
/* WH becomes H,
WR becomes R
W if followed by a vowel */
case 'W':
if (Next_Letter == 'H' ||
Next_Letter == 'R') {
Phonize(Next_Letter);
w_idx += 2;
} else if (isvowel(Next_Letter)) {
Phonize('W');
w_idx += 2;
}
/* else ignore */
break;
/* X becomes S */
case 'X':
Phonize('S');
w_idx++;
break;
/* Vowels are kept */
/* We did A already
case 'A':
case 'a':
*/
case 'E':
case 'I':
case 'O':
case 'U':
Phonize(Curr_Letter);
w_idx++;
break;
default:
/* do nothing */
break;
}
/* On to the metaphoning */
for (; Curr_Letter != '\0' &&
(max_phonemes == 0 || Phone_Len < max_phonemes);
w_idx++) {
/* How many letters to skip because an eariler encoding handled
* multiple letters */
unsigned short int skip_letter = 0;
/* THOUGHT: It would be nice if, rather than having things like...
* well, SCI. For SCI you encode the S, then have to remember
* to skip the C. So the phonome SCI invades both S and C. It would
* be better, IMHO, to skip the C from the S part of the encoding.
* Hell, I'm trying it.
*/
/* Ignore non-alphas */
if (!isalpha(Curr_Letter))
continue;
/* Drop duplicates, except CC */
if (Curr_Letter == Prev_Letter &&
Curr_Letter != 'C')
continue;
switch (Curr_Letter) {
/* B -> B unless in MB */
case 'B':
if (Prev_Letter != 'M')
Phonize('B');
break;
/* 'sh' if -CIA- or -CH, but not SCH, except SCHW.
* (SCHW is handled in S)
* S if -CI-, -CE- or -CY-
* dropped if -SCI-, SCE-, -SCY- (handed in S)
* else K
*/
case 'C':
if (MAKESOFT(Next_Letter)) { /* C[IEY] */
if (After_Next_Letter == 'A' &&
Next_Letter == 'I') { /* CIA */
Phonize(SH);
}
/* SC[IEY] */
else if (Prev_Letter == 'S') {
/* Dropped */
} else {
Phonize('S');
}
} else if (Next_Letter == 'H') {
if ((!traditional) && (After_Next_Letter == 'R' || Prev_Letter == 'S')) { /* Christ, School */
Phonize('K');
} else {
Phonize(SH);
}
skip_letter++;
} else {
Phonize('K');
}
break;
/* J if in -DGE-, -DGI- or -DGY-
* else T
*/
case 'D':
if (Next_Letter == 'G' &&
MAKESOFT(After_Next_Letter)) {
Phonize('J');
skip_letter++;
} else
Phonize('T');
break;
/* F if in -GH and not B--GH, D--GH, -H--GH, -H---GH
* else dropped if -GNED, -GN,
* else dropped if -DGE-, -DGI- or -DGY- (handled in D)
* else J if in -GE-, -GI, -GY and not GG
* else K
*/
case 'G':
if (Next_Letter == 'H') {
if (!(NOGHTOF(Look_Back_Letter(3)) ||
Look_Back_Letter(4) == 'H')) {
Phonize('F');
skip_letter++;
} else {
/* silent */
}
} else if (Next_Letter == 'N') {
if (Isbreak(After_Next_Letter) ||
(After_Next_Letter == 'E' &&
Look_Ahead_Letter(3) == 'D')) {
/* dropped */
} else
Phonize('K');
} else if (MAKESOFT(Next_Letter) &&
Prev_Letter != 'G') {
Phonize('J');
} else {
Phonize('K');
}
break;
/* H if before a vowel and not after C,G,P,S,T */
case 'H':
if (isvowel(Next_Letter) &&
!AFFECTH(Prev_Letter))
Phonize('H');
break;
/* dropped if after C
* else K
*/
case 'K':
if (Prev_Letter != 'C')
Phonize('K');
break;
/* F if before H
* else P
*/
case 'P':
if (Next_Letter == 'H') {
Phonize('F');
} else {
Phonize('P');
}
break;
/* K
*/
case 'Q':
Phonize('K');
break;
/* 'sh' in -SH-, -SIO- or -SIA- or -SCHW-
* else S
*/
case 'S':
if (Next_Letter == 'I' &&
(After_Next_Letter == 'O' ||
After_Next_Letter == 'A')) {
Phonize(SH);
} else if (Next_Letter == 'H') {
Phonize(SH);
skip_letter++;
} else if ((!traditional) && (Next_Letter == 'C' && Look_Ahead_Letter(2) == 'H' && Look_Ahead_Letter(3) == 'W')) {
Phonize(SH);
skip_letter += 2;
} else {
Phonize('S');
}
break;
/* 'sh' in -TIA- or -TIO-
* else 'th' before H
* else T
*/
case 'T':
if (Next_Letter == 'I' &&
(After_Next_Letter == 'O' ||
After_Next_Letter == 'A')) {
Phonize(SH);
} else if (Next_Letter == 'H') {
Phonize(TH);
skip_letter++;
} else {
Phonize('T');
}
break;
/* F */
case 'V':
Phonize('F');
break;
/* W before a vowel, else dropped */
case 'W':
if (isvowel(Next_Letter))
Phonize('W');
break;
/* KS */
case 'X':
Phonize('K');
Phonize('S');
break;
/* Y if followed by a vowel */
case 'Y':
if (isvowel(Next_Letter))
Phonize('Y');
break;
/* S */
case 'Z':
Phonize('S');
break;
/* No transformation */
case 'F':
case 'J':
case 'L':
case 'M':
case 'N':
case 'R':
Phonize(Curr_Letter);
break;
default:
/* nothing */
break;
} /* END SWITCH */
w_idx += skip_letter;
} /* END FOR */
End_Phoned_Word;
return 0;
} /* END metaphone */
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+149
View File
@@ -0,0 +1,149 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Paul Panotzki - Bunyip Information Systems |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef PHP_WIN32
#include "win32/time.h"
#else
#include <sys/time.h>
#endif
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include "microtime.h"
#define NUL '\0'
#define MICRO_IN_SEC 1000000.00
/* {{{ proto string microtime(void)
Returns a string containing the current time in seconds and microseconds */
PHP_FUNCTION(microtime)
{
#ifdef HAVE_GETTIMEOFDAY
struct timeval tp;
long sec = 0L;
double msec = 0.0;
char ret[100];
if (gettimeofday((struct timeval *) &tp, (NUL)) == 0) {
msec = (double) (tp.tv_usec / MICRO_IN_SEC);
sec = tp.tv_sec;
if (msec >= 1.0) msec -= (long) msec;
snprintf(ret, 100, "%.8f %ld", msec, sec);
RETVAL_STRING(ret,1);
} else
#endif
RETURN_FALSE;
}
/* }}} */
/* {{{ proto array gettimeofday(void)
Returns the current time as array */
PHP_FUNCTION(gettimeofday)
{
#ifdef HAVE_GETTIMEOFDAY
struct timeval tp;
struct timezone tz;
memset(&tp, 0, sizeof(tp));
memset(&tz, 0, sizeof(tz));
if(gettimeofday(&tp, &tz) == 0) {
array_init(return_value);
add_assoc_long(return_value, "sec", tp.tv_sec);
add_assoc_long(return_value, "usec", tp.tv_usec);
add_assoc_long(return_value, "minuteswest", tz.tz_minuteswest);
add_assoc_long(return_value, "dsttime", tz.tz_dsttime);
return;
} else
#endif
RETURN_FALSE;
}
/* }}} */
#ifdef HAVE_GETRUSAGE
/* {{{ proto array getrusage([int who])
Returns an array of usage statistics */
PHP_FUNCTION(getrusage)
{
struct rusage usg;
int ac = ZEND_NUM_ARGS();
pval **pwho;
int who = RUSAGE_SELF;
if(ac == 1 &&
zend_get_parameters_ex(ac, &pwho) != FAILURE) {
convert_to_long_ex(pwho);
if((*pwho)->value.lval == 1)
who = RUSAGE_CHILDREN;
}
memset(&usg, 0, sizeof(usg));
if(getrusage(who, &usg) == -1) {
RETURN_FALSE;
}
array_init(return_value);
#define PHP_RUSAGE_PARA(a) \
add_assoc_long(return_value, #a, usg.a)
#if !defined( _OSD_POSIX) && !defined(__BEOS__) /* BS2000 has only a few fields in the rusage struct */
PHP_RUSAGE_PARA(ru_oublock);
PHP_RUSAGE_PARA(ru_inblock);
PHP_RUSAGE_PARA(ru_msgsnd);
PHP_RUSAGE_PARA(ru_msgrcv);
PHP_RUSAGE_PARA(ru_maxrss);
PHP_RUSAGE_PARA(ru_ixrss);
PHP_RUSAGE_PARA(ru_idrss);
PHP_RUSAGE_PARA(ru_minflt);
PHP_RUSAGE_PARA(ru_majflt);
PHP_RUSAGE_PARA(ru_nsignals);
PHP_RUSAGE_PARA(ru_nvcsw);
PHP_RUSAGE_PARA(ru_nivcsw);
#endif /*_OSD_POSIX*/
PHP_RUSAGE_PARA(ru_utime.tv_usec);
PHP_RUSAGE_PARA(ru_utime.tv_sec);
PHP_RUSAGE_PARA(ru_stime.tv_usec);
PHP_RUSAGE_PARA(ru_stime.tv_sec);
#undef PHP_RUSAGE_PARA
}
#endif /* HAVE_GETRUSAGE */
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+28
View File
@@ -0,0 +1,28 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Paul Panotzki - Bunyip Information Systems |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef MICROTIME_H
#define MICROTIME_H
PHP_FUNCTION(microtime);
PHP_FUNCTION(gettimeofday);
PHP_FUNCTION(getrusage);
#endif /* MICROTIME_H */
+877
View File
@@ -0,0 +1,877 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Chris Schneider <cschneid@relog.ch> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef PHP_WIN32
#include <windows.h>
#include <winsock.h>
#define O_RDONLY _O_RDONLY
#include "win32/param.h"
#else
#include <sys/param.h>
#endif
#include "ext/standard/head.h"
#include "safe_mode.h"
#include "php_string.h"
#include "pack.h"
#if HAVE_PWD_H
#ifdef PHP_WIN32
#include "win32/pwd.h"
#else
#include <pwd.h>
#endif
#endif
#include "fsock.h"
#if HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
/* Whether machine is little endian */
char machine_little_endian;
/* Mapping of byte from char (8bit) to long for machine endian */
static int byte_map[1];
/* Mappings of bytes from int (machine dependant) to int for machine endian */
static int int_map[sizeof(int)];
/* Mappings of bytes from shorts (16bit) for all endian environments */
static int machine_endian_short_map[2];
static int big_endian_short_map[2];
static int little_endian_short_map[2];
/* Mappings of bytes from longs (32bit) for all endian environments */
static int machine_endian_long_map[4];
static int big_endian_long_map[4];
static int little_endian_long_map[4];
/* {{{ php_pack
*/
static void php_pack(pval **val, int size, int *map, char *output)
{
int i;
char *v;
convert_to_long_ex(val);
v = (char *)&(*val)->value.lval;
for (i = 0; i < size; i++) {
*(output++) = v[map[i]];
}
}
/* }}} */
/* pack() idea stolen from Perl (implemented formats behave the same as there)
* Implemented formats are A, a, h, H, c, C, s, S, i, I, l, L, n, N, f, d, x, X, @.
*/
/* {{{ proto string pack(string format, mixed arg1 [, mixed arg2 [, mixed ...]])
Takes one or more arguments and packs them into a binary string according to the format argument */
PHP_FUNCTION(pack)
{
pval ***argv;
int argc, i;
int currentarg;
char *format;
int formatlen;
char *formatcodes;
int *formatargs;
int formatcount = 0;
int outputpos = 0, outputsize = 0;
char *output;
argc = ZEND_NUM_ARGS();
if (argc < 1) {
WRONG_PARAM_COUNT;
}
argv = emalloc(argc * sizeof(pval **));
if (zend_get_parameters_array_ex(argc, argv) == FAILURE) {
efree(argv);
WRONG_PARAM_COUNT;
}
convert_to_string_ex(argv[0]);
format = (*argv[0])->value.str.val;
formatlen = (*argv[0])->value.str.len;
/* We have a maximum of <formatlen> format codes to deal with */
formatcodes = emalloc(formatlen * sizeof(*formatcodes));
formatargs = emalloc(formatlen * sizeof(*formatargs));
currentarg = 1;
/* Preprocess format into formatcodes and formatargs */
for (i = 0; i < formatlen; formatcount++) {
char code = format[i++];
int arg = 1;
/* Handle format arguments if any */
if (i < formatlen) {
char c = format[i];
if (c == '*') {
arg = -1;
i++;
}
else if ((c >= '0') && (c <= '9')) {
arg = atoi(&format[i]);
while (format[i] >= '0' && format[i] <= '9' && i < formatlen) {
i++;
}
}
}
/* Handle special arg '*' for all codes and check argv overflows */
switch ((int)code) {
/* Never uses any args */
case 'x': case 'X': case '@': {
if (arg < 0) {
php_error(E_WARNING, "pack type %c: '*' ignored", code);
arg = 1;
}
break;
}
/* Always uses one arg */
case 'a': case 'A': case 'h': case 'H': {
if (currentarg >= argc) {
efree(argv);
efree(formatcodes);
efree(formatargs);
php_error(E_ERROR, "pack type %c: not enough arguments", code);
RETURN_FALSE;
}
if (arg < 0) {
arg = (*argv[currentarg])->value.str.len;
}
currentarg++;
break;
}
/* Use as many args as specified */
case 'c': case 'C': case 's': case 'S': case 'i': case 'I':
case 'l': case 'L': case 'n': case 'N': case 'v': case 'V':
case 'f': case 'd': {
if (arg < 0) {
arg = argc - currentarg;
}
currentarg += arg;
if (currentarg > argc) {
efree(argv);
efree(formatcodes);
efree(formatargs);
php_error(E_ERROR, "pack type %c: too few arguments", code);
RETURN_FALSE;
}
break;
}
default: {
php_error(E_ERROR, "pack type %c: unknown format code", code);
RETURN_FALSE;
}
}
formatcodes[formatcount] = code;
formatargs[formatcount] = arg;
}
if (currentarg < argc) {
php_error(E_WARNING, "pack %d arguments unused", (argc - currentarg));
}
/* Calculate output length and upper bound while processing*/
for (i = 0; i < formatcount; i++) {
int code = (int)formatcodes[i];
int arg = formatargs[i];
switch ((int)code) {
case 'h': case 'H': {
outputpos += (arg + 1) / 2; /* 4 bit per arg */
break;
}
case 'a': case 'A':
case 'c': case 'C':
case 'x': {
outputpos += arg; /* 8 bit per arg */
break;
}
case 's': case 'S': case 'n': case 'v': {
outputpos += arg * 2; /* 16 bit per arg */
break;
}
case 'i': case 'I': {
outputpos += arg * sizeof(int);
break;
}
case 'l': case 'L': case 'N': case 'V': {
outputpos += arg * 4; /* 32 bit per arg */
break;
}
case 'f': {
outputpos += arg * sizeof(float);
break;
}
case 'd': {
outputpos += arg * sizeof(double);
break;
}
case 'X': {
outputpos -= arg;
if (outputpos < 0) {
php_error(E_WARNING, "pack type %c: outside of string", code);
outputpos = 0;
}
break;
}
case '@': {
outputpos = arg;
break;
}
}
if (outputsize < outputpos) {
outputsize = outputpos;
}
}
output = emalloc(outputsize + 1);
outputpos = 0;
currentarg = 1;
/* Do actual packing */
for (i = 0; i < formatcount; i++) {
int code = (int)formatcodes[i];
int arg = formatargs[i];
pval **val;
switch ((int)code) {
case 'a': case 'A': {
memset(&output[outputpos], (code == 'a') ? '\0' : ' ', arg);
val = argv[currentarg++];
convert_to_string_ex(val);
memcpy(&output[outputpos], (*val)->value.str.val,
((*val)->value.str.len < arg) ? (*val)->value.str.len : arg);
outputpos += arg;
break;
}
case 'h': case 'H': {
int nibbleshift = (code == 'h') ? 0 : 4;
int first = 1;
char *v;
val = argv[currentarg++];
convert_to_string_ex(val);
v = (*val)->value.str.val;
outputpos--;
if(arg > (*val)->value.str.len) {
php_error(E_WARNING, "pack type %c: not enough characters in string", code);
arg = (*val)->value.str.len;
}
while (arg-- > 0) {
char n = *(v++);
if ((n >= '0') && (n <= '9')) {
n -= '0';
} else if ((n >= 'A') && (n <= 'F')) {
n -= ('A' - 10);
} else if ((n >= 'a') && (n <= 'f')) {
n -= ('a' - 10);
} else {
php_error(E_WARNING, "pack type %c: illegal hex digit %c", code, n);
n = 0;
}
if (first--) {
output[++outputpos] = 0;
} else {
first = 1;
}
output[outputpos] |= (n << nibbleshift);
nibbleshift = (nibbleshift + 4) & 7;
}
outputpos++;
break;
}
case 'c': case 'C': {
while (arg-- > 0) {
php_pack(argv[currentarg++], 1, byte_map, &output[outputpos]);
outputpos++;
}
break;
}
case 's': case 'S': case 'n': case 'v': {
int *map = machine_endian_short_map;
if (code == 'n') {
map = big_endian_short_map;
} else if (code == 'v') {
map = little_endian_short_map;
}
while (arg-- > 0) {
php_pack(argv[currentarg++], 2, map, &output[outputpos]);
outputpos += 2;
}
break;
}
case 'i': case 'I': {
while (arg-- > 0) {
php_pack(argv[currentarg++], sizeof(int), int_map, &output[outputpos]);
outputpos += sizeof(int);
}
break;
}
case 'l': case 'L': case 'N': case 'V': {
int *map = machine_endian_long_map;
if (code == 'N') {
map = big_endian_long_map;
} else if (code == 'V') {
map = little_endian_long_map;
}
while (arg-- > 0) {
php_pack(argv[currentarg++], 4, map, &output[outputpos]);
outputpos += 4;
}
break;
}
case 'f': {
float v;
while (arg-- > 0) {
val = argv[currentarg++];
convert_to_double_ex(val);
v = (float)(*val)->value.dval;
memcpy(&output[outputpos], &v, sizeof(v));
outputpos += sizeof(v);
}
break;
}
case 'd': {
double v;
while (arg-- > 0) {
val = argv[currentarg++];
convert_to_double_ex(val);
v = (double)(*val)->value.dval;
memcpy(&output[outputpos], &v, sizeof(v));
outputpos += sizeof(v);
}
break;
}
case 'x': {
memset(&output[outputpos], '\0', arg);
outputpos += arg;
break;
}
case 'X': {
outputpos -= arg;
if (outputpos < 0) {
outputpos = 0;
}
break;
}
case '@': {
if (arg > outputpos) {
memset(&output[outputpos], '\0', arg - outputpos);
}
outputpos = arg;
break;
}
}
}
efree(argv);
efree(formatcodes);
efree(formatargs);
output[outputpos] = '\0';
RETVAL_STRINGL(output, outputpos, 1);
efree(output);
}
/* }}} */
/* {{{ php_unpack
*/
static long php_unpack(char *data, int size, int issigned, int *map)
{
long result;
char *cresult = (char *)&result;
int i;
result = issigned ? -1 : 0;
for (i = 0; i < size; i++) {
cresult[map[i]] = *(data++);
}
return result;
}
/* }}} */
/* unpack() is based on Perl's unpack(), but is modified a bit from there.
* Rather than depending on error-prone ordered lists or syntactically
* unpleasant pass-by-reference, we return an object with named paramters
* (like *_fetch_object()). Syntax is "f[repeat]name/...", where "f" is the
* formatter char (like pack()), "[repeat]" is the optional repeater argument,
* and "name" is the name of the variable to use.
* Example: "c2chars/nints" will return an object with fields
* chars1, chars2, and ints.
* Numeric pack types will return numbers, a and A will return strings,
* f and d will return doubles.
* Implemented formats are A, a, h, H, c, C, s, S, i, I, l, L, n, N, f, d, x, X, @.
*/
/* {{{ proto array unpack(string format, string input)
Unpack binary string into named array elements according to format argument */
PHP_FUNCTION(unpack)
{
pval **formatarg;
pval **inputarg;
char *format;
char *input;
int formatlen;
int inputpos, inputlen;
int i;
if ((ZEND_NUM_ARGS() != 2) || zend_get_parameters_ex(2, &formatarg, &inputarg) == FAILURE) {
WRONG_PARAM_COUNT;
}
convert_to_string_ex(formatarg);
convert_to_string_ex(inputarg);
format = (*formatarg)->value.str.val;
formatlen = (*formatarg)->value.str.len;
input = (*inputarg)->value.str.val;
inputlen = (*inputarg)->value.str.len;
inputpos = 0;
if (array_init(return_value) == FAILURE)
return;
while (formatlen-- > 0) {
char type = *(format++);
char c;
int arg = 1;
char *name;
int namelen;
int size=0;
/* Handle format arguments if any */
if (formatlen > 0) {
c = *format;
if ((c >= '0') && (c <= '9')) {
arg = atoi(format);
while ((formatlen > 0) && (*format >= '0') && (*format <= '9')) {
format++;
formatlen--;
}
} else if (c == '*') {
arg = -1;
format++;
formatlen--;
}
}
/* Get of new value in array */
name = format;
while ((formatlen > 0) && (*format != '/')) {
formatlen--;
format++;
}
namelen = format - name;
if (namelen > 200)
namelen = 200;
switch ((int)type) {
/* Never use any input */
case 'X': {
size = -1;
break;
}
case '@': {
size = 0;
break;
}
case 'a': case 'A': {
size = arg;
arg = 1;
break;
}
case 'h': case 'H': {
size = (arg>0)?arg/2:arg;
arg = 1;
break;
}
/* Use 1 byte of input */
case 'c': case 'C': case 'x': {
size = 1;
break;
}
/* Use 2 bytes of input */
case 's': case 'S': case 'n': case 'v': {
size = 2;
break;
}
/* Use sizeof(int) bytes of input */
case 'i': case 'I': {
size = sizeof(int);
break;
}
/* Use 4 bytes of input */
case 'l': case 'L': case 'N': case 'V': {
size = 4;
break;
}
/* Use sizeof(float) bytes of input */
case 'f': {
size = sizeof(float);
break;
}
/* Use sizeof(double) bytes of input */
case 'd': {
size = sizeof(double);
break;
}
}
/* Do actual unpacking */
for (i = 0; (i != arg); i++ ) {
/* Space for name + number, safe as namelen is ensured <= 200 */
char n[256];
if (arg != 1) {
/* Need to add element number to name */
sprintf(n, "%.*s%d", namelen, name, i + 1);
} else {
/* Truncate name to next format code or end of string */
sprintf(n, "%.*s", namelen, name);
}
if ((inputpos + size) <= inputlen) {
switch ((int)type) {
case 'a': case 'A': {
char pad = (type == 'a') ? '\0' : ' ';
int len = inputlen - inputpos; /* Remaining string */
/* If size was given take minimum of len and size */
if ((size >= 0) && (len > size)) {
len = size;
}
size = len;
/* Remove padding chars from unpacked data */
while (--len >= 0) {
if (input[inputpos + len] != pad)
break;
}
add_assoc_stringl(return_value, n, &input[inputpos], len + 1, 1);
break;
}
case 'h': case 'H': {
int len = (inputlen - inputpos) * 2; /* Remaining */
int nibbleshift = (type == 'h') ? 0 : 4;
int first = 1;
char *buf;
int ipos, opos;
/* If size was given take minimum of len and size */
if ((size >= 0) && (len > size*2)) {
len = size*2;
}
buf = emalloc(len + 1);
for (ipos = opos = 0; opos < len; opos++) {
char c = (input[inputpos + ipos] >> nibbleshift) & 0xf;
if (c < 10) {
c += '0';
} else {
c += 'a' - 10;
}
buf[opos] = c;
nibbleshift = (nibbleshift + 4) & 7;
if (first-- == 0) {
ipos++;
first = 1;
}
}
buf[len] = '\0';
add_assoc_stringl(return_value, n, buf, len, 1);
efree(buf);
break;
}
case 'c': case 'C': {
int issigned = (type == 'c') ? (input[inputpos] & 0x80) : 0;
long v = php_unpack(&input[inputpos], 1, issigned, byte_map);
add_assoc_long(return_value, n, v);
break;
}
case 's': case 'S': case 'n': case 'v': {
long v;
int issigned = 0;
int *map = machine_endian_short_map;
if (type == 's') {
issigned = input[inputpos + (machine_little_endian ? 1 : 0)] & 0x80;
} else if (type == 'n') {
map = big_endian_short_map;
} else if (type == 'v') {
map = little_endian_short_map;
}
v = php_unpack(&input[inputpos], 2, issigned, map);
add_assoc_long(return_value, n, v);
break;
}
case 'i': case 'I': {
long v;
int issigned = 0;
if (type == 'i') {
issigned = input[inputpos + (machine_little_endian ? (sizeof(int) - 1) : 0)] & 0x80;
}
v = php_unpack(&input[inputpos], sizeof(int), issigned, int_map);
add_assoc_long(return_value, n, v);
break;
}
case 'l': case 'L': case 'N': case 'V': {
int issigned = 0;
int *map = machine_endian_long_map;
long v;
if (type == 'l') {
issigned = input[inputpos + (machine_little_endian ? 3 : 0)] & 0x80;
} else if (type == 'N') {
map = big_endian_long_map;
} else if (type == 'V') {
map = little_endian_long_map;
}
v = php_unpack(&input[inputpos], 4, issigned, map);
add_assoc_long(return_value, n, v);
break;
}
case 'f': {
float v;
memcpy(&v, &input[inputpos], sizeof(float));
add_assoc_double(return_value, n, (double)v);
break;
}
case 'd': {
double v;
memcpy(&v, &input[inputpos], sizeof(double));
add_assoc_double(return_value, n, v);
break;
}
case 'x': {
/* Do nothing with input, just skip it */
break;
}
case 'X': {
if (inputpos < size) {
inputpos = -size;
i = arg - 1; /* Break out of for loop */
if (arg >= 0) {
php_error(E_WARNING, "pack type %c: outside of string", type);
}
}
break;
}
case '@': {
if (arg <= inputlen) {
inputpos = arg;
} else {
php_error(E_WARNING, "pack type %c: outside of string", type);
}
i = arg - 1; /* Done, break out of for loop */
break;
}
}
inputpos += size;
} else if (arg < 0) {
/* Reached end of input for '*' repeater */
break;
} else {
php_error(E_ERROR, "pack type %c: not enough input, need %d, have %d", type, size, inputlen - inputpos);
RETURN_FALSE;
}
}
formatlen--; /* Skip '/' separator, does no harm if inputlen == 0 */
format++;
}
}
/* }}} */
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(pack)
{
int machine_endian_check = 1;
int i;
machine_little_endian = ((char *)&machine_endian_check)[0];
if (machine_little_endian) {
/* Where to get lo to hi bytes from */
byte_map[0] = 0;
for (i = 0; i < sizeof(int); i++) {
int_map[i] = i;
}
machine_endian_short_map[0] = 0;
machine_endian_short_map[1] = 1;
big_endian_short_map[0] = 1;
big_endian_short_map[1] = 0;
little_endian_short_map[0] = 0;
little_endian_short_map[1] = 1;
machine_endian_long_map[0] = 0;
machine_endian_long_map[1] = 1;
machine_endian_long_map[2] = 2;
machine_endian_long_map[3] = 3;
big_endian_long_map[0] = 3;
big_endian_long_map[1] = 2;
big_endian_long_map[2] = 1;
big_endian_long_map[3] = 0;
little_endian_long_map[0] = 0;
little_endian_long_map[1] = 1;
little_endian_long_map[2] = 2;
little_endian_long_map[3] = 3;
}
else {
pval val;
int size = sizeof(val.value.lval);
val.value.lval=0; /*silence a warning*/
/* Where to get hi to lo bytes from */
byte_map[0] = size - 1;
for (i = 0; i < sizeof(int); i++) {
int_map[i] = size - (sizeof(int) - i);
}
machine_endian_short_map[0] = size - 2;
machine_endian_short_map[1] = size - 1;
big_endian_short_map[0] = size - 2;
big_endian_short_map[1] = size - 1;
little_endian_short_map[0] = size - 1;
little_endian_short_map[1] = size - 2;
machine_endian_long_map[0] = size - 4;
machine_endian_long_map[1] = size - 3;
machine_endian_long_map[2] = size - 2;
machine_endian_long_map[3] = size - 1;
big_endian_long_map[0] = size - 4;
big_endian_long_map[1] = size - 3;
big_endian_long_map[2] = size - 2;
big_endian_long_map[3] = size - 1;
little_endian_long_map[0] = size - 1;
little_endian_long_map[1] = size - 2;
little_endian_long_map[2] = size - 3;
little_endian_long_map[3] = size - 4;
}
return SUCCESS;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+28
View File
@@ -0,0 +1,28 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PACK_H
#define PACK_H
PHP_MINIT_FUNCTION(pack);
PHP_FUNCTION(pack);
PHP_FUNCTION(unpack);
#endif /* PACK_H */
+160
View File
@@ -0,0 +1,160 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Jim Winstead <jimw@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "pageinfo.h"
#include "SAPI.h"
#include <stdio.h>
#include <stdlib.h>
#if HAVE_PWD_H
#ifdef PHP_WIN32
#include "win32/pwd.h"
#else
#include <pwd.h>
#endif
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <sys/stat.h>
#ifdef PHP_WIN32
#include <process.h>
#endif
#include "ext/standard/basic_functions.h"
/* {{{ php_statpage
*/
static void php_statpage(TSRMLS_D)
{
struct stat *pstat;
pstat = sapi_get_stat(TSRMLS_C);
if (BG(page_uid)==-1 || BG(page_gid)==-1) {
if(pstat) {
BG(page_uid) = pstat->st_uid;
BG(page_gid) = pstat->st_gid;
BG(page_inode) = pstat->st_ino;
BG(page_mtime) = pstat->st_mtime;
}
}
}
/* }}} */
/* {{{ php_getuid
*/
long php_getuid(void)
{
TSRMLS_FETCH();
php_statpage(TSRMLS_C);
return (BG(page_uid));
}
/* }}} */
long php_getgid(void)
{
TSRMLS_FETCH();
php_statpage(TSRMLS_C);
return (BG(page_gid));
}
/* {{{ proto int getmyuid(void)
Get PHP script owner's UID */
PHP_FUNCTION(getmyuid)
{
long uid;
uid = php_getuid();
if (uid < 0) {
RETURN_FALSE;
} else {
RETURN_LONG(uid);
}
}
/* }}} */
/* {{{ proto int getmygid(void)
Get PHP script owner's GID */
PHP_FUNCTION(getmygid)
{
long gid;
gid = php_getgid();
if (gid < 0) {
RETURN_FALSE;
} else {
RETURN_LONG(gid);
}
}
/* }}} */
/* {{{ proto int getmypid(void)
Get current process ID */
PHP_FUNCTION(getmypid)
{
int pid;
pid = getpid();
if (pid < 0) {
RETURN_FALSE;
} else {
RETURN_LONG((long) pid);
}
}
/* }}} */
/* {{{ proto int getmyinode(void)
Get the inode of the current script being parsed */
PHP_FUNCTION(getmyinode)
{
php_statpage(TSRMLS_C);
if (BG(page_inode) < 0) {
RETURN_FALSE;
} else {
RETURN_LONG(BG(page_inode));
}
}
/* }}} */
/* {{{ proto int getlastmod(void)
Get time of last page modification */
PHP_FUNCTION(getlastmod)
{
php_statpage(TSRMLS_C);
if (BG(page_mtime) < 0) {
RETURN_FALSE;
} else {
RETURN_LONG(BG(page_mtime));
}
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+33
View File
@@ -0,0 +1,33 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Jim Winstead <jimw@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PAGEINFO_H
#define PAGEINFO_H
PHP_FUNCTION(getmyuid);
PHP_FUNCTION(getmygid);
PHP_FUNCTION(getmypid);
PHP_FUNCTION(getmyinode);
PHP_FUNCTION(getlastmod);
extern long php_getuid(void);
extern long php_getgid(void);
#endif
File diff suppressed because it is too large. Load diff
+99
View File
@@ -0,0 +1,99 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Andi Gutmans <andi@zend.com> |
| Zeev Suraski <zeev@zend.com> |
| Rasmus Lerdorf <rasmus@php.net> |
| Andrei Zmievski <andrei@ispi.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PHP_ARRAY_H
#define PHP_ARRAY_H
PHP_MINIT_FUNCTION(array);
PHP_MSHUTDOWN_FUNCTION(array);
PHP_FUNCTION(ksort);
PHP_FUNCTION(krsort);
PHP_FUNCTION(natsort);
PHP_FUNCTION(natcasesort);
PHP_FUNCTION(asort);
PHP_FUNCTION(arsort);
PHP_FUNCTION(sort);
PHP_FUNCTION(rsort);
PHP_FUNCTION(usort);
PHP_FUNCTION(uasort);
PHP_FUNCTION(uksort);
PHP_FUNCTION(array_walk);
PHP_FUNCTION(count);
PHP_FUNCTION(end);
PHP_FUNCTION(prev);
PHP_FUNCTION(next);
PHP_FUNCTION(reset);
PHP_FUNCTION(current);
PHP_FUNCTION(key);
PHP_FUNCTION(min);
PHP_FUNCTION(max);
PHP_FUNCTION(in_array);
PHP_FUNCTION(array_search);
PHP_FUNCTION(extract);
PHP_FUNCTION(compact);
PHP_FUNCTION(range);
PHP_FUNCTION(shuffle);
PHP_FUNCTION(array_multisort);
PHP_FUNCTION(array_push);
PHP_FUNCTION(array_pop);
PHP_FUNCTION(array_shift);
PHP_FUNCTION(array_unshift);
PHP_FUNCTION(array_splice);
PHP_FUNCTION(array_slice);
PHP_FUNCTION(array_merge);
PHP_FUNCTION(array_merge_recursive);
PHP_FUNCTION(array_keys);
PHP_FUNCTION(array_values);
PHP_FUNCTION(array_count_values);
PHP_FUNCTION(array_reverse);
PHP_FUNCTION(array_reduce);
PHP_FUNCTION(array_pad);
PHP_FUNCTION(array_flip);
PHP_FUNCTION(array_rand);
PHP_FUNCTION(array_unique);
PHP_FUNCTION(array_intersect);
PHP_FUNCTION(array_diff);
PHP_FUNCTION(array_sum);
PHP_FUNCTION(array_filter);
PHP_FUNCTION(array_map);
PHP_FUNCTION(key_exists);
HashTable* php_splice(HashTable *, int, int, zval ***, int, HashTable **);
PHPAPI void php_array_merge(HashTable *dest, HashTable *src, int recursive);
int multisort_compare(const void *a, const void *b);
typedef struct {
int *multisort_flags[2];
int (*compare_func)(zval *result, zval *op1, zval *op2 TSRMLS_DC);
} php_array_globals;
#ifdef ZTS
#define ARRAYG(v) TSRMG(array_globals_id, php_array_globals *, v)
extern int array_globals_id;
#else
#define ARRAYG(v) (array_globals.v)
extern php_array_globals array_globals;
#endif
#endif /* PHP_ARRAY_H */
+32
View File
@@ -0,0 +1,32 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Thies C. Arntzen (thies@thieso.net) |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PHP_ASSERT_H
#define PHP_ASSERT_H
PHP_MINIT_FUNCTION(assert);
PHP_MSHUTDOWN_FUNCTION(assert);
PHP_RINIT_FUNCTION(assert);
PHP_RSHUTDOWN_FUNCTION(assert);
PHP_MINFO_FUNCTION(assert);
PHP_FUNCTION(assert);
PHP_FUNCTION(assert_options);
#endif /* PHP_ASSERT_H */
+29
View File
@@ -0,0 +1,29 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Zeev Suraski <zeev@zend.com> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PHP_BROWSCAP_H
#define PHP_BROWSCAP_H
PHP_MINIT_FUNCTION(browscap);
PHP_MSHUTDOWN_FUNCTION(browscap);
PHP_FUNCTION(get_browser);
#endif /* PHP_BROWSCAP_H */
+38
View File
@@ -0,0 +1,38 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Stig Bakken <ssb@gaurdian.no> |
| Zeev Suraski <zeev@zend.com> |
| Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PHP_CRYPT_H
#define PHP_CRYPT_H
PHP_FUNCTION(crypt);
#if HAVE_CRYPT
PHP_MINIT_FUNCTION(crypt);
#endif
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
*/
+39
View File
@@ -0,0 +1,39 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: |
| PHP 4.0 patches by Thies C. Arntzen (thies@thieso.net) |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PHP_DIR_H
#define PHP_DIR_H
/* directory functions */
PHP_MINIT_FUNCTION(dir);
PHP_RINIT_FUNCTION(dir);
PHP_FUNCTION(opendir);
PHP_FUNCTION(closedir);
PHP_FUNCTION(chdir);
#if defined(HAVE_CHROOT) && !defined(ZTS)
PHP_FUNCTION(chroot);
#endif
PHP_FUNCTION(getcwd);
PHP_FUNCTION(rewinddir);
PHP_NAMED_FUNCTION(php_if_readdir);
PHP_FUNCTION(getdir);
#endif /* PHP_DIR_H */
+39
View File
@@ -0,0 +1,39 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Stig Sæther Bakken <ssb@fast.no> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PHP_EXT_SYSLOG_H
#define PHP_EXT_SYSLOG_H
#ifdef HAVE_SYSLOG_H
#include "php_syslog.h"
PHP_MINIT_FUNCTION(syslog);
PHP_RINIT_FUNCTION(syslog);
PHP_RSHUTDOWN_FUNCTION(syslog);
PHP_FUNCTION(openlog);
PHP_FUNCTION(syslog);
PHP_FUNCTION(closelog);
PHP_FUNCTION(define_syslog_variables);
#endif
#endif /* PHP_EXT_SYSLOG_H */
+76
View File
@@ -0,0 +1,76 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Jim Winstead <jimw@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PHP_FILESTAT_H
#define PHP_FILESTAT_H
PHP_RINIT_FUNCTION(filestat);
PHP_RSHUTDOWN_FUNCTION(filestat);
PHP_FUNCTION(clearstatcache);
PHP_FUNCTION(fileatime);
PHP_FUNCTION(filectime);
PHP_FUNCTION(filegroup);
PHP_FUNCTION(fileinode);
PHP_FUNCTION(filemtime);
PHP_FUNCTION(fileowner);
PHP_FUNCTION(fileperms);
PHP_FUNCTION(filesize);
PHP_FUNCTION(filetype);
PHP_FUNCTION(is_writable);
PHP_FUNCTION(is_readable);
PHP_FUNCTION(is_executable);
PHP_FUNCTION(is_file);
PHP_FUNCTION(is_dir);
PHP_FUNCTION(is_link);
PHP_FUNCTION(file_exists);
PHP_NAMED_FUNCTION(php_if_stat);
PHP_NAMED_FUNCTION(php_if_lstat);
PHP_FUNCTION(disk_total_space);
PHP_FUNCTION(disk_free_space);
PHP_FUNCTION(chown);
PHP_FUNCTION(chgrp);
PHP_FUNCTION(chmod);
PHP_FUNCTION(touch);
PHP_FUNCTION(clearstatcache);
#define MAKE_LONG_ZVAL_INCREF(name, val)\
MAKE_STD_ZVAL(name); \
ZVAL_LONG(name, val); \
name->refcount++;
#ifdef PHP_WIN32
#define S_IRUSR S_IREAD
#define S_IWUSR S_IWRITE
#define S_IXUSR S_IEXEC
#define S_IRGRP S_IREAD
#define S_IWGRP S_IWRITE
#define S_IXGRP S_IEXEC
#define S_IROTH S_IREAD
#define S_IWOTH S_IWRITE
#define S_IXOTH S_IEXEC
#undef getgid
#define getgroups(a, b) 0
#define getgid() 1
#define getuid() 1
#endif
#endif /* PHP_FILESTAT_H */
+61
View File
@@ -0,0 +1,61 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
| Jim Winstead <jimw@php.net> |
| Hartmut Holzgraefe <hholzgra@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include <stdio.h>
#include <stdlib.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "php.h"
#include "php_globals.h"
#include "php_standard.h"
#include "php_fopen_wrappers.h"
/* {{{ php_fopen_url_wrap_php
*/
FILE *php_fopen_url_wrap_php(const char *path, char *mode, int options, int *issock, int *socketd, char **opened_path TSRMLS_DC)
{
const char *res = path + 6;
*issock = 0;
if (!strcasecmp(res, "stdin")) {
return fdopen(dup(STDIN_FILENO), mode);
} else if (!strcasecmp(res, "stdout")) {
return fdopen(dup(STDOUT_FILENO), mode);
} else if (!strcasecmp(res, "stderr")) {
return fdopen(dup(STDERR_FILENO), mode);
}
return NULL;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 tw=78 fdm=marker
* vim<600: sw=4 ts=4 tw=78
*/
+30
View File
@@ -0,0 +1,30 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
| Jim Winstead <jimw@php.net> |
| Hartmut Holzgraefe <hholzgra@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PHP_FOPEN_WRAPPERS_H
#define PHP_FOPEN_WRAPPERS_H
FILE *php_fopen_url_wrap_http(const char *, char *, int, int *, int *, char ** TSRMLS_DC);
FILE *php_fopen_url_wrap_ftp(const char *, char *, int, int *, int *, char ** TSRMLS_DC);
FILE *php_fopen_url_wrap_php(const char *, char *, int, int *, int *, char ** TSRMLS_DC);
#endif
+26
View File
@@ -0,0 +1,26 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PHP_IMAGE_H
#define PHP_IMAGE_H
PHP_FUNCTION(getimagesize);
#endif /* PHP_IMAGE_H */
+62
View File
@@ -0,0 +1,62 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Sascha Schumann <sascha@schumann.cx> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PHP_INCOMPLETE_CLASS_H
#define PHP_INCOMPLETE_CLASS_H
#include "ext/standard/basic_functions.h"
#define PHP_IC_ENTRY \
BG(incomplete_class)
#define PHP_SET_CLASS_ATTRIBUTES(struc) \
/* OBJECTS_FIXME: Fix for new object model */ \
if (Z_OBJCE_P(struc) == BG(incomplete_class)) { \
class_name = php_lookup_class_name(struc, &name_len, 1); \
free_class_name = 1; \
} else { \
class_name = Z_OBJCE_P(struc)->name; \
name_len = Z_OBJCE_P(struc)->name_length; \
}
#define PHP_CLEANUP_CLASS_ATTRIBUTES() \
if (free_class_name) efree(class_name)
#define PHP_CLASS_ATTRIBUTES \
char *class_name; \
size_t name_len; \
zend_bool free_class_name = 0 \
#ifdef __cplusplus
extern "C" {
#endif
zend_class_entry *php_create_incomplete_class(TSRMLS_D);
char *php_lookup_class_name(zval *object, size_t *nlen, zend_bool del);
void php_store_class_name(zval *object, const char *name, size_t len);
#ifdef __cplusplus
};
#endif
#endif
+27
View File
@@ -0,0 +1,27 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Thies C. Arntzen <thies@thieso.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PHP_IPTC_H
#define PHP_IPTC_H
PHP_FUNCTION(iptcparse);
PHP_FUNCTION(iptcembed);
#endif /* PHP_IPTC_H */
+42
View File
@@ -0,0 +1,42 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Sascha Schumann <sascha@schumann.cx> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PHP_LCG_H
#define PHP_LCG_H
#include "ext/standard/basic_functions.h"
typedef struct {
php_int32 s1;
php_int32 s2;
} php_lcg_globals;
double php_combined_lcg(TSRMLS_D);
PHP_FUNCTION(lcg_value);
#ifdef ZTS
PHP_MINIT_FUNCTION(lcg);
#define LCG(v) TSRMG(lcg_globals_id, php_lcg_globals *, v)
#else
PHP_RINIT_FUNCTION(lcg);
#define LCG(v) (lcg_globals.v)
#endif
#endif
+33
View File
@@ -0,0 +1,33 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PHP_LINK_H
#define PHP_LINK_H
#ifdef HAVE_SYMLINK
PHP_FUNCTION(link);
PHP_FUNCTION(readlink);
PHP_FUNCTION(linkinfo);
PHP_FUNCTION(symlink);
#endif
#endif /* PHP_LINK_H */
+33
View File
@@ -0,0 +1,33 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PHP_MAIL_H
#define PHP_MAIL_H
#if HAVE_SENDMAIL
PHP_FUNCTION(mail);
PHP_FUNCTION(ezmlm_hash);
PHP_MINFO_FUNCTION(mail);
PHPAPI extern int php_mail(char *to, char *subject, char *message, char *headers, char *extra_cmd);
#endif
#endif /* PHP_MAIL_H */
+138
View File
@@ -0,0 +1,138 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Jim Winstead (jimw@php.net) |
| Stig Sæther Bakken <ssb@guardian.no> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PHP_MATH_H
#define PHP_MATH_H
PHP_FUNCTION(sin);
PHP_FUNCTION(cos);
PHP_FUNCTION(tan);
PHP_FUNCTION(asin);
PHP_FUNCTION(acos);
PHP_FUNCTION(atan);
PHP_FUNCTION(atan2);
PHP_FUNCTION(pi);
PHP_FUNCTION(exp);
PHP_FUNCTION(log);
PHP_FUNCTION(log10);
PHP_FUNCTION(pow);
PHP_FUNCTION(sqrt);
PHP_FUNCTION(abs);
PHP_FUNCTION(ceil);
PHP_FUNCTION(floor);
PHP_FUNCTION(round);
PHP_FUNCTION(decbin);
PHP_FUNCTION(dechex);
PHP_FUNCTION(decoct);
PHP_FUNCTION(bindec);
PHP_FUNCTION(hexdec);
PHP_FUNCTION(octdec);
PHP_FUNCTION(base_convert);
PHP_FUNCTION(number_format);
PHP_FUNCTION(deg2rad);
PHP_FUNCTION(rad2deg);
/*
WARNING: these functions are expermental: they could change their names or
disappear in the next version of PHP!
*/
PHP_FUNCTION(hypot);
PHP_FUNCTION(expm1);
PHP_FUNCTION(log1p);
PHP_FUNCTION(sinh);
PHP_FUNCTION(cosh);
PHP_FUNCTION(tanh);
PHP_FUNCTION(asinh);
PHP_FUNCTION(acosh);
PHP_FUNCTION(atanh);
#include <math.h>
#ifndef M_E
#define M_E 2.7182818284590452354 /* e */
#endif
#ifndef M_LOG2E
#define M_LOG2E 1.4426950408889634074 /* log_2 e */
#endif
#ifndef M_LOG10E
#define M_LOG10E 0.43429448190325182765 /* log_10 e */
#endif
#ifndef M_LN2
#define M_LN2 0.69314718055994530942 /* log_e 2 */
#endif
#ifndef M_LN10
#define M_LN10 2.30258509299404568402 /* log_e 10 */
#endif
#ifndef M_PI
#define M_PI 3.14159265358979323846 /* pi */
#endif
#ifndef M_PI_2
#define M_PI_2 1.57079632679489661923 /* pi/2 */
#endif
#ifndef M_PI_4
#define M_PI_4 0.78539816339744830962 /* pi/4 */
#endif
#ifndef M_1_PI
#define M_1_PI 0.31830988618379067154 /* 1/pi */
#endif
#ifndef M_2_PI
#define M_2_PI 0.63661977236758134308 /* 2/pi */
#endif
#ifndef M_SQRTPI
#define M_SQRTPI 1.77245385090551602729 /* sqrt(pi) */
#endif
#ifndef M_2_SQRTPI
#define M_2_SQRTPI 1.12837916709551257390 /* 2/sqrt(pi) */
#endif
#ifndef M_LNPI
#define M_LNPI 1.14472988584940017414 /* ln(pi) */
#endif
#ifndef M_EULER
#define M_EULER 0.57721566490153286061 /* Euler constant */
#endif
#ifndef M_SQRT2
#define M_SQRT2 1.41421356237309504880 /* sqrt(2) */
#endif
#ifndef M_SQRT1_2
#define M_SQRT1_2 0.70710678118654752440 /* 1/sqrt(2) */
#endif
#ifndef M_SQRT3
#define M_SQRT3 1.73205080756887729352 /* sqrt(3) */
#endif
#endif /* PHP_MATH_H */
+26
View File
@@ -0,0 +1,26 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Thies C. Arntzen <thies@thieso.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PHP_METAPHONE_H
#define PHP_METAPHONE_H
PHP_FUNCTION(metaphone);
#endif
+26
View File
@@ -0,0 +1,26 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Sascha Schumann <sascha@schumann.cx> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_PARSEDATE_H
#define PHP_PARSEDATE_H
#include <time.h>
time_t php_parse_date(char *p, time_t *now);
#endif
+130
View File
@@ -0,0 +1,130 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
| Zeev Suraski <zeev@zend.com> |
| Pedro Melo <melo@ip.pt> |
| Jeroen van Wolffelaar <jeroen@php.net> |
| |
| Based on code from: Shawn Cokus <Cokus@math.washington.edu> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
/* Layout implementation random functions
*
* The PHPAPI contains these functions:
* - long php_rand()
* - long php_rand_range(long min, long max)
* - void php_srand()
* - long php_getrandmax()
*
* Note that it is not possible to choose the algoritm. This is done to
* give the user the possibility to control all randomness by means of
* srand()/php.ini in a portable and consistent way.
*
* rand.c: (the only rand*.c file with PHP_API and PHP_FUNCTION functions)
*
* - PHP_FUNCTION([mt_]srand)
* +-> void php_srand(void)
* +-> void php_srand2(long seed, int alg)
* +-> (rand_sys.c) long php_rand_sys()
* +-> (rand_mt.c ) long php_rand_mt()
*
* - PHP_FUNCTION([mt_]rand)
* +-> long php_rand()
* +-> (rand_sys.c) long php_rand_sys()
* +-> (rand_mt.c ) long php_rand_mt()
* +-> long php_rand_range(long min, long max)
* +-> calls php_rand()
*
* - PHP_FUNCTION([mt_]getrandmax)
* +-> PHPAPI long php_randmax(void)
* +-> (rand_sys.c) long php_randmax_sys()
* +-> (rand_mt.c ) long php_randmax_mt()
*
* --Jeroen
*/
/* TODO:
* - make constants available to PHP-user
* - MINFO section about which random number generators are available
* - Nuke randmax by enhancing PHP_RAND_RANGE to work well in the case of a
* greater request than the real (internal) randmax is
* - Implement LCG
* - Implement a real-random source? (via internet, and/or /dev/urandom?)
* - Can lrand48 be thread-safe?
* - Is random() useful sometimes?
* - Which system algorithms are available, maybe name them after real
* algorithm by compile-time detection?
* - Get this to compile :-)
*/
#ifndef PHP_RAND_H
#define PHP_RAND_H
#include <stdlib.h>
/* FIXME: that '_php_randgen_entry' needed, or not? */
typedef struct _php_randgen_entry {
void (*srand)(long seed);
long (*rand)(void);
long randmax;
char *ini_str;
} php_randgen_entry;
/* an ARRAY of POINTERS, not vice versa */
extern php_randgen_entry *php_randgen_entries[];
#define PHP_RANDGEN_ENTRY(which, nsrand, nrand, nrandmax, nini_str) { \
php_randgen_entries[which] = emalloc(sizeof(php_randgen_entry)); \
php_randgen_entries[which]->srand = nsrand; \
php_randgen_entries[which]->rand = nrand; \
php_randgen_entries[which]->randmax = nrandmax; \
php_randgen_entries[which]->ini_str = nini_str; \
}
/* Define random generator constants */
#define PHP_RAND_SYS 0
#define PHP_RAND_LRAND48 1
#define PHP_RAND_MT 2
#define PHP_RAND_LCG 3
#define PHP_RAND_DEFAULT PHP_RAND_MT
/* how many there are */
#define PHP_RAND_NUMRANDS 4
/* Proto's */
PHP_FUNCTION(srand);
PHP_FUNCTION(rand);
PHP_FUNCTION(getrandmax);
PHP_FUNCTION(mt_srand);
PHP_FUNCTION(mt_rand);
PHP_FUNCTION(mt_getrandmax);
PHPAPI long php_rand(void);
PHPAPI long php_rand_range(long min, long max);
PHPAPI double php_drand(void);
PHPAPI long php_randmax(void);
#endif /* PHP_RAND_H */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: fdm=marker
* vim: sw=4 ts=4 tw=78
*/
+139
View File
@@ -0,0 +1,139 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Sascha Schumann <sascha@schumann.cx> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_SMART_STR_H
#define PHP_SMART_STR_H
#include "php_smart_str_public.h"
#include <stdlib.h>
#include <zend.h>
#define smart_str_0(x) ((x)->c[(x)->len] = '\0')
#ifndef SMART_STR_PREALLOC
#define SMART_STR_PREALLOC 128
#endif
#define smart_str_alloc(d, n, what) {\
if (!d->c) d->len = d->a = 0; \
newlen = d->len + n; \
if (newlen >= d->a) {\
d->c = perealloc(d->c, newlen + SMART_STR_PREALLOC + 1, what); \
d->a = newlen + SMART_STR_PREALLOC; \
}\
}
#define smart_str_appends_ex(dest, src, what) smart_str_appendl_ex(dest, src, strlen(src), what)
#define smart_str_appends(dest, src) smart_str_appendl(dest, src, strlen(src))
#define smart_str_appendc(dest, c) smart_str_appendc_ex(dest, c, 0)
#define smart_str_free(s) smart_str_free_ex(s, 0)
#define smart_str_appendl(dest, src, len) smart_str_appendl_ex(dest, src, len, 0)
#define smart_str_append(dest, src) smart_str_append_ex(dest, src, 0)
#define smart_str_append_long(dest, val) smart_str_append_long_ex(dest, val, 0)
static inline void smart_str_appendc_ex(smart_str *dest, char c, int what)
{
size_t newlen;
smart_str_alloc(dest, 1, what);
dest->len = newlen;
dest->c[dest->len - 1] = c;
}
static inline void smart_str_free_ex(smart_str *s, int what)
{
if (s->c) {
pefree(s->c, what);
s->c = NULL;
}
s->a = s->len = 0;
}
static inline void smart_str_appendl_ex(smart_str *dest, const char *src, size_t len, int what)
{
size_t newlen;
smart_str_alloc(dest, len, what);
memcpy(dest->c + dest->len, src, len);
dest->len = newlen;
}
static inline char *smart_str_print_long(char *buf, long num)
{
char *p = buf, *end;
int n;
long tmp;
if (num < 0) {
num = -num;
*p++ = '-';
}
/* many numbers are < 10 */
if (num < 10) {
*p++ = num + '0';
return p;
}
n = 1;
tmp = num;
/* calculate the number of digits we need */
do {
tmp /= 10;
n++;
} while (tmp >= 10);
end = p += n;
do {
*--p = (num % 10) + '0';
num /= 10;
} while (--n > 0);
return end;
}
static inline void smart_str_append_long_ex(smart_str *dest, long num, int type)
{
char buf[32];
char *p = smart_str_print_long(buf, num);
smart_str_appendl_ex(dest, buf, p - buf, type);
}
static inline void smart_str_append_ex(smart_str *dest, smart_str *src, int what)
{
smart_str_appendl_ex(dest, src->c, src->len, what);
}
static inline void smart_str_setl(smart_str *dest, const char *src, size_t len)
{
dest->len = len;
dest->a = len + 1;
dest->c = (char *) src;
}
static inline void smart_str_sets(smart_str *dest, const char *src)
{
smart_str_setl(dest, src, strlen(src));
}
#endif
+30
View File
@@ -0,0 +1,30 @@
/*
+----------------------------------------------------------------------+
| PHP version 4.0 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2001 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Sascha Schumann <sascha@schumann.cx> |
+----------------------------------------------------------------------+
*/
#ifndef PHP_SMART_STR_PUBLIC_H
#define PHP_SMART_STR_PUBLIC_H
#include <sys/types.h>
typedef struct {
char *c;
size_t len;
size_t a;
} smart_str;
#endif
Loaded 100 of 187 files, more files were not shown because too many files have changed in this diff. Show more