Example #1
1
static void _php_finfo_get_type(INTERNAL_FUNCTION_PARAMETERS, int mode, int mimetype_emu) /* {{{ */
{
	zend_long options = 0;
	char *ret_val = NULL, *buffer = NULL;
	size_t buffer_len;
	php_fileinfo *finfo = NULL;
	zval *zfinfo, *zcontext = NULL;
	zval *what;
	char mime_directory[] = "directory";

	struct magic_set *magic = NULL;
	FILEINFO_DECLARE_INIT_OBJECT(object)

	if (mimetype_emu) {

		/* mime_content_type(..) emulation */
		if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &what) == FAILURE) {
			return;
		}

		switch (Z_TYPE_P(what)) {
			case IS_STRING:
				buffer = Z_STRVAL_P(what);
				buffer_len = Z_STRLEN_P(what);
				mode = FILEINFO_MODE_FILE;
				break;

			case IS_RESOURCE:
				mode = FILEINFO_MODE_STREAM;
				break;

			default:
				php_error_docref(NULL, E_WARNING, "Can only process string or stream arguments");
				RETURN_FALSE;
		}

		magic = magic_open(MAGIC_MIME_TYPE);
		if (magic_load(magic, NULL) == -1) {
			php_error_docref(NULL, E_WARNING, "Failed to load magic database.");
			goto common;
		}
	} else if (object) {
		if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|lr", &buffer, &buffer_len, &options, &zcontext) == FAILURE) {
			RETURN_FALSE;
		}
		FILEINFO_FROM_OBJECT(finfo, object);
		magic = finfo->magic;
	} else {
		if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs|lr", &zfinfo, &buffer, &buffer_len, &options, &zcontext) == FAILURE) {
			RETURN_FALSE;
		}
		if ((finfo = (php_fileinfo *)zend_fetch_resource(Z_RES_P(zfinfo), "file_info", le_fileinfo)) == NULL) {
			RETURN_FALSE;
		}
		magic = finfo->magic;
	}

	/* Set options for the current file/buffer. */
	if (options) {
		FINFO_SET_OPTION(magic, options)
	}

	switch (mode) {
		case FILEINFO_MODE_BUFFER:
		{
			ret_val = (char *) magic_buffer(magic, buffer, buffer_len);
			break;
		}

		case FILEINFO_MODE_STREAM:
		{
				php_stream *stream;
				zend_off_t streampos;

				php_stream_from_zval_no_verify(stream, what);
				if (!stream) {
					goto common;
				}

				streampos = php_stream_tell(stream); /* remember stream position for restoration */
				php_stream_seek(stream, 0, SEEK_SET);

				ret_val = (char *) magic_stream(magic, stream);

				php_stream_seek(stream, streampos, SEEK_SET);
				break;
		}

		case FILEINFO_MODE_FILE:
		{
			/* determine if the file is a local file or remote URL */
			const char *tmp2;
			php_stream_wrapper *wrap;
			php_stream_statbuf ssb;

			if (buffer == NULL || !*buffer) {
				php_error_docref(NULL, E_WARNING, "Empty filename or path");
				RETVAL_FALSE;
				goto clean;
			}

			wrap = php_stream_locate_url_wrapper(buffer, &tmp2, 0);

			if (wrap) {
				php_stream *stream;
				php_stream_context *context = php_stream_context_from_zval(zcontext, 0);

#ifdef PHP_WIN32
				if (php_stream_stat_path_ex(buffer, 0, &ssb, context) == SUCCESS) {
					if (ssb.sb.st_mode & S_IFDIR) {
						ret_val = mime_directory;
						goto common;
					}
				}
#endif

#if PHP_API_VERSION < 20100412
				stream = php_stream_open_wrapper_ex(buffer, "rb", ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL, context);
#else
				stream = php_stream_open_wrapper_ex(buffer, "rb", REPORT_ERRORS, NULL, context);
#endif

				if (!stream) {
					RETVAL_FALSE;
					goto clean;
				}

				if (php_stream_stat(stream, &ssb) == SUCCESS) {
					if (ssb.sb.st_mode & S_IFDIR) {
						ret_val = mime_directory;
					} else {
						ret_val = (char *)magic_stream(magic, stream);
					}
				}

				php_stream_close(stream);
			}
			break;
		}

		default:
			php_error_docref(NULL, E_WARNING, "Can only process string or stream arguments");
	}

common:
	if (ret_val) {
		RETVAL_STRING(ret_val);
	} else {
		php_error_docref(NULL, E_WARNING, "Failed identify data %d:%s", magic_errno(magic), magic_error(magic));
		RETVAL_FALSE;
	}

clean:
	if (mimetype_emu) {
		magic_close(magic);
	}

	/* Restore options */
	if (options) {
		FINFO_SET_OPTION(magic, finfo->options)
	}
	return;
}
Example #2
0
/**
 * Handles routing information received from command-line arguments
 *
 * @param array $arguments
 */
PHP_METHOD(Phalcon_CLI_Router, handle){

	int i;
	zval *arguments = NULL, *arguments_count, *params, *arg = NULL;
	zval *module_name, *default_module;
	zval *task_name, *default_task, *task_name_tmp, *task_name_parts;
	zval *delimiter, *status;
	zval *action_name, *default_action;

	PHALCON_MM_GROW();

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &arguments) == FAILURE) {
		PHALCON_MM_RESTORE();
		RETURN_NULL();
	}

	if (!arguments) {
		PHALCON_INIT_VAR(arguments);
		array_init(arguments);
	}

	if (Z_TYPE_P(arguments) != IS_ARRAY) {
		PHALCON_THROW_EXCEPTION_STR(phalcon_cli_router_exception_ce, "Arguments must be an Array");
		return;
	}

	/*
	 * process arguments
	 */
	// initial and set default to null
	PHALCON_INIT_VAR(module_name);
	PHALCON_INIT_VAR(task_name);
	PHALCON_INIT_VAR(task_name_tmp);
	PHALCON_INIT_VAR(action_name);
	PHALCON_INIT_VAR(params);
	PHALCON_INIT_VAR(delimiter);

	array_init(params);

	phalcon_update_property_zval(this_ptr, SL("_module"), module_name TSRMLS_CC);
	phalcon_update_property_zval(this_ptr, SL("_task"), task_name TSRMLS_CC);
	phalcon_update_property_zval(this_ptr, SL("_action"), action_name TSRMLS_CC);
	phalcon_update_property_zval(this_ptr, SL("_params"), params TSRMLS_CC);

	ZVAL_STRING(delimiter, ":", 1);

	PHALCON_INIT_VAR(arguments_count);
	phalcon_fast_count(arguments_count, arguments TSRMLS_CC);

	if (Z_LVAL_P(arguments_count) > 3) {
		// script, task, action, params.....
		phalcon_array_fetch_long(&task_name_tmp, arguments, 1, PH_NOISY_CC);
		phalcon_array_fetch_long(&action_name, arguments, 2, PH_NOISY_CC);

		// process params
		for (i = 3; i < Z_LVAL_P(arguments_count); i++) {
			PHALCON_INIT_NVAR(arg);
			phalcon_array_fetch_long(&arg, arguments, i, PH_NOISY_CC);
			phalcon_array_append(&params, arg, PH_SEPARATE TSRMLS_CC);
		}
	} else {
		if (Z_LVAL_P(arguments_count) > 2) {
			// script, task, action
			phalcon_array_fetch_long(&task_name_tmp, arguments, 1, PH_NOISY_CC);
			phalcon_array_fetch_long(&action_name, arguments, 2, PH_NOISY_CC);
		} else {
			if (Z_LVAL_P(arguments_count) > 1) {
				// script, task
				phalcon_array_fetch_long(&task_name_tmp, arguments, 1, PH_NOISY_CC);
			}
		}
	}

	// if task_name settings, parse task_name for module_name
	if (Z_TYPE_P(task_name_tmp) != IS_NULL) {

		PHALCON_INIT_VAR(task_name_parts);
		phalcon_fast_explode(task_name_parts, delimiter, task_name_tmp TSRMLS_CC);

		PHALCON_INIT_VAR(status);
		phalcon_fast_count(status, task_name_parts TSRMLS_CC);
		if (Z_LVAL_P(status) == 2) {
			PHALCON_INIT_NVAR(module_name);
			PHALCON_INIT_NVAR(task_name);
			phalcon_array_fetch_long(&module_name, task_name_parts, 0, PH_NOISY_CC);
			phalcon_array_fetch_long(&task_name, task_name_parts, 1, PH_NOISY_CC);
		}else {
			PHALCON_INIT_NVAR(task_name);
			phalcon_array_fetch_long(&task_name, task_name_parts, 0, PH_NOISY_CC);
		}
	}

	// update properties
	if (Z_TYPE_P(module_name) != IS_NULL) {
		phalcon_update_property_zval(this_ptr, SL("_module"), module_name TSRMLS_CC);
	} else {
		PHALCON_INIT_VAR(default_module);
		phalcon_read_property(&default_module, this_ptr, SL("_defaultModule"), PH_NOISY_CC);
		if (Z_TYPE_P(default_module) != IS_NULL) {
			phalcon_update_property_zval(this_ptr, SL("_module"), default_module TSRMLS_CC);
		}
	}

	PHALCON_INIT_NVAR(module_name);
	phalcon_read_property(&module_name, this_ptr, SL("_module"), PH_NOISY_CC);

	if (Z_TYPE_P(task_name) != IS_NULL) {
		phalcon_update_property_zval(this_ptr, SL("_task"), task_name TSRMLS_CC);
	} else {
		PHALCON_INIT_VAR(default_task);
		phalcon_read_property(&default_task, this_ptr, SL("_defaultTask"), PH_NOISY_CC);
		if (Z_TYPE_P(default_task) != IS_NULL) {
			phalcon_update_property_zval(this_ptr, SL("_task"), default_task TSRMLS_CC);
		}
	}

	PHALCON_INIT_NVAR(task_name);
	phalcon_read_property(&task_name, this_ptr, SL("_task"), PH_NOISY_CC);

	if (Z_TYPE_P(action_name) != IS_NULL) {
		phalcon_update_property_zval(this_ptr, SL("_action"), action_name TSRMLS_CC);
	} else {
		PHALCON_INIT_VAR(default_action);
		phalcon_read_property(&default_action, this_ptr, SL("_defaultAction"), PH_NOISY_CC);
		if (Z_TYPE_P(default_action) != IS_NULL) {
			phalcon_update_property_zval(this_ptr, SL("_action"), default_action TSRMLS_CC);
		}
	}

	phalcon_update_property_zval(this_ptr, SL("_params"), params TSRMLS_CC);

	PHALCON_MM_RESTORE();
}
Example #3
0
File: tag.c Project: meibk/cphalcon
/**
 * Builds a HTML FORM tag
 *
 * <code>
 * echo Phalcon\Tag::form("posts/save");
 * echo Phalcon\Tag::form(array("posts/save", "method" => "post"));
 * </code>
 *
 * @param array $parameters
 * @return string
 */
PHP_METHOD(Phalcon_Tag, form){

	zval *parameters = NULL, *params = NULL, *dispatcher = NULL, *dispatch_params = NULL;
	zval *slash = NULL, *action_parameters = NULL, *action = NULL, *controller_name = NULL;
	zval *action_name = NULL, *url = NULL, *form_action = NULL, *query_parameters = NULL;
	zval *code = NULL, *avalue = NULL, *key = NULL, *attribute = NULL, *final_code = NULL;
	zval *r0 = NULL;
	HashTable *ah0;
	HashPosition hp0;
	zval **hd;
	char *hash_index;
	uint hash_index_len;
	ulong hash_num;
	int hash_type;
	int eval_int;

	PHALCON_MM_GROW();
	
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &parameters) == FAILURE) {
		PHALCON_MM_RESTORE();
		RETURN_NULL();
	}

	if (!parameters) {
		PHALCON_ALLOC_ZVAL_MM(parameters);
		ZVAL_NULL(parameters);
	} else {
		PHALCON_SEPARATE_PARAM(parameters);
	}
	
	if (Z_TYPE_P(parameters) != IS_ARRAY) { 
		PHALCON_INIT_VAR(params);
		array_init(params);
		phalcon_array_append(&params, parameters, PH_SEPARATE TSRMLS_CC);
	} else {
		PHALCON_CPY_WRT(params, parameters);
	}
	
	PHALCON_INIT_VAR(dispatcher);
	PHALCON_CALL_SELF(dispatcher, this_ptr, "getdispatcherservice");
	
	PHALCON_INIT_VAR(dispatch_params);
	PHALCON_CALL_METHOD(dispatch_params, dispatcher, "getparams", PH_NO_CHECK);
	
	PHALCON_INIT_VAR(slash);
	ZVAL_STRING(slash, "/", 1);
	
	PHALCON_INIT_VAR(action_parameters);
	phalcon_fast_join(action_parameters, slash, dispatch_params TSRMLS_CC);
	eval_int = phalcon_array_isset_long(params, 0);
	if (!eval_int) {
		eval_int = phalcon_array_isset_string(params, SL("action")+1);
		if (eval_int) {
			PHALCON_INIT_VAR(action);
			phalcon_array_fetch_string(&action, params, SL("action"), PH_NOISY_CC);
		} else {
			PHALCON_INIT_VAR(controller_name);
			PHALCON_CALL_METHOD(controller_name, dispatcher, "getcontrollername", PH_NO_CHECK);
			
			PHALCON_INIT_VAR(action_name);
			PHALCON_CALL_METHOD(action_name, dispatcher, "getactionname", PH_NO_CHECK);
			
			PHALCON_INIT_VAR(action);
			PHALCON_CONCAT_VSV(action, controller_name, "/", action_name);
		}
	} else {
		PHALCON_INIT_VAR(action);
		phalcon_array_fetch_long(&action, params, 0, PH_NOISY_CC);
	}
	
	eval_int = phalcon_array_isset_string(params, SL("method")+1);
	if (!eval_int) {
		phalcon_array_update_string_string(&params, SL("method"), SL("post"), PH_SEPARATE TSRMLS_CC);
	}
	
	PHALCON_INIT_VAR(url);
	PHALCON_CALL_SELF(url, this_ptr, "geturlservice");
	if (zend_is_true(action_parameters)) {
		PHALCON_ALLOC_ZVAL_MM(r0);
		PHALCON_CALL_METHOD_PARAMS_1(r0, url, "get", action, PH_NO_CHECK);
		PHALCON_CPY_WRT(action, r0);
	} else {
		PHALCON_INIT_VAR(form_action);
		PHALCON_CONCAT_VSV(form_action, action, "/", action_parameters);
		
		PHALCON_INIT_VAR(action);
		PHALCON_CALL_METHOD_PARAMS_1(action, url, "get", form_action, PH_NO_CHECK);
	}
	
	eval_int = phalcon_array_isset_string(params, SL("parameters")+1);
	if (eval_int) {
		PHALCON_INIT_VAR(parameters);
		phalcon_array_fetch_string(&parameters, params, SL("parameters"), PH_NOISY_CC);
		
		PHALCON_INIT_VAR(query_parameters);
		PHALCON_CONCAT_SV(query_parameters, "?", parameters);
		phalcon_concat_self(&action, query_parameters TSRMLS_CC);
	}
	
	PHALCON_INIT_VAR(code);
	PHALCON_CONCAT_SVS(code, "<form action=\"", action, "\" ");
	if (!phalcon_valid_foreach(params TSRMLS_CC)) {
		return;
	}
	
	ah0 = Z_ARRVAL_P(params);
	zend_hash_internal_pointer_reset_ex(ah0, &hp0);
	fes_9b93_5:
		if(zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) != SUCCESS){
			goto fee_9b93_5;
		}
		
		PHALCON_INIT_VAR(key);
		PHALCON_GET_FOREACH_KEY(key, ah0, hp0);
		PHALCON_INIT_VAR(avalue);
		ZVAL_ZVAL(avalue, *hd, 1, 0);
		if (Z_TYPE_P(key) != IS_LONG) {
			PHALCON_INIT_VAR(attribute);
			PHALCON_CONCAT_VSVS(attribute, key, "= \"", avalue, "\" ");
			phalcon_concat_self(&code, attribute TSRMLS_CC);
		}
		zend_hash_move_forward_ex(ah0, &hp0);
		goto fes_9b93_5;
	fee_9b93_5:
	
	PHALCON_INIT_VAR(final_code);
	PHALCON_CONCAT_VS(final_code, code, ">");
	
	RETURN_CTOR(final_code);
}
Example #4
0
File: tag.c Project: meibk/cphalcon
/**
 * Builds a HTML input[type="submit"] tag
 *
 * <code>echo Phalcon\Tag::submitButton("Save")</code>
 *
 * @param array $params
 * @return string
 */
