Esempio n. 1
0
/**
 * Manually bind params to a SQL statement. This method requires an active connection to a database system
 *
 *<code>
 *	$sql = $connection->bindParams('SELECT * FROM robots WHERE name = ?0', array('Bender'));
 *  echo $sql; // SELECT * FROM robots WHERE name = 'Bender'
 *</code>
 *
 * @param string $sqlStatement
 * @param array $params
 * @return string
 */
PHP_METHOD(Phalcon_Db_Adapter_Pdo, bindParams){

	zval *sql_statement, *params, *sql = NULL, *pdo, *bind_value = NULL;
	zval *index = NULL, *value = NULL, *place_key = NULL, *replaced_sql = NULL;
	HashTable *ah0;
	HashPosition hp0;
	zval **hd;

	PHALCON_MM_GROW();

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &sql_statement, &params) == FAILURE) {
		RETURN_MM_NULL();
	}

	if (Z_TYPE_P(params) == IS_ARRAY) { 
		if (phalcon_fast_count_ev(params TSRMLS_CC)) {
			PHALCON_CPY_WRT(sql, sql_statement);
	
			PHALCON_OBS_VAR(pdo);
			phalcon_read_property(&pdo, this_ptr, SL("_pdo"), PH_NOISY_CC);
	
			if (!phalcon_is_iterable(params, &ah0, &hp0, 0, 0 TSRMLS_CC)) {
				return;
			}
	
			while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) {
	
				PHALCON_GET_FOREACH_KEY(index, ah0, hp0);
				PHALCON_GET_FOREACH_VALUE(bind_value);
	
				if (phalcon_is_numeric(bind_value)) {
					PHALCON_CPY_WRT(value, bind_value);
				} else {
					if (Z_TYPE_P(bind_value) == IS_OBJECT) {
						PHALCON_INIT_NVAR(value);
						PHALCON_CALL_FUNC_PARAMS_1(value, "strval", bind_value);
					} else {
						PHALCON_INIT_NVAR(value);
						PHALCON_CALL_METHOD_PARAMS_1(value, pdo, "quote", bind_value);
					}
				}
	
				/** 
				 * Handle long parameters as numeric placeholders: ?0, ?1
				 */
				if (Z_TYPE_P(index) == IS_LONG) {
					PHALCON_INIT_NVAR(place_key);
					PHALCON_CONCAT_SV(place_key, "?", index);
	
					PHALCON_INIT_NVAR(replaced_sql);
					phalcon_fast_str_replace(replaced_sql, place_key, value, sql TSRMLS_CC);
					PHALCON_CPY_WRT(sql, replaced_sql);
					zend_hash_move_forward_ex(ah0, &hp0);
					continue;
				}
	
				/** 
				 * Handle long parameters as string placeholders: :name:, :other:
				 */
				if (Z_TYPE_P(index) == IS_STRING) {
					PHALCON_INIT_NVAR(place_key);
					PHALCON_CONCAT_SVS(place_key, ":", index, ":");
	
					PHALCON_INIT_NVAR(replaced_sql);
					phalcon_fast_str_replace(replaced_sql, place_key, value, sql TSRMLS_CC);
					PHALCON_CPY_WRT(sql, replaced_sql);
					zend_hash_move_forward_ex(ah0, &hp0);
					continue;
				}
	
				/** 
				 * Unrecognized parameter type
				 */
				PHALCON_THROW_EXCEPTION_STR(phalcon_db_exception_ce, "Invalid bind parameter");
				return;
	
				zend_hash_move_forward_ex(ah0, &hp0);
			}
	
	
			RETURN_CCTOR(sql);
		}
	}
	
	RETURN_CCTOR(sql_statement);
}
Esempio n. 2
0
PHP_METHOD(MongoDB, command) {
  zval limit, *temp, *cmd, *cursor, *ns, *options = 0;
  mongo_db *db;
  mongo_link *link;
  char *cmd_ns;

  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|a", &cmd, &options) == FAILURE) {
    return;
  }
  if (IS_SCALAR_P(cmd)) {
    zend_error(E_WARNING, "MongoDB::command() expects parameter 1 to be an array or object");
    return;
  }

  PHP_MONGO_GET_DB(getThis());

  // create db.$cmd
  MAKE_STD_ZVAL(ns);
  cmd_ns = get_cmd_ns(Z_STRVAL_P(db->name), Z_STRLEN_P(db->name));
  ZVAL_STRING(ns, cmd_ns, 0);

  // create cursor
  MAKE_STD_ZVAL(cursor);
  object_init_ex(cursor, mongo_ce_Cursor);
  MAKE_STD_ZVAL(temp);
  ZVAL_NULL(temp);

  MONGO_METHOD3(MongoCursor, __construct, temp, cursor, db->link, ns, cmd);

  zval_ptr_dtor(&ns);
  zval_ptr_dtor(&temp);
  MAKE_STD_ZVAL(temp);
  ZVAL_NULL(temp);

  // limit
  Z_TYPE(limit) = IS_LONG;
  Z_LVAL(limit) = -1;
  MONGO_METHOD1(MongoCursor, limit, temp, cursor, &limit);

  zval_ptr_dtor(&temp);

  if (options) {
    zval **timeout;
    if (zend_hash_find(HASH_P(options), "timeout", strlen("timeout")+1, (void**)&timeout) == SUCCESS) {
      MAKE_STD_ZVAL(temp);
      ZVAL_NULL(temp);
      MONGO_METHOD1(MongoCursor, timeout, temp, cursor, *timeout);
      zval_ptr_dtor(&temp);
    }
  }

  // make sure commands aren't be sent to slaves
  PHP_MONGO_GET_LINK(db->link);
  if (link->rs) {
    zval slave_okay;
    Z_TYPE(slave_okay) = IS_BOOL;
    Z_LVAL(slave_okay) = 0;

    MAKE_STD_ZVAL(temp);
    ZVAL_NULL(temp);
    MONGO_METHOD1(MongoCursor, slaveOkay, temp, cursor, &slave_okay);
    zval_ptr_dtor(&temp);
  }

  // query
  MONGO_METHOD(MongoCursor, getNext, return_value, cursor);
  clear_exception(return_value TSRMLS_CC);

  zend_objects_store_del_ref(cursor TSRMLS_CC);
  zval_ptr_dtor(&cursor);
}
Esempio n. 3
0
/* {{{
 * common code shared by display_xyz functions to  get the value from ICU 
 }}} */
static void get_icu_disp_value_src_php( char* tag_name, INTERNAL_FUNCTION_PARAMETERS) 
{
	const char* loc_name        	= NULL;
	int         loc_name_len    	= 0;

	const char* disp_loc_name       = NULL;
	int         disp_loc_name_len   = 0;
	int         free_loc_name       = 0;

	UChar*      disp_name      	= NULL;
	int32_t     disp_name_len  	= 0;

	char*       mod_loc_name        = NULL;

	int32_t     buflen          	= 512;
	UErrorCode  status          	= U_ZERO_ERROR;

	char*       utf8value		= NULL;
	int         utf8value_len   	= 0;

  	char*       msg             	= NULL;
	int         grOffset    	= 0;

	intl_error_reset( NULL TSRMLS_CC );

	if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
		&loc_name, &loc_name_len , 
		&disp_loc_name ,&disp_loc_name_len ) == FAILURE)
	{
		spprintf(&msg , 0, "locale_get_display_%s : unable to parse input params", tag_name );
		intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,  msg , 1 TSRMLS_CC );
		efree(msg);
		RETURN_FALSE;
	}

    if(loc_name_len > ULOC_FULLNAME_CAPACITY) {
        /* See bug 67397: overlong locale names cause trouble in uloc_getDisplayName */
		spprintf(&msg , 0, "locale_get_display_%s : name too long", tag_name );
		intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,  msg , 1 TSRMLS_CC );
		efree(msg);
		RETURN_FALSE;
    }

	if(loc_name_len == 0) {
		loc_name = intl_locale_get_default(TSRMLS_C);
	}

	if( strcmp(tag_name, DISP_NAME) != 0 ){
		/* Handle grandfathered languages */
		grOffset = findOffset( LOC_GRANDFATHERED , loc_name );
		if( grOffset >= 0 ){
			if( strcmp(tag_name , LOC_LANG_TAG)==0 ){
				mod_loc_name = getPreferredTag( loc_name );
			} else {
				/* Since Grandfathered, no value, do nothing, retutn NULL */
				RETURN_FALSE;
			}
		}
	} /* end of if != LOC_CANONICAL_TAG */

	if( mod_loc_name==NULL ){
		mod_loc_name = estrdup( loc_name );
	}
	
	/* Check if disp_loc_name passed , if not use default locale */
	if( !disp_loc_name){
		disp_loc_name = estrdup(intl_locale_get_default(TSRMLS_C));
		free_loc_name = 1;
	}

    /* Get the disp_value for the given locale */
    do{
        disp_name = erealloc( disp_name , buflen * sizeof(UChar)  );
        disp_name_len = buflen;

		if( strcmp(tag_name , LOC_LANG_TAG)==0 ){
			buflen = uloc_getDisplayLanguage ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status);
		} else if( strcmp(tag_name , LOC_SCRIPT_TAG)==0 ){
			buflen = uloc_getDisplayScript ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status);
		} else if( strcmp(tag_name , LOC_REGION_TAG)==0 ){
			buflen = uloc_getDisplayCountry ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status);
		} else if( strcmp(tag_name , LOC_VARIANT_TAG)==0 ){
			buflen = uloc_getDisplayVariant ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status);
		} else if( strcmp(tag_name , DISP_NAME)==0 ){
			buflen = uloc_getDisplayName ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status);
		}

		/* U_STRING_NOT_TERMINATED_WARNING is admissible here; don't look for it */
		if( U_FAILURE( status ) )
		{
			if( status == U_BUFFER_OVERFLOW_ERROR )
			{
				status = U_ZERO_ERROR;
				continue;
			}

			spprintf(&msg, 0, "locale_get_display_%s : unable to get locale %s", tag_name , tag_name );
			intl_error_set( NULL, status, msg , 1 TSRMLS_CC );
			efree(msg);
			if( disp_name){
				efree( disp_name );
			}
			if( mod_loc_name){
				efree( mod_loc_name );
			}
			if (free_loc_name) {
				efree((void *)disp_loc_name);
				disp_loc_name = NULL;
			}
			RETURN_FALSE;
		}
	} while( buflen > disp_name_len );

	if( mod_loc_name){
		efree( mod_loc_name );
	}
	if (free_loc_name) {
		efree((void *)disp_loc_name);
		disp_loc_name = NULL;
	}
	/* Convert display locale name from UTF-16 to UTF-8. */
	intl_convert_utf16_to_utf8( &utf8value, &utf8value_len, disp_name, buflen, &status );
	efree( disp_name );
	if( U_FAILURE( status ) )
	{
		spprintf(&msg, 0, "locale_get_display_%s :error converting display name for %s to UTF-8", tag_name , tag_name );
		intl_error_set( NULL, status, msg , 1 TSRMLS_CC );
		efree(msg);
		RETURN_FALSE;
	}

	RETVAL_STRINGL( utf8value, utf8value_len , FALSE);

}
Esempio n. 4
0
/**
 * Gets the column name in PostgreSQL
 *
 * @param Phalcon\Db\Column $column
 */
