예제 #1
0
static void _php_cal_info(int cal, zval **ret)
{
	zval *months, *smonths;
	int i;
	struct cal_entry_t *calendar;

	calendar = &cal_conversion_table[cal];
	array_init(*ret);

	MAKE_STD_ZVAL(months);
	MAKE_STD_ZVAL(smonths);
	array_init(months);
	array_init(smonths);

	for (i = 1; i <= calendar->num_months; i++) {
		add_index_string(months, i, calendar->month_name_long[i], 1);
		add_index_string(smonths, i, calendar->month_name_short[i], 1);
	}
	add_assoc_zval(*ret, "months", months);
	add_assoc_zval(*ret, "abbrevmonths", smonths);
	add_assoc_long(*ret, "maxdaysinmonth", calendar->max_days_in_month);
	add_assoc_string(*ret, "calname", calendar->name, 1);
	add_assoc_string(*ret, "calsymbol", calendar->symbol, 1);
	
}
예제 #2
0
PHP_METHOD(Pinyin, exactConvert)
{
    IPYNotation *pynotation = get_pinyin_notation(getThis());
    char        *str        = NULL;
    int          len;
    zend_bool    get_tone   = 0;
    bool         result     = 0;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &str, &len, &get_tone) == FAILURE) {
        RETURN_FALSE;
    }

    vector<string> py_result;
    if(get_tone) {
        result = pynotation->exactToTonePY(str, &py_result);
    } else {
        result = pynotation->exactToPY(str, &py_result); 
    }
    if(result) {
        array_init(return_value);
        int i = 0;
        for(vector<string>::iterator it = py_result.begin(); it != py_result.end(); it++) {
            add_index_string(return_value, i++, (*it).c_str(), 1);
        }
    } else {
        RETURN_FALSE;
    }
}
예제 #3
0
파일: source.c 프로젝트: gtkforphp/glib
static void
glib_source_callback_helper(zval *retval, zval *source_zval, const char *name, zval *params, uint32_t param_count)
{
	zend_fcall_info fci;
	zend_fcall_info_cache fci_cache;
	zval caller;

	array_init(&caller);
	add_index_zval(&caller, 0, source_zval);
	add_index_string(&caller, 1, name);

	char * callback_error;
	if(FAILURE == zend_fcall_info_init(&caller, IS_CALLABLE_STRICT, &fci, &fci_cache, NULL, &callback_error))
	{
		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
			"Could not call %s source handler, %s", name, callback_error);
		zval_dtor(&caller);
		return;
	}

	/* Handle arguments if necessary */
	fci.param_count = param_count;
	if(param_count > 0) {
		fci.params = params;
	}

	fci.retval = retval;
	if(FAILURE == zend_call_function(&fci, &fci_cache)) {
		zend_throw_exception_ex(spl_ce_BadFunctionCallException, 0,
			"Could not call %s source handler", name);
	}
	zval_dtor(&caller);
}
예제 #4
0
파일: objects1.c 프로젝트: Leon2012/php-ext
static PHP_METHOD(Hello, addProperties) {
    zval *obj;
    obj = getThis();

    /*add zval property*/
    zval *arr;
    MAKE_STD_ZVAL(arr);
    array_init(arr);
    add_assoc_string(arr, "e", "hello", 1);
    add_index_string(arr, 1, "hello1111", 1);
    add_property_zval_ex(obj, "persons", strlen("persons")+1, arr TSRMLS_CC);
    Z_DELREF_P(arr);


    /*add double property*/
    add_property_double(obj, "d", 10.5);

    /*add bool property*/
    add_property_bool(obj, "b", 1);

    /*add string property*/
    char *str = "hello str";
    add_property_string(obj, "str", str, 1);
    
    /*add long property*/
    add_property_long(obj, "l", 12);
}
예제 #5
0
static void _php_cal_info(int cal, zval *ret)
{
	zval months, smonths;
	int i;
	struct cal_entry_t *calendar;

	calendar = &cal_conversion_table[cal];
	array_init(ret);

	array_init(&months);
	array_init(&smonths);

	for (i = 1; i <= calendar->num_months; i++) {
		add_index_string(&months, i, calendar->month_name_long[i]);
		add_index_string(&smonths, i, calendar->month_name_short[i]);
	}
	
	add_assoc_zval(ret, "months", &months);
	add_assoc_zval(ret, "abbrevmonths", &smonths);
	add_assoc_long(ret, "maxdaysinmonth", calendar->max_days_in_month);
	add_assoc_string(ret, "calname", calendar->name);
	add_assoc_string(ret, "calsymbol", calendar->symbol);
	
}
static PHP_METHOD(midgard_workspace_storage, list_workspace_names)
{
	if (zend_parse_parameters_none() == FAILURE)
		return;

	guint n_names;
	MidgardWorkspaceStorage *self = MIDGARD_WORKSPACE_STORAGE(__php_gobject_ptr(getThis()));
	char **names = midgard_workspace_storage_list_workspace_names(self, &n_names);

	array_init(return_value);

	if (!names)
		return;

	int i;
	for (i = 0; i < n_names; i++)
		add_index_string(return_value, i, names[i], 1);
}
예제 #7
0
파일: return.c 프로젝트: Leon2012/php-ext
//返回array类型
static PHP_FUNCTION(return_array) {
  zval *sub;

  //zval *return_value ,此参数已经被定义在zif函数声明里了,要操作返回值时只需要操作此值函数会自动返回这个结果出去
  array_init(return_value); // $ret = array();
  add_next_index_bool(return_value, 1); // $ret[] = true;
  add_index_string(return_value, 5, "Hello", 1); // $ret[5] = "Hello";
  add_assoc_long(return_value, "a", 42); //$ret["a"] = 42;
  add_assoc_string(return_value, "c", "d", 1); //$ret["c"] = "d"; 

  //$sub = array()
  MAKE_STD_ZVAL(sub);
  array_init(sub);

  add_assoc_double(sub, "pi", 3.1415926535); //$sub["pi"] = 3.1415926535
  add_next_index_zval(return_value, sub); //$ret[] = $sub;

}
static PHP_METHOD(midgard_query_result, get_column_names)
{
	if (zend_parse_parameters_none() == FAILURE)
		return;

	guint n_names;
	MidgardQueryResult *result = MIDGARD_QUERY_RESULT(__php_gobject_ptr(getThis()));
	gchar **names = midgard_query_result_get_column_names(result, &n_names, NULL);

	array_init(return_value);
	if (names == NULL)
		return;

	guint i;
	for (i = 0; i < n_names; i++) {
		add_index_string(return_value, i, (gchar *)names[i], 1);
	}
	
	g_free(names);	
}
예제 #9
0
파일: zlib.c 프로젝트: Furgas/php-src
/* {{{ proto array gzfile(string filename [, int use_include_path])
   Read and uncompress entire .gz-file into an array */