PHP_METHOD(Phalcon_Tag, submitButton){

	zval *parameters = NULL, *params = NULL, *value = NULL, *code = NULL, *avalue = NULL;
	zval *key = NULL, *attribute = NULL;
	zval *t0 = NULL;
	HashTable *ah0;
	HashPosition hp0;
	zval **hd;
	char *hash_index;
	uint hash_index_len;
	ulong hash_num;
	int hash_type;
	int eval_int;

	PHALCON_MM_GROW();
	
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &parameters) == FAILURE) {
		PHALCON_MM_RESTORE();
		RETURN_NULL();
	}

	if (Z_TYPE_P(parameters) != IS_ARRAY) { 
		PHALCON_INIT_VAR(params);
		array_init(params);
		phalcon_array_append(&params, parameters, PH_SEPARATE TSRMLS_CC);
	} else {
		PHALCON_CPY_WRT(params, parameters);
	}
	eval_int = phalcon_array_isset_string(params, SL("value")+1);
	if (eval_int) {
		PHALCON_INIT_VAR(value);
		phalcon_array_fetch_string(&value, params, SL("value"), PH_NOISY_CC);
		PHALCON_SEPARATE(params);
		phalcon_array_unset_string(params, SL("value")+1);
	} else {
		eval_int = phalcon_array_isset_long(params, 0);
		if (eval_int) {
			PHALCON_INIT_VAR(value);
			phalcon_array_fetch_long(&value, params, 0, PH_NOISY_CC);
		} else {
			PHALCON_INIT_VAR(value);
			ZVAL_STRING(value, "", 1);
		}
	}
	
	PHALCON_INIT_VAR(code);
	PHALCON_CONCAT_SVS(code, "<input type=\"submit\" value=\"", value, "\" ");
	if (!phalcon_valid_foreach(params TSRMLS_CC)) {
		return;
	}
	
	ah0 = Z_ARRVAL_P(params);
	zend_hash_internal_pointer_reset_ex(ah0, &hp0);
	fes_9b93_3:
		if(zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) != SUCCESS){
			goto fee_9b93_3;
		}
		
		PHALCON_INIT_VAR(key);
		PHALCON_GET_FOREACH_KEY(key, ah0, hp0);
		PHALCON_INIT_VAR(avalue);
		ZVAL_ZVAL(avalue, *hd, 1, 0);
		if (Z_TYPE_P(key) != IS_LONG) {
			PHALCON_INIT_VAR(attribute);
			PHALCON_CONCAT_VSVS(attribute, key, "=\"", avalue, "\" ");
			phalcon_concat_self(&code, attribute TSRMLS_CC);
		}
		zend_hash_move_forward_ex(ah0, &hp0);
		goto fes_9b93_3;
	fee_9b93_3:
	
	PHALCON_INIT_VAR(t0);
	ZVAL_STRING(t0, " />", 1);
	phalcon_concat_self(&code, t0 TSRMLS_CC);
	
	RETURN_CTOR(code);
}
Example #5
0
File: tag.c Project: meibk/cphalcon
/**
 * Builds HTML IMG tags
 *
 * @param  array $parameters
 * @return string
 */
PHP_METHOD(Phalcon_Tag, image){

	zval *parameters = NULL, *params = NULL, *first_param = NULL, *url = NULL, *src = NULL;
	zval *code = NULL, *value = NULL, *key = NULL, *attribute = NULL;
	zval *r0 = NULL;
	zval *t0 = NULL;
	HashTable *ah0;
	HashPosition hp0;
	zval **hd;
	char *hash_index;
	uint hash_index_len;
	ulong hash_num;
	int hash_type;
	int eval_int;

	PHALCON_MM_GROW();
	
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &parameters) == FAILURE) {
		PHALCON_MM_RESTORE();
		RETURN_NULL();
	}

	if (!parameters) {
		PHALCON_ALLOC_ZVAL_MM(parameters);
		ZVAL_NULL(parameters);
	}
	
	if (Z_TYPE_P(parameters) != IS_ARRAY) { 
		PHALCON_INIT_VAR(params);
		array_init(params);
		phalcon_array_append(&params, parameters, PH_SEPARATE TSRMLS_CC);
	} else {
		PHALCON_CPY_WRT(params, parameters);
	}
	eval_int = phalcon_array_isset_string(params, SL("src")+1);
	if (!eval_int) {
		eval_int = phalcon_array_isset_long(params, 0);
		if (eval_int) {
			PHALCON_INIT_VAR(first_param);
			phalcon_array_fetch_long(&first_param, params, 0, PH_NOISY_CC);
			phalcon_array_update_string(&params, SL("src"), &first_param, PH_COPY | PH_SEPARATE TSRMLS_CC);
		} else {
			phalcon_array_update_string_string(&params, SL("src"), SL(""), PH_SEPARATE TSRMLS_CC);
		}
	}
	
	PHALCON_INIT_VAR(url);
	PHALCON_CALL_SELF(url, this_ptr, "geturlservice");
	
	PHALCON_ALLOC_ZVAL_MM(r0);
	phalcon_array_fetch_string(&r0, params, SL("src"), PH_NOISY_CC);
	
	PHALCON_INIT_VAR(src);
	PHALCON_CALL_METHOD_PARAMS_1(src, url, "get", r0, PH_NO_CHECK);
	phalcon_array_update_string(&params, SL("src"), &src, PH_COPY | PH_SEPARATE TSRMLS_CC);
	
	PHALCON_INIT_VAR(code);
	ZVAL_STRING(code, "<img", 1);
	if (!phalcon_valid_foreach(params TSRMLS_CC)) {
		return;
	}
	
	ah0 = Z_ARRVAL_P(params);
	zend_hash_internal_pointer_reset_ex(ah0, &hp0);
	fes_9b93_8:
		if(zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) != SUCCESS){
			goto fee_9b93_8;
		}
		
		PHALCON_INIT_VAR(key);
		PHALCON_GET_FOREACH_KEY(key, ah0, hp0);
		PHALCON_INIT_VAR(value);
		ZVAL_ZVAL(value, *hd, 1, 0);
		if (Z_TYPE_P(key) != IS_LONG) {
			PHALCON_INIT_VAR(attribute);
			PHALCON_CONCAT_SVSVS(attribute, " ", key, "=\"", value, "\"");
			phalcon_concat_self(&code, attribute TSRMLS_CC);
		}
		zend_hash_move_forward_ex(ah0, &hp0);
		goto fes_9b93_8;
	fee_9b93_8:
	
	PHALCON_INIT_VAR(t0);
	ZVAL_STRING(t0, "/>", 1);
	phalcon_concat_self(&code, t0 TSRMLS_CC);
	
	RETURN_CTOR(code);
}
Example #6
0
static unsigned char safeexec_exec(INTERNAL_FUNCTION_PARAMETERS, int mode) /* {{{ */
{
	char *cmd, cwd;
	int cmd_len, cwd_len;
	zval *ret_code=NULL, *ret_array=NULL;
	zval *pipes;
	zval *environment = NULL;
	zval *other_options = NULL;
	int ret;

	if (mode) {
		if(mode == 4)
		{
			if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "saz|s!a!a!", &cmd,
						&cmd_len, &ret_code, &pipes, &cwd, &cwd_len, &environment,
						&other_options) == FAILURE) {
				return '0';
			}
		} else if (mode == 5) {
			if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ps", &cmd, &cmd_len, &mode, &cwd_len) == FAILURE) {
				return '0';
			}
		} else {
			if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|z/", &cmd, &cmd_len, &ret_code) == FAILURE) {
				return '0';
			}
		}
	} else {
		if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|z/z/", &cmd, &cmd_len, &ret_array, &ret_code) == FAILURE) {
			return '0';
		}
	}

	if(SAFEEXEC_G(dissallow_sudo_command))
	{
		char *searchSudoWord;
		searchSudoWord = strstr(cmd, "sudo ");

		 if (searchSudoWord != NULL)
		 {
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot execute %s command. Sudo command is not allowed with safeexec extension", cmd);
			return '0';
		 }

		 searchSudoWord = strstr(cmd, "su ");

		 if (searchSudoWord != NULL)
		 {
			php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot execute %s command. Su command is not allowed with safeexec extension", cmd);
			return '0';
		 }
	}

	if(SAFEEXEC_G(dissallow_all_expect_php))
	{
		char *searchCommand = "php ";
		int lenpre = strlen(searchCommand),
	        lenstr = strlen(cmd);
	    unsigned char isCommandStartsWithPhp = '0';

	    if(lenstr >= lenpre)
	    {
	    	if(strncmp(searchCommand, cmd, lenpre) == 0)
	    	{
	    		isCommandStartsWithPhp	= '1';
	    	}
	    }

	    if(isCommandStartsWithPhp == '0')
	    {
	    	php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot execute %s command. Only PHP commands allowed with safeexec extension", cmd);
	    	return '0';
	    }
	}

	return '1';

}
Example #7
0
/* {{{ proto array Aerospike::infoMany( string request, [, array config [, array options ]] )
    Sends an info command to several or all cluster nodes */
