示例#1
0
/* {{{ MongoCode::__toString()
 */
PHP_METHOD(MongoCode, __toString)
{
	zval *zode = zend_read_property(mongo_ce_Code, getThis(), "code", strlen("code"), NOISY TSRMLS_CC);
	convert_to_string_ex(&zode);

	RETURN_STRING(Z_STRVAL_P(zode), 1);
}
示例#2
0
static zval *com_property_read(zval *object, zval *member, int type, void **cahce_slot, zval *rv)
{
	php_com_dotnet_object *obj;
	VARIANT v;
	HRESULT res;

	ZVAL_NULL(rv);

	obj = CDNO_FETCH(object);

	if (V_VT(&obj->v) == VT_DISPATCH) {
		VariantInit(&v);

		convert_to_string_ex(member);

		res = php_com_do_invoke(obj, Z_STRVAL_P(member), Z_STRLEN_P(member),
				DISPATCH_METHOD|DISPATCH_PROPERTYGET, &v, 0, NULL, 1);

		if (res == SUCCESS) {
			php_com_zval_from_variant(rv, &v, obj->code_page);
			VariantClear(&v);
		} else if (res == DISP_E_BADPARAMCOUNT) {
			php_com_saproxy_create(object, rv, member);
		}
	} else {
		php_com_throw_exception(E_INVALIDARG, "this variant has no properties");
	}

	return rv;
}
示例#3
0
U_CFUNC PHP_FUNCTION(intltz_create_enumeration)
{
	zval				*arg = NULL;
	StringEnumeration	*se	  = NULL;
	intl_error_reset(NULL);

	/* double indirection to have the zend engine destroy the new zval that
	 * results from separation */
	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|z", &arg) == FAILURE) {
		intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR,
			"intltz_create_enumeration: bad arguments", 0);
		RETURN_FALSE;
	}

	if (arg == NULL || Z_TYPE_P(arg) == IS_NULL) {
		se = TimeZone::createEnumeration();
	} else if (Z_TYPE_P(arg) == IS_LONG) {
int_offset:
		if (Z_LVAL_P(arg) < (zend_long)INT32_MIN ||
				Z_LVAL_P(arg) > (zend_long)INT32_MAX) {
			intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR,
				"intltz_create_enumeration: value is out of range", 0);
			RETURN_FALSE;
		} else {
			se = TimeZone::createEnumeration((int32_t) Z_LVAL_P(arg));
		}
	} else if (Z_TYPE_P(arg) == IS_DOUBLE) {
double_offset:
		convert_to_long_ex(arg);
		goto int_offset;
	} else if (Z_TYPE_P(arg) == IS_OBJECT || Z_TYPE_P(arg) == IS_STRING) {
		zend_long lval;
		double dval;
		convert_to_string_ex(arg);
		switch (is_numeric_string(Z_STRVAL_P(arg), Z_STRLEN_P(arg), &lval, &dval, 0)) {
		case IS_DOUBLE:
			zval_ptr_dtor(arg);
			ZVAL_DOUBLE(arg, dval);
			goto double_offset;
		case IS_LONG:
			zval_ptr_dtor(arg);
			ZVAL_LONG(arg, lval);
			goto int_offset;
		}
		/* else call string version */
		se = TimeZone::createEnumeration(Z_STRVAL_P(arg));
	} else {
		intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR,
			"intltz_create_enumeration: invalid argument type", 0);
		RETURN_FALSE;
	}

	if (se) {
		IntlIterator_from_StringEnumeration(se, return_value);
	} else {
		intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR,
			"intltz_create_enumeration: error obtaining enumeration", 0);
		RETVAL_FALSE;
	}
}
static void accel_file_in_cache(int type, INTERNAL_FUNCTION_PARAMETERS)
{
	char *filename;
	int filename_len;
#if ZEND_EXTENSION_API_NO < PHP_5_3_X_API_NO
	zval **zfilename;

	if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &zfilename) == FAILURE) {
		WRONG_PARAM_COUNT;
	}
	convert_to_string_ex(zfilename);
	filename = Z_STRVAL_PP(zfilename);
	filename_len = Z_STRLEN_PP(zfilename);
#elif ZEND_EXTENSION_API_NO == PHP_5_3_X_API_NO
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &filename, &filename_len) == FAILURE) {
		return;
	}
#else
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &filename, &filename_len) == FAILURE) {
		return;
	}
#endif
	if(filename_len > 0) {
		if(filename_is_in_cache(filename, filename_len TSRMLS_CC)) {
			RETURN_TRUE;
		}
	}

	php_stat(filename, filename_len, type, return_value TSRMLS_CC);
}
示例#5
0
static int php_get_if_index_from_zval(zval *val, unsigned *out)
{
	int ret;

	if (Z_TYPE_P(val) == IS_LONG) {
		if (Z_LVAL_P(val) < 0 || (zend_ulong)Z_LVAL_P(val) > UINT_MAX) {
			php_error_docref(NULL, E_WARNING,
				"the interface index cannot be negative or larger than %u;"
				" given " ZEND_LONG_FMT, UINT_MAX, Z_LVAL_P(val));
			ret = FAILURE;
		} else {
			*out = Z_LVAL_P(val);
			ret = SUCCESS;
		}
	} else {
		if (Z_REFCOUNTED_P(val)) {
			Z_ADDREF_P(val);
		}
		convert_to_string_ex(val);
		ret = php_string_to_if_index(Z_STRVAL_P(val), out);
		zval_ptr_dtor(val);
	}

	return ret;
}
示例#6
0
static zval *com_property_read(zval *object, zval *member, int type TSRMLS_DC)
{
	zval *return_value;
	php_com_dotnet_object *obj;
	VARIANT v;
	HRESULT res;

	MAKE_STD_ZVAL(return_value);
	ZVAL_NULL(return_value);
	Z_SET_REFCOUNT_P(return_value, 0);
	Z_UNSET_ISREF_P(return_value);

	obj = CDNO_FETCH(object);

	if (V_VT(&obj->v) == VT_DISPATCH) {
		VariantInit(&v);

		convert_to_string_ex(&member);

		res = php_com_do_invoke(obj, Z_STRVAL_P(member), Z_STRLEN_P(member),
				DISPATCH_METHOD|DISPATCH_PROPERTYGET, &v, 0, NULL, 1 TSRMLS_CC);

		if (res == SUCCESS) {
			php_com_zval_from_variant(return_value, &v, obj->code_page TSRMLS_CC);
			VariantClear(&v);
		} else if (res == DISP_E_BADPARAMCOUNT) {
			php_com_saproxy_create(object, return_value, member TSRMLS_CC);
		}
	} else {
		php_com_throw_exception(E_INVALIDARG, "this variant has no properties" TSRMLS_CC);
	}

	return return_value;
}
示例#7
0
static void php_dba_update(INTERNAL_FUNCTION_PARAMETERS, int mode)
{
	DBA_ID_PARS;
	pval **val, **key;

	if(ac != 3 || zend_get_parameters_ex(ac, &key, &val, &id) != SUCCESS) {
		WRONG_PARAM_COUNT;
	}
	convert_to_string_ex(key);
	convert_to_string_ex(val);
	DBA_ID_GET;

	DBA_WRITE_CHECK;
	
	if(info->hnd->update(info, VALLEN(key), VALLEN(val), mode) == SUCCESS)
		RETURN_TRUE;
	RETURN_FALSE;
}
示例#8
0
/* {{{ _php_bbcode_callback_handler
   Common code for content and parameter handlers */
static int _php_bbcode_callback_handler(int cb_type, bstring content, bstring param, zval *func_name)
{
	zval *retval = NULL;
	zval ***zargs = NULL;
	char *callable = NULL;
	int i, res;
	bstring target;
	char *cb_name = "";
	TSRMLS_FETCH();

	switch (cb_type) {
		case PHP_BBCODE_CONTENT_CB:
			target = content;
			break;

		case PHP_BBCODE_PARAM_CB:
			target = param;
			break;
	}

	zargs = (zval ***) emalloc(sizeof(zval **) * 2);
	zargs[0] = emalloc(sizeof(zval *));
	MAKE_STD_ZVAL(*zargs[0]);
	ZVAL_STRINGL(*zargs[0], bdata(content), blength(content), 1);
	zargs[1] = emalloc(sizeof(zval *));
	MAKE_STD_ZVAL(*zargs[1]);
	ZVAL_STRINGL(*zargs[1], bdata(param), blength(param), 1);

	res = call_user_function_ex(EG(function_table), NULL, func_name, &retval, 2, zargs, 1, NULL TSRMLS_CC);
	
	if (res != SUCCESS) {
		if (!zend_is_callable(func_name, 0, &callable TSRMLS_CC)) {
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "function `%s' is not callable", callable);
		} else {
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "callback function %s() failed", callable);
		}
		efree(callable);
	} else if (&retval != NULL) {
		convert_to_string_ex(&retval);
		if (Z_STRLEN_P(retval)) {
			bassignblk(target, Z_STRVAL_P(retval), Z_STRLEN_P(retval));
		} else {
			bdelete(target, 0, blength(target));
		}
		zval_ptr_dtor(&retval);
	}

	/* Free zargs */
	for (i = 0; i < 2; i++) {
		zval_ptr_dtor(zargs[i]);
		efree(zargs[i]);
	}
	efree(zargs);

	return 0;
}
示例#9
0
/* {{{ mysqlnd_stmt_execute_prepare_param_types */
static enum_func_status
mysqlnd_stmt_execute_prepare_param_types(MYSQLND_STMT_DATA * stmt, zval ** copies_param, int * resend_types_next_time)
{
	unsigned int i;
	DBG_ENTER("mysqlnd_stmt_execute_prepare_param_types");
	for (i = 0; i < stmt->param_count; i++) {
		short current_type = stmt->param_bind[i].type;
		zval *parameter = &stmt->param_bind[i].zv;

		ZVAL_DEREF(parameter);
		if (!Z_ISNULL_P(parameter) && (current_type == MYSQL_TYPE_LONG || current_type == MYSQL_TYPE_LONGLONG)) {
			/* always copy the var, because we do many conversions */
			if (Z_TYPE_P(parameter) != IS_LONG &&
				PASS != mysqlnd_stmt_copy_it(copies_param, parameter, stmt->param_count, i))
			{
				SET_OOM_ERROR(*stmt->error_info);
				goto end;
			}
			/*
			  if it doesn't fit in a long send it as a string.
			  Check bug #52891 : Wrong data inserted with mysqli/mysqlnd when using bind_param, value > LONG_MAX
			*/
			if (Z_TYPE_P(parameter) != IS_LONG) {
				zval *tmp_data = (*copies_param && !Z_ISUNDEF((*copies_param)[i]))? &(*copies_param)[i]: parameter;
				/*
				  Because converting to double and back to long can lead
				  to losing precision we need second variable. Conversion to double is to see if
				  value is too big for a long. As said, precision could be lost.
				*/
				zval tmp_data_copy;
				ZVAL_COPY(&tmp_data_copy, tmp_data);
				convert_to_double_ex(&tmp_data_copy);

				/*
				  if it doesn't fit in a long send it as a string.
				  Check bug #52891 : Wrong data inserted with mysqli/mysqlnd when using bind_param, value > LONG_MAX
				  We do transformation here, which will be used later when sending types. The code later relies on this.
				*/
				if (Z_DVAL(tmp_data_copy) > ZEND_LONG_MAX || Z_DVAL(tmp_data_copy) < ZEND_LONG_MIN) {
					stmt->send_types_to_server = *resend_types_next_time = 1;
					convert_to_string_ex(tmp_data);
				} else {
					convert_to_long_ex(tmp_data);
				}

				zval_ptr_dtor(&tmp_data_copy);
			}
		}
	}
	DBG_RETURN(PASS);
end:
	DBG_RETURN(FAIL);
}
示例#10
0
文件: dba.c 项目: Apfelfrisch/php-src
/* {{{ php_dba_myke_key */
static size_t php_dba_make_key(zval *key, char **key_str, char **key_free)
{
	if (Z_TYPE_P(key) == IS_ARRAY) {
		zval *group, *name;
		HashPosition pos;
		size_t len;

		if (zend_hash_num_elements(Z_ARRVAL_P(key)) != 2) {
			php_error_docref(NULL, E_RECOVERABLE_ERROR, "Key does not have exactly two elements: (key, name)");
			return 0;
		}
		zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(key), &pos);
		group = zend_hash_get_current_data_ex(Z_ARRVAL_P(key), &pos);
		zend_hash_move_forward_ex(Z_ARRVAL_P(key), &pos);
		name = zend_hash_get_current_data_ex(Z_ARRVAL_P(key), &pos);
		convert_to_string_ex(group);
		convert_to_string_ex(name);
		if (Z_STRLEN_P(group) == 0) {
			*key_str = Z_STRVAL_P(name);
			*key_free = NULL;
			return Z_STRLEN_P(name);
		}
		len = spprintf(key_str, 0, "[%s]%s", Z_STRVAL_P(group), Z_STRVAL_P(name));
		*key_free = *key_str;
		return len;
	} else {
		zval tmp;
		int len;

		ZVAL_COPY(&tmp, key);
		convert_to_string(&tmp);

		len = Z_STRLEN(tmp);
		if (len) {
			*key_free = *key_str = estrndup(Z_STRVAL(tmp), Z_STRLEN(tmp));
		}
		zval_ptr_dtor(&tmp);
		return len;
	}
}
示例#11
0
/* {{{ proto mixed hstore_encode(array hstore)
   Decodes the hStore representation into a PHP value */