static PHP_FUNCTION(gzfile)
{
	char *filename;
	size_t filename_len;
	int flags = REPORT_ERRORS;
	char buf[8192] = {0};
	register int i = 0;
	zend_long use_include_path = 0;
	php_stream *stream;

	if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "p|l", &filename, &filename_len, &use_include_path)) {
		return;
	}

	if (use_include_path) {
		flags |= USE_PATH;
	}

	/* using a stream here is a bit more efficient (resource wise) than php_gzopen_wrapper */
	stream = php_stream_gzopen(NULL, filename, "rb", flags, NULL, NULL STREAMS_CC);

	if (!stream) {
		/* Error reporting is already done by stream code */
		RETURN_FALSE;
	}

	/* Initialize return array */
	array_init(return_value);

	/* Now loop through the file and do the magic quotes thing if needed */
	memset(buf, 0, sizeof(buf));

	while (php_stream_gets(stream, buf, sizeof(buf) - 1) != NULL) {
		add_index_string(return_value, i++, buf);
	}
	php_stream_close(stream);
}
예제 #10
0
static PHP_METHOD(midgard_config, list_files)
{
	RETVAL_FALSE;
	zend_bool user = FALSE;

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

	array_init(return_value);

	gchar **files = midgard_config_list_files(user);

	if (!files)
		return;

	size_t i = 0;
	while (files[i] != NULL) {
		add_index_string(return_value, i, files[i], 1);
		i++;
	}

	g_strfreev(files);
}
예제 #11
0
파일: scanf.c 프로젝트: 13572293130/php-src
PHPAPI int php_sscanf_internal( char *string, char *format,
				int argCount, zval *args,
				int varStart, zval *return_value)
{
	int  numVars, nconversions, totalVars = -1;
	int  i, result;
	zend_long value;
	int  objIndex;
	char *end, *baseString;
	zval *current;
	char op   = 0;
	int  base = 0;
	int  underflow = 0;
	size_t width;
	zend_long (*fn)() = NULL;
	char *ch, sch;
	int  flags;
	char buf[64];	/* Temporary buffer to hold scanned number
					 * strings before they are passed to strtoul() */

	/* do some sanity checking */
	if ((varStart > argCount) || (varStart < 0)){
		varStart = SCAN_MAX_ARGS + 1;
	}
	numVars = argCount - varStart;
	if (numVars < 0) {
		numVars = 0;
	}

#if 0
	zend_printf("<br>in sscanf_internal : <br> string is \"%s\", format = \"%s\"<br> NumVars = %d. VarStart = %d<br>-------------------------<br>",
					string, format, numVars, varStart);
#endif
	/*
	 * Check for errors in the format string.
	 */
	if (ValidateFormat(format, numVars, &totalVars) != SCAN_SUCCESS) {
		scan_set_error_return( numVars, return_value );
		return SCAN_ERROR_INVALID_FORMAT;
	}

	objIndex = numVars ? varStart : 0;

	/*
	 * If any variables are passed, make sure they are all passed by reference
	 */
	if (numVars) {
		for (i = varStart;i < argCount;i++){
			if ( ! Z_ISREF(args[ i ] ) ) {
				php_error_docref(NULL, E_WARNING, "Parameter %d must be passed by reference", i);
				scan_set_error_return(numVars, return_value);
				return SCAN_ERROR_VAR_PASSED_BYVAL;
			}
		}
	}

	/*
	 * Allocate space for the result objects. Only happens when no variables
	 * are specified
	 */
	if (!numVars) {
		zval tmp;

		/* allocate an array for return */
		array_init(return_value);

		for (i = 0; i < totalVars; i++) {
			ZVAL_NULL(&tmp);
			if (add_next_index_zval(return_value, &tmp) == FAILURE) {
				scan_set_error_return(0, return_value);
				return FAILURE;
			}
		}
		varStart = 0; /* Array index starts from 0 */
	}

	baseString = string;

	/*
	 * Iterate over the format string filling in the result objects until
	 * we reach the end of input, the end of the format string, or there
	 * is a mismatch.
	 */
	nconversions = 0;
	/* note ! - we need to limit the loop for objIndex to keep it in bounds */

	while (*format != '\0') {
		ch    = format++;
		flags = 0;

		/*
		 * If we see whitespace in the format, skip whitespace in the string.
		 */
		if ( isspace( (int)*ch ) ) {
			sch = *string;
			while ( isspace( (int)sch ) ) {
				if (*string == '\0') {
					goto done;
				}
				string++;
				sch = *string;
			}
			continue;
		}

		if (*ch != '%') {
literal:
			if (*string == '\0') {
				underflow = 1;
				goto done;
			}
			sch = *string;
			string++;
			if (*ch != sch) {
				goto done;
			}
			continue;
		}

		ch = format++;
		if (*ch == '%') {
			goto literal;
		}

		/*
		 * Check for assignment suppression ('*') or an XPG3-style
		 * assignment ('%n$').
		 */
		if (*ch == '*') {
			flags |= SCAN_SUPPRESS;
			ch = format++;
		} else if ( isdigit(UCHAR(*ch))) {
			value = ZEND_STRTOUL(format-1, &end, 10);
			if (*end == '$') {
				format = end+1;
				ch = format++;
				objIndex = varStart + value - 1;
			}
		}

		/*
		 * Parse any width specifier.
		 */
		if ( isdigit(UCHAR(*ch))) {
			width = ZEND_STRTOUL(format-1, &format, 10);
			ch = format++;
		} else {
			width = 0;
		}

		/*
		 * Ignore size specifier.
		 */
		if ((*ch == 'l') || (*ch == 'L') || (*ch == 'h')) {
			ch = format++;
		}

		/*
		 * Handle the various field types.
		 */
		switch (*ch) {
			case 'n':
				if (!(flags & SCAN_SUPPRESS)) {
					if (numVars && objIndex >= argCount) {
						break;
					} else if (numVars) {
						current = Z_REFVAL(args[objIndex++]);
						zval_ptr_dtor(current);
						ZVAL_LONG(current, (zend_long)(string - baseString) );
					} else {
						add_index_long(return_value, objIndex++, string - baseString);
					}
				}
				nconversions++;
				continue;

			case 'd':
			case 'D':
				op = 'i';
				base = 10;
				fn = (zend_long (*)())ZEND_STRTOL_PTR;
				break;
			case 'i':
				op = 'i';
				base = 0;
				fn = (zend_long (*)())ZEND_STRTOL_PTR;
				break;
			case 'o':
				op = 'i';
				base = 8;
				fn = (zend_long (*)())ZEND_STRTOL_PTR;
				break;
			case 'x':
			case 'X':
				op = 'i';
				base = 16;
				fn = (zend_long (*)())ZEND_STRTOL_PTR;
				break;
			case 'u':
				op = 'i';
				base = 10;
				flags |= SCAN_UNSIGNED;
				fn = (zend_long (*)())ZEND_STRTOUL_PTR;
				break;

			case 'f':
			case 'e':
			case 'E':
			case 'g':
				op = 'f';
				break;

			case 's':
				op = 's';
				break;

			case 'c':
				op = 's';
				flags |= SCAN_NOSKIP;
				/*-cc-*/
				if (0 == width) {
					width = 1;
				}
				/*-cc-*/
				break;
			case '[':
				op = '[';
				flags |= SCAN_NOSKIP;
				break;
		}   /* switch */

		/*
		 * At this point, we will need additional characters from the
		 * string to proceed.
		 */
		if (*string == '\0') {
			underflow = 1;
			goto done;
		}

		/*
		 * Skip any leading whitespace at the beginning of a field unless
		 * the format suppresses this behavior.
		 */
		if (!(flags & SCAN_NOSKIP)) {
			while (*string != '\0') {
				sch = *string;
				if (! isspace((int)sch) ) {
					break;
				}
				string++;
			}
			if (*string == '\0') {
				underflow = 1;
				goto done;
			}
		}

		/*
		 * Perform the requested scanning operation.
		 */
		switch (op) {
			case 'c':
			case 's':
				/*
				 * Scan a string up to width characters or whitespace.
				 */
				if (width == 0) {
					width = (size_t) ~0;
				}
				end = string;
				while (*end != '\0') {
					sch = *end;
					if ( isspace( (int)sch ) ) {
						break;
					}
					end++;
					if (--width == 0) {
					   break;
					}
				}
				if (!(flags & SCAN_SUPPRESS)) {
					if (numVars && objIndex >= argCount) {
						break;
					} else if (numVars) {
						current = Z_REFVAL(args[objIndex++]);
						zval_ptr_dtor(current);
						ZVAL_STRINGL(current, string, end-string);
					} else {
						add_index_stringl(return_value, objIndex++, string, end-string);
					}
				}
				string = end;
				break;

			case '[': {
				CharSet cset;

				if (width == 0) {
					width = (size_t) ~0;
				}
				end = string;

				format = BuildCharSet(&cset, format);
				while (*end != '\0') {
					sch = *end;
					if (!CharInSet(&cset, (int)sch)) {
						break;
					}
					end++;
					if (--width == 0) {
						break;
					}
				}
				ReleaseCharSet(&cset);

				if (string == end) {
					/*
					 * Nothing matched the range, stop processing
					 */
					goto done;
				}
				if (!(flags & SCAN_SUPPRESS)) {
					if (numVars && objIndex >= argCount) {
						break;
					} else if (numVars) {
						current = Z_REFVAL(args[objIndex++]);
						zval_ptr_dtor(current);
						ZVAL_STRINGL(current, string, end-string);
					} else {
						add_index_stringl(return_value, objIndex++, string, end-string);
					}
				}
				string = end;
				break;
			}
/*
			case 'c':
			   / Scan a single character./

				sch = *string;
				string++;
				if (!(flags & SCAN_SUPPRESS)) {
					if (numVars) {
						char __buf[2];
						__buf[0] = sch;
						__buf[1] = '\0';;
						current = args[objIndex++];
						zval_dtor(*current);
						ZVAL_STRINGL( *current, __buf, 1);
					} else {
						add_index_stringl(return_value, objIndex++, &sch, 1);
					}
				}
				break;
*/
			case 'i':
				/*
				 * Scan an unsigned or signed integer.
				 */
				/*-cc-*/
				buf[0] = '\0';
				/*-cc-*/
				if ((width == 0) || (width > sizeof(buf) - 1)) {
					width = sizeof(buf) - 1;
				}

				flags |= SCAN_SIGNOK | SCAN_NODIGITS | SCAN_NOZERO;
				for (end = buf; width > 0; width--) {
					switch (*string) {
						/*
						 * The 0 digit has special meaning at the beginning of
						 * a number.  If we are unsure of the base, it
						 * indicates that we are in base 8 or base 16 (if it is
						 * followed by an 'x').
						 */
						case '0':
							/*-cc-*/
							if (base == 16) {
								flags |= SCAN_XOK;
							}
							/*-cc-*/
							if (base == 0) {
								base = 8;
								flags |= SCAN_XOK;
							}
							if (flags & SCAN_NOZERO) {
								flags &= ~(SCAN_SIGNOK | SCAN_NODIGITS | SCAN_NOZERO);
							} else {
								flags &= ~(SCAN_SIGNOK | SCAN_XOK | SCAN_NODIGITS);
							}
							goto addToInt;

						case '1': case '2': case '3': case '4':
						case '5': case '6': case '7':
							if (base == 0) {
								base = 10;
							}
							flags &= ~(SCAN_SIGNOK | SCAN_XOK | SCAN_NODIGITS);
							goto addToInt;

						case '8': case '9':
							if (base == 0) {
								base = 10;
							}
							if (base <= 8) {
							   break;
							}
							flags &= ~(SCAN_SIGNOK | SCAN_XOK | SCAN_NODIGITS);
							goto addToInt;

						case 'A': case 'B': case 'C':
						case 'D': case 'E': case 'F':
						case 'a': case 'b': case 'c':
						case 'd': case 'e': case 'f':
							if (base <= 10) {
								break;
							}
							flags &= ~(SCAN_SIGNOK | SCAN_XOK | SCAN_NODIGITS);
							goto addToInt;

						case '+': case '-':
							if (flags & SCAN_SIGNOK) {
								flags &= ~SCAN_SIGNOK;
								goto addToInt;
							}
							break;

						case 'x': case 'X':
							if ((flags & SCAN_XOK) && (end == buf+1)) {
								base = 16;
								flags &= ~SCAN_XOK;
								goto addToInt;
							}
							break;
					}

					/*
					 * We got an illegal character so we are done accumulating.
					 */
					break;

addToInt:
					/*
					 * Add the character to the temporary buffer.
					 */
					*end++ = *string++;
					if (*string == '\0') {
						break;
					}
				}

				/*
				 * Check to see if we need to back up because we only got a
				 * sign or a trailing x after a 0.
				 */
				if (flags & SCAN_NODIGITS) {
					if (*string == '\0') {
						underflow = 1;
					}
					goto done;
				} else if (end[-1] == 'x' || end[-1] == 'X') {
					end--;
					string--;
				}

				/*
				 * Scan the value from the temporary buffer.  If we are
				 * returning a large unsigned value, we have to convert it back
				 * to a string since PHP only supports signed values.
				 */
				if (!(flags & SCAN_SUPPRESS)) {
					*end = '\0';
					value = (zend_long) (*fn)(buf, NULL, base);
					if ((flags & SCAN_UNSIGNED) && (value < 0)) {
						snprintf(buf, sizeof(buf), ZEND_ULONG_FMT, value); /* INTL: ISO digit */
						if (numVars && objIndex >= argCount) {
							break;
						} else if (numVars) {
						  /* change passed value type to string */
							current = Z_REFVAL(args[objIndex++]);
							zval_ptr_dtor(current);
							ZVAL_STRING(current, buf);
						} else {
							add_index_string(return_value, objIndex++, buf);
						}
					} else {
						if (numVars && objIndex >= argCount) {
							break;
						} else if (numVars) {
							current = Z_REFVAL(args[objIndex++]);
							zval_ptr_dtor(current);
							ZVAL_LONG(current, value);
						} else {
							add_index_long(return_value, objIndex++, value);
						}
					}
				}
				break;

			case 'f':
				/*
				 * Scan a floating point number
				 */
				buf[0] = '\0';     /* call me pedantic */
				if ((width == 0) || (width > sizeof(buf) - 1)) {
					width = sizeof(buf) - 1;
				}
				flags |= SCAN_SIGNOK | SCAN_NODIGITS | SCAN_PTOK | SCAN_EXPOK;
				for (end = buf; width > 0; width--) {
					switch (*string) {
						case '0': case '1': case '2': case '3':
						case '4': case '5': case '6': case '7':
						case '8': case '9':
							flags &= ~(SCAN_SIGNOK | SCAN_NODIGITS);
							goto addToFloat;
						case '+':
						case '-':
							if (flags & SCAN_SIGNOK) {
								flags &= ~SCAN_SIGNOK;
								goto addToFloat;
							}
							break;
						case '.':
							if (flags & SCAN_PTOK) {
								flags &= ~(SCAN_SIGNOK | SCAN_PTOK);
								goto addToFloat;
							}
							break;
						case 'e':
						case 'E':
							/*
							 * An exponent is not allowed until there has
							 * been at least one digit.
							 */
							if ((flags & (SCAN_NODIGITS | SCAN_EXPOK)) == SCAN_EXPOK) {
								flags = (flags & ~(SCAN_EXPOK|SCAN_PTOK))
									| SCAN_SIGNOK | SCAN_NODIGITS;
								goto addToFloat;
							}
							break;
					}

					/*
					 * We got an illegal character so we are done accumulating.
					 */
					break;

addToFloat:
					/*
					 * Add the character to the temporary buffer.
					 */
					*end++ = *string++;
					if (*string == '\0') {
						break;
					}
				}

				/*
				 * Check to see if we need to back up because we saw a
				 * trailing 'e' or sign.
				 */
				if (flags & SCAN_NODIGITS) {
					if (flags & SCAN_EXPOK) {
						/*
						 * There were no digits at all so scanning has
						 * failed and we are done.
						 */
						if (*string == '\0') {
							underflow = 1;
						}
						goto done;
					}

					/*
					 * We got a bad exponent ('e' and maybe a sign).
					 */
					end--;
					string--;
					if (*end != 'e' && *end != 'E') {
						end--;
						string--;
					}
				}

				/*
				 * Scan the value from the temporary buffer.
				 */
				if (!(flags & SCAN_SUPPRESS)) {
					double dvalue;
					*end = '\0';
					dvalue = zend_strtod(buf, NULL);
					if (numVars && objIndex >= argCount) {
						break;
					} else if (numVars) {
						current = Z_REFVAL(args[objIndex++]);
						zval_ptr_dtor(current);
						ZVAL_DOUBLE(current, dvalue);
					} else {
						add_index_double(return_value, objIndex++, dvalue );
					}
				}
				break;
		} /* switch (op) */
		nconversions++;
	} /*  while (*format != '\0') */

done:
	result = SCAN_SUCCESS;

	if (underflow && (0==nconversions)) {
		scan_set_error_return( numVars, return_value );
		result = SCAN_ERROR_EOF;
	} else if (numVars) {
		convert_to_long(return_value );
		Z_LVAL_P(return_value) = nconversions;
	} else if (nconversions < totalVars) {
		/* TODO: not all elements converted. we need to prune the list - cc */
	}
	return result;
}
예제 #12
0
PHP_METHOD(Pinyin, multiConvert)
{
    IPYNotation *pynotation = get_pinyin_notation(getThis());
    zval        *strs, **str;
    HashTable   *strshash;
    HashPosition pointer;
    bool         result     = 0;
    int          strs_num   = 0;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &strs) == FAILURE) {
        RETURN_FALSE;
    }

    vector<string> convert_strs;
    string strtmp;
    strshash = Z_ARRVAL_P(strs);
    for (zend_hash_internal_pointer_reset_ex(strshash, &pointer);
             zend_hash_get_current_data_ex(strshash, (void **)&str, &pointer) == SUCCESS;
             zend_hash_move_forward_ex(strshash, &pointer)) {
        convert_to_string_ex(str);
        strtmp.assign(Z_STRVAL_PP(str), Z_STRLEN_PP(str));
        convert_strs.push_back(strtmp);
        strs_num++;
    }

    vector<vector<string> * > py_results;
    py_results.reserve(strs_num);

    // py_result to store one sentence's pinyin result