PHP_METHOD(Aerospike, infoMany) {

	as_error err;
	as_error_init(&err);
	reset_client_error(getThis());

	char* request = NULL;
	size_t request_len;
	zval* z_policy = NULL;
	HashTable* filter_hosts = NULL;
	zval* cb_filter_zval = NULL;
	HashTable* cb_filter_hosts = NULL;

	as_policy_info info_policy;
	as_policy_info* info_policy_p = NULL;
	AerospikeClient* php_client = NULL;
	aerospike* as_client = NULL;

	info_each_cb_data cb_data;

	if (check_object_and_connection(getThis(), &err) != AEROSPIKE_OK) {
		update_client_error(getThis(), err.code, err.message, err.in_doubt);
		RETURN_NULL();
	}
	php_client = get_aerospike_from_zobj(Z_OBJ_P(getThis()));
	as_client = php_client->as_client;


	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|h!z", &request,
			&request_len, &filter_hosts, &z_policy ) == FAILURE) {
		update_client_error(getThis(), AEROSPIKE_ERR_PARAM, "Invalid parameters for infoMany.", false);
		RETURN_NULL();
	}

	if (filter_hosts) {
		if (!is_valid_hosts_list(filter_hosts)) {
			update_client_error(getThis(), AEROSPIKE_ERR_PARAM, "Invalid list of hosts.", false);
			RETURN_NULL();
		}
		cb_filter_zval = zend_hash_str_find(filter_hosts, "hosts", strlen("hosts"));
		if (!cb_filter_zval || Z_TYPE_P(cb_filter_zval) != IS_ARRAY) {
			update_client_error(getThis(), AEROSPIKE_ERR_PARAM, "Invalid list of hosts.", false);
			RETURN_NULL();
		}
		cb_filter_hosts = Z_ARRVAL_P(cb_filter_zval);
	}

	if (z_policy){
		if (zval_to_as_policy_info(z_policy, &info_policy,
				&info_policy_p, &as_client->config.policies.info) != AEROSPIKE_OK) {
			update_client_error(getThis(), AEROSPIKE_ERR_PARAM, "Invalid policy for infoMany.", false);
			RETURN_NULL();
		}
		info_policy_p = &info_policy;
	}

	array_init(return_value);
	cb_data.err = &err;
	cb_data.response_array = return_value;
	cb_data.filter_hosts = cb_filter_hosts;

	aerospike_info_foreach(as_client, &err, info_policy_p, request,
			(aerospike_info_foreach_callback)AerospikeClient_Info_each, (void*)&cb_data);

	if (err.code != AEROSPIKE_OK) {
		update_client_error(getThis(), err.code, err.message, err.in_doubt);
		zval_dtor(return_value);
		RETURN_NULL();
	}
	return;
}
Example #8
0
/* {{{ _php_mb_regex_ereg_replace_exec */
static void _php_mb_regex_ereg_replace_exec(INTERNAL_FUNCTION_PARAMETERS, OnigOptionType options, int is_callable)
{
	zval *arg_pattern_zval;

	char *arg_pattern;
	size_t arg_pattern_len;

	char *replace;
	size_t replace_len;

	zend_fcall_info arg_replace_fci;
	zend_fcall_info_cache arg_replace_fci_cache;

	char *string;
	size_t string_len;

	char *p;
	php_mb_regex_t *re;
	OnigSyntaxType *syntax;
	OnigRegion *regs = NULL;
	smart_str out_buf = {0};
	smart_str eval_buf = {0};
	smart_str *pbuf;
	size_t i;
	int err, eval, n;
	OnigUChar *pos;
	OnigUChar *string_lim;
	char *description = NULL;
	char pat_buf[6];

	const mbfl_encoding *enc;

	{
		const char *current_enc_name;
		current_enc_name = _php_mb_regex_mbctype2name(MBREX(current_mbctype));
		if (current_enc_name == NULL ||
			(enc = mbfl_name2encoding(current_enc_name)) == NULL) {
			php_error_docref(NULL, E_WARNING, "Unknown error");
			RETURN_FALSE;
		}
	}
	eval = 0;
	{
		char *option_str = NULL;
		size_t option_str_len = 0;

		if (!is_callable) {
			if (zend_parse_parameters(ZEND_NUM_ARGS(), "zss|s",
						&arg_pattern_zval,
						&replace, &replace_len,
						&string, &string_len,
						&option_str, &option_str_len) == FAILURE) {
				RETURN_FALSE;
			}
		} else {
			if (zend_parse_parameters(ZEND_NUM_ARGS(), "zfs|s",
						&arg_pattern_zval,
						&arg_replace_fci, &arg_replace_fci_cache,
						&string, &string_len,
						&option_str, &option_str_len) == FAILURE) {
				RETURN_FALSE;
			}
		}

		if (option_str != NULL) {
			_php_mb_regex_init_options(option_str, option_str_len, &options, &syntax, &eval);
		} else {
			options |= MBREX(regex_default_options);
			syntax = MBREX(regex_default_syntax);
		}
	}
	if (Z_TYPE_P(arg_pattern_zval) == IS_STRING) {
		arg_pattern = Z_STRVAL_P(arg_pattern_zval);
		arg_pattern_len = Z_STRLEN_P(arg_pattern_zval);
	} else {
		/* FIXME: this code is not multibyte aware! */
		convert_to_long_ex(arg_pattern_zval);
		pat_buf[0] = (char)Z_LVAL_P(arg_pattern_zval);
		pat_buf[1] = '\0';
		pat_buf[2] = '\0';
		pat_buf[3] = '\0';
		pat_buf[4] = '\0';
		pat_buf[5] = '\0';

		arg_pattern = pat_buf;
		arg_pattern_len = 1;
	}
	/* create regex pattern buffer */
	re = php_mbregex_compile_pattern(arg_pattern, arg_pattern_len, options, MBREX(current_mbctype), syntax);
	if (re == NULL) {
		RETURN_FALSE;
	}

	if (eval || is_callable) {
		pbuf = &eval_buf;
		description = zend_make_compiled_string_description("mbregex replace");
	} else {
		pbuf = &out_buf;
		description = NULL;
	}

	if (is_callable) {
		if (eval) {
			php_error_docref(NULL, E_WARNING, "Option 'e' cannot be used with replacement callback");
			RETURN_FALSE;
		}
	}

	/* do the actual work */
	err = 0;
	pos = (OnigUChar *)string;
	string_lim = (OnigUChar*)(string + string_len);
	regs = onig_region_new();
	while (err >= 0) {
		err = onig_search(re, (OnigUChar *)string, (OnigUChar *)string_lim, pos, (OnigUChar *)string_lim, regs, 0);
		if (err <= -2) {
			OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
			onig_error_code_to_str(err_str, err);
			php_error_docref(NULL, E_WARNING, "mbregex search failure in php_mbereg_replace_exec(): %s", err_str);
			break;
		}
		if (err >= 0) {
#if moriyoshi_0
			if (regs->beg[0] == regs->end[0]) {
				php_error_docref(NULL, E_WARNING, "Empty regular expression");
				break;
			}
#endif
			/* copy the part of the string before the match */
			smart_str_appendl(&out_buf, (char *)pos, (size_t)((OnigUChar *)(string + regs->beg[0]) - pos));

			if (!is_callable) {
				/* copy replacement and backrefs */
				i = 0;
				p = replace;
				while (i < replace_len) {
					int fwd = (int) php_mb_mbchar_bytes_ex(p, enc);
					n = -1;
					if ((replace_len - i) >= 2 && fwd == 1 &&
					p[0] == '\\' && p[1] >= '0' && p[1] <= '9') {
						n = p[1] - '0';
					}
					if (n >= 0 && n < regs->num_regs) {
						if (regs->beg[n] >= 0 && regs->beg[n] < regs->end[n] && (size_t)regs->end[n] <= string_len) {
							smart_str_appendl(pbuf, string + regs->beg[n], regs->end[n] - regs->beg[n]);
						}
						p += 2;
						i += 2;
					} else {
						smart_str_appendl(pbuf, p, fwd);
						p += fwd;
						i += fwd;
					}
				}
			}

			if (eval) {
				zval v;
				zend_string *eval_str;
				/* null terminate buffer */
				smart_str_0(&eval_buf);

				if (eval_buf.s) {
					eval_str = eval_buf.s;
				} else {
					eval_str = ZSTR_EMPTY_ALLOC();
				}

				/* do eval */
				if (zend_eval_stringl(ZSTR_VAL(eval_str), ZSTR_LEN(eval_str), &v, description) == FAILURE) {
					efree(description);
					php_error_docref(NULL,E_ERROR, "Failed evaluating code: %s%s", PHP_EOL, ZSTR_VAL(eval_str));
					/* zend_error() does not return in this case */
				}

				/* result of eval */
				convert_to_string(&v);
				smart_str_appendl(&out_buf, Z_STRVAL(v), Z_STRLEN(v));
				/* Clean up */
				smart_str_free(&eval_buf);
				zval_dtor(&v);
			} else if (is_callable) {
				zval args[1];
				zval subpats, retval;
				int i;

				array_init(&subpats);
				for (i = 0; i < regs->num_regs; i++) {
					add_next_index_stringl(&subpats, string + regs->beg[i], regs->end[i] - regs->beg[i]);
				}

				ZVAL_COPY_VALUE(&args[0], &subpats);
				/* null terminate buffer */
				smart_str_0(&eval_buf);

				arg_replace_fci.param_count = 1;
				arg_replace_fci.params = args;
				arg_replace_fci.retval = &retval;
				if (zend_call_function(&arg_replace_fci, &arg_replace_fci_cache) == SUCCESS &&
						!Z_ISUNDEF(retval)) {
					convert_to_string_ex(&retval);
					smart_str_appendl(&out_buf, Z_STRVAL(retval), Z_STRLEN(retval));
					smart_str_free(&eval_buf);
					zval_ptr_dtor(&retval);
				} else {
					if (!EG(exception)) {
						php_error_docref(NULL, E_WARNING, "Unable to call custom replacement function");
					}
				}
				zval_ptr_dtor(&subpats);
			}

			n = regs->end[0];
			if ((pos - (OnigUChar *)string) < n) {
				pos = (OnigUChar *)string + n;
			} else {
				if (pos < string_lim) {
					smart_str_appendl(&out_buf, (char *)pos, 1);
				}
				pos++;
			}
		} else { /* nomatch */
			/* stick that last bit of string on our output */
			if (string_lim - pos > 0) {
				smart_str_appendl(&out_buf, (char *)pos, string_lim - pos);
			}
		}
		onig_region_free(regs, 0);
	}

	if (description) {
		efree(description);
	}
	if (regs != NULL) {
		onig_region_free(regs, 1);
	}
	smart_str_free(&eval_buf);

	if (err <= -2) {
		smart_str_free(&out_buf);
		RETVAL_FALSE;
	} else if (out_buf.s) {
		smart_str_0(&out_buf);
		RETVAL_STR(out_buf.s);
	} else {
		RETVAL_EMPTY_STRING();
	}
}
Example #9
0
/* {{{ proto DOMDocument dom_domimplementation_create_document(string namespaceURI, string qualifiedName, DOMDocumentType doctype) U
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Level-2-Core-DOM-createDocument
Since: DOM Level 2
*/
PHP_METHOD(domimplementation, createDocument)
{
    zval *node = NULL, *rv = NULL;
    xmlDoc *docp;
    xmlNode *nodep;
    xmlDtdPtr doctype = NULL;
    xmlNsPtr nsptr = NULL;
    int ret, uri_len = 0, name_len = 0, errorcode = 0;
    char *uri = NULL, *name = NULL;
    char *prefix = NULL, *localname = NULL;
    dom_object *doctobj;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s&s&O", &uri, &uri_len, UG(utf8_conv), &name, &name_len, UG(utf8_conv), &node, dom_documenttype_class_entry) == FAILURE) {
        return;
    }

    if (node != NULL) {
        DOM_GET_OBJ(doctype, node, xmlDtdPtr, doctobj);
        if (doctype->type == XML_DOCUMENT_TYPE_NODE) {
            php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid DocumentType object");
            RETURN_FALSE;
        }
        if (doctype->doc != NULL) {
            php_dom_throw_error(WRONG_DOCUMENT_ERR, 1 TSRMLS_CC);
            RETURN_FALSE;
        }
    } else {
        doctobj = NULL;
    }

    if (name_len > 0) {
        errorcode = dom_check_qname(name, &localname, &prefix, 1, name_len);
        if (errorcode == 0 && uri_len > 0 && ((nsptr = xmlNewNs(NULL, uri, prefix)) == NULL)) {
            errorcode = NAMESPACE_ERR;
        }
    }

    if (prefix != NULL) {
        xmlFree(prefix);
    }

    if (errorcode != 0) {
        if (localname != NULL) {
            xmlFree(localname);
        }
        php_dom_throw_error(errorcode, 1 TSRMLS_CC);
        RETURN_FALSE;
    }

    /* currently letting libxml2 set the version string */
    docp = xmlNewDoc(NULL);
    if (!docp) {
        if (localname != NULL) {
            xmlFree(localname);
        }
        RETURN_FALSE;
    }

    if (doctype != NULL) {
        docp->intSubset = doctype;
        doctype->parent = docp;
        doctype->doc = docp;
        docp->children = (xmlNodePtr) doctype;
        docp->last = (xmlNodePtr) doctype;
    }

    if (localname != NULL) {
        nodep = xmlNewDocNode (docp, nsptr, localname, NULL);
        if (!nodep) {
            if (doctype != NULL) {
                docp->intSubset = NULL;
                doctype->parent = NULL;
                doctype->doc = NULL;
                docp->children = NULL;
                docp->last = NULL;
            }
            xmlFreeDoc(docp);
            xmlFree(localname);
            /* Need some type of error here */
            php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unexpected Error");
            RETURN_FALSE;
        }

        nodep->nsDef = nsptr;

        xmlDocSetRootElement(docp, nodep);
        xmlFree(localname);
    }

    DOM_RET_OBJ(rv, (xmlNodePtr) docp, &ret, NULL);

    if (doctobj != NULL) {
        doctobj->document = ((dom_object *)((php_libxml_node_ptr *)docp->_private)->_private)->document;
        php_libxml_increment_doc_ref((php_libxml_node_object *)doctobj, docp TSRMLS_CC);
    }
}
Example #10
0
/* {{{ _php_mb_regex_ereg_search_exec */
static void
_php_mb_regex_ereg_search_exec(INTERNAL_FUNCTION_PARAMETERS, int mode)
{
	char *arg_pattern = NULL, *arg_options = NULL;
	size_t arg_pattern_len, arg_options_len;
	int n, i, err, pos, len, beg, end;
	OnigOptionType option;
	OnigUChar *str;
	OnigSyntaxType *syntax;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|ss", &arg_pattern, &arg_pattern_len, &arg_options, &arg_options_len) == FAILURE) {
		return;
	}

	option = MBREX(regex_default_options);

	if (arg_options) {
		option = 0;
		_php_mb_regex_init_options(arg_options, arg_options_len, &option, &syntax, NULL);
	}

	if (arg_pattern) {
		/* create regex pattern buffer */
		if ((MBREX(search_re) = php_mbregex_compile_pattern(arg_pattern, arg_pattern_len, option, MBREX(current_mbctype), MBREX(regex_default_syntax))) == NULL) {
			RETURN_FALSE;
		}
	}

	pos = MBREX(search_pos);
	str = NULL;
	len = 0;
	if (!Z_ISUNDEF(MBREX(search_str)) && Z_TYPE(MBREX(search_str)) == IS_STRING){
		str = (OnigUChar *)Z_STRVAL(MBREX(search_str));
		len = Z_STRLEN(MBREX(search_str));
	}

	if (MBREX(search_re) == NULL) {
		php_error_docref(NULL, E_WARNING, "No regex given");
		RETURN_FALSE;
	}

	if (str == NULL) {
		php_error_docref(NULL, E_WARNING, "No string given");
		RETURN_FALSE;
	}

	if (MBREX(search_regs)) {
		onig_region_free(MBREX(search_regs), 1);
	}
	MBREX(search_regs) = onig_region_new();

	err = onig_search(MBREX(search_re), str, str + len, str + pos, str  + len, MBREX(search_regs), 0);
	if (err == ONIG_MISMATCH) {
		MBREX(search_pos) = len;
		RETVAL_FALSE;
	} else if (err <= -2) {
		OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
		onig_error_code_to_str(err_str, err);
		php_error_docref(NULL, E_WARNING, "mbregex search failure in mbregex_search(): %s", err_str);
		RETVAL_FALSE;
	} else {
		if (MBREX(search_regs)->beg[0] == MBREX(search_regs)->end[0]) {
			php_error_docref(NULL, E_WARNING, "Empty regular expression");
		}
		switch (mode) {
		case 1:
			array_init(return_value);
			beg = MBREX(search_regs)->beg[0];
			end = MBREX(search_regs)->end[0];
			add_next_index_long(return_value, beg);
			add_next_index_long(return_value, end - beg);
			break;
		case 2:
			array_init(return_value);
			n = MBREX(search_regs)->num_regs;
			for (i = 0; i < n; i++) {
				beg = MBREX(search_regs)->beg[i];
				end = MBREX(search_regs)->end[i];
				if (beg >= 0 && beg <= end && end <= len) {
					add_index_stringl(return_value, i, (char *)&str[beg], end - beg);
				} else {
					add_index_bool(return_value, i, 0);
				}
			}
			break;
		default:
			RETVAL_TRUE;
			break;
		}
		end = MBREX(search_regs)->end[0];
		if (pos < end) {
			MBREX(search_pos) = end;
		} else {
			MBREX(search_pos) = pos + 1;
		}
	}

	if (err < 0) {
		onig_region_free(MBREX(search_regs), 1);
		MBREX(search_regs) = (OnigRegion *)NULL;
	}
}
Example #11
0
/* {{{ _php_mb_regex_ereg_exec */
static void _php_mb_regex_ereg_exec(INTERNAL_FUNCTION_PARAMETERS, int icase)
{
	zval *arg_pattern, *array = NULL;
	char *string;
	size_t string_len;
	php_mb_regex_t *re;
	OnigRegion *regs = NULL;
	int i, match_len, beg, end;
	OnigOptionType options;
	char *str;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "zs|z/", &arg_pattern, &string, &string_len, &array) == FAILURE) {
		RETURN_FALSE;
	}

	options = MBREX(regex_default_options);
	if (icase) {
		options |= ONIG_OPTION_IGNORECASE;
	}

	/* compile the regular expression from the supplied regex */
	if (Z_TYPE_P(arg_pattern) != IS_STRING) {
		/* we convert numbers to integers and treat them as a string */
		if (Z_TYPE_P(arg_pattern) == IS_DOUBLE) {
			convert_to_long_ex(arg_pattern);	/* get rid of decimal places */
		}
		convert_to_string_ex(arg_pattern);
		/* don't bother doing an extended regex with just a number */
	}

	if (Z_STRLEN_P(arg_pattern) == 0) {
		php_error_docref(NULL, E_WARNING, "empty pattern");
		RETVAL_FALSE;
		goto out;
	}

	re = php_mbregex_compile_pattern(Z_STRVAL_P(arg_pattern), Z_STRLEN_P(arg_pattern), options, MBREX(current_mbctype), MBREX(regex_default_syntax));
	if (re == NULL) {
		RETVAL_FALSE;
		goto out;
	}

	regs = onig_region_new();

	/* actually execute the regular expression */
	if (onig_search(re, (OnigUChar *)string, (OnigUChar *)(string + string_len), (OnigUChar *)string, (OnigUChar *)(string + string_len), regs, 0) < 0) {
		RETVAL_FALSE;
		goto out;
	}

	match_len = 1;
	str = string;
	if (array != NULL) {
		zval_dtor(array);
		array_init(array);

		match_len = regs->end[0] - regs->beg[0];
		for (i = 0; i < regs->num_regs; i++) {
			beg = regs->beg[i];
			end = regs->end[i];
			if (beg >= 0 && beg < end && (size_t)end <= string_len) {
				add_index_stringl(array, i, (char *)&str[beg], end - beg);
			} else {
				add_index_bool(array, i, 0);
			}
		}
	}

	if (match_len == 0) {
		match_len = 1;
	}
	RETVAL_LONG(match_len);