static PHP_FUNCTION(hstore_encode)
{
    zval *array, *value;
	zend_ulong num_idx;
    zend_string *str_idx;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) {
        return;
    }

    smart_str buf = {};
    smart_str_alloc(&buf, 2048, 0);

    zend_bool need_comma = 0;

    ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(array), num_idx, str_idx, value) {
        if (need_comma) {
            smart_str_appendl(&buf, ", ", 2);
        } else {
            need_comma = 1;
        }

        smart_str_appendc(&buf, '"');

        if (str_idx) {
            escape_string(&buf, str_idx);
        } else {
            smart_str_append_long(&buf, (long) num_idx);
        }

        smart_str_appendl(&buf, "\"=>", 3);

        if (Z_TYPE_P(value) == IS_NULL) {
            smart_str_appendl(&buf, "NULL", 4);
        } else {
            convert_to_string_ex(value);

            smart_str_appendc(&buf, '"');
            zend_string *str = zval_get_string(value);
            escape_string(&buf, str);
            zend_string_release(str);
            smart_str_appendc(&buf, '"');
        }
    } ZEND_HASH_FOREACH_END();

	smart_str_0(&buf); /* copy? */
	ZVAL_NEW_STR(return_value, buf.s);
}
示例#12
0
文件: arrr.c 项目: tony2001/arrr
/* {{{ proto void R::init([array argv])
 
 */
static PHP_METHOD(R, init)
{ 
	zval *argv = NULL;
	int argc = 3;
	HashPosition pos;
	char **argv_arr;
	zval **element;
	int i;
	char *r_home;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|a", &argv) == FAILURE) {
		return;
	}

	r_home = getenv("R_HOME");
	if (!r_home || r_home[0] == '\0') {
		setenv("R_HOME", PHP_R_DIR, 0);
	}

	R_SetErrorHook(php_r_error_handler);
	R_SetWarningHook(php_r_warning_handler);

	if (argv) {
		argc += zend_hash_num_elements(Z_ARRVAL_P(argv));
	}
	argv_arr = safe_emalloc(argc, sizeof(char *), 0);

	argv_arr[0] = "REmbeddedPHP";
	argv_arr[1] = "--gui=none";
	argv_arr[2] = "--silent";

	if (argv) {
		i = 3;
		for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(argv), &pos);
				zend_hash_get_current_data_ex(Z_ARRVAL_P(argv), (void **) &element, &pos) == SUCCESS;
				zend_hash_move_forward_ex(Z_ARRVAL_P(argv), &pos)
			) {
			convert_to_string_ex(element);
			argv_arr[i] = Z_STRVAL_PP(element); /* no copy here, libR does strdup() itself */
			i++;
		}
	}
	Rf_initEmbeddedR(argc, argv_arr);
	efree(argv_arr);
}
示例#13
0
文件: xml.c 项目: chosen1/php-src
/* {{{ xml_set_handler() */
static void xml_set_handler(zval *handler, zval *data)
{
	/* If we have already a handler, release it */
	if (handler) {
		zval_ptr_dtor(handler);
	}

	/* IS_ARRAY might indicate that we're using array($obj, 'method') syntax */
	if (Z_TYPE_P(data) != IS_ARRAY && Z_TYPE_P(data) != IS_OBJECT) {
		convert_to_string_ex(data);
		if (Z_STRLEN_P(data) == 0) {
			ZVAL_UNDEF(handler);
			return;
		}
	}

	ZVAL_COPY(handler, data);
}
示例#14
0
static void com_property_write(zval *object, zval *member, zval *value, void **cache_slot)
{
	php_com_dotnet_object *obj;
	VARIANT v;

	obj = CDNO_FETCH(object);

	if (V_VT(&obj->v) == VT_DISPATCH) {
		VariantInit(&v);

		convert_to_string_ex(member);
		if (SUCCESS == php_com_do_invoke(obj, Z_STRVAL_P(member), Z_STRLEN_P(member),
				DISPATCH_PROPERTYPUT|DISPATCH_PROPERTYPUTREF, &v, 1, value, 0)) {
			VariantClear(&v);
		}
	} else {
		php_com_throw_exception(E_INVALIDARG, "this variant has no properties");
	}
}
示例#15
0
static int com_property_exists(zval *object, zval *member, int check_empty, void **cache_slot)
{
	DISPID dispid;
	php_com_dotnet_object *obj;

	obj = CDNO_FETCH(object);

	if (V_VT(&obj->v) == VT_DISPATCH) {
		convert_to_string_ex(member);
		if (SUCCEEDED(php_com_get_id_of_name(obj, Z_STRVAL_P(member), Z_STRLEN_P(member), &dispid))) {
			/* TODO: distinguish between property and method! */
			return 1;
		}
	} else {
		/* TODO: check for safearray */
	}

	return 0;
}
示例#16
0
文件: readline.c 项目: AzerTyQsdF/osx
static char *_readline_command_generator(const char *text, int state)
{
	HashTable  *myht = Z_ARRVAL(_readline_array);
	zval **entry;
	
	if (!state) {
		zend_hash_internal_pointer_reset(myht);
	}
	
	while (zend_hash_get_current_data(myht, (void **)&entry) == SUCCESS) {
		zend_hash_move_forward(myht);

		convert_to_string_ex(entry);
		if (strncmp (Z_STRVAL_PP(entry), text, strlen(text)) == 0) {
			return (strdup(Z_STRVAL_PP(entry)));
		}
	}

	return NULL;
}
示例#17
0
static int php_get_address_from_array(const HashTable *ht, const char *key,
	php_socket *sock, php_sockaddr_storage *ss, socklen_t *ss_len)
{
	zval *val;

	if ((val = zend_hash_str_find(ht, key, strlen(key))) == NULL) {
		php_error_docref(NULL, E_WARNING, "no key \"%s\" passed in optval", key);
		return FAILURE;
	}
	if (Z_REFCOUNTED_P(val)) {
		Z_ADDREF_P(val);
	}
	convert_to_string_ex(val);
	if (!php_set_inet46_addr(ss, ss_len, Z_STRVAL_P(val), sock)) {
		zval_ptr_dtor(val);
		return FAILURE;
	}
	zval_ptr_dtor(val);
	return SUCCESS;
}
示例#18
0
/* {{{ php_tmpl_set */
int php_tmpl_set(t_template* tmpl, zval* path, zval** data) {
zval		**iteration, *cp_data, **ztag;
t_tmpl_tag	*tag;
char		*p;

	if(FAILURE == zend_hash_find(Z_ARRVAL_P(tmpl->tags), ZV(path), ZL(path)+1, (void*)&ztag)) {
		/* php_error(E_NOTICE, "Can't set value for tag/context \"%s\" which doesn't exist", ZV(path)); */
		return FAILURE;
	}
	tag = Z_TMPL_TAG(ztag);

	if(TMPL_TAG == tag->typ) {
		if((iteration = (zval**)php_tmpl_get_iteration(tmpl, path, TMPL_ITERATION_CURRENT)) == NULL) {
			return FAILURE;
		}
	} else {
		for(p = ZV(path)+ZL(path); p >= ZV(path) && *p != '/'; p--);
		*(p > ZV(path) ? p++ : ++p) = 0;
		ZL(path) = strlen(ZV(path));
		if((iteration = (zval**)php_tmpl_get_iteration(tmpl, path, TMPL_ITERATION_CURRENT)) == NULL) {
			return FAILURE;
		}
	}

	convert_to_string_ex(data); 
	MAKE_STD_ZVAL(cp_data); 
	ZVAL_STRINGL(cp_data, Z_STRVAL_PP(data), Z_STRLEN_PP(data), 1);

	if(SUCCESS == zend_hash_find(Z_ARRVAL_PP(iteration), ZV(tag->name), ZL(tag->name)+1, (void*)&ztag)) {
		if(IS_ARRAY == Z_TYPE_PP(ztag)) {
			/* MEMORY LEAK CAUSED BY THE NEXT LINE !!! */
			zend_hash_del(Z_ARRVAL_PP(iteration), ZV(tag->name), ZL(tag->name)+1);
		} else {
			tmpl->size -= (Z_STRLEN_PP(ztag) * tag->tag_num);
		}
	}
	zend_hash_update(Z_ARRVAL_PP(iteration), ZV(tag->name), ZL(tag->name)+1, (void*)&cp_data, sizeof(zval**), NULL);
	tmpl->size += (ZL(cp_data) * tag->tag_num);

	return SUCCESS;
}
示例#19
0
/* {{{ xslt_make_array()
   Make an XSLT array (char **) from a zval array (HashTable *) */