PHP_METHOD(Phalcon_Db_Dialect_Postgresql, getColumnDefinition){

	zval *column = NULL, *size = NULL, *column_type = NULL, *column_sql = NULL;
	zval *scale = NULL;

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

	if (Z_TYPE_P(column) != IS_OBJECT) {
		PHALCON_THROW_EXCEPTION_STR(phalcon_db_exception_ce, "Column definition must be an instance of Phalcon\\Db\\Column");
		return;
	}
	
	PHALCON_INIT_VAR(size);
	PHALCON_CALL_METHOD(size, column, "getsize", PH_NO_CHECK);
	
	PHALCON_INIT_VAR(column_type);
	PHALCON_CALL_METHOD(column_type, column, "gettype", PH_NO_CHECK);
	
	if (phalcon_compare_strict_long(column_type, 0 TSRMLS_CC)) {
		PHALCON_INIT_VAR(column_sql);
		ZVAL_STRING(column_sql, "INT", 1);
		goto ph_end_0;
	}
	
	if (phalcon_compare_strict_long(column_type, 1 TSRMLS_CC)) {
		PHALCON_INIT_VAR(column_sql);
		ZVAL_STRING(column_sql, "DATE", 1);
		goto ph_end_0;
	}
	
	if (phalcon_compare_strict_long(column_type, 2 TSRMLS_CC)) {
		PHALCON_INIT_VAR(column_sql);
		PHALCON_CONCAT_SVS(column_sql, "CHARACTER VARYING(", size, ")");
		goto ph_end_0;
	}
	
	if (phalcon_compare_strict_long(column_type, 3 TSRMLS_CC)) {
		PHALCON_INIT_VAR(scale);
		PHALCON_CALL_METHOD(scale, column, "getscale", PH_NO_CHECK);
		
		PHALCON_INIT_VAR(column_sql);
		PHALCON_CONCAT_SVSVS(column_sql, "NUMERIC(", size, ",", scale, ")");
		goto ph_end_0;
	}
	
	if (phalcon_compare_strict_long(column_type, 4 TSRMLS_CC)) {
		PHALCON_INIT_VAR(column_sql);
		ZVAL_STRING(column_sql, "TIMESTAMP", 1);
		goto ph_end_0;
	}
	
	if (phalcon_compare_strict_long(column_type, 5 TSRMLS_CC)) {
		PHALCON_INIT_VAR(column_sql);
		PHALCON_CONCAT_SVS(column_sql, "CHARACTER(", size, ")");
		goto ph_end_0;
	}
	
	if (phalcon_compare_strict_long(column_type, 6 TSRMLS_CC)) {
		PHALCON_INIT_VAR(column_sql);
		ZVAL_STRING(column_sql, "TEXT", 1);
		goto ph_end_0;
	}
	
	if (phalcon_compare_strict_long(column_type, 7 TSRMLS_CC)) {
		PHALCON_INIT_VAR(column_sql);
		ZVAL_STRING(column_sql, "FLOAT", 1);
		goto ph_end_0;
	}
	
	PHALCON_THROW_EXCEPTION_STR(phalcon_db_exception_ce, "Unrecognized PostgreSQL data type");
	return;
	
	ph_end_0:
	
	RETURN_CTOR(column_sql);
}
static void _php_intlrbbi_constructor_body(INTERNAL_FUNCTION_PARAMETERS)
{
    zval		*object		= getThis();
    char		*rules;
    int			rules_len;
    zend_bool	compiled	= 0;
    UErrorCode	status		= U_ZERO_ERROR;
    intl_error_reset(NULL TSRMLS_CC);

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b",
                              &rules, &rules_len, &compiled) == FAILURE) {
        intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR,
                       "rbbi_create_instance: bad arguments", 0 TSRMLS_CC);
        RETURN_NULL();
    }

    // instantiation of ICU object
    RuleBasedBreakIterator *rbbi;

    if (!compiled) {
        UnicodeString	rulesStr;
        UParseError		parseError = UParseError();
        if (intl_stringFromChar(rulesStr, rules, rules_len, &status)
                == FAILURE) {
            intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR,
                           "rbbi_create_instance: rules were not a valid UTF-8 string",
                           0 TSRMLS_CC);
            RETURN_NULL();
        }

        rbbi = new RuleBasedBreakIterator(rulesStr, parseError, status);
        intl_error_set_code(NULL, status TSRMLS_CC);
        if (U_FAILURE(status)) {
            char *msg;
            smart_str parse_error_str;
            parse_error_str = intl_parse_error_to_string(&parseError);
            spprintf(&msg, 0, "rbbi_create_instance: unable to create "
                     "RuleBasedBreakIterator from rules (%s)", parse_error_str.c);
            smart_str_free(&parse_error_str);
            intl_error_set_custom_msg(NULL, msg, 1 TSRMLS_CC);
            efree(msg);
            delete rbbi;
            RETURN_NULL();
        }
    } else { // compiled
#if U_ICU_VERSION_MAJOR_NUM * 10 + U_ICU_VERSION_MINOR_NUM >= 48
        rbbi = new RuleBasedBreakIterator((uint8_t*)rules, rules_len, status);
        if (U_FAILURE(status)) {
            intl_error_set(NULL, status, "rbbi_create_instance: unable to "
                           "create instance from compiled rules", 0 TSRMLS_CC);
            delete rbbi;
            RETURN_NULL();
        }
#else
        intl_error_set(NULL, U_UNSUPPORTED_ERROR, "rbbi_create_instance: "
                       "compiled rules require ICU >= 4.8", 0 TSRMLS_CC);
        RETURN_NULL();
#endif
    }

    breakiterator_object_create(return_value, rbbi TSRMLS_CC);
}
Esempio n. 6
0
/* {{{ proto int pspell_config_create(string language [, string spelling [, string jargon [, string encoding]]])
   Create a new config to be used later to create a manager */
static PHP_FUNCTION(pspell_config_create)
{
	char *language, *spelling = NULL, *jargon = NULL, *encoding = NULL;
	size_t language_len, spelling_len = 0, jargon_len = 0, encoding_len = 0;
	zval *ind;
	PspellConfig *config;

#ifdef PHP_WIN32
	TCHAR aspell_dir[200];
	TCHAR data_dir[220];
	TCHAR dict_dir[220];
	HKEY hkey;
	DWORD dwType,dwLen;
#endif

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|sss", &language, &language_len, &spelling, &spelling_len,
		&jargon, &jargon_len, &encoding, &encoding_len) == FAILURE) {
		return;
	}

	config = new_pspell_config();

#ifdef PHP_WIN32
    /* If aspell was installed using installer, we should have a key
     * pointing to the location of the dictionaries
     */
	if (0 == RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\Aspell", &hkey)) {
		LONG result;
		dwLen = sizeof(aspell_dir) - 1;
		result = RegQueryValueEx(hkey, "", NULL, &dwType, (LPBYTE)&aspell_dir, &dwLen);
		RegCloseKey(hkey);
		if (result == ERROR_SUCCESS) {
			strlcpy(data_dir, aspell_dir, sizeof(data_dir));
			strlcat(data_dir, "\\data", sizeof(data_dir));
			strlcpy(dict_dir, aspell_dir, sizeof(dict_dir));
			strlcat(dict_dir, "\\dict", sizeof(dict_dir));

			pspell_config_replace(config, "data-dir", data_dir);
			pspell_config_replace(config, "dict-dir", dict_dir);
		}
	}
#endif

	pspell_config_replace(config, "language-tag", language);

 	if (spelling_len) {
		pspell_config_replace(config, "spelling", spelling);
	}

	if (jargon_len) {
		pspell_config_replace(config, "jargon", jargon);
	}

	if (encoding_len) {
		pspell_config_replace(config, "encoding", encoding);
	}

	/* By default I do not want to write anything anywhere because it'll try to write to $HOME
	which is not what we want */
	pspell_config_replace(config, "save-repl", "false");

	ind = zend_list_insert(config, le_pspell_config);
	RETURN_LONG(Z_RES_HANDLE_P(ind));
}
Esempio n. 7
0
PHP_METHOD(Edge_Loader, autoload)
{
    char *class_name;
    char *dir = NULL;
    int cnlen;
    int drlen;
    
    if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &class_name, &cnlen, &dir, &drlen) == FAILURE)
    {
        printf("autoload get class name error\n");
        return;
    }
    char *_home_path = NULL;
    char *file;
    char *delim = "_";
   
    if(dir == NULL)
    {
        char *lib_path = "LIB_PATH";
        int lib_path_len = strlen(lib_path);
        zval c;
        if (zend_get_constant_ex(lib_path, lib_path_len, &c, NULL, ZEND_FETCH_CLASS_SILENT TSRMLS_CC)) {
            _home_path = estrdup(Z_STRVAL(c));
            zval_dtor(&c);
        } else {
            _home_path = estrdup("IfLib/");
        }
    }else
    {
        _home_path = estrdup(dir);
    }

    if(!strncmp(class_name, "If", 2) || !strncmp(class_name, "IF", 2))
    {
        strtok(class_name, delim);
        file = strtok(NULL, delim);
    }else
    {
        class_name[0] = toupper(class_name[0]);
        file = class_name;
    }
    char *include_file_path;
    /*
    include_file_path = emalloc(sizeof(char *) * strlen(EDGE_G(root_path)) + 
                                sizeof(char *) * strlen(_home_path) +
                                sizeof(char *) * strlen(file) + 
                                sizeof(char *) * strlen(".php"));
                                */
    /*
    strcpy(include_file_path, EDGE_G(root_path));
    strcat(include_file_path, _home_path);
    strcat(include_file_path, file);
    strcat(include_file_path, ".php");
    */
    spprintf(&include_file_path, 0, "%s%s%s%s", EDGE_G(root_path), _home_path, file, ".php");
    zval *func_name;
    MAKE_STD_ZVAL(func_name);
    ZVAL_STRING(func_name, "file_exists", 1);

    zval **call_args[1];
    zval *str;
    MAKE_STD_ZVAL(str);
    ZVAL_STRING(str, include_file_path, 1);
    call_args[0] = &str;
    
    zval *ret, *fret;
    MAKE_STD_ZVAL(ret);
    if(call_user_function_ex(CG(function_table), NULL, func_name, &fret, 1, call_args, 0, NULL TSRMLS_CC) == FAILURE)
    {
        ZVAL_FALSE(ret);
        RETURN_ZVAL(ret, 1, 1);
    }
  
    if(!Z_BVAL_P(fret))
    {
        efree(_home_path);
        efree(include_file_path);
        zval_ptr_dtor(&func_name);
        zval_ptr_dtor(&fret);
        zval_ptr_dtor(*call_args);
        ZVAL_FALSE(ret);
        RETURN_ZVAL(ret, 1, 1);
    }
    if(!edge_file_include(include_file_path))
    {
        efree(_home_path);
        efree(include_file_path);
        ZVAL_FALSE(ret);
    }else{
        efree(_home_path);
        efree(include_file_path);
        ZVAL_TRUE(ret);
    }
    zval_ptr_dtor(&func_name);
    zval_ptr_dtor(*call_args);
    zval_ptr_dtor(&fret);
    RETURN_ZVAL(ret, 1, 1);

}
Esempio n. 8
0
/**
 * Applies the internal format to the message
 *
 * @param  string $message
 * @param  int $type
 * @param  int $time
 * @return string
 */
PHP_METHOD(Phalcon_Logger_Adapter_File, _applyFormat){

	zval *message = NULL, *type = NULL, *time = NULL, *format = NULL;
	zval *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *r4 = NULL, *r5 = NULL;
	zval *t0 = NULL, *t1 = NULL;
	zval *c0 = NULL, *c1 = NULL, *c2 = NULL;

	PHALCON_MM_GROW();
	
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|z", &message, &type, &time) == FAILURE) {
		PHALCON_MM_RESTORE();
		RETURN_NULL();
	}

	if (!time) {
		PHALCON_INIT_VAR(time);
		ZVAL_LONG(time, 0);
	} else {
		PHALCON_SEPARATE_PARAM(time);
	}
	
	if (!zend_is_true(time)) {
		PHALCON_ALLOC_ZVAL_MM(r0);
		PHALCON_CALL_FUNC(r0, "time", 0x018);
		PHALCON_CPY_WRT(time, r0);
	}
	
	PHALCON_ALLOC_ZVAL_MM(t0);
	phalcon_read_property(&t0, this_ptr, "_format", sizeof("_format")-1, PHALCON_NOISY TSRMLS_CC);
	PHALCON_CPY_WRT(format, t0);
	
	PHALCON_ALLOC_ZVAL_MM(r1);
	
	PHALCON_INIT_VAR(c0);
	ZVAL_STRING(c0, "%date%", 1);
	
	PHALCON_ALLOC_ZVAL_MM(r2);
	
	PHALCON_ALLOC_ZVAL_MM(t1);
	phalcon_read_property(&t1, this_ptr, "_dateFormat", sizeof("_dateFormat")-1, PHALCON_NOISY TSRMLS_CC);
	PHALCON_CALL_FUNC_PARAMS_2(r2, "date", t1, time, 0x04E);
	PHALCON_CALL_FUNC_PARAMS_3(r1, "str_replace", c0, r2, format, 0x003);
	PHALCON_CPY_WRT(format, r1);
	
	PHALCON_ALLOC_ZVAL_MM(r3);
	
	PHALCON_INIT_VAR(c1);
	ZVAL_STRING(c1, "%type%", 1);
	
	PHALCON_ALLOC_ZVAL_MM(r4);
	PHALCON_CALL_METHOD_PARAMS_1(r4, this_ptr, "gettypestring", type, PHALCON_NO_CHECK);
	PHALCON_CALL_FUNC_PARAMS_3(r3, "str_replace", c1, r4, format, 0x003);
	PHALCON_CPY_WRT(format, r3);
	
	PHALCON_ALLOC_ZVAL_MM(r5);
	
	PHALCON_INIT_VAR(c2);
	ZVAL_STRING(c2, "%message%", 1);
	PHALCON_CALL_FUNC_PARAMS_3(r5, "str_replace", c2, message, format, 0x003);
	PHALCON_CPY_WRT(format, r5);
	
	PHALCON_RETURN_CHECK_CTOR(format);
}
Esempio n. 9
0
/* {{{ proto array accelerator_get_status([bool fetch_scripts])
   Obtain statistics information regarding code acceleration */