out:
	if (regs != NULL) {
		onig_region_free(regs, 1);
	}
}
Example #12
0
static void php_hash_do_hash_hmac(INTERNAL_FUNCTION_PARAMETERS, int isfilename, zend_bool raw_output_default) /* {{{ */
{
	char *algo, *data, *digest, *key, *K;
	int algo_len, data_len, key_len, i;
	zend_bool raw_output = raw_output_default;
	const php_hash_ops *ops;
	void *context;
	php_stream *stream = NULL;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sss|b", &algo, &algo_len, &data, &data_len, 
																  &key, &key_len, &raw_output) == FAILURE) {
		return;
	}

	ops = php_hash_fetch_ops(algo, algo_len);
	if (!ops) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown hashing algorithm: %s", algo);
		RETURN_FALSE;
	}
	if (isfilename) {
		stream = php_stream_open_wrapper_ex(data, "rb", REPORT_ERRORS, NULL, DEFAULT_CONTEXT);
		if (!stream) {
			/* Stream will report errors opening file */
			RETURN_FALSE;
		}
	}

	context = emalloc(ops->context_size);
	ops->hash_init(context);

	K = emalloc(ops->block_size);
	memset(K, 0, ops->block_size);

	if (key_len > ops->block_size) {
		/* Reduce the key first */
		ops->hash_update(context, (unsigned char *) key, key_len);
		ops->hash_final((unsigned char *) K, context);
		/* Make the context ready to start over */
		ops->hash_init(context);
	} else {
		memcpy(K, key, key_len);
	}
			
	/* XOR ipad */
	for(i=0; i < ops->block_size; i++) {
		K[i] ^= 0x36;
	}
	ops->hash_update(context, (unsigned char *) K, ops->block_size);

	if (isfilename) {
		char buf[1024];
		int n;

		while ((n = php_stream_read(stream, buf, sizeof(buf))) > 0) {
			ops->hash_update(context, (unsigned char *) buf, n);
		}
		php_stream_close(stream);
	} else {
		ops->hash_update(context, (unsigned char *) data, data_len);
	}

	digest = emalloc(ops->digest_size + 1);
	ops->hash_final((unsigned char *) digest, context);

	/* Convert K to opad -- 0x6A = 0x36 ^ 0x5C */
	for(i=0; i < ops->block_size; i++) {
		K[i] ^= 0x6A;
	}

	/* Feed this result into the outter hash */
	ops->hash_init(context);
	ops->hash_update(context, (unsigned char *) K, ops->block_size);
	ops->hash_update(context, (unsigned char *) digest, ops->digest_size);
	ops->hash_final((unsigned char *) digest, context);

	/* Zero the key */
	memset(K, 0, ops->block_size);
	efree(K);
	efree(context);

	if (raw_output) {
		digest[ops->digest_size] = 0;
		RETURN_STRINGL(digest, ops->digest_size, 0);
	} else {
		char *hex_digest = safe_emalloc(ops->digest_size, 2, 1);

		php_hash_bin2hex(hex_digest, (unsigned char *) digest, ops->digest_size);
		hex_digest[2 * ops->digest_size] = 0;
		efree(digest);
		RETURN_STRINGL(hex_digest, 2 * ops->digest_size, 0);
	}
}
Example #13
0
static void php_intl_idn_handoff(INTERNAL_FUNCTION_PARAMETERS, int mode)
{
	char *domain;
	int domain_len;
	long option = 0,
		 variant = INTL_IDN_VARIANT_2003;
	zval *idna_info = NULL;

	intl_error_reset(NULL TSRMLS_CC);

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|llz/",
			&domain, &domain_len, &option, &variant, &idna_info) == FAILURE) {
		php_intl_bad_args("bad arguments", mode TSRMLS_CC);
		RETURN_NULL(); /* don't set FALSE because that's not the way it was before... */
	}

#ifdef HAVE_46_API
	if (variant != INTL_IDN_VARIANT_2003 && variant != INTL_IDN_VARIANT_UTS46) {
		php_intl_bad_args("invalid variant, must be one of {"
			"INTL_IDNA_VARIANT_2003, INTL_IDNA_VARIANT_UTS46}", mode TSRMLS_CC);
		RETURN_FALSE;
	}
#else
	if (variant != INTL_IDN_VARIANT_2003) {
		php_intl_bad_args("invalid variant, PHP was compiled against "
			"an old version of ICU and only supports INTL_IDN_VARIANT_2003",
			mode TSRMLS_CC);
		RETURN_FALSE;
	}
#endif

	if (domain_len < 1) {
		php_intl_bad_args("empty domain name", mode TSRMLS_CC);
		RETURN_FALSE;
	}
	if (domain_len > INT32_MAX - 1) {
		php_intl_bad_args("domain name too large", mode TSRMLS_CC);
		RETURN_FALSE;
	}
	/* don't check options; it wasn't checked before */

	if (idna_info != NULL) {
		if (variant == INTL_IDN_VARIANT_2003) {
			php_error_docref0(NULL TSRMLS_CC, E_NOTICE,
				"4 arguments were provided, but INTL_IDNA_VARIANT_2003 only "
				"takes 3 - extra argument ignored");
		} else {
			zval_dtor(idna_info);
			array_init(idna_info);
		}
	}
	
	if (variant == INTL_IDN_VARIANT_2003) {
		php_intl_idn_to(INTERNAL_FUNCTION_PARAM_PASSTHRU,
				domain, domain_len, (uint32_t)option, mode);
	}
#ifdef HAVE_46_API
	else {
		php_intl_idn_to_46(INTERNAL_FUNCTION_PARAM_PASSTHRU, domain, domain_len,
				(uint32_t)option, mode, idna_info);
	}
#endif
}
Example #14
0
	return_value = getThis();
	numfmt_ctor(INTERNAL_FUNCTION_PARAM_PASSTHRU);
}
/* }}} */

/* {{{ proto int NumberFormatter::getErrorCode()
 * Get formatter's last error code. }}} */
/* {{{ proto int numfmt_get_error_code( NumberFormatter $nf )
 * Get formatter's last error code.
 */
PHP_FUNCTION( numfmt_get_error_code )
{
	FORMATTER_METHOD_INIT_VARS

	/* Parse parameters. */
	if( zend_parse_method_parameters( ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O",
		&object, NumberFormatter_ce_ptr ) == FAILURE )
	{
		intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
			"numfmt_get_error_code: unable to parse input params", 0 TSRMLS_CC );

		RETURN_FALSE;
	}

	nfo = (NumberFormatter_object *) zend_object_store_get_object( object TSRMLS_CC );

	/* Return formatter's last error code. */
	RETURN_LONG( INTL_DATA_ERROR_CODE(nfo) );
}
/* }}} */
Example #15
0
/**
 * Add a route to the router
 *
 * @param string $pattern
 * @param string/array $paths
 */
PHP_METHOD(Phalcon_Mvc_Router, add){

	zval *pattern = NULL, *paths = NULL, *parts = NULL, *route_paths = NULL, *pcre_pattern = NULL;
	zval *matches = NULL, *match = NULL, *n = NULL;
	zval *c0 = NULL, *c1 = NULL, *c2 = NULL;
	zval *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *r4 = NULL, *r5 = NULL, *r6 = NULL;
	zval *r7 = NULL, *r8 = NULL, *r9 = NULL, *r10 = NULL, *r11 = NULL;
	zval *t0 = NULL, *t1 = NULL, *t2 = NULL;
	zval *a0 = NULL;
	zval *p0[] = { NULL, NULL, NULL, NULL };
	HashTable *ah0;
	HashPosition hp0;
	zval **hd;
	char *hash_index;
	uint hash_index_len;
	ulong hash_num;
	int hash_type;
	int eval_int;

	PHALCON_MM_GROW();
	
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &pattern, &paths) == FAILURE) {
		PHALCON_MM_RESTORE();
		RETURN_NULL();
	}

	if (Z_TYPE_P(paths) == IS_STRING) {
		PHALCON_INIT_VAR(c0);
		ZVAL_STRING(c0, "::", 1);
		PHALCON_INIT_VAR(parts);
		phalcon_fast_explode(parts, c0, paths TSRMLS_CC);
		
		PHALCON_INIT_VAR(route_paths);
		array_init(route_paths);
		
		PHALCON_ALLOC_ZVAL_MM(r0);
		phalcon_array_fetch_long(&r0, parts, 0, PH_NOISY_CC);
		
		PHALCON_ALLOC_ZVAL_MM(r1);
		PHALCON_CALL_FUNC_PARAMS_1(r1, "strtolower", r0);
		phalcon_array_update_string(&route_paths, SL("controller"), &r1, PH_COPY | PH_SEPARATE TSRMLS_CC);
		eval_int = phalcon_array_isset_long(parts, 1);
		if (eval_int) {
			PHALCON_ALLOC_ZVAL_MM(r2);
			phalcon_array_fetch_long(&r2, parts, 1, PH_NOISY_CC);
			phalcon_array_update_string(&route_paths, SL("action"), &r2, PH_COPY | PH_SEPARATE TSRMLS_CC);
		}
	} else {
		PHALCON_CPY_WRT(route_paths, paths);
	}
	
	PHALCON_INIT_VAR(c1);
	ZVAL_STRING(c1, "#", 1);
	
	PHALCON_INIT_VAR(c2);
	ZVAL_STRING(c2, "\\#", 1);
	
	PHALCON_INIT_VAR(pcre_pattern);
	phalcon_fast_str_replace(pcre_pattern, c1, c2, pattern TSRMLS_CC);
	
	PHALCON_ALLOC_ZVAL_MM(r3);
	phalcon_fast_strpos_str(r3, pcre_pattern, SL("{") TSRMLS_CC);
	if (zend_is_true(r3)) {
		PHALCON_INIT_VAR(matches);
		array_init(matches);
		
		PHALCON_INIT_VAR(p0[0]);
		ZVAL_STRING(p0[0], "#{([a-zA-Z0-9\\_\\-]+):([^}]+)}#", 1);
		p0[1] = pcre_pattern;
		Z_SET_ISREF_P(matches);
		p0[2] = matches;
		
		PHALCON_INIT_VAR(t0);
		ZVAL_LONG(t0, 2);
		p0[3] = t0;
		
		PHALCON_ALLOC_ZVAL_MM(r4);
		PHALCON_CALL_FUNC_PARAMS(r4, "preg_match_all", 4, p0);
		Z_UNSET_ISREF_P(p0[2]);
		if (zend_is_true(r4)) {
			if (!phalcon_valid_foreach(matches TSRMLS_CC)) {
				return;
			}
			
			ah0 = Z_ARRVAL_P(matches);
			zend_hash_internal_pointer_reset_ex(ah0, &hp0);
			fes_c9ff_0:
				if(zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) != SUCCESS){
					goto fee_c9ff_0;
				}
				
				PHALCON_INIT_VAR(n);
				PHALCON_GET_FOREACH_KEY(n, ah0, hp0);
				PHALCON_INIT_VAR(match);
				ZVAL_ZVAL(match, *hd, 1, 0);
				PHALCON_INIT_VAR(r5);
				phalcon_array_fetch_long(&r5, match, 0, PH_NOISY_CC);
				PHALCON_INIT_VAR(r6);
				phalcon_array_fetch_long(&r6, match, 2, PH_NOISY_CC);
				PHALCON_INIT_VAR(r7);
				PHALCON_CONCAT_SVS(r7, "(", r6, ")");
				PHALCON_INIT_VAR(r8);
				phalcon_fast_str_replace(r8, r5, r7, pcre_pattern TSRMLS_CC);
				PHALCON_CPY_WRT(pcre_pattern, r8);
				
				PHALCON_INIT_VAR(t1);
				ZVAL_LONG(t1, 1);
				
				PHALCON_INIT_VAR(r9);
				phalcon_add_function(r9, n, t1 TSRMLS_CC);
				
				PHALCON_INIT_VAR(r10);
				phalcon_array_fetch_long(&r10, match, 1, PH_NOISY_CC);
				phalcon_array_update_zval(&route_paths, r10, &r9, PH_COPY | PH_SEPARATE TSRMLS_CC);
				zend_hash_move_forward_ex(ah0, &hp0);
				goto fes_c9ff_0;
			fee_c9ff_0:
			if(0){}
			
		}
	}
	
	PHALCON_ALLOC_ZVAL_MM(a0);
	array_init(a0);
	
	PHALCON_ALLOC_ZVAL_MM(r11);
	PHALCON_CALL_METHOD_PARAMS_1(r11, this_ptr, "compilepattern", pcre_pattern, PH_NO_CHECK);
	phalcon_array_update_string(&a0, SL("pattern"), &r11, PH_COPY | PH_SEPARATE TSRMLS_CC);
	phalcon_array_update_string(&a0, SL("paths"), &route_paths, PH_COPY | PH_SEPARATE TSRMLS_CC);
	
	PHALCON_ALLOC_ZVAL_MM(t2);
	phalcon_read_property(&t2, this_ptr, SL("_routes"), PH_NOISY_CC);
	phalcon_array_append(&t2, a0, 0 TSRMLS_CC);
	phalcon_update_property_zval(this_ptr, SL("_routes"), t2 TSRMLS_CC);
	
	PHALCON_MM_RESTORE();
}
Example #16
0
static PHP_METHOD(swoole_mysql, query)
{
    zval *callback;
    swString sql;
    bzero(&sql, sizeof(sql));

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &sql.str, &sql.length, &callback) == FAILURE)
    {
        return;
    }

    if (sql.length <= 0)
    {
        swoole_php_fatal_error(E_WARNING, "Query is empty.");
        RETURN_FALSE;
    }

    mysql_client *client = swoole_get_object(getThis());
    if (!client)
    {
        swoole_php_fatal_error(E_WARNING, "object is not instanceof swoole_mysql.");
        RETURN_FALSE;
    }

    if (!client->cli)
    {
        swoole_php_fatal_error(E_WARNING, "mysql connection#%d is closed.", client->fd);
        RETURN_FALSE;
    }

    if (client->state != SW_MYSQL_STATE_QUERY)
    {
        swoole_php_fatal_error(E_WARNING, "mysql client is waiting response, cannot send new sql query.");
        RETURN_FALSE;
    }

    client->callback = callback;
    sw_copy_to_stack(client->callback, client->_callback);

    sw_zval_add_ref(&client->callback);
    sw_zval_add_ref(&client->object);
    swString_clear(mysql_request_buffer);

    if (mysql_request(&sql, mysql_request_buffer) < 0)
    {
        RETURN_FALSE;
    }
    //add to eventloop
    if (SwooleG.main_reactor->add(SwooleG.main_reactor, client->fd, PHP_SWOOLE_FD_MYSQL | SW_EVENT_READ) < 0)
    {
        swoole_php_fatal_error(E_WARNING, "swoole_event_add failed.");
        RETURN_FALSE;
    }
    //send query
    if (SwooleG.main_reactor->write(SwooleG.main_reactor, client->fd, mysql_request_buffer->str, mysql_request_buffer->length) < 0)
    {
        //connection is closed
        if (swConnection_error(errno) == SW_CLOSE)
        {
            zend_update_property_bool(swoole_mysql_class_entry_ptr, getThis(), ZEND_STRL("connected"), 0 TSRMLS_CC);
            zend_update_property_bool(swoole_mysql_class_entry_ptr, getThis(), ZEND_STRL("errno"), 2006 TSRMLS_CC);
        }
        RETURN_FALSE;
    }
    else
    {
        client->state = SW_MYSQL_STATE_READ_START;
        RETURN_TRUE;
    }
}
Example #17
0
/**
 * Handles routing information received from the rewrite engine
 *
 * @param string $uri
 */