extern void xslt_make_array(zval **zarr, char ***carr)
{
    zval      **current;
    HashTable  *arr;
    int         idx = 0;

    arr = HASH_OF(*zarr);
    if (! arr) {
        php_error(E_WARNING, "Invalid argument or parameter array to %s",
                  get_active_function_name());
        return;
    }

    *carr = emalloc((zend_hash_num_elements(arr) * 2) + 1);

    for (zend_hash_internal_pointer_reset(arr);
            zend_hash_get_current_data(arr, (void **) &current) == SUCCESS;
            zend_hash_move_forward(arr)) {
        char  *string_key = NULL;
        ulong  num_key;
        int    type;

        SEPARATE_ZVAL(current);
        convert_to_string_ex(current);

        type = zend_hash_get_current_key(arr, &string_key, &num_key, 0);
        if (type == HASH_KEY_IS_LONG) {
            php_error(E_WARNING, "Invalid argument or parameter array to %s",
                      get_active_function_name());
            return;
        }

        (*carr)[idx++] = estrdup(string_key);
        (*carr)[idx++] = estrndup(Z_STRVAL_PP(current), Z_STRLEN_PP(current));
    }

    (*carr)[idx] = NULL;
}
示例#20
0
文件: arrr.c 项目: tony2001/arrr
static SEXP php_zval_to_r(zval **value) /* {{{ */
{
	SEXP result = NULL_USER_OBJECT;

	switch (Z_TYPE_PP(value)) {
		case IS_LONG:
			PROTECT(result = NEW_INTEGER(1));
			INTEGER_DATA(result)[0] = Z_LVAL_PP(value);
			UNPROTECT(1);
			break;
		case IS_DOUBLE:
			PROTECT(result = NEW_NUMERIC(1));
			NUMERIC_DATA(result)[0] = Z_DVAL_PP(value);
			UNPROTECT(1);
			break;
		case IS_STRING:
			PROTECT(result = NEW_CHARACTER(1));
			SET_STRING_ELT(result, 0, COPY_TO_USER_STRING(Z_STRVAL_PP(value)));
			UNPROTECT(1);
			break;
		case IS_BOOL:
			PROTECT(result = NEW_LOGICAL(1));
			LOGICAL_DATA(result)[0] = Z_BVAL_PP(value);
			UNPROTECT(1);
			break;
		case IS_ARRAY:
			result = php_hash_to_r(Z_ARRVAL_PP(value));
			break;
		default:
			convert_to_string_ex(value);
			PROTECT(result = NEW_CHARACTER(1));
			SET_STRING_ELT(result, 0, COPY_TO_USER_STRING(Z_STRVAL_PP(value)));
			UNPROTECT(1);
			break;
	}
	return result;
}
U_CFUNC PHP_FUNCTION(datefmt_format_object)
{
	zval				*object,
						*format = NULL;
	const char			*locale_str	= NULL;
	size_t					locale_len;
	bool				pattern		= false;
	UDate				date;
	TimeZone			*timeZone	= NULL;
	UErrorCode			status		= U_ZERO_ERROR;
	DateFormat			*df			= NULL;
	Calendar			*cal		= NULL;
	DateFormat::EStyle	dateStyle = DateFormat::kDefault,
						timeStyle = DateFormat::kDefault;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "o|zs!",
			&object, &format, &locale_str, &locale_len) == FAILURE) {
		RETURN_FALSE;
	}

	if (!locale_str) {
		locale_str = intl_locale_get_default();
	}

	if (format == NULL || Z_TYPE_P(format) == IS_NULL) {
		//nothing
	} else if (Z_TYPE_P(format) == IS_ARRAY) {
		HashTable		*ht	= Z_ARRVAL_P(format);
		HashPosition	pos	= {0};
		zval			*z;
		if (zend_hash_num_elements(ht) != 2) {
			intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR,
					"datefmt_format_object: bad format; if array, it must have "
					"two elements", 0);
			RETURN_FALSE;
		}

		zend_hash_internal_pointer_reset_ex(ht, &pos);
		z = zend_hash_get_current_data_ex(ht, &pos);
		if (!valid_format(z)) {
			intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR,
					"datefmt_format_object: bad format; the date format (first "
					"element of the array) is not valid", 0);
			RETURN_FALSE;
		}
		dateStyle = (DateFormat::EStyle)Z_LVAL_P(z);

		zend_hash_move_forward_ex(ht, &pos);
		z = zend_hash_get_current_data_ex(ht, &pos);
		if (!valid_format(z)) {
			intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR,
					"datefmt_format_object: bad format; the time format ("
					"second element of the array) is not valid", 0);
			RETURN_FALSE;
		}
		timeStyle = (DateFormat::EStyle)Z_LVAL_P(z);
	} else if (Z_TYPE_P(format) == IS_LONG) {
		if (!valid_format(format)) {
			intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR,
					"datefmt_format_object: the date/time format type is invalid",
					0);
			RETURN_FALSE;
		}
		dateStyle = timeStyle = (DateFormat::EStyle)Z_LVAL_P(format);
	} else {
		convert_to_string_ex(format);
		if (Z_STRLEN_P(format) == 0) {
			intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR,
					"datefmt_format_object: the format is empty", 0);
			RETURN_FALSE;
		}
		pattern = true;
	}

	//there's no support for relative time in ICU yet
	timeStyle = (DateFormat::EStyle)(timeStyle & ~DateFormat::kRelative);

	zend_class_entry *instance_ce = Z_OBJCE_P(object);
	if (instanceof_function(instance_ce, Calendar_ce_ptr)) {
		Calendar *obj_cal = calendar_fetch_native_calendar(object);
		if (obj_cal == NULL) {
			intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR,
					"datefmt_format_object: bad IntlCalendar instance: "
					"not initialized properly", 0);
			RETURN_FALSE;
		}
		timeZone = obj_cal->getTimeZone().clone();
		date = obj_cal->getTime(status);
		if (U_FAILURE(status)) {
			intl_error_set(NULL, status,
					"datefmt_format_object: error obtaining instant from "
					"IntlCalendar", 0);
			RETVAL_FALSE;
			goto cleanup;
		}
		cal = obj_cal->clone();
	} else if (instanceof_function(instance_ce, php_date_get_date_ce())) {
		if (intl_datetime_decompose(object, &date, &timeZone, NULL,
				"datefmt_format_object") == FAILURE) {
			RETURN_FALSE;
		}
		cal = new GregorianCalendar(Locale::createFromName(locale_str), status);
		if (U_FAILURE(status)) {
			intl_error_set(NULL, status,
					"datefmt_format_object: could not create GregorianCalendar",
					0);
			RETVAL_FALSE;
			goto cleanup;
		}
	} else {
		intl_error_set(NULL, status, "datefmt_format_object: the passed object "
				"must be an instance of either IntlCalendar or DateTime",
				0);
		RETURN_FALSE;
	}

	if (pattern) {
		 df = new SimpleDateFormat(
				UnicodeString(Z_STRVAL_P(format), Z_STRLEN_P(format),
						UnicodeString::kInvariant),
				Locale::createFromName(locale_str),
				status);

		if (U_FAILURE(status)) {
			intl_error_set(NULL, status,
					"datefmt_format_object: could not create SimpleDateFormat",
					0);
			RETVAL_FALSE;
			goto cleanup;
		}
	} else {
		df = DateFormat::createDateTimeInstance(dateStyle, timeStyle,
				Locale::createFromName(locale_str));

		if (df == NULL) { /* according to ICU sources, this should never happen */
			intl_error_set(NULL, status,
					"datefmt_format_object: could not create DateFormat",
					0);
			RETVAL_FALSE;
			goto cleanup;
		}
	}

	//must be in this order (or have the cal adopt the tz)
	df->adoptCalendar(cal);
	cal = NULL;
	df->adoptTimeZone(timeZone);
	timeZone = NULL;

	{
		char *ret_str;
		int ret_str_len;
		UnicodeString result = UnicodeString();
		df->format(date, result);

		if (intl_charFromString(result, &ret_str, &ret_str_len, &status) == FAILURE) {
			intl_error_set(NULL, status,
					"datefmt_format_object: error converting result to UTF-8",
					0);
			RETVAL_FALSE;
			goto cleanup;
		}
		RETVAL_STRINGL(ret_str, ret_str_len);
		//???
		efree(ret_str);
	}


cleanup:
	delete df;
	delete timeZone;
	delete cal;
}
示例#22
0
/* {{{ proto string PDO::pgsqlCopyFromArray(string $table_name , array $rows [, string $delimiter [, string $null_as ] [, string $fields])
   Returns true if the copy worked fine or false if error */