static ZEND_FUNCTION(opcache_get_status)
{
	long reqs;
	zval *memory_usage,*statistics,*scripts;
	zend_bool fetch_scripts = 1;

	/* keep the compiler happy */
	(void)ht; (void)return_value_ptr; (void)this_ptr; (void)return_value_used;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &fetch_scripts) == FAILURE) {
		return;
	}
	
	if (!validate_api_restriction(TSRMLS_C)) {
		RETURN_FALSE;
	}

	if (!accel_startup_ok) {
		RETURN_FALSE;
	}

	array_init(return_value);

	/* Trivia */
	add_assoc_bool(return_value, "opcache_enabled", ZCG(enabled) && (ZCG(counted) || ZCSG(accelerator_enabled)));
	add_assoc_bool(return_value, "cache_full", ZSMMG(memory_exhausted));
	add_assoc_bool(return_value, "restart_pending", ZCSG(restart_pending));
	add_assoc_bool(return_value, "restart_in_progress", ZCSG(restart_in_progress));

	/* Memory usage statistics */
	MAKE_STD_ZVAL(memory_usage);
	array_init(memory_usage);
	add_assoc_long(memory_usage, "used_memory", ZCG(accel_directives).memory_consumption-zend_shared_alloc_get_free_memory()-ZSMMG(wasted_shared_memory));
	add_assoc_long(memory_usage, "free_memory", zend_shared_alloc_get_free_memory());
	add_assoc_long(memory_usage, "wasted_memory", ZSMMG(wasted_shared_memory));
	add_assoc_double(memory_usage, "current_wasted_percentage", (((double) ZSMMG(wasted_shared_memory))/ZCG(accel_directives).memory_consumption)*100.0);
	add_assoc_zval(return_value, "memory_usage", memory_usage);

#if ZEND_EXTENSION_API_NO > PHP_5_3_X_API_NO
	if (ZCSG(interned_strings_start) && ZCSG(interned_strings_end) && ZCSG(interned_strings_top)) {
		zval *interned_strings_usage;

		MAKE_STD_ZVAL(interned_strings_usage);
		array_init(interned_strings_usage);
		add_assoc_long(interned_strings_usage, "buffer_size", ZCSG(interned_strings_end) - ZCSG(interned_strings_start));
		add_assoc_long(interned_strings_usage, "used_memory", ZCSG(interned_strings_top) - ZCSG(interned_strings_start));
		add_assoc_long(interned_strings_usage, "free_memory", ZCSG(interned_strings_end) - ZCSG(interned_strings_top));
		add_assoc_long(interned_strings_usage, "number_of_strings", ZCSG(interned_strings).nNumOfElements);
		add_assoc_zval(return_value, "interned_strings_usage", interned_strings_usage);
	}
#endif
	
	/* Accelerator statistics */
	MAKE_STD_ZVAL(statistics);
	array_init(statistics);
	add_assoc_long(statistics, "num_cached_scripts", ZCSG(hash).num_direct_entries);
	add_assoc_long(statistics, "num_cached_keys",    ZCSG(hash).num_entries);
	add_assoc_long(statistics, "max_cached_keys",    ZCSG(hash).max_num_entries);
	add_assoc_long(statistics, "hits", ZCSG(hits));
	add_assoc_long(statistics, "start_time", ZCSG(start_time));
	add_assoc_long(statistics, "last_restart_time", ZCSG(last_restart_time));
	add_assoc_long(statistics, "oom_restarts", ZCSG(oom_restarts));
	add_assoc_long(statistics, "hash_restarts", ZCSG(hash_restarts));
	add_assoc_long(statistics, "manual_restarts", ZCSG(manual_restarts));
	add_assoc_long(statistics, "misses", ZSMMG(memory_exhausted)?ZCSG(misses):ZCSG(misses)-ZCSG(blacklist_misses));
	add_assoc_long(statistics, "blacklist_misses", ZCSG(blacklist_misses));
	reqs = ZCSG(hits)+ZCSG(misses);
	add_assoc_double(statistics, "blacklist_miss_ratio", reqs?(((double) ZCSG(blacklist_misses))/reqs)*100.0:0);
	add_assoc_double(statistics, "opcache_hit_rate", reqs?(((double) ZCSG(hits))/reqs)*100.0:0);
	add_assoc_zval(return_value, "opcache_statistics", statistics);

	if (fetch_scripts) {
		/* accelerated scripts */
		scripts = accelerator_get_scripts(TSRMLS_C);
		if (scripts) {
			add_assoc_zval(return_value, "scripts", scripts);
		}
	}
}
Esempio n. 10
0
/**
 * Outputs a message formatting it with HTML
 *
 * @param string $type
 * @param string $message
 */
PHP_METHOD(Phalcon_Flash, outputMessage){

	zval *type = NULL, *message = NULL, *automatic_html = NULL, *classes = NULL;
	zval *type_classes = NULL, *joined_classes = NULL, *css_classes = NULL;
	zval *eol = NULL, *implicit_flush = NULL, *content = NULL, *msg = NULL, *html_message = NULL;
	zval *c0 = NULL;
	HashTable *ah0;
	HashPosition hp0;
	zval **hd;
	int eval_int;

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

	PHALCON_INIT_VAR(automatic_html);
	phalcon_read_property(&automatic_html, this_ptr, SL("_automaticHtml"), PH_NOISY_CC);
	if (PHALCON_IS_TRUE(automatic_html)) {
		PHALCON_INIT_VAR(classes);
		phalcon_read_property(&classes, this_ptr, SL("_cssClasses"), PH_NOISY_CC);
		eval_int = phalcon_array_isset(classes, type);
		if (eval_int) {
			PHALCON_INIT_VAR(type_classes);
			phalcon_array_fetch(&type_classes, classes, type, PH_NOISY_CC);
			if (Z_TYPE_P(type_classes) == IS_ARRAY) { 
				PHALCON_INIT_VAR(c0);
				ZVAL_STRING(c0, " ", 1);
				PHALCON_INIT_VAR(joined_classes);
				phalcon_fast_join(joined_classes, c0, type_classes TSRMLS_CC);
				
				PHALCON_INIT_VAR(css_classes);
				PHALCON_CONCAT_SVS(css_classes, " class=\"", joined_classes, "\"");
			} else {
				PHALCON_INIT_VAR(css_classes);
				PHALCON_CONCAT_SVS(css_classes, " class=\"", type_classes, "\"");
			}
		} else {
			PHALCON_INIT_VAR(css_classes);
			ZVAL_STRING(css_classes, "", 1);
		}
		
		PHALCON_INIT_VAR(eol);
		zend_get_constant(SL("PHP_EOL"), eol TSRMLS_CC);
	}
	
	PHALCON_INIT_VAR(implicit_flush);
	phalcon_read_property(&implicit_flush, this_ptr, SL("_implicitFlush"), PH_NOISY_CC);
	if (Z_TYPE_P(message) == IS_ARRAY) { 
		if (PHALCON_IS_FALSE(implicit_flush)) {
			PHALCON_INIT_VAR(content);
			ZVAL_STRING(content, "", 1);
		}
		if (!phalcon_valid_foreach(message TSRMLS_CC)) {
			return;
		}
		
		ah0 = Z_ARRVAL_P(message);
		zend_hash_internal_pointer_reset_ex(ah0, &hp0);
		fes_3b3c_0:
			if(zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) != SUCCESS){
				goto fee_3b3c_0;
			}
			
			PHALCON_INIT_VAR(msg);
			ZVAL_ZVAL(msg, *hd, 1, 0);
			if (PHALCON_IS_TRUE(automatic_html)) {
				PHALCON_INIT_VAR(html_message);
				PHALCON_CONCAT_SVSVSV(html_message, "<div", css_classes, ">", msg, "</div>", eol);
			} else {
				PHALCON_CPY_WRT(html_message, msg);
			}
			if (PHALCON_IS_TRUE(implicit_flush)) {
				zend_print_zval(html_message, 1);
			} else {
				phalcon_concat_self(&content, html_message TSRMLS_CC);
			}
			zend_hash_move_forward_ex(ah0, &hp0);
			goto fes_3b3c_0;
		fee_3b3c_0:
		
		if (PHALCON_IS_FALSE(implicit_flush)) {
			
			RETURN_CTOR(content);
		}
	} else {
		if (PHALCON_IS_TRUE(automatic_html)) {
			PHALCON_INIT_VAR(html_message);
			PHALCON_CONCAT_SVSVSV(html_message, "<div", css_classes, ">", message, "</div>", eol);
		} else {
			PHALCON_CPY_WRT(html_message, message);
		}
		if (PHALCON_IS_TRUE(implicit_flush)) {
			zend_print_zval(html_message, 1);
		} else {
			
			RETURN_CCTOR(html_message);
		}
	}
	
	PHALCON_MM_RESTORE();
}
Esempio n. 11
0
/**
 * Returns the string meaning of a logger constant
 *
 * @param  integer $type
 * @return string
 */
PHP_METHOD(Phalcon_Logger_Adapter_File, getTypeString){

	zval *type = NULL;
	zval *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *r4 = NULL, *r5 = NULL, *r6 = NULL;
	zval *r7 = NULL, *r8 = NULL, *r9 = NULL;
	zval *t0 = NULL, *t1 = NULL, *t2 = NULL, *t3 = NULL, *t4 = NULL, *t5 = NULL, *t6 = NULL;
	zval *t7 = NULL, *t8 = NULL, *t9 = NULL;

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

	PHALCON_SEPARATE_PARAM(type);
	
	PHALCON_ALLOC_ZVAL_MM(t0);
	phalcon_get_class_constant(t0, phalcon_logger_ce, "DEBUG", strlen("DEBUG") TSRMLS_CC);
	PHALCON_ALLOC_ZVAL_MM(r0);
	is_equal_function(r0, type, t0 TSRMLS_CC);
	if (zend_is_true(r0)) {
		PHALCON_INIT_VAR(type);
		ZVAL_STRING(type, "DEBUG", 1);
		goto se_654f_0;
	}
	PHALCON_ALLOC_ZVAL_MM(t1);
	phalcon_get_class_constant(t1, phalcon_logger_ce, "ERROR", strlen("ERROR") TSRMLS_CC);
	PHALCON_ALLOC_ZVAL_MM(r1);
	is_equal_function(r1, type, t1 TSRMLS_CC);
	if (zend_is_true(r1)) {
		PHALCON_INIT_VAR(type);
		ZVAL_STRING(type, "ERROR", 1);
		goto se_654f_0;
	}
	PHALCON_ALLOC_ZVAL_MM(t2);
	phalcon_get_class_constant(t2, phalcon_logger_ce, "WARNING", strlen("WARNING") TSRMLS_CC);
	PHALCON_ALLOC_ZVAL_MM(r2);
	is_equal_function(r2, type, t2 TSRMLS_CC);
	if (zend_is_true(r2)) {
		PHALCON_INIT_VAR(type);
		ZVAL_STRING(type, "WARNING", 1);
		goto se_654f_0;
	}
	PHALCON_ALLOC_ZVAL_MM(t3);
	phalcon_get_class_constant(t3, phalcon_logger_ce, "CUSTOM", strlen("CUSTOM") TSRMLS_CC);
	PHALCON_ALLOC_ZVAL_MM(r3);
	is_equal_function(r3, type, t3 TSRMLS_CC);
	if (zend_is_true(r3)) {
		PHALCON_INIT_VAR(type);
		ZVAL_STRING(type, "CUSTOM", 1);
		goto se_654f_0;
	}
	PHALCON_ALLOC_ZVAL_MM(t4);
	phalcon_get_class_constant(t4, phalcon_logger_ce, "CRITICAL", strlen("CRITICAL") TSRMLS_CC);
	PHALCON_ALLOC_ZVAL_MM(r4);
	is_equal_function(r4, type, t4 TSRMLS_CC);
	if (zend_is_true(r4)) {
		PHALCON_INIT_VAR(type);
		ZVAL_STRING(type, "CRITICAL", 1);
		goto se_654f_0;
	}
	PHALCON_ALLOC_ZVAL_MM(t5);
	phalcon_get_class_constant(t5, phalcon_logger_ce, "ALERT", strlen("ALERT") TSRMLS_CC);
	PHALCON_ALLOC_ZVAL_MM(r5);
	is_equal_function(r5, type, t5 TSRMLS_CC);
	if (zend_is_true(r5)) {
		PHALCON_INIT_VAR(type);
		ZVAL_STRING(type, "ALERT", 1);
		goto se_654f_0;
	}
	PHALCON_ALLOC_ZVAL_MM(t6);
	phalcon_get_class_constant(t6, phalcon_logger_ce, "NOTICE", strlen("NOTICE") TSRMLS_CC);
	PHALCON_ALLOC_ZVAL_MM(r6);
	is_equal_function(r6, type, t6 TSRMLS_CC);
	if (zend_is_true(r6)) {
		PHALCON_INIT_VAR(type);
		ZVAL_STRING(type, "NOTICE", 1);
		goto se_654f_0;
	}
	PHALCON_ALLOC_ZVAL_MM(t7);
	phalcon_get_class_constant(t7, phalcon_logger_ce, "EMERGENCE", strlen("EMERGENCE") TSRMLS_CC);
	PHALCON_ALLOC_ZVAL_MM(r7);
	is_equal_function(r7, type, t7 TSRMLS_CC);
	if (zend_is_true(r7)) {
		PHALCON_INIT_VAR(type);
		ZVAL_STRING(type, "EMERGENCE", 1);
		goto se_654f_0;
	}
	PHALCON_ALLOC_ZVAL_MM(t8);
	phalcon_get_class_constant(t8, phalcon_logger_ce, "INFO", strlen("INFO") TSRMLS_CC);
	PHALCON_ALLOC_ZVAL_MM(r8);
	is_equal_function(r8, type, t8 TSRMLS_CC);
	if (zend_is_true(r8)) {
		PHALCON_INIT_VAR(type);
		ZVAL_STRING(type, "INFO", 1);
		goto se_654f_0;
	}
	PHALCON_ALLOC_ZVAL_MM(t9);
	phalcon_get_class_constant(t9, phalcon_logger_ce, "SPECIAL", strlen("SPECIAL") TSRMLS_CC);
	PHALCON_ALLOC_ZVAL_MM(r9);
	is_equal_function(r9, type, t9 TSRMLS_CC);
	if (zend_is_true(r9)) {
		PHALCON_INIT_VAR(type);
		ZVAL_STRING(type, "SPECIAL", 1);
		goto se_654f_0;
	}
	PHALCON_INIT_VAR(type);
	ZVAL_STRING(type, "CUSTOM", 1);
	se_654f_0:
	
	PHALCON_RETURN_CHECK_CTOR(type);
}
Esempio n. 12
0
/* {{{ proto mixed Closure::call(object to [, mixed parameter] [, mixed ...] )
   Call closure, binding to a given object with its class as the scope */