PHP_METHOD(Phalcon_Mvc_Router, handle){

	zval *uri = NULL, *real_uri = NULL, *route_found = NULL, *parts = NULL, *params = NULL;
	zval *matches = NULL, *route = NULL, *position = NULL, *part = NULL, *str_params = NULL;
	zval *t0 = NULL, *t1 = NULL, *t2 = NULL;
	zval *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *r4 = NULL, *r5 = NULL, *r6 = NULL;
	zval *r7 = NULL, *r8 = NULL, *r9 = NULL;
	zval *c0 = NULL, *c1 = NULL;
	zval *a0 = NULL;
	HashTable *ah0, *ah1;
	HashPosition hp0, hp1;
	zval **hd;
	char *hash_index;
	uint hash_index_len;
	ulong hash_num;
	int hash_type;
	int eval_int;

	PHALCON_MM_GROW();
	
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &uri) == FAILURE) {
		PHALCON_MM_RESTORE();
		RETURN_NULL();
	}

	if (!uri) {
		PHALCON_ALLOC_ZVAL_MM(uri);
		ZVAL_NULL(uri);
	}
	
	if (!zend_is_true(uri)) {
		PHALCON_INIT_VAR(real_uri);
		PHALCON_CALL_METHOD(real_uri, this_ptr, "_getrewriteuri", PH_NO_CHECK);
	} else {
		PHALCON_CPY_WRT(real_uri, uri);
	}
	
	PHALCON_INIT_VAR(route_found);
	ZVAL_BOOL(route_found, 0);
	
	PHALCON_INIT_VAR(parts);
	array_init(parts);
	
	PHALCON_INIT_VAR(params);
	array_init(params);
	
	PHALCON_INIT_VAR(matches);
	array_init(matches);
	phalcon_update_property_bool(this_ptr, SL("_wasMatched"), 0 TSRMLS_CC);
	
	PHALCON_ALLOC_ZVAL_MM(t0);
	phalcon_read_property(&t0, this_ptr, SL("_routes"), PH_NOISY_CC);
	
	PHALCON_ALLOC_ZVAL_MM(r0);
	PHALCON_CALL_FUNC_PARAMS_1(r0, "array_reverse", t0);
	if (!phalcon_valid_foreach(r0 TSRMLS_CC)) {
		return;
	}
	
	ah0 = Z_ARRVAL_P(r0);
	zend_hash_internal_pointer_reset_ex(ah0, &hp0);
	fes_c9ff_1:
		if(zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) != SUCCESS){
			goto fee_c9ff_1;
		}
		
		PHALCON_INIT_VAR(route);
		ZVAL_ZVAL(route, *hd, 1, 0);
		PHALCON_INIT_VAR(parts);
		phalcon_array_fetch_string(&parts, route, SL("paths"), PH_NOISY_CC);
		
		PHALCON_INIT_VAR(r1);
		phalcon_array_fetch_string(&r1, route, SL("pattern"), PH_NOISY_CC);
		Z_SET_ISREF_P(matches);
		
		PHALCON_INIT_VAR(r2);
		PHALCON_CALL_FUNC_PARAMS_3(r2, "preg_match", r1, real_uri, matches);
		Z_UNSET_ISREF_P(matches);
		if (zend_is_true(r2)) {
			PHALCON_INIT_VAR(r3);
			phalcon_array_fetch_string(&r3, route, SL("paths"), PH_NOISY_CC);
			if (!phalcon_valid_foreach(r3 TSRMLS_CC)) {
				return;
			}
			
			ah1 = Z_ARRVAL_P(r3);
			zend_hash_internal_pointer_reset_ex(ah1, &hp1);
			fes_c9ff_2:
				if(zend_hash_get_current_data_ex(ah1, (void**) &hd, &hp1) != SUCCESS){
					goto fee_c9ff_2;
				}
				
				PHALCON_INIT_VAR(part);
				PHALCON_GET_FOREACH_KEY(part, ah1, hp1);
				PHALCON_INIT_VAR(position);
				ZVAL_ZVAL(position, *hd, 1, 0);
				eval_int = phalcon_array_isset(matches, position);
				if (eval_int) {
					PHALCON_INIT_VAR(r4);
					phalcon_array_fetch(&r4, matches, position, PH_NOISY_CC);
					phalcon_array_update_zval(&parts, part, &r4, PH_COPY | PH_SEPARATE TSRMLS_CC);
				}
				zend_hash_move_forward_ex(ah1, &hp1);
				goto fes_c9ff_2;
			fee_c9ff_2:
			if(0){}
			
			phalcon_update_property_zval(this_ptr, SL("_matches"), matches TSRMLS_CC);
			phalcon_update_property_zval(this_ptr, SL("_currentRoute"), route TSRMLS_CC);
			
			PHALCON_INIT_VAR(route_found);
			ZVAL_BOOL(route_found, 1);
			goto fee_c9ff_1;
		}
		zend_hash_move_forward_ex(ah0, &hp0);
		goto fes_c9ff_1;
	fee_c9ff_1:
	if(0){}
	
	if (zend_is_true(route_found)) {
		eval_int = phalcon_array_isset_string(parts, SL("module")+1);
		if (eval_int) {
			PHALCON_ALLOC_ZVAL_MM(r5);
			phalcon_array_fetch_string(&r5, parts, SL("module"), PH_NOISY_CC);
			phalcon_update_property_zval(this_ptr, SL("_module"), r5 TSRMLS_CC);
			PHALCON_SEPARATE(parts);
			phalcon_array_unset_string(parts, SL("module")+1);
		} else {
			PHALCON_ALLOC_ZVAL_MM(t1);
			phalcon_read_property(&t1, this_ptr, SL("_defaultModule"), PH_NOISY_CC);
			phalcon_update_property_zval(this_ptr, SL("_module"), t1 TSRMLS_CC);
		}
		eval_int = phalcon_array_isset_string(parts, SL("controller")+1);
		if (eval_int) {
			PHALCON_ALLOC_ZVAL_MM(r6);
			phalcon_array_fetch_string(&r6, parts, SL("controller"), PH_NOISY_CC);
			phalcon_update_property_zval(this_ptr, SL("_controller"), r6 TSRMLS_CC);
			PHALCON_SEPARATE(parts);
			phalcon_array_unset_string(parts, SL("controller")+1);
		} else {
			phalcon_update_property_null(this_ptr, SL("_controller") TSRMLS_CC);
		}
		
		eval_int = phalcon_array_isset_string(parts, SL("action")+1);
		if (eval_int) {
			PHALCON_ALLOC_ZVAL_MM(r7);
			phalcon_array_fetch_string(&r7, parts, SL("action"), PH_NOISY_CC);
			phalcon_update_property_zval(this_ptr, SL("_action"), r7 TSRMLS_CC);
			PHALCON_SEPARATE(parts);
			phalcon_array_unset_string(parts, SL("action")+1);
		} else {
			phalcon_update_property_null(this_ptr, SL("_action") TSRMLS_CC);
		}
		
		eval_int = phalcon_array_isset_string(parts, SL("params")+1);
		if (eval_int) {
			PHALCON_ALLOC_ZVAL_MM(r8);
			phalcon_array_fetch_string(&r8, parts, SL("params"), PH_NOISY_CC);
			PHALCON_INIT_VAR(c0);
			ZVAL_LONG(c0, 1);
			PHALCON_INIT_VAR(str_params);
			PHALCON_CALL_FUNC_PARAMS_2(str_params, "substr", r8, c0);
			if (zend_is_true(str_params)) {
				PHALCON_INIT_VAR(c1);
				ZVAL_STRING(c1, "/", 1);
				PHALCON_INIT_VAR(params);
				phalcon_fast_explode(params, c1, str_params TSRMLS_CC);
			}
			
			PHALCON_SEPARATE(parts);
			phalcon_array_unset_string(parts, SL("params")+1);
		}
		
		PHALCON_ALLOC_ZVAL_MM(r9);
		PHALCON_CALL_FUNC_PARAMS_2(r9, "array_merge", params, parts);
		phalcon_update_property_zval(this_ptr, SL("_params"), r9 TSRMLS_CC);
		phalcon_update_property_bool(this_ptr, SL("_wasMatched"), 1 TSRMLS_CC);
	} else {
		PHALCON_ALLOC_ZVAL_MM(t2);
		phalcon_read_property(&t2, this_ptr, SL("_defaultModule"), PH_NOISY_CC);
		phalcon_update_property_zval(this_ptr, SL("_module"), t2 TSRMLS_CC);
		phalcon_update_property_null(this_ptr, SL("_controller") TSRMLS_CC);
		phalcon_update_property_null(this_ptr, SL("_action") TSRMLS_CC);
		
		PHALCON_ALLOC_ZVAL_MM(a0);
		array_init(a0);
		phalcon_update_property_zval(this_ptr, SL("_params"), a0 TSRMLS_CC);
		phalcon_update_property_bool(this_ptr, SL("_wasMatched"), 0 TSRMLS_CC);
	}
	
	PHALCON_MM_RESTORE();
}
Example #18
0
static PHP_METHOD(swoole_mysql, __construct)
{
    if (!mysql_request_buffer)
    {
        mysql_request_buffer = swString_new(SW_MYSQL_QUERY_INIT_SIZE);
        if (!mysql_request_buffer)
        {
            swoole_php_fatal_error(E_ERROR, "[1] swString_new(%d) failed.", SW_HTTP_RESPONSE_INIT_SIZE);
            RETURN_FALSE;
        }
    }

    char *unixsocket = NULL;
    zend_size_t unixsocket_len = 0;

    mysql_connector connector;
    connector.port = SW_MYSQL_DEFAULT_PORT;

    if (zend_parse_parameters(ZEND_NUM_ARGS()TSRMLS_CC, "ssss|ls", &connector.host, &connector.host_len,
            &connector.user, &connector.user_len, &connector.password, &connector.password_len, &connector.database,
            &connector.database_len, &connector.port, &unixsocket, &unixsocket_len) == FAILURE)
    {
        RETURN_FALSE;
    }

    swClient *cli = emalloc(sizeof(swClient));
    int type = SW_SOCK_TCP;
    if (unixsocket)
    {
        type = SW_SOCK_UNIX_STREAM;
        connector.host = unixsocket;
        connector.host_len = unixsocket_len;
    }
    if (swClient_create(cli, type, 0) < 0)
    {
        zend_throw_exception(swoole_mysql_exception_class_entry, "swClient_create failed.", 1 TSRMLS_CC);
        RETURN_FALSE;
    }
    if (cli->connect(cli, connector.host, connector.port, SW_MYSQL_CONNECT_TIMEOUT, 0) < 0)
    {
        zend_throw_exception(swoole_mysql_exception_class_entry, "connect to mysql server[%s:%d] failed.", 2 TSRMLS_CC);
        RETURN_FALSE;
    }
    int tcp_nodelay = 1;
    if (setsockopt(cli->socket->fd, IPPROTO_TCP, TCP_NODELAY, (const void *) &tcp_nodelay, sizeof(int)) == -1)
    {
        swoole_php_sys_error(E_WARNING, "setsockopt(%d, IPPROTO_TCP, TCP_NODELAY) failed.", cli->socket->fd);
    }

    char buf[2048];

    int n = cli->recv(cli, buf, sizeof(buf), 0);
    if (n < 0)
    {
        zend_throw_exception(swoole_mysql_exception_class_entry, "recvfrom mysql server failed.", 3 TSRMLS_CC);
        RETURN_FALSE;
    }

    if (mysql_handshake(&connector, buf, n) == SW_ERR)
    {
        zend_throw_exception(swoole_mysql_exception_class_entry, "handshake with mysql server failed.", 4 TSRMLS_CC);
        RETURN_FALSE;
    }

    if (cli->send(cli, connector.buf, connector.packet_length + 4, 0) < 0)
    {
        zend_throw_exception(swoole_mysql_exception_class_entry, "sendto mysql server failed.", 5 TSRMLS_CC);
        RETURN_FALSE;
    }

    if (cli->recv(cli, buf, sizeof(buf), 0) < 0)
    {
        zend_throw_exception(swoole_mysql_exception_class_entry, "recvfrom mysql server failed.", 6 TSRMLS_CC);
        RETURN_FALSE;
    }

    mysql_client *client = emalloc(sizeof(mysql_client));
    bzero(client, sizeof(mysql_client));
    client->buffer = swString_new(SW_BUFFER_SIZE_BIG);
    client->fd = cli->socket->fd;
    client->object = getThis();
    client->cli = cli;
    sw_copy_to_stack(client->object, client->_object);

    zend_update_property_bool(swoole_mysql_class_entry_ptr, getThis(), ZEND_STRL("connected"), 1 TSRMLS_CC);

    swoole_set_object(getThis(), client);

    php_swoole_check_reactor();
    swSetNonBlock(cli->socket->fd);

    if (!isset_event_callback)
    {
        SwooleG.main_reactor->setHandle(SwooleG.main_reactor, PHP_SWOOLE_FD_MYSQL | SW_EVENT_READ, swoole_mysql_onRead);
        SwooleG.main_reactor->setHandle(SwooleG.main_reactor, PHP_SWOOLE_FD_MYSQL | SW_EVENT_ERROR, swoole_mysql_onError);
    }

    swConnection *socket = swReactor_get(SwooleG.main_reactor, cli->socket->fd);
    socket->active = 1;
    socket->object = client;
}
Example #19
0
/* {{{ proto int Aerospike::info( string request, string &response [, array host [, array options ]] )
    Sends an info command to a cluster node */