static PHP_METHOD(PDO, pgsqlCopyFromArray)
{
	pdo_dbh_t *dbh;
	pdo_pgsql_db_handle *H;

	zval *pg_rows;

	char *table_name, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL;
	size_t table_name_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len;
	char *query;

	PGresult *pgsql_result;
	ExecStatusType status;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s/a|sss",
					&table_name, &table_name_len, &pg_rows,
					&pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
		return;
	}

	if (!zend_hash_num_elements(Z_ARRVAL_P(pg_rows))) {
		php_error_docref(NULL, E_WARNING, "Cannot copy from an empty array");
		RETURN_FALSE;
	}

	dbh = Z_PDO_DBH_P(getThis());
	PDO_CONSTRUCT_CHECK;
	PDO_DBH_CLEAR_ERR();

	/* using pre-9.0 syntax as PDO_pgsql is 7.4+ compatible */
	if (pg_fields) {
		spprintf(&query, 0, "COPY %s (%s) FROM STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, pg_fields, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
	} else {
		spprintf(&query, 0, "COPY %s FROM STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
	}

	/* Obtain db Handle */
	H = (pdo_pgsql_db_handle *)dbh->driver_data;

	while ((pgsql_result = PQgetResult(H->server))) {
		PQclear(pgsql_result);
	}
	pgsql_result = PQexec(H->server, query);

	efree(query);
	query = NULL;

	if (pgsql_result) {
		status = PQresultStatus(pgsql_result);
	} else {
		status = (ExecStatusType) PQstatus(H->server);
	}

	if (status == PGRES_COPY_IN && pgsql_result) {
		int command_failed = 0;
		int buffer_len = 0;
		zval *tmp;

		PQclear(pgsql_result);
		ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pg_rows), tmp) {
			int query_len;
			convert_to_string_ex(tmp);

			if (buffer_len < Z_STRLEN_P(tmp)) {
				buffer_len = Z_STRLEN_P(tmp);
				query = erealloc(query, buffer_len + 2); /* room for \n\0 */
			}
			memcpy(query, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
			query_len = Z_STRLEN_P(tmp);
			if (query[query_len - 1] != '\n') {
				query[query_len++] = '\n';
			}
			query[query_len] = '\0';
			if (PQputCopyData(H->server, query, query_len) != 1) {
				efree(query);
				pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
				PDO_HANDLE_DBH_ERR();
				RETURN_FALSE;
			}
		} ZEND_HASH_FOREACH_END();
示例#23
0
/* {{{ mysqlnd_stmt_execute_store_params */
static void
mysqlnd_stmt_execute_store_params(MYSQLND_STMT * s, zend_uchar **buf, zend_uchar **p,
								  size_t *buf_len, unsigned int null_byte_offset TSRMLS_DC)
{
	MYSQLND_STMT_DATA * stmt = s->data;
	unsigned int i = 0;
	size_t left = (*buf_len - (*p - *buf));
	size_t data_size = 0;
	zval **copies = NULL;/* if there are different types */

/* 1. Store type information */
	if (stmt->send_types_to_server) {

		/* 2 bytes per type, and leave 20 bytes for future use */
		if (left < ((stmt->param_count * 2) + 20)) {
			unsigned int offset = *p - *buf;
			zend_uchar *tmp_buf;
			*buf_len = offset + stmt->param_count * 2 + 20;
			tmp_buf = mnd_emalloc(*buf_len);
			memcpy(tmp_buf, *buf, offset);
			*buf = tmp_buf;
			
			/* Update our pos pointer */
			*p = *buf + offset;
		}
		for (i = 0; i < stmt->param_count; i++) {
			/* our types are not unsigned */
#if SIZEOF_LONG==8  
			if (stmt->param_bind[i].type == MYSQL_TYPE_LONG) {
				stmt->param_bind[i].type = MYSQL_TYPE_LONGLONG;
			}
#endif
			int2store(*p, stmt->param_bind[i].type);
			*p+= 2;
		}
	}

/* 2. Store data */
	/* 2.1 Calculate how much space we need */
	for (i = 0; i < stmt->param_count; i++) {
		unsigned int j;
		zval *the_var = stmt->param_bind[i].zv;

		if (!the_var || (stmt->param_bind[i].type != MYSQL_TYPE_LONG_BLOB &&
						 Z_TYPE_P(the_var) == IS_NULL)) {
			continue;
		}
		for (j = i + 1; j < stmt->param_count; j++) {
			if (stmt->param_bind[j].zv == the_var) {
				/* Double binding of the same zval, make a copy */
				mysqlnd_stmt_copy_it(&copies, the_var, stmt->param_count, i TSRMLS_CC);
				break; 
			}
		}

		switch (stmt->param_bind[i].type) {
			case MYSQL_TYPE_DOUBLE:
				data_size += 8;
				if (Z_TYPE_P(the_var) != IS_DOUBLE) {
					if (!copies || !copies[i]) {
						mysqlnd_stmt_copy_it(&copies, the_var, stmt->param_count, i TSRMLS_CC);
					}
				}
				break;
#if SIZEOF_LONG==8  
			case MYSQL_TYPE_LONGLONG:
				data_size += 8;
#elif SIZEOF_LONG==4
			case MYSQL_TYPE_LONG:
				data_size += 4;
#else
#error "Should not happen"
#endif
				if (Z_TYPE_P(the_var) != IS_LONG) {
					if (!copies || !copies[i]) {
						mysqlnd_stmt_copy_it(&copies, the_var, stmt->param_count, i TSRMLS_CC);
					}
				}
				break;
			case MYSQL_TYPE_LONG_BLOB:
				if (!(stmt->param_bind[i].flags & MYSQLND_PARAM_BIND_BLOB_USED)) {
					/*
					  User hasn't sent anything, we will send empty string.
					  Empty string has length of 0, encoded in 1 byte. No real
					  data will follows after it.
					*/
					data_size++;
				}
				break;
			case MYSQL_TYPE_VAR_STRING:
				data_size += 8; /* max 8 bytes for size */
#if PHP_MAJOR_VERSION < 6
				if (Z_TYPE_P(the_var) != IS_STRING)
#elif PHP_MAJOR_VERSION >= 6
				if (Z_TYPE_P(the_var) != IS_STRING || Z_TYPE_P(the_var) == IS_UNICODE)
#endif
				{
					if (!copies || !copies[i]) {
						mysqlnd_stmt_copy_it(&copies, the_var, stmt->param_count, i TSRMLS_CC);
					}
					the_var = copies[i];
#if PHP_MAJOR_VERSION >= 6
					if (Z_TYPE_P(the_var) == IS_UNICODE) {
						zval_unicode_to_string_ex(the_var, UG(utf8_conv) TSRMLS_CC);
					}
#endif
				}
				convert_to_string_ex(&the_var);
				data_size += Z_STRLEN_P(the_var);
				break;
		}

	}

	/* 2.2 Enlarge the buffer, if needed */
	left = (*buf_len - (*p - *buf));
	if (left < data_size) {
		unsigned int offset = *p - *buf;
		zend_uchar *tmp_buf;
		*buf_len = offset + data_size + 10; /* Allocate + 10 for safety */
		tmp_buf = mnd_emalloc(*buf_len);
		memcpy(tmp_buf, *buf, offset);
		*buf = tmp_buf;
		/* Update our pos pointer */
		*p = *buf + offset;	
	}

	/* 2.3 Store the actual data */
	for (i = 0; i < stmt->param_count; i++) {
		zval *data = copies && copies[i]? copies[i]: stmt->param_bind[i].zv;
		/* Handle long data */
		if (stmt->param_bind[i].zv && Z_TYPE_P(data) == IS_NULL) {
			(*buf + null_byte_offset)[i/8] |= (zend_uchar) (1 << (i & 7));
		} else {
			switch (stmt->param_bind[i].type) {
				case MYSQL_TYPE_DOUBLE:
					convert_to_double_ex(&data);
					float8store(*p, Z_DVAL_P(data));
					(*p) += 8;
					break;
#if SIZEOF_LONG==8  
				case MYSQL_TYPE_LONGLONG:
					convert_to_long_ex(&data);
					int8store(*p, Z_LVAL_P(data));
					(*p) += 8;
					break;
#elif SIZEOF_LONG==4
				case MYSQL_TYPE_LONG:
					convert_to_long_ex(&data);
					int4store(*p, Z_LVAL_P(data));
					(*p) += 4;
					break;
#else
#error "Should not happen"
#endif
				case MYSQL_TYPE_LONG_BLOB:
					if (stmt->param_bind[i].flags & MYSQLND_PARAM_BIND_BLOB_USED) {
						stmt->param_bind[i].flags &= ~MYSQLND_PARAM_BIND_BLOB_USED;
					} else {
						/* send_long_data() not called, send empty string */
						*p = php_mysqlnd_net_store_length(*p, 0);
					}
					break;
				case MYSQL_TYPE_VAR_STRING:{
						unsigned int len = Z_STRLEN_P(data);
						/* to is after p. The latter hasn't been moved */
						*p = php_mysqlnd_net_store_length(*p, len);
						memcpy(*p, Z_STRVAL_P(data), len);
						(*p) += len;
					}
					break;
				default:
					/* Won't happen, but set to NULL */
					(*buf + null_byte_offset)[i/8] |= (zend_uchar) (1 << (i & 7));
					break;
			}
		}
	}
	if (copies) {
		for (i = 0; i < stmt->param_count; i++) {
			if (copies[i]) {
				zval_ptr_dtor(&copies[i]);
			}
		}
		mnd_efree(copies);	
	}
}
示例#24
0
/* php_formatted_print() {{{
 * New sprintf implementation for PHP.
 *
 * Modifiers:
 *
 *  " "   pad integers with spaces
 *  "-"   left adjusted field
 *   n    field size
 *  "."n  precision (floats only)
 *  "+"   Always place a sign (+ or -) in front of a number
 *
 * 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, int format_offset TSRMLS_DC)
{
	zval ***args, **z_format;
	int argc, size = 240, inpos = 0, outpos = 0, temppos;
	int alignment, currarg, adjusting, argnum, width, precision;
	char *format, *result, padding;
	int always_sign;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &argc) == FAILURE) {
		return NULL;
	}

	/* verify the number of args */
	if ((use_array && argc != (2 + format_offset)) 
			|| (!use_array && argc < (1 + format_offset))) {
		efree(args);
		WRONG_PARAM_COUNT_WITH_RETVAL(NULL);
	}
	
	if (use_array) {
		int i = 1;
		zval ***newargs;
		zval **array;

		z_format = args[format_offset];
		array = args[1 + format_offset];
		
		SEPARATE_ZVAL(array);
		convert_to_array_ex(array);
		
		argc = 1 + zend_hash_num_elements(Z_ARRVAL_PP(array));
		newargs = (zval ***)safe_emalloc(argc, sizeof(zval *), 0);
		newargs[0] = z_format;
		
		for (zend_hash_internal_pointer_reset(Z_ARRVAL_PP(array));
			 zend_hash_get_current_data(Z_ARRVAL_PP(array), (void **)&newargs[i++]) == SUCCESS;
			 zend_hash_move_forward(Z_ARRVAL_PP(array)));

		efree(args);
		args = newargs;
		format_offset = 0;
	}
	
	convert_to_string_ex(args[format_offset]);
	format = Z_STRVAL_PP(args[format_offset]);
	result = emalloc(size);

	currarg = 1;

	while (inpos<Z_STRLEN_PP(args[format_offset])) {
		int expprec = 0, multiuse = 0;
		zval *tmp;

		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 {
			/* starting a new format specifier, reset variables */
			alignment = ALIGN_RIGHT;
			adjusting = 0;
			padding = ' ';
			always_sign = 0;
			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);

					if (argnum <= 0) {
						efree(result);
						efree(args);
						php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument number must be greater than zero");
						return NULL;
					}

					multiuse = 1;
					inpos++;  /* skip the '$' */
				} else {
					argnum = currarg++;
				}

				argnum += format_offset;

				/* 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] == '+') {
						always_sign = 1;
					} 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"));
					if ((width = php_sprintf_getnumber(format, &inpos)) < 0) {
						efree(result);
						efree(args);
						php_error_docref(NULL TSRMLS_CC, E_WARNING, "Width must be greater than zero and less than %d", INT_MAX);
						return NULL;
					}
					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])) {
						if ((precision = php_sprintf_getnumber(format, &inpos)) < 0) {
							efree(result);
							efree(args);
							php_error_docref(NULL TSRMLS_CC, E_WARNING, "Precision must be greater than zero and less than %d", INT_MAX);
							return NULL;
						}
						adjusting |= ADJ_PRECISION;
						expprec = 1;
					} else {
						precision = 0;
					}
				} else {
					precision = 0;
				}
				PRINTF_DEBUG(("sprintf: precision=%d\n", precision));
			} else {
				width = precision = 0;
				argnum = currarg++ + format_offset;
			}

			if (argnum >= argc) {
				efree(result);
				efree(args);
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "Too few arguments");
				return NULL;
			}

			if (format[inpos] == 'l') {
				inpos++;
			}
			PRINTF_DEBUG(("sprintf: format character='%c'\n", format[inpos]));
			/* now we expect to find a type specifier */
			if (multiuse) {
				MAKE_STD_ZVAL(tmp);
				*tmp = **(args[argnum]);
				INIT_PZVAL(tmp);
				zval_copy_ctor(tmp);
			} else {
				SEPARATE_ZVAL(args[argnum]);
				tmp = *(args[argnum]);
			}

			switch (format[inpos]) {
				case 's': {
					zval *var, var_copy;
					int use_copy;

					zend_make_printable_zval(tmp, &var_copy, &use_copy);
					if (use_copy) {
						var = &var_copy;
					} else {
						var = tmp;
					}
					php_sprintf_appendstring(&result, &outpos, &size,
											 Z_STRVAL_P(var),
											 width, precision, padding,
											 alignment,
											 Z_STRLEN_P(var),
											 0, expprec, 0);
					if (use_copy) {
						zval_dtor(&var_copy);
					}
					break;
				}

				case 'd':
					convert_to_long(tmp);
					php_sprintf_appendint(&result, &outpos, &size,
										  Z_LVAL_P(tmp),
										  width, padding, alignment,
										  always_sign);
					break;

				case 'u':
					convert_to_long(tmp);
					php_sprintf_appenduint(&result, &outpos, &size,
										  Z_LVAL_P(tmp),
										  width, padding, alignment);
					break;

				case 'g':
				case 'G':
				case 'e':
				case 'E':
				case 'f':
				case 'F':
					convert_to_double(tmp);
					php_sprintf_appenddouble(&result, &outpos, &size,
											 Z_DVAL_P(tmp),
											 width, padding, alignment,
											 precision, adjusting,
											 format[inpos], always_sign
											 TSRMLS_CC);
					break;
					
				case 'c':
					convert_to_long(tmp);
					php_sprintf_appendchar(&result, &outpos, &size,
										(char) Z_LVAL_P(tmp) TSRMLS_CC);
					break;

				case 'o':
					convert_to_long(tmp);
					php_sprintf_append2n(&result, &outpos, &size,
										 Z_LVAL_P(tmp),
										 width, padding, alignment, 3,
										 hexchars, expprec);
					break;

				case 'x':
					convert_to_long(tmp);
					php_sprintf_append2n(&result, &outpos, &size,
										 Z_LVAL_P(tmp),
										 width, padding, alignment, 4,
										 hexchars, expprec);
					break;

				case 'X':
					convert_to_long(tmp);
					php_sprintf_append2n(&result, &outpos, &size,
										 Z_LVAL_P(tmp),
										 width, padding, alignment, 4,
										 HEXCHARS, expprec);
					break;

				case 'b':
					convert_to_long(tmp);
					php_sprintf_append2n(&result, &outpos, &size,
										 Z_LVAL_P(tmp),
										 width, padding, alignment, 1,
										 hexchars, expprec);
					break;

				case '%':
					php_sprintf_appendchar(&result, &outpos, &size, '%' TSRMLS_CC);

					break;
				default:
					break;
			}
			if (multiuse) {
				zval_ptr_dtor(&tmp);
			}
			inpos++;
		}
	}
	
	efree(args);
	
	/* possibly, we have to make sure we have room for the terminating null? */
	result[outpos]=0;
	*len = outpos;	
	return result;
}
示例#25
0
文件: cookie.c 项目: Myleft/cphalcon7
/**
 * Sends the cookie to the HTTP client
 * Stores the cookie definition in session
 *
 * @return Phalcon\Http\Cookie
 */