ZEND_METHOD(Closure, call)
{
	zval *zclosure, *newthis, closure_result;
	zend_closure *closure;
	zend_fcall_info fci;
	zend_fcall_info_cache fci_cache;
	zval *my_params;
	int my_param_count = 0;
	zend_function my_function;
	zend_object *newobj;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "o*", &newthis, &my_params, &my_param_count) == FAILURE) {
		return;
	}

	zclosure = getThis();
	closure = (zend_closure *) Z_OBJ_P(zclosure);

	newobj = Z_OBJ_P(newthis);

	if (!zend_valid_closure_binding(closure, newthis, Z_OBJCE_P(newthis))) {
		return;
	}

	/* This should never happen as closures will always be callable */
	if (zend_fcall_info_init(zclosure, 0, &fci, &fci_cache, NULL, NULL) != SUCCESS) {
		ZEND_ASSERT(0);
	}

	fci.retval = &closure_result;
	fci.params = my_params;
	fci.param_count = my_param_count;
	fci.object = fci_cache.object = newobj;
	fci_cache.initialized = 1;
	fci_cache.called_scope = Z_OBJCE_P(newthis);

	if (fci_cache.function_handler->common.fn_flags & ZEND_ACC_GENERATOR) {
		zval new_closure;
		zend_create_closure(&new_closure, fci_cache.function_handler, Z_OBJCE_P(newthis), closure->called_scope, newthis);
		closure = (zend_closure *) Z_OBJ(new_closure);
		fci_cache.function_handler = &closure->func;
	} else {
		memcpy(&my_function, fci_cache.function_handler, fci_cache.function_handler->type == ZEND_USER_FUNCTION ? sizeof(zend_op_array) : sizeof(zend_internal_function));
		/* use scope of passed object */
		my_function.common.scope = Z_OBJCE_P(newthis);
		fci_cache.function_handler = &my_function;

		/* Runtime cache relies on bound scope to be immutable, hence we need a separate rt cache in case scope changed */
		if (ZEND_USER_CODE(my_function.type) && closure->func.common.scope != Z_OBJCE_P(newthis)) {
			my_function.op_array.run_time_cache = emalloc(my_function.op_array.cache_size);
			memset(my_function.op_array.run_time_cache, 0, my_function.op_array.cache_size);
		}
	}

	if (zend_call_function(&fci, &fci_cache) == SUCCESS && Z_TYPE(closure_result) != IS_UNDEF) {
		if (Z_ISREF(closure_result)) {
			zend_unwrap_reference(&closure_result);
		}
		ZVAL_COPY_VALUE(return_value, &closure_result);
	}

	if (fci_cache.function_handler->common.fn_flags & ZEND_ACC_GENERATOR) {
		/* copied upon generator creation */
		--GC_REFCOUNT(&closure->std);
	} else if (ZEND_USER_CODE(my_function.type) && closure->func.common.scope != Z_OBJCE_P(newthis)) {
		efree(my_function.op_array.run_time_cache);
	}
}
Esempio n. 13
0
/* {{{ _php_image_output_ctx */
static void _php_image_output_ctx(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, void (*func_p)())
{
	zval *imgind;
	char *file = NULL;
	int file_len = 0;
	long quality, basefilter;
	gdImagePtr im;
	FILE *fp = NULL;
	int argc = ZEND_NUM_ARGS();
	int q = -1, i;
	int f = -1;
	gdIOCtx *ctx;

	/* The third (quality) parameter for Wbmp stands for the threshold when called from image2wbmp().
	 * The third (quality) parameter for Wbmp and Xbm stands for the foreground color index when called
	 * from imagey<type>().
	 */

	if (image_type == PHP_GDIMG_TYPE_XBM) {
		if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs!|ll", &imgind, &file, &file_len, &quality, &basefilter) == FAILURE) {
			return;
		}
	} else {
		/* PHP_GDIMG_TYPE_GIF
		 * PHP_GDIMG_TYPE_PNG 
		 * PHP_GDIMG_TYPE_JPG 
		 * PHP_GDIMG_TYPE_WBM */
		if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|s!ll", &imgind, &file, &file_len, &quality, &basefilter) == FAILURE) {
			return;
		}		
	}

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

	if (argc > 1) {
		if (argc >= 3) {
			q = quality; /* or colorindex for foreground of BW images (defaults to black) */
			if (argc == 4) {
				f = basefilter;
			}
		}
	}

    if (argc > 1 && file_len) {
		PHP_GD_CHECK_OPEN_BASEDIR(file, "Invalid filename");

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

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

	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_PNG:
			(*func_p)(im, ctx, q, f);
			break;
		case PHP_GDIMG_TYPE_XBM:
		case PHP_GDIMG_TYPE_WBM:
			if (argc < 3) {
				for(i=0; i < gdImageColorsTotal(im); i++) {
					if(!gdImageRed(im, i) && !gdImageGreen(im, i) && !gdImageBlue(im, i)) break;
				}
				q = i;
			}
			if (image_type == PHP_GDIMG_TYPE_XBM) {
				(*func_p)(im, file, q, ctx);
			} else {
				(*func_p)(im, q, ctx);
			}
			break;
		default:
			(*func_p)(im, ctx);
			break;
	}

	ctx->gd_free(ctx);

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

    RETURN_TRUE;
}
Esempio n. 14
0
/**
 * Converts bound parameters such as :name: or ?1 into PDO bind params ?
 *
 *<code>
 * print_r($connection->convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender')));
 *</code>
 *
 * @param string $sql
 * @param array $params
 * @return array
 */
PHP_METHOD(Phalcon_Db_Adapter_Pdo, convertBoundParams){

	zval *sql, *params, *query_params = NULL, *placeholders;
	zval *matches, *set_order, *bind_pattern, *status = NULL;
	zval *place_match = NULL, *numeric_place = NULL, *value = NULL, *str_place = NULL;
	zval *question, *bound_sql = NULL;
	zval *r0 = NULL;
	zval *p0[] = { NULL, NULL, NULL, NULL };
	HashTable *ah0;
	HashPosition hp0;
	zval **hd;

	PHALCON_MM_GROW();

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &sql, &params) == FAILURE) {
		RETURN_MM_NULL();
	}

	PHALCON_INIT_VAR(query_params);
	array_init(query_params);
	
	PHALCON_INIT_VAR(placeholders);
	array_init(placeholders);
	
	PHALCON_INIT_VAR(matches);
	
	PHALCON_INIT_VAR(set_order);
	ZVAL_LONG(set_order, 2);
	
	PHALCON_INIT_VAR(bind_pattern);
	ZVAL_STRING(bind_pattern, "/\\?([0-9]+)|:([a-zA-Z0-9_]+):/", 1);
	p0[0] = bind_pattern;
	p0[1] = sql;
	Z_SET_ISREF_P(matches);
	p0[2] = matches;
	p0[3] = set_order;
	
	PHALCON_INIT_VAR(r0);
	PHALCON_CALL_FUNC_PARAMS(r0, "preg_match_all", 4, p0);
	Z_UNSET_ISREF_P(p0[2]);
	PHALCON_CPY_WRT(status, r0);
	if (zend_is_true(status)) {
	
		if (!phalcon_is_iterable(matches, &ah0, &hp0, 0, 0 TSRMLS_CC)) {
			return;
		}
	
		while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) {
	
			PHALCON_GET_FOREACH_VALUE(place_match);
	
			PHALCON_OBS_NVAR(numeric_place);
			phalcon_array_fetch_long(&numeric_place, place_match, 1, PH_NOISY_CC);
			if (phalcon_array_isset(params, numeric_place)) {
				PHALCON_OBS_NVAR(value);
				phalcon_array_fetch(&value, params, numeric_place, PH_NOISY_CC);
			} else {
				if (phalcon_array_isset_long(place_match, 2)) {
	
					PHALCON_OBS_NVAR(str_place);
					phalcon_array_fetch_long(&str_place, place_match, 2, PH_NOISY_CC);
					if (phalcon_array_isset(params, str_place)) {
						PHALCON_OBS_NVAR(value);
						phalcon_array_fetch(&value, params, str_place, PH_NOISY_CC);
					} else {
						PHALCON_THROW_EXCEPTION_STR(phalcon_db_exception_ce, "Matched parameter wasn't found in parameters list");
						return;
					}
				} else {
					PHALCON_THROW_EXCEPTION_STR(phalcon_db_exception_ce, "Matched parameter wasn't found in parameters list");
					return;
				}
			}
	
			phalcon_array_append(&placeholders, value, PH_SEPARATE TSRMLS_CC);
	
			zend_hash_move_forward_ex(ah0, &hp0);
		}
	
		PHALCON_INIT_VAR(question);
		ZVAL_STRING(question, "?", 1);
	
		PHALCON_INIT_VAR(bound_sql);
		PHALCON_CALL_FUNC_PARAMS_3(bound_sql, "preg_replace", bind_pattern, question, sql);
	} else {
		PHALCON_CPY_WRT(bound_sql, sql);
	}
	
	/** 
	 * Returns an array with the processed SQL and paramters
	 */
	PHALCON_INIT_NVAR(query_params);
	array_init_size(query_params, 2);
	phalcon_array_update_string(&query_params, SL("sql"), &bound_sql, PH_COPY | PH_SEPARATE TSRMLS_CC);
	phalcon_array_update_string(&query_params, SL("params"), &placeholders, PH_COPY | PH_SEPARATE TSRMLS_CC);
	
	RETURN_CTOR(query_params);
}
Esempio n. 15
0
static void php_hash_do_hash(INTERNAL_FUNCTION_PARAMETERS, int isfilename, zend_bool raw_output_default) /* {{{ */
{
    zend_string *digest;
    char *algo, *data;
    size_t algo_len, data_len;
    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(), "ss|b", &algo, &algo_len, &data, &data_len, &raw_output) == FAILURE) {
        return;
    }

    ops = php_hash_fetch_ops(algo, algo_len);
    if (!ops) {
        php_error_docref(NULL, E_WARNING, "Unknown hashing algorithm: %s", algo);
        RETURN_FALSE;
    }
    if (isfilename) {
        if (CHECK_NULL_PATH(data, data_len)) {
            RETURN_FALSE;
        }
        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);

    if (isfilename) {
        char buf[1024];
        size_t 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 = zend_string_alloc(ops->digest_size, 0);
    ops->hash_final((unsigned char *) digest->val, context);
    efree(context);

    if (raw_output) {
        digest->val[ops->digest_size] = 0;
        RETURN_NEW_STR(digest);
    } else {
        zend_string *hex_digest = zend_string_safe_alloc(ops->digest_size, 2, 0, 0);

        php_hash_bin2hex(hex_digest->val, (unsigned char *) digest->val, ops->digest_size);
        hex_digest->val[2 * ops->digest_size] = 0;
        zend_string_release(digest);
        RETURN_NEW_STR(hex_digest);
    }
}
Esempio n. 16
0
/**
 * Returns an array of Phalcon\Db\Column objects describing a table
 *
 * <code>
 * print_r($connection->describeColumns("posts")); ?>
 * </code>
 *
 * @param string $table
 * @param string $schema
 * @return Phalcon\Db\Column[]
 */