PHP_METHOD(Aerospike, info)
{
	as_error err;
	as_error_init(&err);
	reset_client_error(getThis());

	char* request = NULL;
	size_t request_len;
	zval* response_zval = NULL;
	zval* z_policy = NULL;

	as_host* host = NULL;
	char* host_str = NULL;
	uint16_t port_number;

	char* response_str = NULL;
	HashTable* destination_host = NULL;
	zval* host_zval = NULL;
	zval* port_zval = NULL;

	as_policy_info info_policy;
	as_policy_info* info_policy_p = NULL;
	AerospikeClient* php_client = NULL;
	aerospike* as_client = NULL;

	if (check_object_and_connection(getThis(), &err) != AEROSPIKE_OK) {
		update_client_error(getThis(), err.code, err.message, err.in_doubt);
		RETURN_LONG(err.code);
	}
	php_client = get_aerospike_from_zobj(Z_OBJ_P(getThis()));
	as_client = php_client->as_client;

	host = (as_host *)as_vector_get(as_client->config.hosts, 0);
	host_str = host->name;
	port_number = host->port;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz/|h!z",
			&request, &request_len,
			&response_zval, &destination_host,
			&z_policy) == FAILURE) {
		update_client_error(getThis(),AEROSPIKE_ERR_PARAM, "Invalid arguments to info", false);
		RETURN_LONG(AEROSPIKE_ERR_PARAM);
	}
	/* Cleanup any thing held by the return parameter */
	zval_dtor(response_zval);
	ZVAL_NULL(response_zval);

	if (z_policy){
		if (zval_to_as_policy_info(z_policy, &info_policy,
				&info_policy_p, &as_client->config.policies.info) != AEROSPIKE_OK) {
			update_client_error(getThis(), AEROSPIKE_ERR_PARAM, "Invalid policy.", false);
			RETURN_LONG(AEROSPIKE_ERR_PARAM);
		}
		info_policy_p = &info_policy;
	}

//	addr hostname or IP of the node
//	port
	/* This should be of the form ['addr'=>'hostname', 'port'=>3000] */
	if (destination_host) {
		host_zval = zend_hash_str_find(destination_host, "addr", strlen("addr"));
		if (!host_zval) {
			as_error_update(&err, AEROSPIKE_ERR_PARAM, "Host entry must contain an addr");
			goto CLEANUP;
		}
		if (Z_TYPE_P(host_zval) != IS_STRING) {
			as_error_update(&err, AEROSPIKE_ERR_PARAM, "addr entry must be a string");
			goto CLEANUP;
		}
		host_str = Z_STRVAL_P(host_zval);

		port_zval = zend_hash_str_find(destination_host, "port", strlen("port"));
		if (!port_zval) {
			as_error_update(&err, AEROSPIKE_ERR_PARAM, "Host entry must contain a port");
			goto CLEANUP;
		}
		if (Z_TYPE_P(port_zval) != IS_LONG) {
			as_error_update(&err, AEROSPIKE_ERR_PARAM, "port entry must be an integer");
			goto CLEANUP;
		}
		port_number = (uint16_t)Z_LVAL_P(port_zval);
	}

	if (aerospike_info_host(as_client, &err, info_policy_p, host_str, port_number, request, &response_str)
			!= AEROSPIKE_OK) {
		goto CLEANUP;
	}
	/* It is possible that an empty response will be returned, so only setup the return
	 * if we get one back.
	 */
	if (response_str) {
		ZVAL_STRING(response_zval, response_str);
	}

CLEANUP:
	if (err.code != AEROSPIKE_OK) {
		update_client_error(getThis(), err.code, err.message, err.in_doubt);
	}
	if (response_str) {
		free(response_str);
	}
	RETURN_LONG(err.code);
}
Example #20
0
/**
 * Initialize the metadata for certain table
 *
 * @param Phalcon\Mvc\ModelInterface $model
 * @param string $key
 * @param string $table
 * @param string $schema
 */
PHP_METHOD(Phalcon_Mvc_Model_MetaData, _initialize){

	zval *model, *key, *table, *schema, *strategy = NULL, *class_name;
	zval *meta_data = NULL, *prefix_key = NULL, *data = NULL, *model_metadata = NULL;
	zval *exception_message, *dependency_injector = NULL;
	zval *key_name, *column_map = NULL, *model_column_map;

	PHALCON_MM_GROW();

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzzz", &model, &key, &table, &schema) == FAILURE) {
		RETURN_MM_NULL();
	}

	PHALCON_INIT_VAR(strategy);
	
	PHALCON_INIT_VAR(class_name);
	phalcon_get_class(class_name, model, 0 TSRMLS_CC);
	if (Z_TYPE_P(key) != IS_NULL) {
	
		PHALCON_OBS_VAR(meta_data);
		phalcon_read_property(&meta_data, this_ptr, SL("_metaData"), PH_NOISY_CC);
		if (!phalcon_array_isset(meta_data, key)) {
	
			PHALCON_INIT_VAR(prefix_key);
			PHALCON_CONCAT_SV(prefix_key, "meta-", key);
	
			/** 
			 * The meta-data is read from the adapter always
			 */
			PHALCON_INIT_VAR(data);
			PHALCON_CALL_METHOD_PARAMS_1(data, this_ptr, "read", prefix_key);
			if (Z_TYPE_P(data) != IS_NULL) {
				if (Z_TYPE_P(meta_data) != IS_ARRAY) { 
					PHALCON_INIT_NVAR(meta_data);
					array_init(meta_data);
				}
				phalcon_array_update_zval(&meta_data, key, &data, PH_COPY | PH_SEPARATE TSRMLS_CC);
				phalcon_update_property_zval(this_ptr, SL("_metaData"), meta_data TSRMLS_CC);
			} else {
				/** 
				 * Check if there is a method 'metaData' in the model to retrieve meta-data from it
				 */
				if (phalcon_method_exists_ex(model, SS("metadata") TSRMLS_CC) == SUCCESS) {
	
					PHALCON_INIT_VAR(model_metadata);
					PHALCON_CALL_METHOD(model_metadata, model, "metadata");
					if (Z_TYPE_P(model_metadata) != IS_ARRAY) { 
						PHALCON_INIT_VAR(exception_message);
						PHALCON_CONCAT_SV(exception_message, "Invalid meta-data for model ", class_name);
						PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message);
						return;
					}
				} else {
					PHALCON_OBS_VAR(dependency_injector);
					phalcon_read_property(&dependency_injector, this_ptr, SL("_dependencyInjector"), PH_NOISY_CC);
	
					/** 
					 * Get the meta-data extraction strategy
					 */
					PHALCON_CALL_METHOD(strategy, this_ptr, "getstrategy");
	
					/** 
					 * Get the meta-data
					 */
					PHALCON_INIT_NVAR(model_metadata);
					PHALCON_CALL_METHOD_PARAMS_2(model_metadata, strategy, "getmetadata", model, dependency_injector);
				}
	
				/** 
				 * Store the meta-data locally
				 */
				phalcon_update_property_array(this_ptr, SL("_metaData"), key, model_metadata TSRMLS_CC);
	
				/** 
				 * Store the meta-data in the adapter
				 */
				PHALCON_CALL_METHOD_PARAMS_2_NORETURN(this_ptr, "write", prefix_key, model_metadata);
			}
		}
	}
	
	/** 
	 * Check for a column map, store in _columnMap in order and reversed order
	 */
	if (!PHALCON_GLOBAL(orm).column_renaming) {
		RETURN_MM_NULL();
	}
	
	PHALCON_INIT_VAR(key_name);
	phalcon_fast_strtolower(key_name, class_name);
	
	PHALCON_OBS_VAR(column_map);
	phalcon_read_property(&column_map, this_ptr, SL("_columnMap"), PH_NOISY_CC);
	if (phalcon_array_isset(column_map, key_name)) {
		RETURN_MM_NULL();
	}
	
	if (Z_TYPE_P(column_map) != IS_ARRAY) { 
		PHALCON_INIT_NVAR(column_map);
		array_init(column_map);
	}
	
	/** 
	 * Create the map key name
	 */
	PHALCON_INIT_NVAR(prefix_key);
	PHALCON_CONCAT_SV(prefix_key, "map-", key_name);
	
	/** 
	 * Check if the meta-data is already in the adapter
	 */
	PHALCON_INIT_NVAR(data);
	PHALCON_CALL_METHOD_PARAMS_1(data, this_ptr, "read", prefix_key);
	if (Z_TYPE_P(data) != IS_NULL) {
		phalcon_array_update_zval(&column_map, key_name, &data, PH_COPY | PH_SEPARATE TSRMLS_CC);
		phalcon_update_property_zval(this_ptr, SL("_columnMap"), column_map TSRMLS_CC);
		RETURN_MM_NULL();
	}
	
	/** 
	 * Get the meta-data extraction strategy
	 */
	if (Z_TYPE_P(strategy) != IS_OBJECT) {
		PHALCON_OBS_NVAR(dependency_injector);
		phalcon_read_property(&dependency_injector, this_ptr, SL("_dependencyInjector"), PH_NOISY_CC);
	
		PHALCON_INIT_NVAR(strategy);
		PHALCON_CALL_METHOD(strategy, this_ptr, "getstrategy");
	}
	
	/** 
	 * Get the meta-data
	 */
	PHALCON_INIT_VAR(model_column_map);
	PHALCON_CALL_METHOD_PARAMS_2(model_column_map, strategy, "getcolumnmaps", model, dependency_injector);
	
	/** 
	 * Update the column map locally
	 */
	phalcon_update_property_array(this_ptr, SL("_columnMap"), key_name, model_column_map TSRMLS_CC);
	
	/** 
	 * Write the data to the adapter
	 */
	PHALCON_CALL_METHOD_PARAMS_2_NORETURN(this_ptr, "write", prefix_key, model_column_map);
	
	PHALCON_MM_RESTORE();
}
Example #21
0
YRMCDS_METHOD(Client, __construct) {
    char* node;
    size_t node_len;
    long port = 11211;
    char* persist_id = NULL;
    size_t persist_id_len = 0;
    char* prefix = NULL;
    size_t prefix_len = 0;

    zval* objptr = getThis();
    if( ! objptr ) {
        php_error(E_ERROR, "Constructor called statically!");
        RETURN_FALSE;
    }

    if( zend_parse_parameters(ZEND_NUM_ARGS(), "s|ls!s!",
                              &node, &node_len, &port,
                              &persist_id, &persist_id_len,
                              &prefix, &prefix_len) == FAILURE ) {
        php_error(E_ERROR, "Invalid argument");
        RETURN_FALSE;
    }

    yrmcds_client_object* obj = YRMCDS_CLIENT_OBJECT_P(objptr);
    if( persist_id_len > 0 ) {
        size_t hash_key_len = 7 + persist_id_len;
        char* hash_key = alloca(hash_key_len);
        memcpy(hash_key, "yrmcds:", 7);
        memcpy(hash_key+7, persist_id, persist_id_len);

        yrmcds_error err = YRMCDS_OK;
        yrmcds_status status = YRMCDS_STATUS_OK;
        uepc_status s = use_existing_persistent_connection(
            hash_key, hash_key_len, &obj->conn, &err, &status);
        if( s == UEPC_BROKEN_AND_OCCUPIED ) {
            // Since the persistent connection is broken and used by other client,
            // we cannot destruct the connection.
            // Therefore, we throw exception and return.
            CHECK_YRMCDS(err);
            zend_throw_exception_ex(ce_yrmcds_error,
                                    PHP_YRMCDS_UNEXPECTED_RESPONSE,
                                    "yrmcds: unexpected response (%d)", status);
            RETURN_FALSE;
        }
        if( s == UEPC_NOT_FOUND || s == UEPC_BROKEN ) {
            // There are no persistent connections with the given ID, or
            // there is a broken persistent connection with the given ID and
            // no one use it.
            // Therefore, we create new persistent connection with the given ID.
            php_yrmcds_t* c = pemalloc(sizeof(php_yrmcds_t), 1);
            c->pkey = pemalloc(hash_key_len, 1);
            c->pkey_len = hash_key_len;
            memcpy(c->pkey, hash_key, hash_key_len);
            c->reference_count = 1;
            CHECK_YRMCDS( yrmcds_connect(&c->res, node, (uint16_t)port) );
            CHECK_YRMCDS( yrmcds_set_compression(
                              &c->res, (size_t)YRMCDS_G(compression_threshold)) );
            CHECK_YRMCDS( yrmcds_set_timeout(
                              &c->res, (int)YRMCDS_G(default_timeout)) );
            obj->conn = c;
            zend_resource le;
            le.type = le_yrmcds;
            le.ptr = c;
            GC_REFCOUNT(&le) = 1;
            zend_hash_str_update_mem(&EG(persistent_list),
                                     hash_key, hash_key_len, &le, sizeof(le));
            // There is no need to free the return value of the above function
            // as plist_entry_destructor defined in Zend/zend_list.c does
            // it automatically.
        }
        // If s == UEPC_OK, we can use the returned presistent connection.
    } else {
        php_yrmcds_t* c = ecalloc(1, sizeof(php_yrmcds_t));
        c->reference_count = 1;
        CHECK_YRMCDS( yrmcds_connect(&c->res, node, (uint16_t)port) );
        CHECK_YRMCDS( yrmcds_set_compression(
                          &c->res, (size_t)YRMCDS_G(compression_threshold)) );
        CHECK_YRMCDS( yrmcds_set_timeout(
                          &c->res, (int)YRMCDS_G(default_timeout)) );
        obj->conn = c;
    }
    if( prefix_len > 0 )
        obj->prefix = zend_string_init(prefix, prefix_len, 0);
}
Example #22
0
/* {{{ */
static void datefmt_ctor(INTERNAL_FUNCTION_PARAMETERS)
{
	zval		*object;

	const char	*locale_str;
	int			locale_len		= 0;
	Locale		locale;
    zend_long		date_type		= 0;
    zend_long		time_type		= 0;
	zval		*calendar_zv	= NULL;
	Calendar	*calendar		= NULL;
	zend_long		calendar_type;
	bool		calendar_owned;
	zval		*timezone_zv	= NULL;
	TimeZone	*timezone		= NULL;
	bool		explicit_tz;
    char*       pattern_str		= NULL;
    int         pattern_str_len	= 0;
    UChar*      svalue			= NULL;		/* UTF-16 pattern_str */
    int         slength			= 0;
	IntlDateFormatter_object* dfo;

	intl_error_reset(NULL TSRMLS_CC);
	object = return_value;
	/* Parse parameters. */
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sll|zzs",
			&locale_str, &locale_len, &date_type, &time_type, &timezone_zv,
			&calendar_zv, &pattern_str, &pattern_str_len) == FAILURE) {
		intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,	"datefmt_create: "
				"unable to parse input parameters", 0 TSRMLS_CC);
		Z_OBJ_P(return_value) = NULL;
		return;
    }

	INTL_CHECK_LOCALE_LEN_OBJ(locale_len, return_value);
	if (locale_len == 0) {
		locale_str = intl_locale_get_default(TSRMLS_C);
	}
	locale = Locale::createFromName(locale_str);

	DATE_FORMAT_METHOD_FETCH_OBJECT_NO_CHECK;

	if (DATE_FORMAT_OBJECT(dfo) != NULL) {
		intl_errors_set(INTL_DATA_ERROR_P(dfo), U_ILLEGAL_ARGUMENT_ERROR,
				"datefmt_create: cannot call constructor twice", 0 TSRMLS_CC);
		return;
	}

	/* process calendar */
	if (datefmt_process_calendar_arg(calendar_zv, locale, "datefmt_create",
			INTL_DATA_ERROR_P(dfo), calendar, calendar_type,
			calendar_owned TSRMLS_CC)
			== FAILURE) {
		goto error;
	}

	/* process timezone */
	explicit_tz = timezone_zv != NULL && Z_TYPE_P(timezone_zv) != IS_NULL;

	if (explicit_tz || calendar_owned ) {
		//we have an explicit time zone or a non-object calendar
		timezone = timezone_process_timezone_argument(timezone_zv,
				INTL_DATA_ERROR_P(dfo), "datefmt_create" TSRMLS_CC);
		if (timezone == NULL) {
			goto error;
		}
	}

	/* Convert pattern (if specified) to UTF-16. */
	if (pattern_str && pattern_str_len > 0) {
		intl_convert_utf8_to_utf16(&svalue, &slength,
				pattern_str, pattern_str_len, &INTL_DATA_ERROR_CODE(dfo));
		if (U_FAILURE(INTL_DATA_ERROR_CODE(dfo))) {
			/* object construction -> only set global error */
			intl_error_set(NULL, INTL_DATA_ERROR_CODE(dfo), "datefmt_create: "
					"error converting pattern to UTF-16", 0 TSRMLS_CC);
			goto error;
		}
	}

	if (pattern_str && pattern_str_len > 0) {
		DATE_FORMAT_OBJECT(dfo) = udat_open(UDAT_IGNORE, UDAT_IGNORE,
				locale_str, NULL, 0, svalue, slength,
				&INTL_DATA_ERROR_CODE(dfo));
	} else {
		DATE_FORMAT_OBJECT(dfo) = udat_open((UDateFormatStyle)time_type,
				(UDateFormatStyle)date_type, locale_str, NULL, 0, svalue,
				slength, &INTL_DATA_ERROR_CODE(dfo));
	}

    if (!U_FAILURE(INTL_DATA_ERROR_CODE(dfo))) {
		DateFormat *df = (DateFormat*)DATE_FORMAT_OBJECT(dfo);
		if (calendar_owned) {
			df->adoptCalendar(calendar);
			calendar_owned = false;
		} else {
			df->setCalendar(*calendar);
		}

		if (timezone != NULL) {
			df->adoptTimeZone(timezone);
		}
    } else {
		intl_error_set(NULL, INTL_DATA_ERROR_CODE(dfo),	"datefmt_create: date "
				"formatter creation failed", 0 TSRMLS_CC);
		goto error;
	}

	/* Set the class variables */
	dfo->date_type			= date_type;
	dfo->time_type			= time_type;
	dfo->calendar			= calendar_type;
	dfo->requested_locale	= estrdup(locale_str);