PHP_METHOD(Phalcon_Http_Cookie, send){

	zval *name, *value, *expire, *domain, *path, *secure;
	zval *http_only, *dependency_injector, *definition;
	zval *service = NULL, *session = NULL, *key, *encryption, *crypt = NULL;
	zval *encrypt_value = NULL, *has_session = NULL;

	PHALCON_MM_GROW();

	name = phalcon_read_property(getThis(), SL("_name"), PH_NOISY);
	value = phalcon_read_property(getThis(), SL("_value"), PH_NOISY);
	expire = phalcon_read_property(getThis(), SL("_expire"), PH_NOISY);
	domain = phalcon_read_property(getThis(), SL("_domain"), PH_NOISY);
	path = phalcon_read_property(getThis(), SL("_path"), PH_NOISY);
	secure = phalcon_read_property(getThis(), SL("_secure"), PH_NOISY);
	http_only = phalcon_read_property(getThis(), SL("_httpOnly"), PH_NOISY);
	dependency_injector = phalcon_read_property(getThis(), SL("_dependencyInjector"), PH_NOISY);
	if (Z_TYPE_P(dependency_injector) == IS_OBJECT) {
		PHALCON_INIT_VAR(service);
		ZVAL_STR(service, IS(session));

		PHALCON_CALL_METHOD(&has_session, dependency_injector, "has", service);
		if (zend_is_true(has_session)) {
			PHALCON_INIT_VAR(definition);
			array_init(definition);
			if (!PHALCON_IS_LONG(expire, 0)) {
				phalcon_array_update_str(definition, SL("expire"), expire, PH_COPY);
			}

			if (PHALCON_IS_NOT_EMPTY(path)) {
				phalcon_array_update_str(definition, SL("path"), path, PH_COPY);
			}

			if (PHALCON_IS_NOT_EMPTY(domain)) {
				phalcon_array_update_string(definition, IS(domain), domain, PH_COPY);
			}

			if (PHALCON_IS_NOT_EMPTY(secure)) {
				phalcon_array_update_str(definition, SL("secure"), secure, PH_COPY);
			}

			if (PHALCON_IS_NOT_EMPTY(http_only)) {
				phalcon_array_update_str(definition, SL("httpOnly"), http_only, PH_COPY);
			}

			/**
			 * The definition is stored in session
			 */
			if (phalcon_fast_count_ev(definition)) {
				PHALCON_CALL_METHOD(&session, dependency_injector, "getshared", service);

				if (Z_TYPE_P(session) != IS_NULL) {
					PHALCON_VERIFY_INTERFACE(session, phalcon_session_adapterinterface_ce);

					PHALCON_INIT_VAR(key);
					PHALCON_CONCAT_SV(key, "_PHCOOKIE_", name);
					PHALCON_CALL_METHOD(NULL, session, "set", key, definition);
				}
			}
		}
	}

	encryption = phalcon_read_property(getThis(), SL("_useEncryption"), PH_NOISY);
	if (zend_is_true(encryption) && PHALCON_IS_NOT_EMPTY(value)) {
		if (Z_TYPE_P(dependency_injector) != IS_OBJECT) {
			PHALCON_THROW_EXCEPTION_STR(phalcon_http_cookie_exception_ce, "A dependency injection object is required to access the 'filter' service");
			return;
		}

		PHALCON_INIT_NVAR(service);
		ZVAL_STRING(service, "crypt");

		PHALCON_CALL_METHOD(&crypt, dependency_injector, "getshared", service);
		PHALCON_VERIFY_INTERFACE(crypt, phalcon_cryptinterface_ce);

		/**
		 * Encrypt the value also coding it with base64
		 */
		PHALCON_CALL_METHOD(&encrypt_value, crypt, "encryptbase64", value);
	} else {
		PHALCON_CPY_WRT(encrypt_value, value);
	}

	/** 
	 * Sets the cookie using the standard 'setcookie' function
	 */
	convert_to_string_ex(name);
	convert_to_string_ex(encrypt_value);
	convert_to_long_ex(expire);
	convert_to_string_ex(path);
	convert_to_string_ex(domain);
	convert_to_long_ex(secure);
	convert_to_long_ex(http_only);

	php_setcookie(Z_STR_P(name), Z_STR_P(encrypt_value), Z_LVAL_P(expire), Z_STR_P(path), Z_STR_P(domain), Z_LVAL_P(secure), 1, Z_LVAL_P(http_only));

	RETURN_THIS();
}
示例#26
0
/*
* Generic SNMP object fetcher
*
* st=1   snmpget() - query an agent and return a single value.
* st=2   snmpwalk() - walk the mib and return a single dimensional array 
*          containing the values.
* st=3 snmprealwalk() and snmpwalkoid() - walk the mib and return an 
*          array of oid,value pairs.
* st=5-8 ** Reserved **
* st=11  snmpset() - query an agent and set a single value
*
*/
void php_snmp(INTERNAL_FUNCTION_PARAMETERS, int st) {
	zval **a1, **a2, **a3, **a4, **a5, **a6, **a7;
	struct snmp_session session, *ss;
	struct snmp_pdu *pdu=NULL, *response;
	struct variable_list *vars;
    char *objid;
    oid name[MAX_NAME_LEN];
    int name_length;
    int status, count,rootlen=0,gotroot=0;
	oid root[MAX_NAME_LEN];
	char buf[2048];
	char buf2[2048];
	int keepwalking=1;
	long timeout=SNMP_DEFAULT_TIMEOUT;
	long retries=SNMP_DEFAULT_RETRIES;
	int myargc = ZEND_NUM_ARGS();
    char type = (char) 0;
    char *value = (char *) 0;
	
	if (myargc < 3 || myargc > 7 ||
		zend_get_parameters_ex(myargc, &a1, &a2, &a3, &a4, &a5, &a6, &a7) == FAILURE) {
		WRONG_PARAM_COUNT;
	}

	convert_to_string_ex(a1);
	convert_to_string_ex(a2);
	convert_to_string_ex(a3);
	
	if (st == 11) {
		if (myargc < 5) {
			WRONG_PARAM_COUNT;
		}

		convert_to_string_ex(a4);
		convert_to_string_ex(a5);
	
		if(myargc > 5) {
			convert_to_long_ex(a6);
			timeout = (*a6)->value.lval;
		}

		if(myargc > 6) {
			convert_to_long_ex(a7);
			retries = (*a7)->value.lval;
		}

		type = (*a4)->value.str.val[0];
		value = (*a5)->value.str.val;
	} else {
		if(myargc > 3) {
			convert_to_long_ex(a4);
			timeout = (*a4)->value.lval;
		}

		if(myargc > 4) {
			convert_to_long_ex(a5);
			retries = (*a5)->value.lval;
		}
	}

	objid = (*a3)->value.str.val;
	
	if (st >= 2) { /* walk */
		rootlen = MAX_NAME_LEN;
		if ( strlen(objid) ) { /* on a walk, an empty string means top of tree - no error */
			if ( read_objid(objid, root, &rootlen) ) {
				gotroot = 1;
			} else {
				php_error(E_WARNING,"Invalid object identifier: %s\n", objid);
			}
		}
		if (gotroot == 0) {
			memmove((char *)root, (char *)objid_mib, sizeof(objid_mib));
			rootlen = sizeof(objid_mib) / sizeof(oid);
			gotroot = 1;
		}
	}
	
	memset(&session, 0, sizeof(struct snmp_session));

	session.peername = (*a1)->value.str.val;
	session.version = SNMP_VERSION_1;
	/*
	* FIXME: potential memory leak
	* This is a workaround for an "artifact" (Mike Slifcak)
	* in (at least) ucd-snmp 3.6.1 which frees
	* memory it did not allocate
	*/
#ifdef UCD_SNMP_HACK
	session.community = (u_char *)strdup((*a2)->value.str.val); /* memory freed by SNMP library, strdup NOT estrdup */
#else
	session.community = (u_char *)(*a2)->value.str.val;
#endif
	session.community_len = (*a2)->value.str.len;
	session.retries = retries;
	session.timeout = timeout;
	
	session.authenticator = NULL;
	snmp_synch_setup(&session);

	if ((ss = snmp_open(&session)) == NULL) {
		php_error(E_WARNING,"Could not open snmp\n");
		RETURN_FALSE;
	}

	if (st >= 2) {
		memmove((char *)name, (char *)root, rootlen * sizeof(oid));
		name_length = rootlen;
		if (array_init(return_value) == FAILURE) {
			php_error(E_WARNING, "Cannot prepare result array");
			RETURN_FALSE;
		}
	}

	while(keepwalking) {
		keepwalking=0;
		if (st == 1) {
			pdu = snmp_pdu_create(SNMP_MSG_GET);
			name_length = MAX_NAME_LEN;
			if ( !read_objid(objid, name, &name_length) ) {
				php_error(E_WARNING,"Invalid object identifier: %s\n", objid);
				RETURN_FALSE;
			}
			snmp_add_null_var(pdu, name, name_length);
		} else if (st == 11) {
			pdu = snmp_pdu_create(SNMP_MSG_SET);
			if (snmp_add_var(pdu, name, name_length, type, value)) {
				php_error(E_WARNING,"Could not add variable: %s\n", name);
				RETURN_FALSE;
			}
		} else if (st >= 2) {
			pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);
			snmp_add_null_var(pdu, name, name_length);
		}
		
retry:
		status = snmp_synch_response(ss, pdu, &response);
		if (status == STAT_SUCCESS) {
			if (response->errstat == SNMP_ERR_NOERROR) {
				for (vars = response->variables; vars; vars = vars->next_variable) {
					if (st >= 2 && st != 11 && 
						(vars->name_length < rootlen || memcmp(root, vars->name, rootlen * sizeof(oid)))) {
						continue;       /* not part of this subtree */
					}

					if (st != 11) {
						sprint_value(buf,vars->name, vars->name_length, vars);
					}
#if 0
					Debug("snmp response is: %s\n",buf);
#endif
					if (st == 1) {
						RETVAL_STRING(buf,1);
					} else if (st == 2) {
						add_next_index_string(return_value,buf,1); /* Add to returned array */
					} else if (st == 3)  {
						sprint_objid(buf2, vars->name, vars->name_length);
						add_assoc_string(return_value,buf2,buf,1);
					}
					if (st >= 2 && st != 11) {
						if (vars->type != SNMP_ENDOFMIBVIEW && 
							vars->type != SNMP_NOSUCHOBJECT && vars->type != SNMP_NOSUCHINSTANCE) {
							memmove((char *)name, (char *)vars->name,vars->name_length * sizeof(oid));
							name_length = vars->name_length;
							keepwalking = 1;
						}
					}
				}	
			} else {
				if (st != 2 || response->errstat != SNMP_ERR_NOSUCHNAME) {
					php_error(E_WARNING,"Error in packet.\nReason: %s\n", snmp_errstring(response->errstat));
					if (response->errstat == SNMP_ERR_NOSUCHNAME) {
						for (count=1, vars = response->variables; vars && count != response->errindex;
						vars = vars->next_variable, count++);
						if (vars) {
							sprint_objid(buf,vars->name, vars->name_length);
						}
						php_error(E_WARNING,"This name does not exist: %s\n",buf);
					}
					if (st == 1) {
						if ((pdu = snmp_fix_pdu(response, SNMP_MSG_GET)) != NULL) {
							goto retry;
						}
					} else if (st == 11) {
						if ((pdu = snmp_fix_pdu(response, SNMP_MSG_SET)) != NULL) {
							goto retry;
						}
					} else if (st >= 2) {
						if ((pdu = snmp_fix_pdu(response, SNMP_MSG_GETNEXT)) != NULL) {
							goto retry;
						}
					}
					RETURN_FALSE;
				}
			}
		} else if (status == STAT_TIMEOUT) {
			php_error(E_WARNING,"No Response from %s\n", (*a1)->value.str.val);
			RETURN_FALSE;
		} else {    /* status == STAT_ERROR */
			php_error(E_WARNING,"An error occurred, Quitting...\n");
			RETURN_FALSE;
		}
		if (response) {
			snmp_free_pdu(response);
		}
	} /* keepwalking */
	snmp_close(ss);
}
示例#27
0
/*===========================================================================================================

    NAME
	thrak_array_to_char - Converts an array to an array of C-strings.

    PROTOTYPE
	char *  thrak_array_to_char ( zval *  array, char ***  argv, int *  argc, int **  argl ) ;

    DESCRIPTION
	Converts an array (of strings) to an array of string

    PARAMETERS
	array (zval *) -
		A pointer to a zval containing either an array or a scalar value.
		If a scalar value is supplied, it will be first converted to string and an array of 1 element
		will be created.

	argv (char **) -
		Address of a char * array that will receive the array of pointers to individual zero-terminated
		strings.
		Note that this array contains (argc + 1) elements ; the last one being a NULL pointer to signal
		the end of the array.

	argc (int *) -
		Address of an integer that will receive the number of elements in the input array.

	argl (int **) -
		If not NULL, will receive the respective lengths of each string in argv. Last item (which
		corresponds to the last NULL item in argv) will be set to -1.

    RETURNS
	A pointer to the memory block allocated to store all the individual array strings. This memory must
	then be freed using the thrak_free_array_to_char() function.

 *===========================================================================================================*/