#if defined(__APPLE_CPP__) || defined(__APPLE_CC__)
# define PY_NEED_DELETE_RESULT
    vector<string> *py_result = new vector<string>[strs_num];
#else
    vector<string>  py_result[strs_num];
#endif

    for(int i = 0; i < strs_num; i++) {
        py_results.push_back(&py_result[i]);
    }
    result = pynotation->convertToPY(convert_strs, &py_results); 
    if(result) {
        array_init(return_value);
        int i = 0;
        vector<vector<string> * >::iterator it = py_results.begin();
        for(; it != py_results.end(); it++) {
            for (vector<string>::iterator iit = (*it)->begin();
                     iit != (*it)->end();
                     iit++) {
                add_index_string(return_value, i++, (*iit).c_str(), 1);
            }
        }
#ifdef PY_NEED_DELETE_RESULT
        delete [] py_result;
#endif
    } else {
#ifdef PY_NEED_DELETE_RESULT
        delete [] py_result;
#endif
        RETURN_FALSE;
    }
}
예제 #13
0
파일: kafka.c 프로젝트: dwieland/phpkafka
int kafka_consume(rd_kafka_t *r, zval* return_value, char* topic, char* offset, int item_count, int partition)
{
    int64_t start_offset = 0;
    int read_counter = 0,
        run = 1;
    //nothing to consume?
    if (item_count == 0)
        return 0;
    if (strlen(offset) != 0)
    {
        if (!strcmp(offset, "end"))
            start_offset = RD_KAFKA_OFFSET_END;
        else if (!strcmp(offset, "beginning"))
            start_offset = RD_KAFKA_OFFSET_BEGINNING;
        else if (!strcmp(offset, "stored"))
            start_offset = RD_KAFKA_OFFSET_STORED;
        else
        {
            start_offset = strtoll(offset, NULL, 10);
            if (start_offset < 1)
                return -1;
        }

    }
    rd_kafka_topic_t *rkt;

    if (r == NULL)
    {
        if (log_level)
        {
            openlog("phpkafka", 0, LOG_USER);
            syslog(LOG_ERR, "phpkafka - no connection to consume from topic: %s", topic);
        }
        return -2;
    }

    rd_kafka_topic_conf_t *topic_conf;

    /* Topic configuration */
    topic_conf = rd_kafka_topic_conf_new();

    /* Create topic */
    rkt = rd_kafka_topic_new(r, topic, topic_conf);
    if (rkt == NULL)
    {
        if (log_level)
        {
            openlog("phpkafka", 0, LOG_USER);
            syslog(
                LOG_ERR,
               "Failed to consume from topic %s: %s",
                topic,
                rd_kafka_err2str(
                    rd_kafka_errno2err(errno)
                )
            );
        }
        return -3;
    }
    if (log_level)
    {
        openlog("phpkafka", 0, LOG_USER);
        syslog(LOG_INFO, "phpkafka - start_offset: %"PRId64" and offset passed: %s", start_offset, offset);

    }
    /* Start consuming */
    if (rd_kafka_consume_start(rkt, partition, start_offset) == -1)
    {
        if (log_level)
        {
            openlog("phpkafka", 0, LOG_USER);
            syslog(LOG_INFO, "phpkafka - %% Failed to start consuming: %s",
                rd_kafka_err2str(rd_kafka_errno2err(errno)));
        }
        return -4;
    }

    /**
     * Keep reading until run == 0, or read_counter == item_count
     */
    for (read_counter=0;read_counter!=item_count;++read_counter)
    {
        if (run == 0)
            break;
        if (log_level)
        {
            openlog("phpkafka", 0, LOG_USER);
            syslog(LOG_INFO, "Consuming, count at %d (of %d - run: %d)",
                read_counter,
                item_count,
                run
            );
        }
        rd_kafka_message_t *rkmessage = NULL,
            *rkmessage_return = NULL;

        /* Consume single message.
         * See rdkafka_performance.c for high speed
         * consuming of messages. */
        rkmessage = rd_kafka_consume(rkt, partition, 1000);
        //timeout ONLY if error didn't cause run to be 0
        if (!rkmessage)
        {
            //break on timeout, makes second call redundant
            if (errno == ETIMEDOUT)
            {
                if (log_level)
                {
                    openlog("phpkafka", 0, LOG_USER);
                    syslog(LOG_INFO, "Consumer timed out, count at %d (of %d) stop consuming after %d messages",
                        read_counter,
                        item_count,
                        read_counter +1
                    );
                }
                break;
            }
            continue;
        }

        rkmessage_return = msg_consume(rkmessage, &run);
        if (rkmessage_return != NULL)
        {
            if ((int) rkmessage_return->len > 0)
            {
                //ensure there is a payload
                char payload[(int) rkmessage_return->len];
                sprintf(payload, "%.*s", (int) rkmessage_return->len, (char *) rkmessage_return->payload);
                add_index_string(return_value, (int) rkmessage_return->offset, payload, 1);
            }
            else
            {
                //add empty value
                char payload[1] = "";//empty string
                add_index_string(return_value, (int) rkmessage_return->offset, payload, 1);
            }
        }
        /* Return message to rdkafka */
        rd_kafka_message_destroy(rkmessage);
    }

    /* Stop consuming */
    rd_kafka_consume_stop(rkt, partition);
    rd_kafka_topic_destroy(rkt);
    return 0;
}
zval * activerecord_create_conditions_from_underscored_string( char * str, int str_len, zval * values, zval * map )
{
	int i, valcount, strsize, curstrsize;
	char * conditions;
	zend_bool use_map, unfinished = 1;
	zval * retval, * condsval;

	if( !name_len || Z_TYPE_P(values) != IS_ARRAY )
		return NULL;

	MAKE_STD_ZVAL( retval );
	array_init( retval );
	add_index_string( retval, 0, "", 1);
	
	use_map = ( map != NULL && Z_TYPE_P(map) == IS_ARRAY );
	valcount = zend_hash_num_elements(Z_ARRVAL_P(values));
	conditions = (char*)emalloc( strsize = valcount*20 );

	for( i = 0; strstr( str, "_and_" ) || strstr( str, "_or_" ) || unfinished; i++ )
	{
		char *attribute, *tmp;
		zend_bool and_condition;
		zval **alias;

		if( tmp = strstr(str,"_and_") )
			and_condition = 1;
		else
		{
			tmp = strstr(str,"_or_");
			and_condition = 0;
		}
		if( tmp )
		{
			attribute = (char*)emalloc( tmp - str );
			strncpy( attribute, str, tmp - str );
			str = tmp + (and_condition? 5 : 4);
		}
		else
		{
			unfinished = 0;
			attribute = str;
		}
		if( i > 0 )
		{
			if( use_map && zend_hash_find( Z_ARRVAL_P(map), attribute, sizeof(attribute), (void**)&alias ) == SUCCESS )
				attribute = Z_STRVAL_PP(alias);

			if( curstrsize + 14 + strlen(attribute) > strsize )
			{
				tmp = (char*)emalloc( strsize*2 );
				strncpy( tmp, conditions, curstrsize );
				efree( conditions );
				conditions = tmp;
				strsize *= 2;
			}

			strsize += (and_condition? 5 : 4) + strlen(attribute);
			strcat( conditions, and_condition? " AND " : " OR " );
			strcat( conditions, activerecord_sql_quote_name(attribute) );

			if( i < valcount )
			{
				zval **value;

				zend_hash_index_find( Z_ARRVAL_P(values), i, (void**)&value );
				if( Z_TYPE_PP(value) != IS_NULL )
				{
					strcat( conditions, Z_TYPE_PP(value) == IS_ARRAY? " IN(?)" : "=?";
					curstrsize += Z_TYPE_PP(value) == IS_ARRAY? 6 : 2;
					add_next_index_zval( retval, *value );
				}
				else
				{
					strcat( conditions, " IS NULL " );
					curstrsize += 9;
				}
			}
예제 #15
0
void kafka_consume(zval* return_value, char* topic, char* offset, int item_count)
{

  int read_counter = 0;

  if (strlen(offset) != 0) {
    if (!strcmp(offset, "end"))
      start_offset = RD_KAFKA_OFFSET_END;
    else if (!strcmp(offset, "beginning"))
      start_offset = RD_KAFKA_OFFSET_BEGINNING;
    else if (!strcmp(offset, "stored"))
      start_offset = RD_KAFKA_OFFSET_STORED;
    else
      start_offset = strtoll(offset, NULL, 10);
  }

    rd_kafka_topic_t *rkt;

    char errstr[512];
    rd_kafka_conf_t *conf;

    /* Kafka configuration */
    conf = rd_kafka_conf_new();

    /* Create Kafka handle */
    if (!(rk = rd_kafka_new(RD_KAFKA_CONSUMER, conf, errstr, sizeof(errstr)))) {
                  openlog("phpkafka", 0, LOG_USER);
                  syslog(LOG_INFO, "phpkafka - failed to create new consumer: %s", errstr);
                  exit(1);
    }

    /* Add brokers */
    if (rd_kafka_brokers_add(rk, brokers) == 0) {
            openlog("phpkafka", 0, LOG_USER);
            syslog(LOG_INFO, "php kafka - No valid brokers specified");
            exit(1);
    }

    rd_kafka_topic_conf_t *topic_conf;

    /* Topic configuration */
    topic_conf = rd_kafka_topic_conf_new();

    /* Create topic */
    rkt = rd_kafka_topic_new(rk, topic, topic_conf);

    openlog("phpkafka", 0, LOG_USER);
    syslog(LOG_INFO, "phpkafka - start_offset: %d and offset passed: %d", start_offset, offset);

    /* Start consuming */
    if (rd_kafka_consume_start(rkt, partition, start_offset) == -1) {
      openlog("phpkafka", 0, LOG_USER);
      syslog(LOG_INFO, "phpkafka - %% Failed to start consuming: %s",
        rd_kafka_err2str(rd_kafka_errno2err(errno)));
      exit(1);
    }

    if (item_count != 0) {
      read_counter = item_count;
    }

    while (run) {
      if (item_count != 0 && read_counter >= 0) {
        read_counter--;
        openlog("phpkafka", 0, LOG_USER);
        syslog(LOG_INFO, "phpkafka - read_counter: %d", read_counter);
        if (read_counter == -1) {
          run = 0;
          continue;
        }
      }

      rd_kafka_message_t *rkmessage;

      /* Consume single message.
       * See rdkafka_performance.c for high speed
       * consuming of messages. */
      rkmessage = rd_kafka_consume(rkt, partition, 1000);
      if (!rkmessage) /* timeout */
        continue;

      rd_kafka_message_t *rkmessage_return;
      rkmessage_return = msg_consume(rkmessage, NULL);
      char payload[(int)rkmessage_return->len];
      sprintf(payload, "%.*s", (int)rkmessage_return->len, (char *)rkmessage_return->payload);
      add_index_string(return_value, (int)rkmessage_return->offset, payload, 1);

      /* Return message to rdkafka */
      rd_kafka_message_destroy(rkmessage);
    }

    /* Stop consuming */
    rd_kafka_consume_stop(rkt, partition);
    rd_kafka_topic_destroy(rkt);
    rd_kafka_destroy(rk);
}