error:
	if (svalue) {
		efree(svalue);
	}
	if (timezone != NULL && DATE_FORMAT_OBJECT(dfo) == NULL) {
		delete timezone;
	}
	if (calendar != NULL && calendar_owned) {
		delete calendar;
	}
	if (U_FAILURE(intl_error_get_code(NULL TSRMLS_CC))) {
		/* free_object handles partially constructed instances fine */
		Z_OBJ_P(return_value) = NULL;
	}
}
Example #23
0
PHP_METHOD(swoole_lock, __construct)
{
	long type = SW_MUTEX;
	char *filelock;
	int filelock_len = 0;
	int ret;

#ifdef ZTS
	if(sw_thread_ctx == NULL)
	{
		TSRMLS_SET_CTX(sw_thread_ctx);
	}
#endif

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ls", &type, &filelock, &filelock_len) == FAILURE)
	{
		RETURN_FALSE;
	}
	swLock *lock = SwooleG.memory_pool->alloc(SwooleG.memory_pool, sizeof(swLock));
	if (lock == NULL)
	{
	    php_error_docref(NULL TSRMLS_CC, E_WARNING, "alloc failed.");
		RETURN_FALSE;
	}

	switch(type)
	{
	case SW_RWLOCK:
		ret = swRWLock_create(lock, 1);
		break;
	case SW_FILELOCK:
		if (filelock_len <= 0)
		{
		    php_error_docref(NULL TSRMLS_CC, E_ERROR, "filelock require lock file name.");
			RETURN_FALSE;
		}
		int fd;
		if ((fd = open(filelock, O_RDWR | O_CREAT, 0666)) < 0)
		{
		    php_error_docref(NULL TSRMLS_CC, E_WARNING, "open file[%s] failed. Error: %s [%d]", filelock, strerror(errno), errno);
			RETURN_FALSE;
		}
		ret = swFileLock_create(lock, fd);
		break;
	case SW_SEM:
		ret = swSem_create(lock, IPC_PRIVATE, 1);
		break;
#ifdef HAVE_SPINLOCK
	case SW_SPINLOCK:
		ret = swSpinLock_create(lock, 1);
		break;
#endif
	case SW_MUTEX:
	default:
		ret = swMutex_create(lock, 1);
		break;
	}
	if (ret < 0)
	{
	    php_error_docref(NULL TSRMLS_CC, E_WARNING, "create lock failed");
		RETURN_FALSE;
	}
	zval *zres;
	MAKE_STD_ZVAL(zres);

	ZEND_REGISTER_RESOURCE(zres, lock, le_swoole_lock);
	zend_update_property(swoole_lock_class_entry_ptr, getThis(), ZEND_STRL("_lock"), zres TSRMLS_CC);

	zval_ptr_dtor(&zres);
	RETURN_TRUE;
}
static PHP_METHOD(swoole_coroutine_util, create)
{
    zval *callback;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &callback) == FAILURE)
    {
        return;
    }

    sw_zval_add_ref(&callback);
    callback = sw_zval_dup(callback);

    char *func_name = NULL;
    zend_fcall_info_cache *func_cache = emalloc(sizeof(zend_fcall_info_cache));
    if (!sw_zend_is_callable_ex(callback, NULL, 0, &func_name, NULL, func_cache, NULL TSRMLS_CC))
    {
        swoole_php_fatal_error(E_ERROR, "Function '%s' is not callable", func_name);
        sw_zval_free(callback);
        efree(func_name);
        return;
    }
    efree(func_name);

    php_swoole_check_reactor();

    if (swReactorCheckPoint == NULL)
    {
        coro_init(TSRMLS_C);
    }

    zval *retval = NULL;
    zval *args[1];

    jmp_buf *prev_checkpoint = swReactorCheckPoint;
    swReactorCheckPoint = emalloc(sizeof(jmp_buf));

    php_context *cxt = emalloc(sizeof(php_context));
    coro_save(cxt);
    int ret = coro_create(func_cache, args, 0, &retval, NULL, NULL);
    efree(func_cache);
    efree(swReactorCheckPoint);

    if (ret < 0)
    {
        sw_zval_free(callback);
        RETURN_FALSE;
    }
    //save callback
    COROG.current_coro->function = callback;

    swReactorCheckPoint = prev_checkpoint;
    coro_resume_parent(cxt, retval, retval);
    efree(cxt);
    if (EG(exception))
    {
        zend_exception_error(EG(exception), E_ERROR TSRMLS_CC);
    }
    if (retval != NULL)
    {
        sw_zval_ptr_dtor(&retval);
    }
    RETURN_TRUE;
}
Example #25
0
File: tag.c Project: meibk/cphalcon
/**
 * Builds a HTML A tag using framework conventions
 *
 * <code>echo Phalcon\Tag::linkTo('signup/register', 'Register Here!')</code>
 *
 * @param array $parameters
 * @return string
 */
PHP_METHOD(Phalcon_Tag, linkTo){

	zval *parameters = NULL, *text = NULL, *params = NULL, *action = NULL, *url = NULL, *internal_url = NULL;
	zval *code = NULL, *value = NULL, *key = NULL, *attribute = NULL;
	zval *r0 = NULL;
	HashTable *ah0;
	HashPosition hp0;
	zval **hd;
	char *hash_index;
	uint hash_index_len;
	ulong hash_num;
	int hash_type;
	int eval_int;

	PHALCON_MM_GROW();
	
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &parameters, &text) == FAILURE) {
		PHALCON_MM_RESTORE();
		RETURN_NULL();
	}

	if (!text) {
		PHALCON_ALLOC_ZVAL_MM(text);
		ZVAL_NULL(text);
	} else {
		PHALCON_SEPARATE_PARAM(text);
	}
	
	if (Z_TYPE_P(parameters) != IS_ARRAY) { 
		PHALCON_INIT_VAR(params);
		array_init(params);
		phalcon_array_append(&params, parameters, PH_SEPARATE TSRMLS_CC);
		phalcon_array_append(&params, text, PH_SEPARATE TSRMLS_CC);
	} else {
		PHALCON_CPY_WRT(params, parameters);
	}
	
	PHALCON_INIT_VAR(action);
	ZVAL_STRING(action, "", 1);
	eval_int = phalcon_array_isset_long(params, 0);
	if (eval_int) {
		PHALCON_INIT_VAR(action);
		phalcon_array_fetch_long(&action, params, 0, PH_NOISY_CC);
	} else {
		eval_int = phalcon_array_isset_string(params, SL("action")+1);
		if (eval_int) {
			PHALCON_INIT_VAR(action);
			phalcon_array_fetch_string(&action, params, SL("action"), PH_NOISY_CC);
			PHALCON_SEPARATE(params);
			phalcon_array_unset_string(params, SL("action")+1);
		}
	}
	
	PHALCON_INIT_VAR(text);
	ZVAL_STRING(text, "", 1);
	eval_int = phalcon_array_isset_long(params, 1);
	if (eval_int) {
		PHALCON_INIT_VAR(text);
		phalcon_array_fetch_long(&text, params, 1, PH_NOISY_CC);
	} else {
		eval_int = phalcon_array_isset_string(params, SL("text")+1);
		if (eval_int) {
			PHALCON_INIT_VAR(text);
			phalcon_array_fetch_string(&text, params, SL("text"), PH_NOISY_CC);
			PHALCON_SEPARATE(params);
			phalcon_array_unset_string(params, SL("text")+1);
		}
	}
	
	PHALCON_INIT_VAR(url);
	PHALCON_CALL_SELF(url, this_ptr, "geturlservice");
	
	PHALCON_INIT_VAR(internal_url);
	PHALCON_CALL_METHOD_PARAMS_1(internal_url, url, "get", action, PH_NO_CHECK);
	
	PHALCON_INIT_VAR(code);
	PHALCON_CONCAT_SVS(code, "<a href=\"", internal_url, "\"");
	if (!phalcon_valid_foreach(params TSRMLS_CC)) {
		return;
	}
	
	ah0 = Z_ARRVAL_P(params);
	zend_hash_internal_pointer_reset_ex(ah0, &hp0);
	fes_9b93_1:
		if(zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) != SUCCESS){
			goto fee_9b93_1;
		}
		
		PHALCON_INIT_VAR(key);
		PHALCON_GET_FOREACH_KEY(key, ah0, hp0);
		PHALCON_INIT_VAR(value);
		ZVAL_ZVAL(value, *hd, 1, 0);
		if (Z_TYPE_P(key) != IS_LONG) {
			PHALCON_INIT_VAR(attribute);
			PHALCON_CONCAT_SVSVS(attribute, " ", key, "=\"", value, "\"");
			phalcon_concat_self(&code, attribute TSRMLS_CC);
		}
		zend_hash_move_forward_ex(ah0, &hp0);
		goto fes_9b93_1;
	fee_9b93_1:
	
	PHALCON_ALLOC_ZVAL_MM(r0);
	PHALCON_CONCAT_SVS(r0, ">", text, "</a>");
	phalcon_concat_self(&code, r0 TSRMLS_CC);
	
	RETURN_CTOR(code);
}
Example #26
0
static void _timecop_gettimeofday(INTERNAL_FUNCTION_PARAMETERS, int mode)
{
	zend_bool get_as_float = 0;
	long fixed_sec = 0, fixed_usec = 0;

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

	switch (TIMECOP_G(timecop_mode)) {
	case TIMECOP_MODE_FREEZE:
		fixed_sec = TIMECOP_G(freezed_timestamp);
		fixed_usec = 0;
		break;
	case TIMECOP_MODE_TRAVEL:
		{
			zval timeofday, *zv_sec, *zv_usec;
			timecop_call_orig_method_with_0_params(NULL, NULL, NULL, "gettimeofday", &timeofday);
			zv_sec = zend_hash_str_find(Z_ARR(timeofday), "sec", sizeof("sec")-1);
			if (zv_sec) {
				fixed_sec = Z_LVAL_P(zv_sec) + TIMECOP_G(travel_offset);
			}
			zv_usec = zend_hash_str_find(Z_ARR(timeofday), "usec", sizeof("usec")-1);
			if (zv_sec) {
				fixed_usec = Z_LVAL_P(zv_usec);
			}
			zval_ptr_dtor(&timeofday);
		}
		break;
	default:
		{
			const char *func_name;
			size_t func_name_len;
			zval *arg1 = NULL, tmp;
			int param_count = 0;

			if (mode) {
				func_name = ORIG_FUNC_NAME("gettimeofday");
				func_name_len = ORIG_FUNC_NAME_SIZEOF("gettimeofday")-1;
			} else {
				func_name = ORIG_FUNC_NAME("microtime");
				func_name_len = ORIG_FUNC_NAME_SIZEOF("microtime")-1;
			}
			if (get_as_float) {
				ZVAL_TRUE(&tmp);
				arg1 = &tmp;
				param_count = 1;
			}
			zend_call_method(NULL, NULL, NULL, func_name, func_name_len, return_value, param_count, arg1, NULL);
			return;
		}
	}

	if (get_as_float) {
		RETURN_DOUBLE((double)(fixed_sec + fixed_usec / MICRO_IN_SEC));
	}
	if (mode) {
		zval zv_offset, zv_dst, format, timestamp;
		long offset = 0, is_dst = 0;

		ZVAL_LONG(&timestamp, fixed_sec);

		/* offset */
		ZVAL_STRING(&format, "Z");
		timecop_call_orig_method_with_2_params(NULL, NULL, NULL, "date", &zv_offset, &format, &timestamp);
		convert_to_long(&zv_offset);
		offset = Z_LVAL(zv_offset);
		zval_ptr_dtor(&zv_offset);
		zval_ptr_dtor(&format);

		/* is_dst */
		ZVAL_STRING(&format, "I");
		timecop_call_orig_method_with_2_params(NULL, NULL, NULL, "date", &zv_dst, &format, &timestamp);
		convert_to_long(&zv_dst);
		is_dst = Z_LVAL(zv_dst);
		zval_ptr_dtor(&zv_dst);
		zval_ptr_dtor(&format);

		array_init(return_value);
		add_assoc_long(return_value, "sec", fixed_sec);
		add_assoc_long(return_value, "usec", fixed_usec);
		add_assoc_long(return_value, "minuteswest", -offset / SEC_IN_MIN);
		add_assoc_long(return_value, "dsttime", is_dst);
	} else {
		char ret[100];
		snprintf(ret, 100, "%.8F %ld", fixed_usec / MICRO_IN_SEC, fixed_sec);
		RETURN_STRING(ret);
	}
}
Example #27
0
File: tag.c Project: meibk/cphalcon
/**
 * Builds a HTML TEXTAREA tag
 *
 * <code>echo Phalcon\Tag::textArea(array("comments", "cols" => 10, "rows" => 4))</code>
 *
 * @param array $parameters
 * @return string
 */