THRAK_API char * 	thrak_array_to_char ( zval *  array, char ***  argv, int *  argc, int **  argl )
{
    HashTable *		array_hash ;
    HashPosition 		array_position ;
    zval ** 		item ;
    char *			buffer ;
    int 			total_size 	=  1 ;
    char **			arg_values ;
    int  			arg_count ;
    int *			arg_lengths ;
    char * 			p ;
    int 			current_argc,
                    length ;
    int 			argv_length,
                    argl_length ;


    /* Ban forbidden zval types, retain only ARRAY and STRING types, and convert all other scalar types to string */
    switch  ( Z_TYPE_P ( array ) )
    {
    case 	IS_OBJECT :
    case 	IS_RESOURCE :
    case	IS_NULL :
        return ( NULL ) ;

    case 	IS_ARRAY :
    case 	IS_STRING :
        break ;

    default :
        convert_to_string_ex ( & array ) ;
    }

    /* Compute the size needed to hold all the strings supplied in the input array */
    if  ( Z_TYPE_P ( array )  ==  IS_ARRAY )
    {
        /* Get hash from array */
        array_hash 	=  Z_ARRVAL_P ( array ) ;

        /* Get item count and allocate this count + one element (the last element being a NULL pointer) */
        arg_count 	=  zend_hash_num_elements ( array_hash ) ;

        /* A first pass through the input array to compute the total size needed */
        for  ( zend_hash_internal_pointer_reset_ex ( array_hash, & array_position ) ;
                zend_hash_get_current_data_ex ( array_hash, ( void ** ) & item, & array_position )  ==  SUCCESS ;
                zend_hash_move_forward_ex ( array_hash, & array_position ) )
        {
            /* Ignore non-scalar types and convert non-strings to strings */
            switch ( Z_TYPE_PP ( item ) )
            {
            case 	IS_OBJECT :
            case 	IS_RESOURCE :
            case 	IS_ARRAY :
            case 	IS_NULL :
                continue ;

            case 	IS_STRING :
                break ;

            default :
                convert_to_string_ex ( item ) ;
            }

            /* Update total needed size */
            total_size 	+=  Z_STRLEN_PP ( item ) + 1 ;
        }

        /***
        	The buffer that will be allocated has the following layout :
        	. offset 0 					: argv
        	. offset sizeof ( char * ) * ( argc + 1 ) 	: argl (optional)
        	. offset argl + ( sizeof ( int ) * ( argc + 1 )	: zero-terminated strings
        	. last byte 					: 0, to indicate the end of zero-terminated strings

         ***/
        argv_length 	=  ( ( arg_count + 1 ) * sizeof ( char * ) ) ;
        argl_length 	=  ( argl  ==  NULL ) ?  0 : ( ( arg_count + 1 ) * sizeof ( int ) ) ;

        buffer 	=  emalloc ( argv_length + argl_length + total_size ) ;

        if  ( buffer  ==  NULL )
            return ( NULL ) ;

        /* Set the pointers to the correct offset into buffer */
        arg_values 	=  ( char ** ) buffer ;

        if  ( argl  !=  NULL )
        {
            arg_lengths 	=  ( int * ) ( buffer + argv_length ) ;
            p 		=  buffer + argv_length + argl_length ;
        }
        else
            p 		=  buffer + argv_length ;

        /* Second pass : copy input array values to buffer and update argv accordingly */
        current_argc 	=  0 ;

        for  ( zend_hash_internal_pointer_reset_ex ( array_hash, & array_position ) ;
                zend_hash_get_current_data_ex ( array_hash, ( void ** ) & item, & array_position )  ==  SUCCESS ;
                zend_hash_move_forward_ex ( array_hash, & array_position ) )
        {
            /* Ignore non-scalar types and convert non-strings to strings */
            switch ( Z_TYPE_PP ( item ) )
            {
            case 	IS_OBJECT :
            case 	IS_RESOURCE :
            case 	IS_ARRAY :
            case 	IS_NULL :
                continue ;

            case 	IS_STRING :
                break ;

            default :
                convert_to_string_ex ( item ) ;
            }

            /* Add current item and make it nul-terminated */
            length 		=  Z_STRLEN_PP ( item ) ;
            memcpy ( p, Z_STRVAL_PP ( item ), length ) ;

            * ( p + length ) 	=  0 ;

            /* Add it to the argv array */
            arg_values [ current_argc ] 		=  p ;

            if  ( argl  !=  NULL )
                arg_lengths [ current_argc ]	=  length ;

            p 	+= length + 1 ;
            current_argc ++ ;
        }
    }
    /* Input value is not an array ; if scalar type, we will convert it to a string and put it in a 1-element argv array */
    else
    {
        /* Ignore non-scalar types and convert non-strings to strings */
        switch ( Z_TYPE_P ( array ) )
        {
        case 	IS_OBJECT :
        case 	IS_RESOURCE :
        case 	IS_NULL :
            return ( NULL ) ;

        case 	IS_STRING :
            break ;

        default :
            convert_to_string_ex ( & array ) ;
        }

        length 		 =  Z_STRLEN_P ( array ) ;
        total_size 	+=  length + 1 ;

        arg_count 	=  1 ;
        argv_length 	=  ( ( arg_count + 1 ) * sizeof ( char * ) ) ;
        argl_length 	=  ( argl  ==  NULL ) ?  0 : ( ( arg_count + 1 ) * sizeof ( int ) ) ;

        buffer 	=  emalloc ( argv_length + argl_length + total_size ) ;

        if  ( buffer  ==  NULL )
            return ( NULL ) ;

        /* Set the pointers to the correct offset into buffer */
        arg_values 	=  ( char ** ) buffer ;

        if  ( argl  !=  NULL )
        {
            arg_lengths 	=  ( int * ) ( buffer + argv_length ) ;
            p 		=  buffer + argv_length + argl_length ;
        }
        else
            p 		=  buffer + argv_length ;

        current_argc 	=  0 ;

        /* Copy the string value in it */
        strncpy ( p, Z_STRVAL_P ( array ), length ) ;

        /* Terminate by a double nul character (one for the string, one for signalling the end of the string list) */
        p [ length ] = p [ length + 1 ] = 0 ;

        /* Add it to the argv array */
        arg_values [0] 	=  p ;

        if  ( argl  !=  NULL )
            arg_lengths [0] 	=  length ;

        current_argc ++ ;
    }

    /* Make sure the last array item is a NULL pointer */
    arg_values [ current_argc ] 	=  NULL ;

    if  ( argl  !=  NULL )
    {
        arg_lengths [ current_argc ] 	=  -1 ;
        * argl 				=  arg_lengths ;
    }

    /* Update caller supplied values */
    * argv 	=  arg_values ;
    * argc 	=  arg_count ;

    /* All done, return */
    return ( buffer ) ;
}
示例#28
0
static void xsl_ext_function_php(xmlXPathParserContextPtr ctxt, int nargs, int type) /* {{{ */
{
	xsltTransformContextPtr tctxt;
	zval *args;
	zval retval;
	int result, i;
	int error = 0;
	zend_fcall_info fci;
	zval handler;
	xmlXPathObjectPtr obj;
	char *str;
	xsl_object *intern;
	zend_string *callable = NULL;


	if (! zend_is_executing()) {
		xsltGenericError(xsltGenericErrorContext,
		"xsltExtFunctionTest: Function called from outside of PHP\n");
		error = 1;
	} else {
		tctxt = xsltXPathGetTransformContext(ctxt);
		if (tctxt == NULL) {
			xsltGenericError(xsltGenericErrorContext,
			"xsltExtFunctionTest: failed to get the transformation context\n");
			error = 1;
		} else {
			intern = (xsl_object*)tctxt->_private;
			if (intern == NULL) {
				xsltGenericError(xsltGenericErrorContext,
				"xsltExtFunctionTest: failed to get the internal object\n");
				error = 1;
			}
			else if (intern->registerPhpFunctions == 0) {
				xsltGenericError(xsltGenericErrorContext,
				"xsltExtFunctionTest: PHP Object did not register PHP functions\n");
				error = 1;
			}
		}
	}

	if (error == 1) {
		for (i = nargs - 1; i >= 0; i--) {
			obj = valuePop(ctxt);
			xmlXPathFreeObject(obj);
		}
		return;
	}

	fci.param_count = nargs - 1;
	if (fci.param_count > 0) {
		args = safe_emalloc(fci.param_count, sizeof(zval), 0);
	}
	/* Reverse order to pop values off ctxt stack */
	for (i = nargs - 2; i >= 0; i--) {
		obj = valuePop(ctxt);
		switch (obj->type) {
			case XPATH_STRING:
				ZVAL_STRING(&args[i], (char *)obj->stringval);
				break;
			case XPATH_BOOLEAN:
				ZVAL_BOOL(&args[i],  obj->boolval);
				break;
			case XPATH_NUMBER:
				ZVAL_DOUBLE(&args[i], obj->floatval);
				break;
			case XPATH_NODESET:
				if (type == 1) {
					str = (char*)xmlXPathCastToString(obj);
					ZVAL_STRING(&args[i], str);
					xmlFree(str);
				} else if (type == 2) {
					int j;
					dom_object *domintern = (dom_object *)intern->doc;
					array_init(&args[i]);
					if (obj->nodesetval && obj->nodesetval->nodeNr > 0) {
						for (j = 0; j < obj->nodesetval->nodeNr; j++) {
							xmlNodePtr node = obj->nodesetval->nodeTab[j];
							zval child;
							/* not sure, if we need this... it's copied from xpath.c */
							if (node->type == XML_NAMESPACE_DECL) {
								xmlNsPtr curns;
								xmlNodePtr nsparent;

								nsparent = node->_private;
								curns = xmlNewNs(NULL, node->name, NULL);
								if (node->children) {
									curns->prefix = xmlStrdup((char *)node->children);
								}
								if (node->children) {
									node = xmlNewDocNode(node->doc, NULL, (char *) node->children, node->name);
								} else {
									node = xmlNewDocNode(node->doc, NULL, (const xmlChar *) "xmlns", node->name);
								}
								node->type = XML_NAMESPACE_DECL;
								node->parent = nsparent;
								node->ns = curns;
							} else {
								node = xmlDocCopyNodeList(domintern->document->ptr, node);
							}

							php_dom_create_object(node, &child, domintern);
							add_next_index_zval(&args[i], &child);
						}
					}
				}
				break;
			default:
				str = (char *) xmlXPathCastToString(obj);
				ZVAL_STRING(&args[i], str);
				xmlFree(str);
		}
		xmlXPathFreeObject(obj);
	}

	fci.size = sizeof(fci);
	fci.function_table = EG(function_table);
	if (fci.param_count > 0) {
		fci.params = args;
	} else {
		fci.params = NULL;
	}


	obj = valuePop(ctxt);
	if (obj->stringval == NULL) {
		php_error_docref(NULL, E_WARNING, "Handler name must be a string");
		xmlXPathFreeObject(obj);
		valuePush(ctxt, xmlXPathNewString((const xmlChar *) ""));
		if (fci.param_count > 0) {
			for (i = 0; i < nargs - 1; i++) {
				zval_ptr_dtor(&args[i]);
			}
			efree(args);
		}
		return;
	}
	ZVAL_STRING(&handler, (char *) obj->stringval);
	xmlXPathFreeObject(obj);

	ZVAL_COPY_VALUE(&fci.function_name, &handler);
	fci.symbol_table = NULL;
	fci.object = NULL;
	fci.retval = &retval;
	fci.no_separation = 0;
	/*fci.function_handler_cache = &function_ptr;*/
	if (!zend_make_callable(&handler, &callable)) {
		php_error_docref(NULL, E_WARNING, "Unable to call handler %s()", ZSTR_VAL(callable));
		valuePush(ctxt, xmlXPathNewString((const xmlChar *) ""));
	} else if ( intern->registerPhpFunctions == 2 && zend_hash_exists(intern->registered_phpfunctions, callable) == 0) {
		php_error_docref(NULL, E_WARNING, "Not allowed to call handler '%s()'", ZSTR_VAL(callable));
		/* Push an empty string, so that we at least have an xslt result... */
		valuePush(ctxt, xmlXPathNewString((const xmlChar *) ""));
	} else {
		result = zend_call_function(&fci, NULL);
		if (result == FAILURE) {
			if (Z_TYPE(handler) == IS_STRING) {
				php_error_docref(NULL, E_WARNING, "Unable to call handler %s()", Z_STRVAL(handler));
				valuePush(ctxt, xmlXPathNewString((const xmlChar *) ""));
			}
		/* retval is == NULL, when an exception occurred, don't report anything, because PHP itself will handle that */
		} else if (Z_ISUNDEF(retval)) {
		} else {
			if (Z_TYPE(retval) == IS_OBJECT && instanceof_function(Z_OBJCE(retval), dom_node_class_entry)) {
				xmlNode *nodep;
				dom_object *obj;
				if (intern->node_list == NULL) {
					ALLOC_HASHTABLE(intern->node_list);
					zend_hash_init(intern->node_list, 0, NULL, ZVAL_PTR_DTOR, 0);
				}
				Z_ADDREF(retval);
				zend_hash_next_index_insert(intern->node_list, &retval);
				obj = Z_DOMOBJ_P(&retval);
				nodep = dom_object_get_node(obj);
				valuePush(ctxt, xmlXPathNewNodeSet(nodep));
			} else if (Z_TYPE(retval) == IS_TRUE || Z_TYPE(retval) == IS_FALSE) {
				valuePush(ctxt, xmlXPathNewBoolean(Z_LVAL(retval)));
			} else if (Z_TYPE(retval) == IS_OBJECT) {
				php_error_docref(NULL, E_WARNING, "A PHP Object cannot be converted to a XPath-string");
				valuePush(ctxt, xmlXPathNewString((const xmlChar *) ""));
			} else {
				convert_to_string_ex(&retval);
				valuePush(ctxt, xmlXPathNewString((xmlChar *) Z_STRVAL(retval)));
			}
			zval_ptr_dtor(&retval);
		}
	}
	zend_string_release(callable);
	zval_ptr_dtor(&handler);
	if (fci.param_count > 0) {
		for (i = 0; i < nargs - 1; i++) {
			zval_ptr_dtor(&args[i]);
		}
		efree(args);
	}
}
示例#29
0
文件: http.c 项目: do-aki/petipeti
/* {{{ php_url_encode_hash */
PHPAPI int php_url_encode_hash_ex(HashTable *ht, smart_str *formstr,
				const char *num_prefix, int num_prefix_len,
				const char *key_prefix, int key_prefix_len,
				const char *key_suffix, int key_suffix_len,
			  zval *type, char *arg_sep, int enc_type TSRMLS_DC)
{
	char *key = NULL;
	char *ekey, *newprefix, *p;
	int arg_sep_len, ekey_len, key_type, newprefix_len;
	uint key_len;
	ulong idx;
	zval **zdata = NULL, *copyzval;

	if (!ht) {
		return FAILURE;
	}

	if (ht->nApplyCount > 0) {
		/* Prevent recursion */
		return SUCCESS;
	}

	if (!arg_sep) {
		arg_sep = INI_STR("arg_separator.output");
		if (!arg_sep || !strlen(arg_sep)) {
			arg_sep = URL_DEFAULT_ARG_SEP;
		}
	}
	arg_sep_len = strlen(arg_sep);

	for (zend_hash_internal_pointer_reset(ht);
		(key_type = zend_hash_get_current_key_ex(ht, &key, &key_len, &idx, 0, NULL)) != HASH_KEY_NON_EXISTANT;
		zend_hash_move_forward(ht)
	) {
		if (key_type == HASH_KEY_IS_STRING && key_len && key[key_len-1] == '\0') {
			/* We don't want that trailing NULL */
			key_len -= 1;
		}

		/* handling for private & protected object properties */
		if (key && *key == '\0' && type != NULL) {
			const char *tmp;

			zend_object *zobj = zend_objects_get_address(type TSRMLS_CC);
			if (zend_check_property_access(zobj, key, key_len-1 TSRMLS_CC) != SUCCESS) {
				/* private or protected property access outside of the class */
				continue;
			}
			zend_unmangle_property_name(key, key_len-1, &tmp, (const char**)&key);
			key_len = strlen(key);		
		}

		if (zend_hash_get_current_data_ex(ht, (void **)&zdata, NULL) == FAILURE || !zdata || !(*zdata)) {
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error traversing form data array");
			return FAILURE;
		}
		if (Z_TYPE_PP(zdata) == IS_ARRAY || Z_TYPE_PP(zdata) == IS_OBJECT) {
			if (key_type == HASH_KEY_IS_STRING) {
				if (enc_type == PHP_QUERY_RFC3986) {
					ekey = php_raw_url_encode(key, key_len, &ekey_len);
				} else {
					ekey = php_url_encode(key, key_len, &ekey_len);
				}
				newprefix_len = key_suffix_len + ekey_len + key_prefix_len + 3 /* %5B */;
				newprefix = emalloc(newprefix_len + 1);
				p = newprefix;

				if (key_prefix) {
					memcpy(p, key_prefix, key_prefix_len);
					p += key_prefix_len;
				}

				memcpy(p, ekey, ekey_len);
				p += ekey_len;
				efree(ekey);

				if (key_suffix) {
					memcpy(p, key_suffix, key_suffix_len);
					p += key_suffix_len;
				}
				*(p++) = '%';
				*(p++) = '5';
				*(p++) = 'B';
				*p = '\0';
			} else {
				/* Is an integer key */
				ekey_len = spprintf(&ekey, 0, "%ld", idx);
				newprefix_len = key_prefix_len + num_prefix_len + ekey_len + key_suffix_len + 3 /* %5B */;
				newprefix = emalloc(newprefix_len + 1);
				p = newprefix;

				if (key_prefix) {
					memcpy(p, key_prefix, key_prefix_len);
					p += key_prefix_len;
				}

				memcpy(p, num_prefix, num_prefix_len);
				p += num_prefix_len;

				memcpy(p, ekey, ekey_len);
				p += ekey_len;
				efree(ekey);

				if (key_suffix) {
					memcpy(p, key_suffix, key_suffix_len);
					p += key_suffix_len;
				}
				*(p++) = '%';
				*(p++) = '5';
				*(p++) = 'B';
				*p = '\0';
			}
			ht->nApplyCount++;
			php_url_encode_hash_ex(HASH_OF(*zdata), formstr, NULL, 0, newprefix, newprefix_len, "%5D", 3, (Z_TYPE_PP(zdata) == IS_OBJECT ? *zdata : NULL), arg_sep, enc_type TSRMLS_CC);
			ht->nApplyCount--;
			efree(newprefix);
		} else if (Z_TYPE_PP(zdata) == IS_NULL || Z_TYPE_PP(zdata) == IS_RESOURCE) {
			/* Skip these types */
			continue;
		} else {
			if (formstr->len) {
				smart_str_appendl(formstr, arg_sep, arg_sep_len);
			}
			/* Simple key=value */
			smart_str_appendl(formstr, key_prefix, key_prefix_len);
			if (key_type == HASH_KEY_IS_STRING) {
				if (enc_type == PHP_QUERY_RFC3986) {
					ekey = php_raw_url_encode(key, key_len, &ekey_len);
				} else {
					ekey = php_url_encode(key, key_len, &ekey_len);
				}
				smart_str_appendl(formstr, ekey, ekey_len);
				efree(ekey);
			} else {
				/* Numeric key */
				if (num_prefix) {
					smart_str_appendl(formstr, num_prefix, num_prefix_len);
				}
				ekey_len = spprintf(&ekey, 0, "%ld", idx);
				smart_str_appendl(formstr, ekey, ekey_len);
				efree(ekey);
			}
			smart_str_appendl(formstr, key_suffix, key_suffix_len);
			smart_str_appendl(formstr, "=", 1);
			switch (Z_TYPE_PP(zdata)) {
				case IS_STRING:
					if (enc_type == PHP_QUERY_RFC3986) {
						ekey = php_raw_url_encode(Z_STRVAL_PP(zdata), Z_STRLEN_PP(zdata), &ekey_len);
					} else {
						ekey = php_url_encode(Z_STRVAL_PP(zdata), Z_STRLEN_PP(zdata), &ekey_len);						
					}
					break;
				case IS_LONG:
				case IS_BOOL:
					ekey_len = spprintf(&ekey, 0, "%ld", Z_LVAL_PP(zdata));
					break;
				case IS_DOUBLE:
					ekey_len = spprintf(&ekey, 0, "%.*G", (int) EG(precision), Z_DVAL_PP(zdata));
					break;
				default:
					/* fall back on convert to string */
					MAKE_STD_ZVAL(copyzval);
					*copyzval = **zdata;
					zval_copy_ctor(copyzval);
					convert_to_string_ex(&copyzval);
					if (enc_type == PHP_QUERY_RFC3986) {
						ekey = php_raw_url_encode(Z_STRVAL_P(copyzval), Z_STRLEN_P(copyzval), &ekey_len);
					} else {
						ekey = php_url_encode(Z_STRVAL_P(copyzval), Z_STRLEN_P(copyzval), &ekey_len);
					}
					zval_ptr_dtor(&copyzval);
			}
			smart_str_appendl(formstr, ekey, ekey_len);
			efree(ekey);
		}
	}

	return SUCCESS;
}
示例#30
0
文件: gd_ctx.c 项目: AzerTyQsdF/osx
static void _php_image_output_ctx(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, void (*func_p)()) 
{
	zval **imgind, **file, **quality;
	gdImagePtr im;
	char *fn = NULL;
	FILE *fp = NULL;
	int argc = ZEND_NUM_ARGS();
	int q = -1, i;
	gdIOCtx *ctx;

	/* The quality parameter for Wbmp stands for the threshold when called from image2wbmp() */
	
	if (argc < 1 || argc > 3 || zend_get_parameters_ex(argc, &imgind, &file, &quality) == FAILURE) 
	{
		WRONG_PARAM_COUNT;
	}

	ZEND_FETCH_RESOURCE(im, gdImagePtr, imgind, -1, "Image", phpi_get_le_gd());

	if (argc > 1) {
		convert_to_string_ex(file);
		fn = Z_STRVAL_PP(file);
		if (argc == 3) {
			convert_to_long_ex(quality);
			q = Z_LVAL_PP(quality);
		}
	}

	if ((argc == 2) || (argc > 2 && Z_STRLEN_PP(file))) {
		PHP_GD_CHECK_OPEN_BASEDIR(fn, "Invalid filename");

		fp = VCWD_FOPEN(fn, "wb");
		if (!fp) {
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for writing", fn);
			RETURN_FALSE;
		}

		ctx = gdNewFileCtx(fp);
	} else {
		ctx = emalloc(sizeof(gdIOCtx));
		ctx->putC = _php_image_output_putc;
		ctx->putBuf = _php_image_output_putbuf;
#if HAVE_LIBGD204
		ctx->gd_free = _php_image_output_ctxfree;
#else
		ctx->free = _php_image_output_ctxfree;
#endif		

#if APACHE && defined(CHARSET_EBCDIC)
		/* XXX this is unlikely to work any more [email protected] */
		/* This is a binary file already: avoid EBCDIC->ASCII conversion */
		ap_bsetflag(php3_rqst->connection->client, B_EBCDIC2ASCII, 0);
#endif
	}

	switch(image_type) {
		case PHP_GDIMG_CONVERT_WBM:
			if(q<0||q>255) {
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid threshold value '%d'. It must be between 0 and 255", q);
			}
		case PHP_GDIMG_TYPE_JPG:
			(*func_p)(im, ctx, q);
			break;
		case PHP_GDIMG_TYPE_WBM:
			for(i=0; i < gdImageColorsTotal(im); i++) {
				if(gdImageRed(im, i) == 0) break;
			} 
			(*func_p)(im, i, ctx);
			break;
		default:
			(*func_p)(im, ctx);
			break;
	}

#if HAVE_LIBGD204	
	ctx->gd_free(ctx);
#else
	ctx->free(ctx);
#endif		

	if(fp) {
		fflush(fp);
		fclose(fp);
	}
	
    RETURN_TRUE;
}