PHP_METHOD(Phalcon_Db_Adapter_Pdo_Sqlite, describeColumns){

	zval *table, *schema = NULL, *columns, *dialect, *size_pattern;
	zval *sql, *fetch_assoc, *describe, *old_column = NULL;
	zval *field = NULL, *definition = NULL, *column_type = NULL, *pos = NULL, *attribute = NULL;
	zval *matches = NULL, *match_one = NULL, *column_name = NULL, *column = NULL;
	HashTable *ah0;
	HashPosition hp0;
	zval **hd;

	PHALCON_MM_GROW();

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &table, &schema) == FAILURE) {
		RETURN_MM_NULL();
	}

	if (!schema) {
		PHALCON_INIT_VAR(schema);
	}
	
	PHALCON_INIT_VAR(columns);
	array_init(columns);
	
	PHALCON_OBS_VAR(dialect);
	phalcon_read_property(&dialect, this_ptr, SL("_dialect"), PH_NOISY_CC);
	
	PHALCON_INIT_VAR(size_pattern);
	ZVAL_STRING(size_pattern, "#\\(([0-9]+)(,[0-9]+)*\\)#", 1);
	
	PHALCON_INIT_VAR(sql);
	PHALCON_CALL_METHOD_PARAMS_2(sql, dialect, "describecolumns", table, schema);
	
	PHALCON_INIT_VAR(fetch_assoc);
	phalcon_get_class_constant(fetch_assoc, phalcon_db_ce, SS("FETCH_ASSOC") TSRMLS_CC);
	
	PHALCON_INIT_VAR(describe);
	PHALCON_CALL_METHOD_PARAMS_2(describe, this_ptr, "fetchall", sql, fetch_assoc);
	
	PHALCON_INIT_VAR(old_column);
	
	if (!phalcon_is_iterable(describe, &ah0, &hp0, 0, 0 TSRMLS_CC)) {
		return;
	}
	
	while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) {
	
		PHALCON_GET_FOREACH_VALUE(field);
	
		PHALCON_INIT_NVAR(definition);
		array_init_size(definition, 1);
		add_assoc_long_ex(definition, SS("bindType"), 2);
	
		PHALCON_OBS_NVAR(column_type);
		phalcon_array_fetch_string(&column_type, field, SL("type"), PH_NOISY_CC);
	
		PHALCON_INIT_NVAR(pos);
		phalcon_fast_stripos_str(pos, column_type, SL("int") TSRMLS_CC);
		if (PHALCON_IS_NOT_FALSE(pos)) {
			phalcon_array_update_string_long(&definition, SL("type"), 0, PH_SEPARATE TSRMLS_CC);
			phalcon_array_update_string_bool(&definition, SL("isNumeric"), 1, PH_SEPARATE TSRMLS_CC);
			phalcon_array_update_string_long(&definition, SL("bindType"), 1, PH_SEPARATE TSRMLS_CC);
	
			PHALCON_OBS_NVAR(attribute);
			phalcon_array_fetch_string(&attribute, field, SL("pk"), PH_NOISY_CC);
			if (zend_is_true(attribute)) {
				phalcon_array_update_string_bool(&definition, SL("autoIncrement"), 1, PH_SEPARATE TSRMLS_CC);
			}
		} else {
			if (phalcon_memnstr_str(column_type, SL("varchar") TSRMLS_CC)) {
				phalcon_array_update_string_long(&definition, SL("type"), 2, PH_SEPARATE TSRMLS_CC);
			} else {
				if (phalcon_memnstr_str(column_type, SL("date") TSRMLS_CC)) {
					phalcon_array_update_string_long(&definition, SL("type"), 1, PH_SEPARATE TSRMLS_CC);
				} else {
					if (phalcon_memnstr_str(column_type, SL("decimal") TSRMLS_CC)) {
						phalcon_array_update_string_long(&definition, SL("type"), 3, PH_SEPARATE TSRMLS_CC);
						phalcon_array_update_string_bool(&definition, SL("isNumeric"), 1, PH_SEPARATE TSRMLS_CC);
						phalcon_array_update_string_long(&definition, SL("bindType"), 32, PH_SEPARATE TSRMLS_CC);
					} else {
						if (phalcon_memnstr_str(column_type, SL("char") TSRMLS_CC)) {
							phalcon_array_update_string_long(&definition, SL("type"), 5, PH_SEPARATE TSRMLS_CC);
						} else {
							if (phalcon_memnstr_str(column_type, SL("datetime") TSRMLS_CC)) {
								phalcon_array_update_string_long(&definition, SL("type"), 4, PH_SEPARATE TSRMLS_CC);
							} else {
								if (phalcon_memnstr_str(column_type, SL("text") TSRMLS_CC)) {
									phalcon_array_update_string_long(&definition, SL("type"), 6, PH_SEPARATE TSRMLS_CC);
								} else {
									if (phalcon_memnstr_str(column_type, SL("float") TSRMLS_CC)) {
										phalcon_array_update_string_long(&definition, SL("type"), 7, PH_SEPARATE TSRMLS_CC);
										phalcon_array_update_string_bool(&definition, SL("isNumeric"), 1, PH_SEPARATE TSRMLS_CC);
										phalcon_array_update_string_long(&definition, SL("bindType"), 32, PH_SEPARATE TSRMLS_CC);
									} else {
										if (phalcon_memnstr_str(column_type, SL("enum") TSRMLS_CC)) {
											phalcon_array_update_string_long(&definition, SL("type"), 5, PH_SEPARATE TSRMLS_CC);
										} else {
											phalcon_array_update_string_long(&definition, SL("type"), 2, PH_SEPARATE TSRMLS_CC);
										}
									}
								}
							}
						}
					}
				}
			}
		}
	
		if (phalcon_memnstr_str(column_type, SL("(") TSRMLS_CC)) {
	
			PHALCON_INIT_NVAR(matches);
			array_init(matches);
			Z_SET_ISREF_P(matches);
	
			PHALCON_INIT_NVAR(pos);
			PHALCON_CALL_FUNC_PARAMS_3(pos, "preg_match", size_pattern, column_type, matches);
			Z_UNSET_ISREF_P(matches);
			if (zend_is_true(pos)) {
				if (phalcon_array_isset_long(matches, 1)) {
					PHALCON_OBS_NVAR(match_one);
					phalcon_array_fetch_long(&match_one, matches, 1, PH_NOISY_CC);
					phalcon_array_update_string(&definition, SL("size"), &match_one, PH_COPY | PH_SEPARATE TSRMLS_CC);
				}
			}
		}
	
		if (phalcon_memnstr_str(column_type, SL("unsigned") TSRMLS_CC)) {
			phalcon_array_update_string_bool(&definition, SL("unsigned"), 1, PH_SEPARATE TSRMLS_CC);
		}
	
		if (!zend_is_true(old_column)) {
			phalcon_array_update_string_bool(&definition, SL("first"), 1, PH_SEPARATE TSRMLS_CC);
		} else {
			phalcon_array_update_string(&definition, SL("after"), &old_column, PH_COPY | PH_SEPARATE TSRMLS_CC);
		}
	
		PHALCON_OBS_NVAR(attribute);
		phalcon_array_fetch_string(&attribute, field, SL("pk"), PH_NOISY_CC);
		if (zend_is_true(attribute)) {
			phalcon_array_update_string_bool(&definition, SL("primary"), 1, PH_SEPARATE TSRMLS_CC);
		}
	
		PHALCON_OBS_NVAR(attribute);
		phalcon_array_fetch_string(&attribute, field, SL("notnull"), PH_NOISY_CC);
		if (zend_is_true(attribute)) {
			phalcon_array_update_string_bool(&definition, SL("notNull"), 1, PH_SEPARATE TSRMLS_CC);
		}
	
		PHALCON_OBS_NVAR(column_name);
		phalcon_array_fetch_string(&column_name, field, SL("name"), PH_NOISY_CC);
	
		PHALCON_INIT_NVAR(column);
		object_init_ex(column, phalcon_db_column_ce);
		PHALCON_CALL_METHOD_PARAMS_2_NORETURN(column, "__construct", column_name, definition);
	
		phalcon_array_append(&columns, column, PH_SEPARATE TSRMLS_CC);
		PHALCON_CPY_WRT(old_column, column_name);
	
		zend_hash_move_forward_ex(ah0, &hp0);
	}
	
	
	RETURN_CTOR(columns);
}
Esempio n. 17
0
/* {{{ proto int pspell_new_personal(string personal, string language [, string spelling [, string jargon [, string encoding [, int mode]]]])
   Load a dictionary with a personal wordlist*/
static PHP_FUNCTION(pspell_new_personal)
{
	char *personal, *language, *spelling = NULL, *jargon = NULL, *encoding = NULL;
	size_t personal_len, language_len, spelling_len = 0, jargon_len = 0, encoding_len = 0;
	zend_long mode = Z_L(0),  speed = Z_L(0);
	int argc = ZEND_NUM_ARGS();
	zval *ind;

#ifdef PHP_WIN32
	TCHAR aspell_dir[200];
	TCHAR data_dir[220];
	TCHAR dict_dir[220];
	HKEY hkey;
	DWORD dwType,dwLen;
#endif

	PspellCanHaveError *ret;
	PspellManager *manager;
	PspellConfig *config;

	if (zend_parse_parameters(argc, "ps|sssl", &personal, &personal_len, &language, &language_len,
		&spelling, &spelling_len, &jargon, &jargon_len, &encoding, &encoding_len, &mode) == FAILURE) {
		return;
	}

	config = new_pspell_config();

#ifdef PHP_WIN32
	/* If aspell was installed using installer, we should have a key
	 * pointing to the location of the dictionaries
	 */
	if (0 == RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\Aspell", &hkey)) {
		LONG result;
		dwLen = sizeof(aspell_dir) - 1;
		result = RegQueryValueEx(hkey, "", NULL, &dwType, (LPBYTE)&aspell_dir, &dwLen);
		RegCloseKey(hkey);
		if (result == ERROR_SUCCESS) {
			strlcpy(data_dir, aspell_dir, sizeof(data_dir));
			strlcat(data_dir, "\\data", sizeof(data_dir));
			strlcpy(dict_dir, aspell_dir, sizeof(dict_dir));
			strlcat(dict_dir, "\\dict", sizeof(dict_dir));

			pspell_config_replace(config, "data-dir", data_dir);
			pspell_config_replace(config, "dict-dir", dict_dir);
		}
	}
#endif

	if (php_check_open_basedir(personal)) {
		delete_pspell_config(config);
		RETURN_FALSE;
	}

	pspell_config_replace(config, "personal", personal);
	pspell_config_replace(config, "save-repl", "false");

	pspell_config_replace(config, "language-tag", language);

	if (spelling_len) {
		pspell_config_replace(config, "spelling", spelling);
	}

	if (jargon_len) {
		pspell_config_replace(config, "jargon", jargon);
	}

	if (encoding_len) {
		pspell_config_replace(config, "encoding", encoding);
	}

	if (argc > 5) {
		speed = mode & PSPELL_SPEED_MASK_INTERNAL;

		/* First check what mode we want (how many suggestions) */
		if (speed == PSPELL_FAST) {
			pspell_config_replace(config, "sug-mode", "fast");
		} else if (speed == PSPELL_NORMAL) {
			pspell_config_replace(config, "sug-mode", "normal");
		} else if (speed == PSPELL_BAD_SPELLERS) {
			pspell_config_replace(config, "sug-mode", "bad-spellers");
		}

		/* Then we see if run-together words should be treated as valid components */
		if (mode & PSPELL_RUN_TOGETHER) {
			pspell_config_replace(config, "run-together", "true");
		}
	}

	ret = new_pspell_manager(config);
	delete_pspell_config(config);

	if (pspell_error_number(ret) != 0) {
		php_error_docref(NULL, E_WARNING, "PSPELL couldn't open the dictionary. reason: %s", pspell_error_message(ret));
		delete_pspell_can_have_error(ret);
		RETURN_FALSE;
	}

	manager = to_pspell_manager(ret);
	ind = zend_list_insert(manager, le_pspell);
	RETURN_LONG(Z_RES_HANDLE_P(ind));
}
Esempio n. 18
0
/**
 * Lists table indexes
 *
 * @param string $table
 * @param string $schema
 * @return Phalcon\Db\Index[]
 */