PHP_METHOD(Phalcon_Tag, textArea){

	zval *parameters = NULL, *params = NULL, *id = NULL, *name = NULL, *content = NULL, *code = NULL;
	zval *avalue = NULL, *key = NULL, *attribute = NULL, *end_code = NULL;
	zval *r0 = NULL;
	HashTable *ah0;
	HashPosition hp0;
	zval **hd;
	char *hash_index;
	uint hash_index_len;
	ulong hash_num;
	int hash_type;
	int eval_int;

	PHALCON_MM_GROW();
	
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &parameters) == FAILURE) {
		PHALCON_MM_RESTORE();
		RETURN_NULL();
	}

	if (Z_TYPE_P(parameters) != IS_ARRAY) { 
		PHALCON_INIT_VAR(params);
		array_init(params);
		phalcon_array_append(&params, parameters, PH_SEPARATE TSRMLS_CC);
	} else {
		PHALCON_CPY_WRT(params, parameters);
	}
	eval_int = phalcon_array_isset_long(params, 0);
	if (!eval_int) {
		PHALCON_ALLOC_ZVAL_MM(r0);
		phalcon_array_fetch_string(&r0, params, SL("id"), PH_NOISY_CC);
		phalcon_array_update_long(&params, 0, &r0, PH_COPY | PH_SEPARATE TSRMLS_CC);
	}
	
	PHALCON_INIT_VAR(id);
	phalcon_array_fetch_long(&id, params, 0, PH_NOISY_CC);
	eval_int = phalcon_array_isset_string(params, SL("name")+1);
	if (!eval_int) {
		phalcon_array_update_string(&params, SL("name"), &id, PH_COPY | PH_SEPARATE TSRMLS_CC);
	} else {
		PHALCON_INIT_VAR(name);
		phalcon_array_fetch_string(&name, params, SL("name"), PH_NOISY_CC);
		if (!zend_is_true(name)) {
			phalcon_array_update_string(&params, SL("name"), &id, PH_COPY | PH_SEPARATE TSRMLS_CC);
		}
	}
	
	eval_int = phalcon_array_isset_string(params, SL("id")+1);
	if (!eval_int) {
		phalcon_array_update_string(&params, SL("id"), &id, PH_COPY | PH_SEPARATE TSRMLS_CC);
	}
	
	eval_int = phalcon_array_isset_string(params, SL("value")+1);
	if (eval_int) {
		PHALCON_INIT_VAR(content);
		phalcon_array_fetch_string(&content, params, SL("value"), PH_NOISY_CC);
		PHALCON_SEPARATE(params);
		phalcon_array_unset_string(params, SL("value")+1);
	} else {
		PHALCON_INIT_VAR(content);
		PHALCON_CALL_SELF_PARAMS_1(content, this_ptr, "getvalue", id);
	}
	
	PHALCON_INIT_VAR(code);
	ZVAL_STRING(code, "<textarea ", 1);
	if (!phalcon_valid_foreach(params TSRMLS_CC)) {
		return;
	}
	
	ah0 = Z_ARRVAL_P(params);
	zend_hash_internal_pointer_reset_ex(ah0, &hp0);
	fes_9b93_4:
		if(zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) != SUCCESS){
			goto fee_9b93_4;
		}
		
		PHALCON_INIT_VAR(key);
		PHALCON_GET_FOREACH_KEY(key, ah0, hp0);
		PHALCON_INIT_VAR(avalue);
		ZVAL_ZVAL(avalue, *hd, 1, 0);
		if (Z_TYPE_P(key) != IS_LONG) {
			PHALCON_INIT_VAR(attribute);
			PHALCON_CONCAT_VSVS(attribute, key, "=\"", avalue, "\" ");
			phalcon_concat_self(&code, attribute TSRMLS_CC);
		}
		zend_hash_move_forward_ex(ah0, &hp0);
		goto fes_9b93_4;
	fee_9b93_4:
	
	PHALCON_INIT_VAR(end_code);
	PHALCON_CONCAT_SVS(end_code, ">", content, "</textarea>");
	phalcon_concat_self(&code, end_code TSRMLS_CC);
	
	RETURN_CTOR(code);
}
Example #28
0
/**
 * Replaces placeholders from pattern returning a valid PCRE regular expression
 *
 * @param string $pattern
 * @return string
 */
PHP_METHOD(Phalcon_Mvc_Router, compilePattern){

	zval *pattern = NULL, *id_pattern = NULL, *compiled_pattern = NULL;
	zval *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *r4 = NULL;
	zval *c0 = NULL, *c1 = NULL, *c2 = NULL, *c3 = NULL, *c4 = NULL, *c5 = NULL, *c6 = NULL;

	PHALCON_MM_GROW();
	
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &pattern) == FAILURE) {
		PHALCON_MM_RESTORE();
		RETURN_NULL();
	}

	PHALCON_INIT_VAR(id_pattern);
	ZVAL_STRING(id_pattern, "/([a-zA-Z0-9\\_]+)", 1);
	
	PHALCON_ALLOC_ZVAL_MM(r0);
	phalcon_fast_strpos_str(r0, pattern, SL(":") TSRMLS_CC);
	if (zend_is_true(r0)) {
		PHALCON_INIT_VAR(c0);
		ZVAL_STRING(c0, "/:module", 1);
		PHALCON_INIT_VAR(compiled_pattern);
		phalcon_fast_str_replace(compiled_pattern, c0, id_pattern, pattern TSRMLS_CC);
		
		PHALCON_INIT_VAR(c1);
		ZVAL_STRING(c1, "/:controller", 1);
		
		PHALCON_INIT_VAR(compiled_pattern);
		phalcon_fast_str_replace(compiled_pattern, c1, id_pattern, pattern TSRMLS_CC);
		
		PHALCON_INIT_VAR(c2);
		ZVAL_STRING(c2, "/:action", 1);
		
		PHALCON_ALLOC_ZVAL_MM(r1);
		phalcon_fast_str_replace(r1, c2, id_pattern, compiled_pattern TSRMLS_CC);
		PHALCON_CPY_WRT(compiled_pattern, r1);
		
		PHALCON_INIT_VAR(c3);
		ZVAL_STRING(c3, "/:params", 1);
		
		PHALCON_INIT_VAR(c4);
		ZVAL_STRING(c4, "(/.*)*", 1);
		
		PHALCON_ALLOC_ZVAL_MM(r2);
		phalcon_fast_str_replace(r2, c3, c4, compiled_pattern TSRMLS_CC);
		PHALCON_CPY_WRT(compiled_pattern, r2);
		
		PHALCON_INIT_VAR(c5);
		ZVAL_STRING(c5, "/:int", 1);
		
		PHALCON_INIT_VAR(c6);
		ZVAL_STRING(c6, "/([0-9]+)", 1);
		
		PHALCON_ALLOC_ZVAL_MM(r3);
		phalcon_fast_str_replace(r3, c5, c6, compiled_pattern TSRMLS_CC);
		PHALCON_CPY_WRT(compiled_pattern, r3);
	} else {
		PHALCON_CPY_WRT(compiled_pattern, pattern);
	}
	
	PHALCON_ALLOC_ZVAL_MM(r4);
	PHALCON_CONCAT_SVS(r4, "#^", compiled_pattern, "$#");
	
	RETURN_CTOR(r4);
}
Example #29
0
/**
 * Executes the validator
 *
 * @param Phalcon\Mvc\Model $record
 * @return boolean
 */
PHP_METHOD(Phalcon_Mvc_Model_Validator_Email, validate){

	zval *record, *option, *field_name, *regs, *invalid = NULL;
	zval *value, *pattern, *match_pattern, *match_zero;
	zval *type, *message;

	PHALCON_MM_GROW();

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &record) == FAILURE) {
		PHALCON_MM_RESTORE();
		RETURN_NULL();
	}

	PHALCON_INIT_VAR(option);
	ZVAL_STRING(option, "field", 1);
	
	PHALCON_INIT_VAR(field_name);
	PHALCON_CALL_METHOD_PARAMS_1(field_name, this_ptr, "getoption", option, PH_NO_CHECK);
	if (Z_TYPE_P(field_name) != IS_STRING) {
		PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Field name must be a string");
		return;
	}
	
	PHALCON_INIT_VAR(regs);
	
	PHALCON_INIT_VAR(invalid);
	ZVAL_BOOL(invalid, 0);
	
	PHALCON_INIT_VAR(value);
	PHALCON_CALL_METHOD_PARAMS_1(value, record, "readattribute", field_name, PH_NO_CHECK);
	
	PHALCON_INIT_VAR(pattern);
	ZVAL_STRING(pattern, "/^[a-zA-Z0-9\\-_\\.\\+]+@[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*$/", 1);
	Z_SET_ISREF_P(regs);
	
	PHALCON_INIT_VAR(match_pattern);
	PHALCON_CALL_FUNC_PARAMS_3(match_pattern, "preg_match", pattern, value, regs);
	Z_UNSET_ISREF_P(regs);
	if (zend_is_true(match_pattern)) {
		PHALCON_INIT_VAR(match_zero);
		phalcon_array_fetch_long(&match_zero, regs, 0, PH_NOISY_CC);
		
		is_not_equal_function(invalid, match_zero, value TSRMLS_CC);
	} else {
		ZVAL_BOOL(invalid, 1);
	}
	
	if (PHALCON_IS_TRUE(invalid)) {
		PHALCON_INIT_VAR(type);
		ZVAL_STRING(type, "email", 1);
		
		PHALCON_INIT_VAR(message);
		PHALCON_CONCAT_SVS(message, "Value of field '", field_name, "' must have a valid e-mail format");
		PHALCON_CALL_METHOD_PARAMS_3_NORETURN(this_ptr, "appendmessage", message, field_name, type, PH_NO_CHECK);
		PHALCON_MM_RESTORE();
		RETURN_FALSE;
	}
	
	PHALCON_MM_RESTORE();
	RETURN_TRUE;
}
Example #30
0
/**
 * Rollbacks the transaction
 *
 * @param  string $rollbackMessage
 * @param  Phalcon\Mvc\Model $rollbackRecord
 * @return boolean
 */
PHP_METHOD(Phalcon_Mvc_Model_Transaction, rollback){

	zval *rollback_message = NULL, *rollback_record = NULL;
	zval *manager = NULL, *call_object = NULL, *arguments = NULL, *connection = NULL;
	zval *success = NULL, *exception = NULL;

	PHALCON_MM_GROW();
	
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|zz", &rollback_message, &rollback_record) == FAILURE) {
		PHALCON_MM_RESTORE();
		RETURN_NULL();
	}

	if (!rollback_message) {
		PHALCON_ALLOC_ZVAL_MM(rollback_message);
		ZVAL_NULL(rollback_message);
	} else {
		PHALCON_SEPARATE_PARAM(rollback_message);
	}
	
	if (!rollback_record) {
		PHALCON_ALLOC_ZVAL_MM(rollback_record);
		ZVAL_NULL(rollback_record);
	} else {
		PHALCON_SEPARATE_PARAM(rollback_record);
	}
	
	PHALCON_INIT_VAR(manager);
	phalcon_read_property(&manager, this_ptr, SL("_manager"), PH_NOISY_CC);
	if (zend_is_true(manager)) {
		PHALCON_INIT_VAR(call_object);
		array_init(call_object);
		phalcon_array_append(&call_object, manager, PH_SEPARATE TSRMLS_CC);
		add_next_index_stringl(call_object, SL("notifyRollback"), 1);
		
		PHALCON_INIT_VAR(arguments);
		array_init(arguments);
		phalcon_array_append(&arguments, this_ptr, PH_SEPARATE TSRMLS_CC);
		PHALCON_CALL_FUNC_PARAMS_2_NORETURN("call_user_func_array", call_object, arguments);
	}
	
	PHALCON_INIT_VAR(connection);
	phalcon_read_property(&connection, this_ptr, SL("_connection"), PH_NOISY_CC);
	
	PHALCON_INIT_VAR(success);
	PHALCON_CALL_METHOD(success, connection, "rollback", PH_NO_CHECK);
	if (zend_is_true(success)) {
		if (!zend_is_true(rollback_message)) {
			PHALCON_INIT_VAR(rollback_message);
			ZVAL_STRING(rollback_message, "Transaction aborted", 1);
		}
		if (zend_is_true(rollback_record)) {
			phalcon_update_property_zval(this_ptr, SL("_rollbackRecord"), rollback_record TSRMLS_CC);
		}
		
		PHALCON_INIT_VAR(rollback_record);
		phalcon_read_property(&rollback_record, this_ptr, SL("_rollbackRecord"), PH_NOISY_CC);
		
		PHALCON_INIT_VAR(exception);
		object_init_ex(exception, phalcon_mvc_model_transaction_failed_ce);
		PHALCON_CALL_METHOD_PARAMS_2_NORETURN(exception, "__construct", rollback_message, rollback_record, PH_CHECK);
		phalcon_throw_exception(exception TSRMLS_CC);
		return;
	}
	
	PHALCON_MM_RESTORE();
}