static int php_password_make_salt(size_t length, char *ret) /* {{{ */ { size_t raw_length; char *buffer; char *result; if (length > (INT_MAX / 3)) { php_error_docref(NULL, E_WARNING, "Length is too large to safely generate"); return FAILURE; } raw_length = length * 3 / 4 + 1; buffer = (char *) safe_emalloc(raw_length, 1, 1); if (FAILURE == php_random_bytes_silent(buffer, raw_length)) { php_error_docref(NULL, E_WARNING, "Unable to generate salt"); efree(buffer); return FAILURE; } result = safe_emalloc(length, 1, 1); if (php_password_salt_to64(buffer, raw_length, length, result) == FAILURE) { php_error_docref(NULL, E_WARNING, "Generated salt too short"); efree(buffer); efree(result); return FAILURE; } memcpy(ret, result, length); efree(result); efree(buffer); ret[length] = 0; return SUCCESS; }
/* {{{ reference_levdist * reference implementation, only optimized for memory usage, not speed */ static zend_long reference_levdist(const char *s1, size_t l1, const char *s2, size_t l2, zend_long cost_ins, zend_long cost_rep, zend_long cost_del ) { zend_long *p1, *p2, *tmp; zend_long c0, c1, c2; size_t i1, i2; if (l1 == 0) { return l2 * cost_ins; } if (l2 == 0) { return l1 * cost_del; } if ((l1 > LEVENSHTEIN_MAX_LENGTH) || (l2 > LEVENSHTEIN_MAX_LENGTH)) { return -1; } p1 = safe_emalloc((l2 + 1), sizeof(zend_long), 0); p2 = safe_emalloc((l2 + 1), sizeof(zend_long), 0); for (i2 = 0; i2 <= l2; i2++) { p1[i2] = i2 * cost_ins; } for (i1 = 0; i1 < l1 ; i1++) { p2[0] = p1[0] + cost_del; for (i2 = 0; i2 < l2; i2++) { c0 = p1[i2] + ((s1[i1] == s2[i2]) ? 0 : cost_rep); c1 = p1[i2 + 1] + cost_del; if (c1 < c0) { c0 = c1; } c2 = p2[i2] + cost_ins; if (c2 < c0) { c0 = c2; } p2[i2 + 1] = c0; } tmp = p1; p1 = p2; p2 = tmp; } c0 = p1[l2]; efree(p1); efree(p2); return c0; }
static int com_call_method(zend_string *method, zend_object *object, INTERNAL_FUNCTION_PARAMETERS) { zval *args = NULL; php_com_dotnet_object *obj = (php_com_dotnet_object*)object; int nargs; VARIANT v; int ret = FAILURE; if (V_VT(&obj->v) != VT_DISPATCH) { return FAILURE; } nargs = ZEND_NUM_ARGS(); if (nargs) { args = (zval *)safe_emalloc(sizeof(zval), nargs, 0); zend_get_parameters_array_ex(nargs, args); } VariantInit(&v); if (SUCCESS == php_com_do_invoke_byref(obj, (zend_internal_function*)EX(func), DISPATCH_METHOD|DISPATCH_PROPERTYGET, &v, nargs, args)) { php_com_zval_from_variant(return_value, &v, obj->code_page); ret = SUCCESS; VariantClear(&v); } if (args) { efree(args); } return ret; }
zend_object_iterator *php_com_saproxy_iter_get(zend_class_entry *ce, zval *object, int by_ref) { php_com_saproxy *proxy = SA_FETCH(object); php_com_saproxy_iter *I; int i; if (by_ref) { zend_throw_error(NULL, "An iterator cannot be used with foreach by reference"); return NULL; } I = ecalloc(1, sizeof(*I)); I->iter.funcs = &saproxy_iter_funcs; Z_PTR(I->iter.data) = I; I->proxy = proxy; ZVAL_COPY(&I->proxy_obj, object); I->indices = safe_emalloc(proxy->dimensions + 1, sizeof(LONG), 0); for (i = 0; i < proxy->dimensions; i++) { convert_to_long(&proxy->indices[i]); I->indices[i] = (LONG)Z_LVAL(proxy->indices[i]); } SafeArrayGetLBound(V_ARRAY(&proxy->obj->v), proxy->dimensions, &I->imin); SafeArrayGetUBound(V_ARRAY(&proxy->obj->v), proxy->dimensions, &I->imax); I->key = I->imin; return &I->iter; }
static inline void *accounted_safe_ecalloc(size_t nmemb, size_t alloc_size, size_t offset, ser_context *ctx) { void *ret = safe_emalloc(nmemb, alloc_size, offset); memset(ret, '\0', nmemb * alloc_size + offset); zend_llist_add_element(&ctx->allocations, &ret); return ret; }
static void php_hash_do_hash(INTERNAL_FUNCTION_PARAMETERS, int isfilename, zend_bool raw_output_default) /* {{{ */ { char *algo, *data, *digest; int 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() TSRMLS_CC, "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 TSRMLS_CC, 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]; int n; while ((n = php_stream_read(stream, buf, sizeof(buf))) > 0) { ops->hash_update(context, (unsigned char *) buf, n); } php_stream_close(stream); } else { ops->hash_update(context, (unsigned char *) data, data_len); } digest = emalloc(ops->digest_size + 1); ops->hash_final((unsigned char *) digest, context); efree(context); if (raw_output) { digest[ops->digest_size] = 0; RETURN_STRINGL(digest, ops->digest_size, 0); } else { char *hex_digest = safe_emalloc(ops->digest_size, 2, 1); php_hash_bin2hex(hex_digest, (unsigned char *) digest, ops->digest_size); hex_digest[2 * ops->digest_size] = 0; efree(digest); RETURN_STRINGL(hex_digest, 2 * ops->digest_size, 0); } }
void php_filter_callback(PHP_INPUT_FILTER_PARAM_DECL) { zval retval; zval *args; int status; if (!option_array || !zend_is_callable(option_array, IS_CALLABLE_CHECK_NO_ACCESS, NULL TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "First argument is expected to be a valid callback"); zval_ptr_dtor(value); ZVAL_NULL(value); return; } args = safe_emalloc(sizeof(zval), 1, 0); ZVAL_COPY(&args[0], value); status = call_user_function_ex(EG(function_table), NULL, option_array, &retval, 1, args, 0, NULL TSRMLS_CC); if (status == SUCCESS && !Z_ISUNDEF(retval)) { zval_ptr_dtor(value); ZVAL_COPY_VALUE(value, &retval); } else { zval_ptr_dtor(value); ZVAL_NULL(value); } zval_ptr_dtor(&args[0]); efree(args); }
/* {{{ _timecop_call_mktime - timecop_(gm)mktime helper */ static void _timecop_call_mktime(INTERNAL_FUNCTION_PARAMETERS, const char *mktime_function_name, const char *date_function_name) { zval *params; uint32_t param_count; int i; param_count = MAX(ZEND_NUM_ARGS(), MKTIME_NUM_ARGS); params = (zval *)safe_emalloc(param_count, sizeof(zval), 0); if (zend_get_parameters_array_ex(ZEND_NUM_ARGS(), params) == FAILURE) { efree(params); zend_throw_error(NULL, "Cannot get arguments for calling"); return; } param_count = ZEND_NUM_ARGS(); if (param_count < MKTIME_NUM_ARGS) { fill_mktime_params(params, date_function_name, param_count); param_count = MKTIME_NUM_ARGS; } if (ZEND_NUM_ARGS() == 0) { php_error_docref(NULL, E_STRICT, "You should be using the time() function instead"); } simple_call_function(mktime_function_name, return_value, param_count, params); for (i = ZEND_NUM_ARGS(); i < MKTIME_NUM_ARGS; i++) { zval_ptr_dtor(¶ms[i]); } efree(params); }
/* {{{ proto TimecopDateTime::__construct([string time[, DateTimeZone object]]) Creates new TimecopDateTime object */ PHP_METHOD(TimecopDateTime, __construct) { zval *params; zval *obj = getThis(); params = (zval *)safe_emalloc(ZEND_NUM_ARGS(), sizeof(zval), 0); if (zend_get_parameters_array_ex(ZEND_NUM_ARGS(), params) == FAILURE) { efree(params); zend_throw_error(NULL, "Cannot get arguments for TimecopDateTime::__construct"); RETURN_FALSE; } /* call original DateTime::__construct() */ timecop_call_original_constructor(obj, TIMECOP_G(ce_DateTime), params, ZEND_NUM_ARGS()); if (!EG(exception)) { zval *time = NULL, *timezone_obj = NULL; if (ZEND_NUM_ARGS() >= 1) { time = ¶ms[0]; } if (ZEND_NUM_ARGS() >= 2) { timezone_obj = ¶ms[1]; } fix_datetime_timestamp(obj, time, timezone_obj); } efree(params); }
void php_filter_callback(PHP_INPUT_FILTER_PARAM_DECL) { zval *retval_ptr; zval ***args; int status; if (!option_array || !zend_is_callable(option_array, IS_CALLABLE_CHECK_NO_ACCESS, NULL TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "First argument is expected to be a valid callback"); zval_dtor(value); Z_TYPE_P(value) = IS_NULL; return; } args = safe_emalloc(sizeof(zval **), 1, 0); args[0] = &value; status = call_user_function_ex(EG(function_table), NULL, option_array, &retval_ptr, 1, args, 0, NULL TSRMLS_CC); if (status == SUCCESS && retval_ptr != NULL) { if (retval_ptr != value) { zval_dtor(value); COPY_PZVAL_TO_ZVAL(*value, retval_ptr); } else { zval_ptr_dtor(&retval_ptr); } } else { zval_dtor(value); Z_TYPE_P(value) = IS_NULL; } efree(args); }
char *str_repeat(const char *input_str, int len) { char *result; size_t result_len; if (input_str == NULL) return NULL; if (len <= 0) return ""; result_len = strlen(input_str) * len; result = (char *)safe_emalloc(strlen(input_str), len, 1); /* Heavy optimization for situations where input string is 1 byte long */ if (strlen(input_str) == 1) { memset(result, *(input_str), len); } else { char *s, *e, *ee; int l=0; memcpy(result, input_str, strlen(input_str)); s = result; e = result + strlen(input_str); ee = result + result_len; while (e<ee) { l = (e-s) < (ee-e) ? (e-s) : (ee-e); memmove(e, s, l); e += l; } } result[result_len] = '\0'; return result; }
/* NB: doesn't handle binary strings... use prepared stmts for that */ static int sqlite_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, size_t unquotedlen, char **quoted, size_t *quotedlen, enum pdo_param_type paramtype ) { *quoted = safe_emalloc(2, unquotedlen, 3); sqlite3_snprintf(2*unquotedlen + 3, *quoted, "'%q'", unquoted); *quotedlen = strlen(*quoted); return 1; }
PHPAPI char *php_com_olestring_to_string(OLECHAR *olestring, uint *string_len, int codepage TSRMLS_DC) { char *string; uint length = 0; BOOL ok; length = WideCharToMultiByte(codepage, 0, olestring, -1, NULL, 0, NULL, NULL); if (length) { string = (char*)safe_emalloc(length, sizeof(char), 0); length = WideCharToMultiByte(codepage, 0, olestring, -1, string, length, NULL, NULL); ok = length > 0; } else { string = (char*)emalloc(sizeof(char)); *string = '\0'; ok = FALSE; length = 0; } if (!ok) { char *msg = php_win32_error_to_msg(GetLastError()); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not convert string from unicode: `%s'", msg); LocalFree(msg); } if (string_len) { *string_len = length-1; } return string; }
PHPAPI OLECHAR *php_com_string_to_olestring(char *string, uint string_len, int codepage TSRMLS_DC) { OLECHAR *olestring = NULL; DWORD flags = codepage == CP_UTF8 ? 0 : MB_PRECOMPOSED | MB_ERR_INVALID_CHARS; BOOL ok; if (string_len == -1) { /* determine required length for the buffer (includes NUL terminator) */ string_len = MultiByteToWideChar(codepage, flags, string, -1, NULL, 0); } else { /* allow room for NUL terminator */ string_len++; } if (string_len > 0) { olestring = (OLECHAR*)safe_emalloc(string_len, sizeof(OLECHAR), 0); ok = MultiByteToWideChar(codepage, flags, string, string_len, olestring, string_len); } else { ok = FALSE; olestring = (OLECHAR*)emalloc(sizeof(OLECHAR)); *olestring = 0; } if (!ok) { char *msg = php_win32_error_to_msg(GetLastError()); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not convert string to unicode: `%s'", msg); LocalFree(msg); } return olestring; }
static int _common_callback_no_arg(void *yajl_ctx, char *type) { php_yajl_record *instance = (php_yajl_record *)yajl_ctx; zval *return_handle = NULL; HashTable *hash; zval zType, zArg, *pzType=&zType, *pzArg=&zArg; /* Tell PHP where to put the return value */ php_printf("%p\n", &instance->fci); instance->fci.retval_ptr_ptr = &return_handle; /* Bundle all the input parameters into an array. */ instance->fci.params = safe_emalloc(sizeof(zval *), 3, 0); instance->fci.param_count = 3; instance->fci.params[0] = &instance->php_ctx; ZVAL_STRING(pzType, type, 1); instance->fci.params[1] = &pzType; ZVAL_NULL(pzArg); instance->fci.params[2] = &pzArg; /* Call the supplied function. */ zend_call_function(&instance->fci, &instance->fci_cache TSRMLS_CC); /* If the allocation succeeded, free the parameter array. */ if(instance->fci.params) { efree(instance->fci.params); } /* Without this, PHP seems to want to abort trap on me. */ return 1; }
static void ra_index_change_keys(const char *cmd, zval *z_keys, zval *z_redis) { int i, argc; zval z_fun, z_ret, *z_args; /* alloc */ argc = 1 + zend_hash_num_elements(Z_ARRVAL_P(z_keys)); z_args = emalloc(argc * sizeof(zval*)); /* prepare first parameters */ ZVAL_STRING(&z_fun, cmd); z_args = safe_emalloc(sizeof(zval), argc, 0); ZVAL_STRING(&z_args[0], PHPREDIS_INDEX_NAME); /* prepare keys */ for (i = 0; i < argc - 1; ++i) { zval *zpp; zpp = zend_hash_index_find(Z_ARRVAL_P(z_keys), i); ZVAL_COPY(&z_args[i+1], zpp); } /* run cmd */ call_user_function(&redis_ce->function_table, z_redis, &z_fun, &z_ret, argc, z_args); /* don't dtor z_ret, since we're returning z_redis */ /* free index name zval */ for (i = 0; i < argc; i++) { zval_ptr_dtor(&z_args[i]); efree(&z_args[i]); /* free index name zval */ } efree(z_args); /* free container */ }
static char *urlencode(char const *s, int len, int *new_length) { #define safe_emalloc(nmemb, size, offset) zmalloc((nmemb) * (size) + (offset)) static unsigned char hexchars[] = "0123456789ABCDEF"; register unsigned char c; unsigned char *to, *start; unsigned char const *from, *end; from = (unsigned char *)s; end = (unsigned char *)s + len; start = to = (unsigned char *) safe_emalloc(3, len, 1); while (from < end) { c = *from++; if (c == ' ') { *to++ = '+'; #ifndef CHARSET_EBCDIC } else if ((c < '0' && c != '-' && c != '.') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a' && c != '_') || (c > 'z')) { to[0] = '%'; to[1] = hexchars[c >> 4]; to[2] = hexchars[c & 15]; to += 3; #else /*CHARSET_EBCDIC*/ } else if (!isalnum(c) && strchr("_-.", c) == NULL) {
static int pgsql_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, int unquotedlen, char **quoted, int *quotedlen, enum pdo_param_type paramtype) { unsigned char *escaped; pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data; size_t tmp_len; switch (paramtype) { case PDO_PARAM_LOB: /* escapedlen returned by PQescapeBytea() accounts for trailing 0 */ escaped = PQescapeByteaConn(H->server, (unsigned char *)unquoted, (size_t)unquotedlen, &tmp_len); *quotedlen = (int)tmp_len + 1; *quoted = emalloc(*quotedlen + 1); memcpy((*quoted)+1, escaped, *quotedlen-2); (*quoted)[0] = '\''; (*quoted)[*quotedlen-1] = '\''; (*quoted)[*quotedlen] = '\0'; PQfreemem(escaped); break; default: *quoted = safe_emalloc(2, unquotedlen, 3); (*quoted)[0] = '\''; *quotedlen = PQescapeStringConn(H->server, *quoted + 1, unquoted, (size_t)unquotedlen, NULL); (*quoted)[*quotedlen + 1] = '\''; (*quoted)[*quotedlen + 2] = '\0'; *quotedlen += 2; } return 1; }
int php_com_saproxy_create(zend_object *com_object, zval *proxy_out, zval *index) { php_com_saproxy *proxy, *rel = NULL; proxy = ecalloc(1, sizeof(*proxy)); proxy->dimensions = 1; if (com_object->ce == php_com_saproxy_class_entry) { rel = (php_com_saproxy*) com_object; proxy->obj = rel->obj; proxy->dimensions += rel->dimensions; } else { proxy->obj = (php_com_dotnet_object*) com_object; } GC_ADDREF(&proxy->obj->zo); proxy->indices = safe_emalloc(proxy->dimensions, sizeof(zval *), 0); if (rel) { clone_indices(proxy, rel, rel->dimensions); } ZVAL_DUP(&proxy->indices[proxy->dimensions-1], index); zend_object_std_init(&proxy->std, php_com_saproxy_class_entry); proxy->std.handlers = &php_com_saproxy_handlers; ZVAL_OBJ(proxy_out, &proxy->std); return 1; }
/* {{{ php_url_encode */ PHPAPI char *php_url_encode(char const *s, int len, int *new_length) { register unsigned char c; unsigned char *to, *start; unsigned char const *from, *end; from = (unsigned char *)s; end = (unsigned char *)s + len; start = to = (unsigned char *) safe_emalloc(3, len, 1); while (from < end) { c = *from++; if (c == ' ') { *to++ = '+'; #ifndef CHARSET_EBCDIC } else if ((c < '0' && c != '-' && c != '.') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a' && c != '_') || (c > 'z')) { to[0] = '%'; to[1] = hexchars[c >> 4]; to[2] = hexchars[c & 15]; to += 3; #else /*CHARSET_EBCDIC*/ } else if (!isalnum(c) && strchr("_-.", c) == NULL) {
/* {{{ wddx_stack_init */ static int wddx_stack_init(wddx_stack *stack) { stack->top = 0; stack->elements = (void **) safe_emalloc(sizeof(void **), STACK_BLOCK_SIZE, 0); stack->max = STACK_BLOCK_SIZE; stack->varname = NULL; stack->done = 0; return SUCCESS; }
// time critical bool PHPQt::qt_metacall(smokephp_object* o, Smoke::Stack args) { Context::setCallType( Context::SlotCall ); const QMetaObject* staticMetaObject = o->meta(); const int _id = args[2].s_int; const int offset = staticMetaObject->methodOffset(); const QByteArray signature( staticMetaObject->method(_id).signature() ); const QByteArray metaMethodName = signature.left( signature.indexOf("(") ); //! - if we have a slot overridden in php user space: call it //! @see InvokeSlot if( PHPQt::methodExists( o->ce_ptr() , metaMethodName.constData()) ) { pDebug( PHPQt::Slot ) << " userspace " << signature << o->ce_ptr()->name; const int count = staticMetaObject->method( args[2].s_int ).parameterTypes().count() + 1; // zval* zmem = ALLOCA_N(zval, count); zval** zmem = (zval**) safe_emalloc( sizeof(zval*), count+1, 0); for( int i=0;i<count;i++ ) { ALLOC_INIT_ZVAL( zmem[i] ); } // NOTICE is memory allocation safe here? InvokeSlot c( o->smoke(), args, o->zval_ptr(), zmem, _id, staticMetaObject, (void**) args[3].s_voidp, metaMethodName ); c.next(); efree(zmem); return true; } else { if ( staticMetaObject->indexOfSlot( signature ) != -1 ) { pDebug( PHPQt::Slot ) << " C++ " << signature; // return false means this will be done by smoke return false; } else { // TODO error case for undefined methods, see php_qt proxyMethod // const int i = staticMetaObject->indexOfSignal( signature ); // const int offset = staticMetaObject->methodOffset(); // The offset is the summary of all methods in the class's superclasses pDebug( PHPQt::Signal ) << signature << staticMetaObject->className() << _id << staticMetaObject->methodOffset(); /* C++ */ //if( _id < offset ) { qWarning() << "got an id smaller than offset"; } /** * We go through QMetaObject::activate, because it can either be connected to a C++ Slot or a user space Slot * cast to a QObject using smoke cast * */ QObject* ptr = (QObject*) o->smoke()->cast( const_cast<void*>( o->ptr() ), o->classId(), cachedQObjectSmokeId ); void *_b[] = { 0, ((void**) args[3].s_voidp)[1] }; QMetaObject::activate( ptr, staticMetaObject, 0, _b ); return true; // success } } // else method exist return false; }
/* {{{ mysql_handle_quoter */ static int mysql_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, int unquotedlen, char **quoted, int *quotedlen, enum pdo_param_type paramtype ) { pdo_mysql_db_handle *H = (pdo_mysql_db_handle *)dbh->driver_data; PDO_DBG_ENTER("mysql_handle_quoter"); PDO_DBG_INF_FMT("dbh=%p", dbh); PDO_DBG_INF_FMT("unquoted=%.*s", unquotedlen, unquoted); *quoted = safe_emalloc(2, unquotedlen, 3); *quotedlen = mysql_real_escape_string(H->server, *quoted + 1, unquoted, unquotedlen); (*quoted)[0] =(*quoted)[++*quotedlen] = '\''; (*quoted)[++*quotedlen] = '\0'; PDO_DBG_INF_FMT("quoted=%.*s", *quotedlen, *quoted); PDO_DBG_RETURN(1); }
/* {{{ php_xsl_xslt_string_to_xpathexpr() Translates a string to a XPath Expression */ static char *php_xsl_xslt_string_to_xpathexpr(const char *str) { const xmlChar *string = (const xmlChar *)str; xmlChar *value; int str_len; str_len = xmlStrlen(string) + 3; if (xmlStrchr(string, '"')) { if (xmlStrchr(string, '\'')) { php_error_docref(NULL, E_WARNING, "Cannot create XPath expression (string contains both quote and double-quotes)"); return NULL; } value = (xmlChar*) safe_emalloc (str_len, sizeof(xmlChar), 0); snprintf((char*)value, str_len, "'%s'", string); } else { value = (xmlChar*) safe_emalloc (str_len, sizeof(xmlChar), 0); snprintf((char *)value, str_len, "\"%s\"", string); } return (char *) value; }
/* {{{ reference_levdist * reference implementation, only optimized for memory usage, not speed */ static int reference_levdist(const char *s1, int l1, const char *s2, int l2, int cost_ins, int cost_rep, int cost_del ) { int *p1, *p2, *tmp; int i1, i2, c0, c1, c2; if(l1==0) return l2*cost_ins; if(l2==0) return l1*cost_del; if((l1>LEVENSHTEIN_MAX_LENTH)||(l2>LEVENSHTEIN_MAX_LENTH)) return -1; p1 = safe_emalloc((l2+1), sizeof(int), 0); p2 = safe_emalloc((l2+1), sizeof(int), 0); for(i2=0;i2<=l2;i2++) p1[i2] = i2*cost_ins; for(i1=0;i1<l1;i1++) { p2[0]=p1[0]+cost_del; for(i2=0;i2<l2;i2++) { c0=p1[i2]+((s1[i1]==s2[i2])?0:cost_rep); c1=p1[i2+1]+cost_del; if(c1<c0) c0=c1; c2=p2[i2]+cost_ins; if(c2<c0) c0=c2; p2[i2+1]=c0; } tmp=p1; p1=p2; p2=tmp; } c0=p1[l2]; efree(p1); efree(p2); return c0; }
static void _start_element_handler_ns(void *user, const xmlChar *name, const xmlChar *prefix, const xmlChar *URI, int nb_namespaces, const xmlChar ** namespaces, int nb_attributes, int nb_defaulted, const xmlChar ** attributes) { XML_Parser parser = (XML_Parser) user; xmlChar *qualified_name = NULL; xmlChar **attrs = NULL; int i; int z = 0; int y = 0; if (nb_namespaces > 0 && parser->h_start_ns != NULL) { for (i = 0; i < nb_namespaces; i += 1) { parser->h_start_ns(parser->user, (const XML_Char *) namespaces[y], (const XML_Char *) namespaces[y+1]); y += 2; } y = 0; } if (parser->h_start_element == NULL && parser->h_default == NULL) { return; } _qualify_namespace(parser, name, URI, &qualified_name); if (attributes != NULL) { xmlChar *qualified_name_attr = NULL; attrs = safe_emalloc((nb_attributes * 2) + 1, sizeof(int *), 0); for (i = 0; i < nb_attributes; i += 1) { if (attributes[y+1] != NULL) { _qualify_namespace(parser, attributes[y] , attributes[y + 2], &qualified_name_attr); } else { qualified_name_attr = xmlStrdup(attributes[y]); } attrs[z] = qualified_name_attr; attrs[z + 1] = xmlStrndup(attributes[y + 3] , (int) (attributes[y + 4] - attributes[y + 3])); z += 2; y += 5; } attrs[z] = NULL; } parser->h_start_element(parser->user, (const XML_Char *) qualified_name, (const XML_Char **) attrs); if (attrs) { for (i = 0; i < z; i++) { xmlFree(attrs[i]); } efree(attrs); } xmlFree(qualified_name); }
/* bring the palette colors in im2 to be closer to im1 * */ int gdImageColorMatch (gdImagePtr im1, gdImagePtr im2) { unsigned long *buf; /* stores our calculations */ unsigned long *bp; /* buf ptr */ int color, rgb; int x,y; int count; if( !im1->trueColor ) { return -1; /* im1 must be True Color */ } if( im2->trueColor ) { return -2; /* im2 must be indexed */ } if( (im1->sx != im2->sx) || (im1->sy != im2->sy) ) { return -3; /* the images are meant to be the same dimensions */ } if (im2->colorsTotal<1) { return -4; /* At least 1 color must be allocated */ } buf = (unsigned long *)safe_emalloc(sizeof(unsigned long), 5 * im2->colorsTotal, 0); memset( buf, 0, sizeof(unsigned long) * 5 * im2->colorsTotal ); for (x=0; x<im1->sx; x++) { for( y=0; y<im1->sy; y++ ) { color = im2->pixels[y][x]; rgb = im1->tpixels[y][x]; bp = buf + (color * 5); (*(bp++))++; *(bp++) += gdTrueColorGetRed(rgb); *(bp++) += gdTrueColorGetGreen(rgb); *(bp++) += gdTrueColorGetBlue(rgb); *(bp++) += gdTrueColorGetAlpha(rgb); } } bp = buf; for (color=0; color<im2->colorsTotal; color++) { count = *(bp++); if( count > 0 ) { im2->red[color] = *(bp++) / count; im2->green[color] = *(bp++) / count; im2->blue[color] = *(bp++) / count; im2->alpha[color] = *(bp++) / count; } else { bp += 4; } } gdFree(buf); return 0; }
/* {{{ metaphone */ static int metaphone(unsigned char *word, int word_len, long max_phonemes, char **phoned_word, int traditional) { int w_idx = 0; /* point in the phonization we're at. */ int p_idx = 0; /* end of the phoned phrase */ int max_buffer_len = 0; /* maximum length of the destination buffer */ /*-- Parameter checks --*/ /* Negative phoneme length is meaningless */ if (max_phonemes < 0) return -1; /* Empty/null string is meaningless */ /* Overly paranoid */ /* assert(word != NULL && word[0] != '\0'); */ if (word == NULL) return -1; /*-- Allocate memory for our phoned_phrase --*/ if (max_phonemes == 0) { /* Assume largest possible */ max_buffer_len = word_len; *phoned_word = safe_emalloc(sizeof(char), word_len, 1); } else { max_buffer_len = max_phonemes; *phoned_word = safe_emalloc(sizeof(char), max_phonemes, 1); } /*-- The first phoneme has to be processed specially. --*/ /* Find our first letter */ for (; !isalpha(Curr_Letter); w_idx++) { /* On the off chance we were given nothing but crap... */ if (Curr_Letter == '\0') { End_Phoned_Word return SUCCESS; /* For testing */ } }
char *php_geo_geohash_encode(double latitude, double longitude, int precision) { char *hash; int steps; double coord, mid; int is_even = 1; unsigned int hash_char = 0; int i; interval_struct lat_interval = { MAX_LAT, MIN_LAT }; interval_struct lng_interval = { MAX_LONG, MIN_LONG }; interval_struct *interval; if (precision < 0) { precision = 0; } hash = (char*)safe_emalloc(precision, sizeof(char), 1); hash[precision] = '\0'; steps = precision * 5.0; for (i = 1; i <= steps; i++) { if (is_even) { interval = &lng_interval; coord = longitude; } else { interval = &lat_interval; coord = latitude; } mid = (interval->low + interval->high) / 2.0; hash_char = hash_char << 1; if (coord > mid) { interval->low = mid; hash_char |= 0x01; } else { interval->high = mid; } if (!(i % 5)) { hash[(i - 1) / 5] = char_map[hash_char]; hash_char = 0; } is_even = !is_even; } return hash; }
char *php_addslashes(char *str, int length, int *new_length) { /* maximum string length, worst case situation */ char *new_str; char *source, *target; char *end; int local_new_length; if (!new_length) { new_length = &local_new_length; } if (!str) { *new_length = 0; return str; } new_str = (char *) safe_emalloc(2, (length ? length : (length = strlen(str))), 1); source = str; end = source + length; target = new_str; while (source < end) { switch (*source) { case '\0': *target++ = '\\'; *target++ = '0'; break; case '\'': case '\"': case '\\': *target++ = '\\'; /* break is missing *intentionally* */ default: *target++ = *source; break; } source++; } *target = 0; *new_length = target - new_str; new_str = (char *) realloc(new_str, *new_length + 1); return new_str; }