PHP_METHOD(Phalcon_Db_Adapter_Pdo_Sqlite, describeIndexes){

	zval *table, *schema = NULL, *dialect, *fetch_assoc, *sql;
	zval *describe, *indexes, *index = NULL, *key_name = NULL, *empty_arr = NULL;
	zval *sql_index_describe = NULL, *describe_index = NULL;
	zval *index_column = NULL, *column_name = NULL, *index_objects;
	zval *index_columns = NULL, *name = NULL;
	HashTable *ah0, *ah1, *ah2;
	HashPosition hp0, hp1, hp2;
	zval **hd;

	PHALCON_MM_GROW();

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &table, &schema) == FAILURE) {
		RETURN_MM_NULL();
	}

	if (!schema) {
		PHALCON_INIT_VAR(schema);
	}
	
	PHALCON_OBS_VAR(dialect);
	phalcon_read_property(&dialect, this_ptr, SL("_dialect"), PH_NOISY_CC);
	
	PHALCON_INIT_VAR(fetch_assoc);
	phalcon_get_class_constant(fetch_assoc, phalcon_db_ce, SS("FETCH_ASSOC") TSRMLS_CC);
	
	PHALCON_INIT_VAR(sql);
	PHALCON_CALL_METHOD_PARAMS_2(sql, dialect, "describeindexes", table, schema);
	
	PHALCON_INIT_VAR(describe);
	PHALCON_CALL_METHOD_PARAMS_2(describe, this_ptr, "fetchall", sql, fetch_assoc);
	
	PHALCON_INIT_VAR(indexes);
	array_init(indexes);
	
	if (!phalcon_is_iterable(describe, &ah0, &hp0, 0, 0 TSRMLS_CC)) {
		return;
	}
	
	while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) {
	
		PHALCON_GET_FOREACH_VALUE(index);
	
		PHALCON_OBS_NVAR(key_name);
		phalcon_array_fetch_string(&key_name, index, SL("name"), PH_NOISY_CC);
		if (!phalcon_array_isset(indexes, key_name)) {
			PHALCON_INIT_NVAR(empty_arr);
			array_init(empty_arr);
			phalcon_array_update_zval(&indexes, key_name, &empty_arr, PH_COPY | PH_SEPARATE TSRMLS_CC);
		}
	
		PHALCON_INIT_NVAR(sql_index_describe);
		PHALCON_CALL_METHOD_PARAMS_1(sql_index_describe, dialect, "describeindex", key_name);
	
		PHALCON_INIT_NVAR(describe_index);
		PHALCON_CALL_METHOD_PARAMS_2(describe_index, this_ptr, "fetchall", sql_index_describe, fetch_assoc);
	
		if (!phalcon_is_iterable(describe_index, &ah1, &hp1, 0, 0 TSRMLS_CC)) {
			return;
		}
	
		while (zend_hash_get_current_data_ex(ah1, (void**) &hd, &hp1) == SUCCESS) {
	
			PHALCON_GET_FOREACH_VALUE(index_column);
	
			PHALCON_OBS_NVAR(column_name);
			phalcon_array_fetch_string(&column_name, index_column, SL("name"), PH_NOISY_CC);
			phalcon_array_update_append_multi_2(&indexes, key_name, column_name, 0 TSRMLS_CC);
	
			zend_hash_move_forward_ex(ah1, &hp1);
		}
	
	
		zend_hash_move_forward_ex(ah0, &hp0);
	}
	
	PHALCON_INIT_VAR(index_objects);
	array_init(index_objects);
	
	if (!phalcon_is_iterable(indexes, &ah2, &hp2, 0, 0 TSRMLS_CC)) {
		return;
	}
	
	while (zend_hash_get_current_data_ex(ah2, (void**) &hd, &hp2) == SUCCESS) {
	
		PHALCON_GET_FOREACH_KEY(name, ah2, hp2);
		PHALCON_GET_FOREACH_VALUE(index_columns);
	
		PHALCON_INIT_NVAR(index);
		object_init_ex(index, phalcon_db_index_ce);
		PHALCON_CALL_METHOD_PARAMS_2_NORETURN(index, "__construct", name, index_columns);
	
		phalcon_array_update_zval(&index_objects, name, &index, PH_COPY | PH_SEPARATE TSRMLS_CC);
	
		zend_hash_move_forward_ex(ah2, &hp2);
	}
	
	
	RETURN_CTOR(index_objects);
}
Esempio n. 19
0
/* {{{ proto void SplDoublyLinkedList::offsetUnset(mixed index)
 Unsets the value at the specified $index. */
SPL_METHOD(SplDoublyLinkedList, offsetUnset)
{
	zval                  *zindex;
	zend_long             index;
	spl_dllist_object     *intern;
	spl_ptr_llist_element *element;
	spl_ptr_llist         *llist;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &zindex) == FAILURE) {
		return;
	}

	intern = Z_SPLDLLIST_P(ZEND_THIS);
	index  = spl_offset_convert_to_long(zindex);
	llist  = intern->llist;

	if (index < 0 || index >= intern->llist->count) {
		zend_throw_exception(spl_ce_OutOfRangeException, "Offset out of range", 0);
		return;
	}

	element = spl_ptr_llist_offset(intern->llist, index, intern->flags & SPL_DLLIST_IT_LIFO);

	if (element != NULL) {
		/* connect the neightbors */
		if (element->prev) {
			element->prev->next = element->next;
		}

		if (element->next) {
			element->next->prev = element->prev;
		}

		/* take care of head/tail */
		if (element == llist->head) {
			llist->head = element->next;
		}

		if (element == llist->tail) {
			llist->tail = element->prev;
		}

		/* finally, delete the element */
		llist->count--;

		if(llist->dtor) {
			llist->dtor(element);
		}

		if (intern->traverse_pointer == element) {
			SPL_LLIST_DELREF(element);
			intern->traverse_pointer = NULL;
		}
		zval_ptr_dtor(&element->data);
		ZVAL_UNDEF(&element->data);

		SPL_LLIST_DELREF(element);
	} else {
		zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid", 0);
		return;
	}
} /* }}} */
Esempio n. 20
0
/**
 * Lists table references
 *
 * @param string $table
 * @param string $schema
 * @return Phalcon\Db\Reference[]
 */
PHP_METHOD(Phalcon_Db_Adapter_Pdo_Sqlite, describeReferences){

	zval *table, *schema = NULL, *dialect, *sql, *fetch_assoc;
	zval *describe, *reference_objects, *reference_describe = NULL;
	zval *number = NULL, *constraint_name = NULL, *referenced_table = NULL;
	zval *from = NULL, *to = NULL, *columns = NULL, *referenced_columns = NULL;
	zval *reference_array = NULL, *reference = NULL;
	HashTable *ah0;
	HashPosition hp0;
	zval **hd;

	PHALCON_MM_GROW();

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &table, &schema) == FAILURE) {
		RETURN_MM_NULL();
	}

	if (!schema) {
		PHALCON_INIT_VAR(schema);
	}
	
	PHALCON_OBS_VAR(dialect);
	phalcon_read_property(&dialect, this_ptr, SL("_dialect"), PH_NOISY_CC);
	
	PHALCON_INIT_VAR(sql);
	PHALCON_CALL_METHOD_PARAMS_2(sql, dialect, "describereferences", table, schema);
	
	PHALCON_INIT_VAR(fetch_assoc);
	phalcon_get_class_constant(fetch_assoc, phalcon_db_ce, SS("FETCH_ASSOC") TSRMLS_CC);
	
	PHALCON_INIT_VAR(describe);
	PHALCON_CALL_METHOD_PARAMS_2(describe, this_ptr, "fetchall", sql, fetch_assoc);
	
	PHALCON_INIT_VAR(reference_objects);
	array_init(reference_objects);
	
	if (!phalcon_is_iterable(describe, &ah0, &hp0, 0, 0 TSRMLS_CC)) {
		return;
	}
	
	while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) {
	
		PHALCON_GET_FOREACH_KEY(number, ah0, hp0);
		PHALCON_GET_FOREACH_VALUE(reference_describe);
	
		PHALCON_INIT_NVAR(constraint_name);
		PHALCON_CONCAT_SV(constraint_name, "foreign_key_", number);
	
		PHALCON_OBS_NVAR(referenced_table);
		phalcon_array_fetch_string(&referenced_table, reference_describe, SL("table"), PH_NOISY_CC);
	
		PHALCON_OBS_NVAR(from);
		phalcon_array_fetch_string(&from, reference_describe, SL("from"), PH_NOISY_CC);
	
		PHALCON_OBS_NVAR(to);
		phalcon_array_fetch_string(&to, reference_describe, SL("to"), PH_NOISY_CC);
	
		PHALCON_INIT_NVAR(columns);
		array_init_size(columns, 1);
		phalcon_array_append(&columns, from, PH_SEPARATE TSRMLS_CC);
	
		PHALCON_INIT_NVAR(referenced_columns);
		array_init_size(referenced_columns, 1);
		phalcon_array_append(&referenced_columns, to, PH_SEPARATE TSRMLS_CC);
	
		PHALCON_INIT_NVAR(reference_array);
		array_init_size(reference_array, 4);
		add_assoc_null_ex(reference_array, SS("referencedSchema"));
		phalcon_array_update_string(&reference_array, SL("referencedTable"), &referenced_table, PH_COPY | PH_SEPARATE TSRMLS_CC);
		phalcon_array_update_string(&reference_array, SL("columns"), &columns, PH_COPY | PH_SEPARATE TSRMLS_CC);
		phalcon_array_update_string(&reference_array, SL("referencedColumns"), &referenced_columns, PH_COPY | PH_SEPARATE TSRMLS_CC);
	
		PHALCON_INIT_NVAR(reference);
		object_init_ex(reference, phalcon_db_reference_ce);
		PHALCON_CALL_METHOD_PARAMS_2_NORETURN(reference, "__construct", constraint_name, reference_array);
	
		phalcon_array_update_zval(&reference_objects, constraint_name, &reference, PH_COPY | PH_SEPARATE TSRMLS_CC);
	
		zend_hash_move_forward_ex(ah0, &hp0);
	}
	
	
	RETURN_CTOR(reference_objects);
}
Esempio n. 21
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;
}
PHP_METHOD(ExecutionOptions, __get)
{
  char *name;
  php5to7_size name_len;

  cassandra_execution_options *self = NULL;

  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) {
    return;
  }

  self = PHP_CASSANDRA_GET_EXECUTION_OPTIONS(getThis());

  if (name_len == 11 && strncmp("consistency", name, name_len) == 0) {
    if (self->consistency == -1) {
      RETURN_NULL();
    }
    RETURN_LONG(self->consistency);
  } else if (name_len == 17 && strncmp("serialConsistency", name, name_len) == 0) {
    if (self->serial_consistency == -1) {
      RETURN_NULL();
    }
    RETURN_LONG(self->serial_consistency);
  } else if (name_len == 8 && strncmp("pageSize", name, name_len) == 0) {
    if (self->page_size == -1) {
      RETURN_NULL();
    }
    RETURN_LONG(self->page_size);
  } else if (name_len == 16 && strncmp("pagingStateToken", name, name_len) == 0) {
    if (!self->paging_state_token) {
      RETURN_NULL();
    }
    PHP5TO7_RETURN_STRINGL(self->paging_state_token,
                           self->paging_state_token_size);
  } else if (name_len == 7 && strncmp("timeout", name, name_len) == 0) {
    if (PHP5TO7_ZVAL_IS_UNDEF(self->timeout)) {
      RETURN_NULL();
    }
    RETURN_ZVAL(PHP5TO7_ZVAL_MAYBE_P(self->timeout), 1, 0);
  } else if (name_len == 9 && strncmp("arguments", name, name_len) == 0) {
    if (PHP5TO7_ZVAL_IS_UNDEF(self->arguments)) {
      RETURN_NULL();
    }
    RETURN_ZVAL(PHP5TO7_ZVAL_MAYBE_P(self->arguments), 1, 0);
  } else if (name_len == 11 && strncmp("retryPolicy", name, name_len) == 0) {
    if (PHP5TO7_ZVAL_IS_UNDEF(self->retry_policy)) {
      RETURN_NULL();
    }
    RETURN_ZVAL(PHP5TO7_ZVAL_MAYBE_P(self->retry_policy), 1, 0);
  } else if (name_len == 9 && strncmp("timestamp", name, name_len) == 0) {
    char *string;
    if (self->timestamp == INT64_MIN) {
      RETURN_NULL();
    }
#ifdef WIN32
    spprintf(&string, 0, "%I64d", (long long int) self->timestamp);
#else
    spprintf(&string, 0, "%lld", (long long int) self->timestamp);
#endif
    PHP5TO7_RETVAL_STRING(string);
    efree(string);
  }
}
Esempio n. 23
0
static void php_facedetect(INTERNAL_FUNCTION_PARAMETERS, int return_type)
{
	char *file, *casc;
	long flen, clen;

	zval *array;

	CvHaarClassifierCascade* cascade;
	IplImage *img, *gray;
	CvMemStorage *storage;
	CvSeq *faces;
	CvRect *rect;

	if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ssd", &file, &flen, &casc, &clen, scalefactor) == FAILURE) {
		RETURN_NULL();
	}

	img = cvLoadImage(file, 1);
	if(!img) {
		RETURN_FALSE;
	}

	cascade = (CvHaarClassifierCascade*)cvLoad(casc, 0, 0, 0);
	if(!cascade) {
		RETURN_FALSE;
	}

	gray = cvCreateImage(cvSize(img->width, img->height), 8, 1);
	cvCvtColor(img, gray, CV_BGR2GRAY);
	cvEqualizeHist(gray, gray);

	storage = cvCreateMemStorage(0);

	faces = cvHaarDetectObjects(gray, cascade, storage, scalefactor, 2, CV_HAAR_DO_CANNY_PRUNING, cvSize(0, 0), cvSize(0, 0));

	if(return_type) {

		array_init(return_value);

		if(faces && faces->total > 0) {
			int i;
			for(i = 0; i < faces->total; i++) {
				MAKE_STD_ZVAL(array);
				array_init(array);

				rect = (CvRect *)cvGetSeqElem(faces, i);

				add_assoc_long(array, "x", rect->x);
				add_assoc_long(array, "y", rect->y);
				add_assoc_long(array, "w", rect->width);
				add_assoc_long(array, "h", rect->height);

				add_next_index_zval(return_value, array);
			}
		}
	} else {
		RETVAL_LONG(faces ? faces->total : 0);
	}

	cvReleaseMemStorage(&storage);
	cvReleaseImage(&gray);
	cvReleaseImage(&img);
}
PHP_METHOD(ExecutionOptions, __construct)
{
  zval *options = NULL;
  cassandra_execution_options *self = NULL;
  php5to7_zval *consistency = NULL;
  php5to7_zval *serial_consistency = NULL;
  php5to7_zval *page_size = NULL;
  php5to7_zval *paging_state_token = NULL;
  php5to7_zval *timeout = NULL;
  php5to7_zval *arguments = NULL;
  php5to7_zval *retry_policy = NULL;
  php5to7_zval *timestamp = NULL;

  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &options) == FAILURE) {
    return;
  }

  if (!options) return;

  if (Z_TYPE_P(options) != IS_ARRAY) {
    INVALID_ARGUMENT(options, "an array");
  }

  self = PHP_CASSANDRA_GET_EXECUTION_OPTIONS(getThis());

  if (PHP5TO7_ZEND_HASH_FIND(Z_ARRVAL_P(options), "consistency", sizeof("consistency"), consistency)) {
    if (php_cassandra_get_consistency(PHP5TO7_ZVAL_MAYBE_DEREF(consistency), &self->consistency TSRMLS_CC) == FAILURE) {
      return;
    }
  }

  if (PHP5TO7_ZEND_HASH_FIND(Z_ARRVAL_P(options), "serial_consistency", sizeof("serial_consistency"), serial_consistency)) {
    if (php_cassandra_get_serial_consistency(PHP5TO7_ZVAL_MAYBE_DEREF(serial_consistency), &self->serial_consistency TSRMLS_CC) == FAILURE) {
      return;
    }
  }

  if (PHP5TO7_ZEND_HASH_FIND(Z_ARRVAL_P(options), "page_size", sizeof("page_size"), page_size)) {
    if (Z_TYPE_P(PHP5TO7_ZVAL_MAYBE_DEREF(page_size)) != IS_LONG || Z_LVAL_P(PHP5TO7_ZVAL_MAYBE_DEREF(page_size)) <= 0) {
      throw_invalid_argument(PHP5TO7_ZVAL_MAYBE_DEREF(page_size), "page_size", "greater than zero" TSRMLS_CC);
      return;
    }
    self->page_size = Z_LVAL_P(PHP5TO7_ZVAL_MAYBE_DEREF(page_size));
  }

  if (PHP5TO7_ZEND_HASH_FIND(Z_ARRVAL_P(options), "paging_state_token", sizeof("paging_state_token"), paging_state_token)) {
    if (Z_TYPE_P(PHP5TO7_ZVAL_MAYBE_DEREF(paging_state_token)) != IS_STRING) {
      throw_invalid_argument(PHP5TO7_ZVAL_MAYBE_DEREF(paging_state_token), "paging_state_token", "a string" TSRMLS_CC);
      return;
    }
    self->paging_state_token = estrndup(Z_STRVAL_P(PHP5TO7_ZVAL_MAYBE_DEREF(paging_state_token)),
                                        Z_STRLEN_P(PHP5TO7_ZVAL_MAYBE_DEREF(paging_state_token)));
    self->paging_state_token_size = Z_STRLEN_P(PHP5TO7_ZVAL_MAYBE_DEREF(paging_state_token));
  }

  if (PHP5TO7_ZEND_HASH_FIND(Z_ARRVAL_P(options), "timeout", sizeof("timeout"), timeout)) {
    if (!(Z_TYPE_P(PHP5TO7_ZVAL_MAYBE_DEREF(timeout)) == IS_LONG   && Z_LVAL_P(PHP5TO7_ZVAL_MAYBE_DEREF(timeout)) > 0) &&
        !(Z_TYPE_P(PHP5TO7_ZVAL_MAYBE_DEREF(timeout)) == IS_DOUBLE && Z_DVAL_P(PHP5TO7_ZVAL_MAYBE_DEREF(timeout)) > 0) &&
        !(Z_TYPE_P(PHP5TO7_ZVAL_MAYBE_DEREF(timeout)) == IS_NULL)) {
      throw_invalid_argument(PHP5TO7_ZVAL_MAYBE_DEREF(timeout), "timeout", "a number of seconds greater than zero or null" TSRMLS_CC);
      return;
    }

    PHP5TO7_ZVAL_COPY(PHP5TO7_ZVAL_MAYBE_P(self->timeout), PHP5TO7_ZVAL_MAYBE_DEREF(timeout));
  }

  if (PHP5TO7_ZEND_HASH_FIND(Z_ARRVAL_P(options), "arguments", sizeof("arguments"), arguments)) {
    if (Z_TYPE_P(PHP5TO7_ZVAL_MAYBE_DEREF(arguments)) != IS_ARRAY) {
      throw_invalid_argument(PHP5TO7_ZVAL_MAYBE_DEREF(arguments), "arguments", "an array" TSRMLS_CC);
      return;
    }
    PHP5TO7_ZVAL_COPY(PHP5TO7_ZVAL_MAYBE_P(self->arguments), PHP5TO7_ZVAL_MAYBE_DEREF(arguments));
  }

  if (PHP5TO7_ZEND_HASH_FIND(Z_ARRVAL_P(options), "retry_policy", sizeof("retry_policy"), retry_policy)) {
    if (Z_TYPE_P(PHP5TO7_ZVAL_MAYBE_DEREF(retry_policy)) != IS_OBJECT &&
        !instanceof_function(Z_OBJCE_P(PHP5TO7_ZVAL_MAYBE_DEREF(retry_policy)),
                                       cassandra_retry_policy_ce TSRMLS_CC)) {
      throw_invalid_argument(PHP5TO7_ZVAL_MAYBE_DEREF(retry_policy),
                             "retry_policy",
                             "an instance of Cassandra\\RetryPolicy" TSRMLS_CC);
      return;
    }
    PHP5TO7_ZVAL_COPY(PHP5TO7_ZVAL_MAYBE_P(self->retry_policy), PHP5TO7_ZVAL_MAYBE_DEREF(retry_policy));
  }

  if (PHP5TO7_ZEND_HASH_FIND(Z_ARRVAL_P(options), "timestamp", sizeof("timestamp"), timestamp)) {
    if (Z_TYPE_P(PHP5TO7_ZVAL_MAYBE_DEREF(timestamp)) == IS_LONG) {
      self->timestamp = Z_LVAL_P(PHP5TO7_ZVAL_MAYBE_DEREF(timestamp));
    } else if (Z_TYPE_P(PHP5TO7_ZVAL_MAYBE_DEREF(timestamp)) == IS_STRING) {
      if (!php_cassandra_parse_bigint(Z_STRVAL_P(PHP5TO7_ZVAL_MAYBE_DEREF(timestamp)),
                                      Z_STRLEN_P(PHP5TO7_ZVAL_MAYBE_DEREF(timestamp)),
                                      &self->timestamp TSRMLS_CC)) {
        return;
      }
    } else {
      throw_invalid_argument(PHP5TO7_ZVAL_MAYBE_DEREF(timestamp), "timestamp", "an integer or integer string" TSRMLS_CC);
      return;
    }
  }
}
Esempio n. 25
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;
}
Esempio n. 26
0
/**
 * Moves internal resulset cursor to another position letting us to fetch a certain row
 *
 *<code>
 *	$result = $connection->query("SELECT * FROM robots ORDER BY name");
 *	$result->dataSeek(2); // Move to third row on result
 *	$row = $result->fetch(); // Fetch third row
 *</code>
 *
 * @param int $number
 */
PHP_METHOD(Phalcon_Db_Result_Pdo, dataSeek){

	long number = 0, n;
	zval *connection, *pdo = NULL, *sql_statement;
	zval *bind_params, *bind_types, *statement = NULL;
	zval *temp_statement = NULL;
	pdo_stmt_t *stmt;

	PHALCON_MM_GROW();

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &number) == FAILURE) {
		RETURN_MM_NULL();
	}

	connection = phalcon_read_property(getThis(), SL("_connection"), PH_NOISY);

	PHALCON_CALL_METHOD(&pdo, connection, "getinternalhandler");

	sql_statement = phalcon_read_property(getThis(), SL("_sqlStatement"), PH_NOISY);
	bind_params = phalcon_read_property(getThis(), SL("_bindParams"), PH_NOISY);

	/**
	 * PDO doesn't support scrollable cursors, so we need to re-execute the statement again
	 */
	if (Z_TYPE_P(bind_params) == IS_ARRAY) {
		bind_types = phalcon_read_property(getThis(), SL("_bindTypes"), PH_NOISY);

		PHALCON_CALL_METHOD(&statement, pdo, "prepare", sql_statement);
		if (Z_TYPE_P(statement) == IS_OBJECT) {
			PHALCON_CALL_METHOD(&temp_statement, connection, "executeprepared", statement, bind_params, bind_types);
			PHALCON_CPY_WRT(statement, temp_statement);
		}

	} else {
		PHALCON_CALL_METHOD(&statement, pdo, "query", sql_statement);
	}

	phalcon_update_property_zval(getThis(), SL("_pdoStatement"), statement);

	/**
	 * This a fetch scroll to reach the desired position, however with a big number of records
	 * maybe it may be very slow
	 */

	stmt = Z_PDO_STMT_P(statement);
	if (!stmt->dbh) {
		PHALCON_MM_RESTORE();
		RETURN_FALSE;
	}

	n = -1;
	number--;
	while (n != number) {

		if(!stmt->methods->fetcher(stmt, PDO_FETCH_ORI_NEXT, 0)) {
			PHALCON_MM_RESTORE();
			RETURN_NULL();
		}

		n++;
	}

	PHALCON_MM_RESTORE();
}
Esempio n. 27
0
/**
 * Stores cached content into the APC backend and stops the frontend
 *
 * @param string $keyName
 * @param string $content
 * @param long $lifetime
 * @param boolean $stopBuffer
 */
PHP_METHOD(Phalcon_Cache_Backend_Apc, save) {

    zval *key_name = NULL, *content = NULL, *lifetime = NULL, *stop_buffer = NULL;
    zval *last_key = NULL, *prefix, *frontend, *cached_content = NULL;
    zval *prepared_content, *ttl = NULL, *is_buffering;

    PHALCON_MM_GROW();

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|zzzz", &key_name, &content, &lifetime, &stop_buffer) == FAILURE) {
        RETURN_MM_NULL();
    }

    if (!key_name) {
        PHALCON_INIT_VAR(key_name);
    }

    if (!content) {
        PHALCON_INIT_VAR(content);
    }

    if (!lifetime) {
        PHALCON_INIT_VAR(lifetime);
    }

    if (!stop_buffer) {
        PHALCON_INIT_VAR(stop_buffer);
        ZVAL_BOOL(stop_buffer, 1);
    }

    if (Z_TYPE_P(key_name) == IS_NULL) {
        PHALCON_OBS_VAR(last_key);
        phalcon_read_property_this(&last_key, this_ptr, SL("_lastKey"), PH_NOISY_CC);
    } else {
        PHALCON_OBS_VAR(prefix);
        phalcon_read_property_this(&prefix, this_ptr, SL("_prefix"), PH_NOISY_CC);

        PHALCON_INIT_NVAR(last_key);
        PHALCON_CONCAT_SVV(last_key, "_PHCA", prefix, key_name);
    }
    if (!zend_is_true(last_key)) {
        PHALCON_THROW_EXCEPTION_STR(phalcon_cache_exception_ce, "The cache must be started first");
        return;
    }

    PHALCON_OBS_VAR(frontend);
    phalcon_read_property_this(&frontend, this_ptr, SL("_frontend"), PH_NOISY_CC);
    if (Z_TYPE_P(content) == IS_NULL) {
        PHALCON_INIT_VAR(cached_content);
        PHALCON_CALL_METHOD(cached_content, frontend, "getcontent");
    } else {
        PHALCON_CPY_WRT(cached_content, content);
    }

    PHALCON_INIT_VAR(prepared_content);
    PHALCON_CALL_METHOD_PARAMS_1(prepared_content, frontend, "beforestore", cached_content);
    if (Z_TYPE_P(lifetime) == IS_NULL) {
        PHALCON_INIT_VAR(ttl);
        PHALCON_CALL_METHOD(ttl, frontend, "getlifetime");
    } else {
        PHALCON_CPY_WRT(ttl, lifetime);
    }

    PHALCON_CALL_FUNC_PARAMS_3_NORETURN("apc_store", last_key, prepared_content, ttl);

    PHALCON_INIT_VAR(is_buffering);
    PHALCON_CALL_METHOD(is_buffering, frontend, "isbuffering");
    if (PHALCON_IS_TRUE(stop_buffer)) {
        PHALCON_CALL_METHOD_NORETURN(frontend, "stop");
    }

    if (PHALCON_IS_TRUE(is_buffering)) {
        zend_print_zval(cached_content, 0);
    }

    phalcon_update_property_bool(this_ptr, SL("_started"), 0 TSRMLS_CC);

    PHALCON_MM_RESTORE();
}
Esempio n. 28
0
/**
 * Moves internal resulset cursor to another position letting us to fetch a certain row
 *
 *<code>
 *	$result = $connection->query("SELECT * FROM robots ORDER BY name");
 *	$result->dataSeek(2); // Move to third row on result
 *	$row = $result->fetch(); // Fetch third row
 *</code>
 *
 * @param int $number
 */
PHP_METHOD(Phalcon_Db_Result_Pdo, dataSeek){

	long number = 0, n;
	zval *connection, *pdo, *sql_statement;
	zval *bind_params, *bind_types, *statement = NULL;
	zval *temp_statement = NULL;
	pdo_stmt_t *stmt;

	PHALCON_MM_GROW();

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

	PHALCON_INIT_VAR(connection);
	phalcon_read_property(&connection, this_ptr, SL("_connection"), PH_NOISY_CC);

	PHALCON_INIT_VAR(pdo);
	PHALCON_CALL_METHOD(pdo, connection, "getinternalhandler", PH_NO_CHECK);

	PHALCON_INIT_VAR(sql_statement);
	phalcon_read_property(&sql_statement, this_ptr, SL("_sqlStatement"), PH_NOISY_CC);

	PHALCON_INIT_VAR(bind_params);
	phalcon_read_property(&bind_params, this_ptr, SL("_bindParams"), PH_NOISY_CC);

	/**
	 * PDO doesn't support scrollable cursors, so we need to re-execute the statement again
	 */
	if (Z_TYPE_P(bind_params) == IS_ARRAY) {

		PHALCON_INIT_VAR(bind_types);
		phalcon_read_property(&bind_types, this_ptr, SL("_bindTypes"), PH_NOISY_CC);

		PHALCON_INIT_VAR(statement);
		PHALCON_CALL_METHOD_PARAMS_1(statement, pdo, "prepare", sql_statement, PH_NO_CHECK);
		if (Z_TYPE_P(statement) == IS_OBJECT) {
			PHALCON_INIT_VAR(temp_statement);
			PHALCON_CALL_METHOD_PARAMS_3(temp_statement, connection, "executeprepared", statement, bind_params, bind_types, PH_NO_CHECK);
			PHALCON_CPY_WRT(statement, temp_statement);
		}

	} else {
		PHALCON_INIT_NVAR(statement);
		PHALCON_CALL_METHOD_PARAMS_1(statement, pdo, "query", sql_statement, PH_NO_CHECK);
	}

	phalcon_update_property_zval(this_ptr, SL("_pdoStatement"), statement TSRMLS_CC);

	/**
	 * This a fetch scroll to reach the desired position, however with a big number of records
	 * maybe it may be very slow
	 */

	stmt = (pdo_stmt_t*) zend_object_store_get_object(statement TSRMLS_CC);
	if (!stmt->dbh) {
		PHALCON_MM_RESTORE();
		RETURN_FALSE;
	}

	n = -1;
	number--;
	while (n != number) {

		if(!stmt->methods->fetcher(stmt, PDO_FETCH_ORI_NEXT, 0 TSRMLS_CC)) {
			PHALCON_MM_RESTORE();
			RETURN_NULL();
		}

		n++;
	}

	PHALCON_MM_RESTORE();
}
Esempio n. 29
0
/* {{{ proto void run()
   */
PHP_METHOD(SlightPHP, run)
{
	zval *zone=NULL;
	zval *page=NULL;
	zval *entry=NULL;

	zval **token;
	//zval *path=NULL;
	zval *server=NULL;
	zval *path_array;

	//{{{
	int isPart;
	zval * path = NULL;
	if (ZEND_NUM_ARGS()>0 && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z/", &path) != FAILURE) {
		if (Z_TYPE_P(path)!= IS_STRING){
				RETURN_FALSE;
		}
		isPart = 1;
	}else{
		isPart = 0;
		zend_is_auto_global("_SERVER", sizeof("_SERVER") - 1 TSRMLS_CC);
		server = PG(http_globals)[TRACK_VARS_SERVER];
		if(!server){
			RETURN_FALSE;
		}
		if(zend_hash_find(HASH_OF(server), "PATH_INFO", sizeof("PATH_INFO"), (void **) &token) == SUCCESS
		){
			path = *token;
		}
	}

	//}}}

	MAKE_STD_ZVAL(path_array);
	array_init(path_array);

	if (path){
		//{{{
		zval quotedFlag;
		regex_t re;
		char	*regex;
		regmatch_t subs[1];
		int err,size;
		char *strp = Z_STRVAL_P(path);
		char *endp = strp + Z_STRLEN_P(path);
		zval *splitFlag = zend_read_static_property(SlightPHP_ce_ptr,"splitFlag",sizeof("splitFlag")-1,1 TSRMLS_CC);

		if(preg_quote(splitFlag,&quotedFlag)>0){
			spprintf(&regex,0,"[%s\\/]",Z_STRVAL(quotedFlag));
		}else{
			spprintf(&regex,0,"[\\/]");
		}
		err = regcomp(&re, regex, REG_ICASE);
		if (err) {
		}else{
			while (!(err = regexec(&re, strp, 1, subs, 0))) {
				if (subs[0].rm_so == 0 && subs[0].rm_eo) {
					//ignore empty string 
					strp += subs[0].rm_eo;
				}else if (subs[0].rm_so == 0 && subs[0].rm_eo == 0) {
				}else{
						size = subs[0].rm_so;
			            add_next_index_stringl(path_array, strp, size, 1);
			            strp += size;
			
				}
			}
			if (!err || err == REG_NOMATCH) {
				size = endp - strp;
				if(size>0) add_next_index_stringl(path_array, strp, size, 1);
			}
			regfree(&re);
		}
		efree(regex);
		//}}}
		int n_elems = zend_hash_num_elements(Z_ARRVAL_P(path_array));
		if(zend_hash_index_find(Z_ARRVAL_P(path_array), 0, (void **)&token) != FAILURE) {
			zone = *token;
		}
		if(zend_hash_index_find(Z_ARRVAL_P(path_array), 1, (void **)&token) != FAILURE) {
			page = *token;
		}
		if(zend_hash_index_find(Z_ARRVAL_P(path_array), 2, (void **)&token) != FAILURE) {
			entry = *token;
		}
			
	}
	if(!zone){
		zone = zend_read_static_property(SlightPHP_ce_ptr,"defaultZone",sizeof("defaultZone")-1,1 TSRMLS_CC);
		zend_hash_next_index_insert(Z_ARRVAL_P(path_array),&zone,sizeof(zval*),NULL);
	}
	if(!page){
		page = zend_read_static_property(SlightPHP_ce_ptr,"defaultPage",sizeof("defaultPage")-1,1 TSRMLS_CC);
		zend_hash_next_index_insert(Z_ARRVAL_P(path_array),&page,sizeof(zval*),NULL);
	}
	if(!entry){
		entry = zend_read_static_property(SlightPHP_ce_ptr,"defaultEntry",sizeof("defaultEntry")-1,1 TSRMLS_CC);
		zend_hash_next_index_insert(Z_ARRVAL_P(path_array),&entry,sizeof(zval*),NULL);
	}
	//{{{
	zval *zoneAlias = zend_read_static_property(SlightPHP_ce_ptr,"zoneAlias",sizeof("zoneAlias")-1,1 TSRMLS_CC);
	if(zoneAlias && Z_TYPE_P(zoneAlias)==IS_ARRAY){
		char *string_key;uint str_key_len;ulong num_key;
		HashPosition pos;
		zval **entry2;
		zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(zoneAlias), &pos);
		while (zend_hash_get_current_data_ex(Z_ARRVAL_P(zoneAlias), (void **)&entry2, &pos) == SUCCESS) {
			if(strcmp(Z_STRVAL_PP(entry2) ,Z_STRVAL_P(zone))==0){
				switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(zoneAlias), &string_key, &str_key_len, &num_key, 0, &pos)) {
					case HASH_KEY_IS_STRING:
						ZVAL_STRING(zone,string_key,1);
						break;
				}
			}
			zend_hash_move_forward_ex(Z_ARRVAL_P(zoneAlias), &pos);
		}
	}
	//}}}
	if(!isPart){
		zend_update_static_property(SlightPHP_ce_ptr,"zone",sizeof("zone")-1,zone TSRMLS_CC);
		zend_update_static_property(SlightPHP_ce_ptr,"page",sizeof("page")-1,page TSRMLS_CC);
		zend_update_static_property(SlightPHP_ce_ptr,"entry",sizeof("entry")-1,entry TSRMLS_CC);
	}else{
		if(
			strcmp(Z_STRVAL_P(zone),Z_STRVAL_P(zend_read_static_property(SlightPHP_ce_ptr,"zone",sizeof("zone")-1,1 TSRMLS_CC)))==0 
			&&
			strcmp(Z_STRVAL_P(page),Z_STRVAL_P(zend_read_static_property(SlightPHP_ce_ptr,"page",sizeof("page")-1,1 TSRMLS_CC)))==0 
			&&
			strcmp(Z_STRVAL_P(entry),Z_STRVAL_P(zend_read_static_property(SlightPHP_ce_ptr,"entry",sizeof("entry")-1,1 TSRMLS_CC)))==0 
			){
			debug("part ignored [%s]",Z_STRVAL_P(path));
			return;
		}
	}

	zval *tmp_result=NULL;

	zval *appDir = zend_read_static_property(SlightPHP_ce_ptr,"appDir",sizeof("appDir")-1,1 TSRMLS_CC);
	
	zval **params[1];
	params[0]=&path_array;


	if(SlightPHP_load(appDir,zone,page TSRMLS_CC) == SUCCESS){
		if(SlightPHP_run(zone,page,entry,&tmp_result,1,params TSRMLS_CC)==SUCCESS){
		};
	}
	FREE_ZVAL(path_array);

	if(tmp_result){
		*return_value = *tmp_result;
		zval_copy_ctor(return_value);
		zval_ptr_dtor(&tmp_result);
	}else{
		RETURN_FALSE;
	}
}
Esempio n. 30
0
/**
 * Sends SQL statements to the database server returning the success state.
 * Use this method only when the SQL statement sent to the server doesn't return any row
 *
 *<code>
 *	//Inserting data
 *	$success = $connection->execute("INSERT INTO robots VALUES (1, 'Astro Boy')");
 *	$success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy'));
 *</code>
 *
 * @param  string $sqlStatement
 * @param  array $bindParams
 * @param  array $bindTypes
 * @return boolean
 */
PHP_METHOD(Phalcon_Db_Adapter_Pdo, execute){

	zval *sql_statement, *bind_params = NULL, *bind_types = NULL;
	zval *events_manager, *event_name = NULL, *status, *pdo;
	zval *statement = NULL, *affected_rows = NULL;
	zval *r0 = NULL;

	PHALCON_MM_GROW();

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|zz", &sql_statement, &bind_params, &bind_types) == FAILURE) {
		RETURN_MM_NULL();
	}

	if (!bind_params) {
		PHALCON_INIT_VAR(bind_params);
	}
	
	if (!bind_types) {
		PHALCON_INIT_VAR(bind_types);
	}
	
	/** 
	 * Execute the beforeQuery event if a EventsManager is available
	 */
	PHALCON_OBS_VAR(events_manager);
	phalcon_read_property(&events_manager, this_ptr, SL("_eventsManager"), PH_NOISY_CC);
	if (Z_TYPE_P(events_manager) == IS_OBJECT) {
	
		PHALCON_INIT_VAR(event_name);
		ZVAL_STRING(event_name, "db:beforeQuery", 1);
		phalcon_update_property_zval(this_ptr, SL("_sqlStatement"), sql_statement TSRMLS_CC);
		phalcon_update_property_zval(this_ptr, SL("_sqlVariables"), bind_params TSRMLS_CC);
		phalcon_update_property_zval(this_ptr, SL("_sqlBindTypes"), bind_types TSRMLS_CC);
	
		PHALCON_INIT_VAR(status);
		PHALCON_CALL_METHOD_PARAMS_3(status, events_manager, "fire", event_name, this_ptr, bind_params);
		if (PHALCON_IS_FALSE(status)) {
			RETURN_MM_FALSE;
		}
	}
	
	PHALCON_OBS_VAR(pdo);
	phalcon_read_property(&pdo, this_ptr, SL("_pdo"), PH_NOISY_CC);
	if (Z_TYPE_P(bind_params) == IS_ARRAY) { 
	
		PHALCON_INIT_VAR(statement);
		PHALCON_CALL_METHOD_PARAMS_1(statement, pdo, "prepare", sql_statement);
		if (Z_TYPE_P(statement) == IS_OBJECT) {
			PHALCON_INIT_VAR(r0);
			PHALCON_CALL_METHOD_PARAMS_3(r0, this_ptr, "executeprepared", statement, bind_params, bind_types);
			PHALCON_CPY_WRT(statement, r0);
	
			PHALCON_INIT_VAR(affected_rows);
			PHALCON_CALL_METHOD(affected_rows, statement, "rowcount");
		}
	} else {
		PHALCON_INIT_NVAR(affected_rows);
		PHALCON_CALL_METHOD_PARAMS_1(affected_rows, pdo, "exec", sql_statement);
	}
	
	/** 
	 * Execute the afterQuery event if a EventsManager is available
	 */
	if (Z_TYPE_P(affected_rows) == IS_LONG) {
		phalcon_update_property_zval(this_ptr, SL("_affectedRows"), affected_rows TSRMLS_CC);
		if (Z_TYPE_P(events_manager) == IS_OBJECT) {
			PHALCON_INIT_NVAR(event_name);
			ZVAL_STRING(event_name, "db:afterQuery", 1);
			PHALCON_CALL_METHOD_PARAMS_3_NORETURN(events_manager, "fire", event_name, this_ptr, bind_params);
		}
	}
	
	RETURN_MM_TRUE;
}