Exemple #1
0
/**
 * Internal sanizite wrapper to filter_var
 *
 * @param  mixed $value
 * @param  mixed $filters
 * @param  boolean $silent
 * @return mixed
 */
PHP_METHOD(Phalcon_Filter, _sanitize){

	zval *v0 = NULL, *v1 = NULL, *v2 = NULL;
	zval *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *r4 = NULL, *r5 = NULL, *r6 = NULL;
	zval *r7 = NULL, *r8 = NULL;
	zval *t0 = NULL, *t1 = NULL, *t2 = NULL, *t3 = NULL, *t4 = NULL, *t5 = NULL, *t6 = NULL;
	zval *t7 = NULL, *t8 = NULL;
	zval *c0 = NULL, *c1 = NULL, *c2 = NULL;
	zval *a0 = NULL;
	zval *i0 = NULL;
	zval *p3[] = { NULL, NULL, NULL }, *p4[] = { NULL };

	PHALCON_MM_GROW();
	
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|z", &v0, &v1, &v2) == FAILURE) {
		PHALCON_MM_RESTORE();
		RETURN_NULL();
	}

	
	if (!v2) {
		PHALCON_INIT_VAR(v2);
		ZVAL_BOOL(v2, 0);
	}
	
	PHALCON_INIT_VAR(t0);
	ZVAL_STRING(t0, "email", 1);
	PHALCON_ALLOC_ZVAL_MM(r0);
	is_equal_function(r0, v1, t0 TSRMLS_CC);
	if (zend_is_true(r0)) {
		PHALCON_ALLOC_ZVAL_MM(r1);
		PHALCON_INIT_VAR(t1);
		ZVAL_LONG(t1, 517);
		PHALCON_CALL_FUNC_PARAMS_2(r1, "filter_var", v0, t1, 0x03D);
		PHALCON_RETURN_DZVAL(r1);
	}
	PHALCON_INIT_VAR(t2);
	ZVAL_STRING(t2, "int", 1);
	PHALCON_ALLOC_ZVAL_MM(r2);
	is_equal_function(r2, v1, t2 TSRMLS_CC);
	if (zend_is_true(r2)) {
		PHALCON_ALLOC_ZVAL_MM(r3);
		PHALCON_INIT_VAR(t3);
		ZVAL_LONG(t3, 519);
		PHALCON_CALL_FUNC_PARAMS_2(r3, "filter_var", v0, t3, 0x03D);
		PHALCON_RETURN_DZVAL(r3);
	}
	PHALCON_INIT_VAR(t4);
	ZVAL_STRING(t4, "string", 1);
	PHALCON_ALLOC_ZVAL_MM(r4);
	is_equal_function(r4, v1, t4 TSRMLS_CC);
	if (zend_is_true(r4)) {
		PHALCON_ALLOC_ZVAL_MM(r5);
		PHALCON_INIT_VAR(t5);
		ZVAL_LONG(t5, 513);
		PHALCON_CALL_FUNC_PARAMS_2(r5, "filter_var", v0, t5, 0x03D);
		PHALCON_RETURN_DZVAL(r5);
	}
	PHALCON_INIT_VAR(t6);
	ZVAL_STRING(t6, "float", 1);
	PHALCON_ALLOC_ZVAL_MM(r6);
	is_equal_function(r6, v1, t6 TSRMLS_CC);
	if (zend_is_true(r6)) {
		PHALCON_ALLOC_ZVAL_MM(r7);
		p3[0] = v0;
		PHALCON_INIT_VAR(t7);
		ZVAL_LONG(t7, 520);
		p3[1] = t7;
		PHALCON_INIT_VAR(a0);
		array_init(a0);
		PHALCON_INIT_VAR(t8);
		ZVAL_LONG(t8, 4096);
		Z_ADDREF_P(t8);
		PHALCON_SEPARATE_ARRAY(a0);
		add_assoc_zval(a0, "flags", t8);
		p3[2] = a0;
		PHALCON_CALL_FUNC_PARAMS(r7, "filter_var", 3, p3, 0x03D);
		PHALCON_RETURN_DZVAL(r7);
	}
	if (!zend_is_true(v2)) {
		PHALCON_ALLOC_ZVAL_MM(i0);
		object_init_ex(i0, phalcon_exception_class_entry);
		PHALCON_ALLOC_ZVAL_MM(r8);
		PHALCON_CONCAT_BOTH(r8,  "Sanitize filter ", v1, " is not supported");
		Z_ADDREF_P(r8);
		p4[0] = r8;
		PHALCON_CALL_METHOD_PARAMS_NORETURN(i0, "__construct", 1, p4, PHALCON_CALL_CHECK);
		Z_DELREF_P(p4[0]);
		zend_throw_exception_object(i0 TSRMLS_CC);
		Z_ADDREF_P(i0);
		PHALCON_MM_RESTORE();
		return;
	} else {
		PHALCON_RETURN_CHECK_CTOR(v0);
	}
	se_e618_2:
	if(0) { };
	PHALCON_MM_RESTORE();
	RETURN_NULL();
}
static int php_mimepart_process_header(php_mimepart *part)
{
	php_rfc822_tokenized_t *toks;
	char *header_key, *header_val, *header_val_stripped;
	zval *zheaderval;
	zend_string *header_zstring;

	if (part->parsedata.headerbuf.len == 0)
		return SUCCESS;

	smart_string_0(&part->parsedata.headerbuf);

	/* parse the header line */
	toks = php_mailparse_rfc822_tokenize((const char*)part->parsedata.headerbuf.c, 0);

	/* valid headers consist of at least three tokens, with the first being a string and the
	 * second token being a ':' */
	if (toks->ntokens < 2 || toks->tokens[0].token != 0 || toks->tokens[1].token != ':') {
		part->parsedata.headerbuf.len = 0;

		php_rfc822_tokenize_free(toks);
		return FAILURE;
	}

	/* get a lower-case version of the first token */
	header_key = php_rfc822_recombine_tokens(toks, 0, 1, PHP_RFC822_RECOMBINE_IGNORE_COMMENTS|PHP_RFC822_RECOMBINE_STRTOLOWER);

	header_val = strchr(part->parsedata.headerbuf.c, ':');
	header_val_stripped = php_rfc822_recombine_tokens(toks, 2, toks->ntokens-2, PHP_RFC822_RECOMBINE_IGNORE_COMMENTS|PHP_RFC822_RECOMBINE_STRTOLOWER);

	if (header_val) {
		header_val++;
		while (isspace(*header_val))
			header_val++;

		/* add the header to the hash.
		 * join multiple To: or Cc: lines together */
		header_zstring = zend_string_init(header_key, strlen(header_key), 0);
		if ((strcmp(header_key, "to") == 0 || strcmp(header_key, "cc") == 0) && (zheaderval = zend_hash_find(Z_ARRVAL_P(&part->headerhash), header_zstring)) != NULL) {
			int newlen;
			char *newstr;

			newlen = strlen(header_val) + Z_STRLEN_P(zheaderval) + 3;
			newstr = emalloc(newlen);

			strcpy(newstr, Z_STRVAL_P(zheaderval));
			strcat(newstr, ", ");
			strcat(newstr, header_val);
			add_assoc_string(&part->headerhash, header_key, newstr);
			efree(newstr);
		} else {
			if((zheaderval = zend_hash_find(Z_ARRVAL_P(&part->headerhash), header_zstring)) != NULL) {
			      if(Z_TYPE_P(zheaderval) == IS_ARRAY) {
          add_next_index_string(zheaderval, header_val);
        } else {
          /* Create a nested array if there is more than one of the same header */
          zval zarr;
          array_init(&zarr);
          Z_ADDREF_P(zheaderval);

          add_next_index_zval(&zarr, zheaderval);
          add_next_index_string(&zarr, header_val);
          add_assoc_zval(&part->headerhash, header_key, &zarr);
        }
      } else {
        add_assoc_string(&part->headerhash, header_key, header_val);
      }
		}
		zend_string_release(header_zstring);
		/* if it is useful, keep a pointer to it in the mime part */
		if (strcmp(header_key, "mime-version") == 0)
			STR_SET_REPLACE(part->mime_version, header_val_stripped);

		if (strcmp(header_key, "content-location") == 0) {
			STR_FREE(part->content_location);
			part->content_location = php_rfc822_recombine_tokens(toks, 2, toks->ntokens-2, PHP_RFC822_RECOMBINE_IGNORE_COMMENTS);
		}
		if (strcmp(header_key, "content-base") == 0) {
			STR_FREE(part->content_base);
			part->content_base = php_rfc822_recombine_tokens(toks, 2, toks->ntokens-2, PHP_RFC822_RECOMBINE_IGNORE_COMMENTS);
		}

		if (strcmp(header_key, "content-transfer-encoding") == 0)
			STR_SET_REPLACE(part->content_transfer_encoding, header_val_stripped);
		if (strcmp(header_key, "content-type") == 0) {
			char *charset, *boundary;

			if (part->content_type) {
				php_mimeheader_free(part->content_type);
				part->content_type = NULL;
			}

			part->content_type = php_mimeheader_alloc_from_tok(toks);

			boundary = php_mimepart_attribute_get(part->content_type, "boundary");
			if (boundary) {
				part->boundary = estrdup(boundary);
			}

			charset = php_mimepart_attribute_get(part->content_type, "charset");
			if (charset) {
				STR_SET_REPLACE(part->charset, charset);
			}
		}
		if (strcmp(header_key, "content-disposition") == 0) {
			part->content_disposition = php_mimeheader_alloc_from_tok(toks);
		}

	}
	STR_FREE(header_key);
	STR_FREE(header_val_stripped);

	php_rfc822_tokenize_free(toks);

	/* zero the buffer size */
	part->parsedata.headerbuf.len = 0;
	return SUCCESS;
}
/* {{{ proto array accelerator_get_status([bool fetch_scripts])
   Obtain statistics information regarding code acceleration */
static ZEND_FUNCTION(opcache_get_status)
{
	zend_long reqs;
	zval memory_usage, statistics, scripts;
	zend_bool fetch_scripts = 1;

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

	if (!validate_api_restriction()) {
		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)));

#ifdef HAVE_OPCACHE_FILE_CACHE
	if (ZCG(accel_directives).file_cache) {
		add_assoc_string(return_value, "file_cache", ZCG(accel_directives).file_cache);
	}
	if (ZCG(accel_directives).file_cache_only) {
		add_assoc_bool(return_value, "file_cache_only", 1);
		return;
	}
#endif

	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 */
	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 (ZCSG(interned_strings_start) && ZCSG(interned_strings_end) && ZCSG(interned_strings_top)) {
		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);
	}

	/* Accelerator 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", (zend_long)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 */
		if (accelerator_get_scripts(&scripts)) {
			add_assoc_zval(return_value, "scripts", &scripts);
		}
	}
}
Exemple #4
0
PHP_METHOD(jsonrpc_server, register)
{
  zval *closure=NULL;
  zval *val;
  zval *name;
  zval *callbacks;
  char *lcname;
  char *name_str, *tmp;
  int name_len, tmp_len;
  zval *classname;

  zend_class_entry **pce;
  zend_class_entry *ce;
  zend_function *fptr;

  zval *object = getThis();

  if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "zO", &name, &closure, zend_ce_closure) == SUCCESS) {
    fptr = (zend_function*)zend_get_closure_method_def(closure TSRMLS_CC);
    Z_ADDREF_P(closure);
  } else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zs", &name, &name_str, &name_len) == SUCCESS) { 
    if ((tmp = strstr(name_str, "::")) == NULL) {
      char *nsname;

      lcname = zend_str_tolower_dup(name_str, name_len);

      // Ignore leading "\" 
      nsname = lcname;
      if (lcname[0] == '\\') {
      nsname = &lcname[1];
      name_len--;
      }

      if (zend_hash_find(EG(function_table), nsname, name_len + 1, (void **)&fptr) == FAILURE) {
        efree(lcname);
        php_error_docref(NULL TSRMLS_CC, E_WARNING, 
          "Function %s() does not exist", name_str);
        return;
      }
      efree(lcname);
    }else {
      tmp_len = tmp - name_str;
      MAKE_STD_ZVAL(classname);
      ZVAL_STRINGL(classname, name_str, tmp_len, 1);
      name_len = name_len - (tmp_len + 2);
      name_str = tmp + 2;
      //php_printf("classname: %s, method: %s\n", Z_STRVAL_P(classname), name_str);
      if (zend_lookup_class(Z_STRVAL_P(classname), Z_STRLEN_P(classname), &pce TSRMLS_CC) == FAILURE) {
        php_error_docref(NULL TSRMLS_CC, E_WARNING,
          "Class %s does exist", Z_STRVAL_P(classname));
        //zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC,
        //    "Class %s does not exist", Z_STRVAL_P(classname)); 
        zval_dtor(classname);
        return;
      }
      ce = *pce;

      lcname = zend_str_tolower_dup(name_str, name_len);

      if (zend_hash_find(&ce->function_table, lcname, name_len + 1, (void **) &fptr) == FAILURE) {
        efree(lcname);
        php_error_docref(NULL TSRMLS_CC, E_WARNING,
          "Method %s::%s() does not exist", ce->name, name_str);
        //zend_throw_exception_ex(reflection_exception_ptr, 0 TSRMLS_CC, 
        //  "Method %s::%s() does not exist", ce->name, name_str);
        return;
      }
      efree(lcname);
    }
  }else {
    return ;
  }


  callbacks = zend_read_property(
    php_jsonrpc_server_entry, object, "callbacks", sizeof("callbacks")-1, 0 TSRMLS_CC
  );

  MAKE_STD_ZVAL(val);

#if PHP_VERSION_ID < 50399
  zend_create_closure(val, fptr TSRMLS_CC);
#else
  zend_create_closure(val, fptr, NULL, NULL TSRMLS_CC);
#endif


  add_assoc_zval(callbacks, Z_STRVAL_P(name), val);

  zend_update_property(php_jsonrpc_server_entry, object, "callbacks", sizeof("callbacks")-1, callbacks TSRMLS_CC);

  RETURN_ZVAL(object,1,0);

}
Exemple #5
0
/* {{{ MongoDBRef::get()
 */
PHP_METHOD(MongoDBRef, get)
{
	zval *db, *ref, *collection, *query;
	zval **ns, **id, **dbname;
	zend_bool alloced_db = 0;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Oz", &db, mongo_ce_DB, &ref) == FAILURE) {
		return;
	}

	if (
		IS_SCALAR_P(ref) ||
		zend_hash_find(HASH_P(ref), "$ref", strlen("$ref") + 1, (void**)&ns) == FAILURE ||
		zend_hash_find(HASH_P(ref), "$id", strlen("$id") + 1, (void**)&id) == FAILURE
	) {
		RETURN_NULL();
	}

	if (Z_TYPE_PP(ns) != IS_STRING) {
		zend_throw_exception(mongo_ce_Exception, "MongoDBRef::get: $ref field must be a string", 10 TSRMLS_CC);
		return;
	}

	/* if this reference contains a db name, we have to switch dbs */
	if (zend_hash_find(HASH_P(ref), "$db", strlen("$db") + 1, (void**)&dbname) == SUCCESS) {
		mongo_db *temp_db = (mongo_db*)zend_object_store_get_object(db TSRMLS_CC);

		/* just to be paranoid, make sure dbname is a string */
		if (Z_TYPE_PP(dbname) != IS_STRING) {
			zend_throw_exception(mongo_ce_Exception, "MongoDBRef::get: $db field must be a string", 11 TSRMLS_CC);
			return;
		}

		/* if the name in the $db field doesn't match the current db, make up
		 * a new db */
		if (strcmp(Z_STRVAL_PP(dbname), Z_STRVAL_P(temp_db->name)) != 0) {
			zval *new_db_z;

			MAKE_STD_ZVAL(new_db_z);
			ZVAL_NULL(new_db_z);

			MONGO_METHOD1(MongoClient, selectDB, new_db_z, temp_db->link, *dbname);

			/* make the new db the current one */
			db = new_db_z;

			/* so we can dtor this later */
			alloced_db = 1;
		}
	}

	/* get the collection */
	MAKE_STD_ZVAL(collection);
	MONGO_METHOD1(MongoDB, selectCollection, collection, db, *ns);

	/* query for the $id */
	MAKE_STD_ZVAL(query);
	array_init(query);
	add_assoc_zval(query, "_id", *id);
	zval_add_ref(id);

	/* return whatever's there */
	MONGO_METHOD1(MongoCollection, findOne, return_value, collection, query);

	/* cleanup */
	zval_ptr_dtor(&collection);
	zval_ptr_dtor(&query);
	if (alloced_db) {
		zval_ptr_dtor(&db);
	}
}
Exemple #6
0
/* Iterate over the given protobuf message pointer and transform values into native
   php types. writes an associative array into the given zval**. */
void message_php (zval* return_value, const ProtobufCMessage *message)
{
    unsigned int i, j;
    for (i=0;i<message->descriptor->n_fields;i++) {
        const ProtobufCFieldDescriptor *field = message->descriptor->fields + i;
        const void* member = get_member(message, field);
        size_t* num_fields = get_quantifier(message, field);
        const ProtobufCMessage** sub_messages;
        const ProtobufCMessage* sub_message;
        zval *inner, *inner_repeated;

        switch (field->type) {

            case PROTOBUF_C_TYPE_INT32:
                if (field->label == PROTOBUF_C_LABEL_OPTIONAL && (protobuf_c_boolean)*num_fields) {
                    int32_php_single(return_value, (char*)field->name, (const int32_t*)member);
                } else if (field->label == PROTOBUF_C_LABEL_REQUIRED) {
                    int32_php_single(return_value, (char*)field->name, (const int32_t*)member);
                } else if (field->label == PROTOBUF_C_LABEL_REPEATED && *num_fields) {
                    int32_php_repeated(return_value, (char*)field->name, (const int32_t**)member, *num_fields);
                }
            break;

            case PROTOBUF_C_TYPE_UINT32:
                if (field->label == PROTOBUF_C_LABEL_OPTIONAL && (protobuf_c_boolean)*num_fields) {
                    uint32_php_single(return_value, (char*)field->name, (const uint32_t*)member);
                } else if (field->label == PROTOBUF_C_LABEL_REQUIRED) {
                    uint32_php_single(return_value, (char*)field->name, (const uint32_t*)member);
                } else if (field->label == PROTOBUF_C_LABEL_REPEATED && *num_fields) {
                    uint32_php_repeated(return_value, (char*)field->name, (const uint32_t**)member, *num_fields);
                }
            break;

            case PROTOBUF_C_TYPE_STRING:
                if (field->label == PROTOBUF_C_LABEL_OPTIONAL) {
                    char** pos = (char**)member;
                    if (*pos != NULL) {
                        string_php_single(return_value, (char*)field->name, (char* const*)member);
                    }
                } else if (field->label == PROTOBUF_C_LABEL_REQUIRED) {
                    string_php_single(return_value, (char*)field->name, (char* const*)member);
                } else if (field->label == PROTOBUF_C_LABEL_REPEATED && *num_fields) {
                    string_php_repeated(return_value, (char*)field->name, (char** const*)member, *num_fields);
                }
            break;

            case PROTOBUF_C_TYPE_BOOL:
                bool_php(return_value, field->name, *(const protobuf_c_boolean *)member);
            break;

            case PROTOBUF_C_TYPE_MESSAGE:

                // optional or repeated field with no entries shouldn't make it to PHP
                if (field->label == PROTOBUF_C_LABEL_OPTIONAL || field->label == PROTOBUF_C_LABEL_REPEATED) {
                    if (*((const ProtobufCMessage**)member) == NULL) {
                        break;
                    }
                }

                MAKE_STD_ZVAL(inner);
                array_init(inner);

                if (field->label == PROTOBUF_C_LABEL_OPTIONAL || field->label == PROTOBUF_C_LABEL_REQUIRED) {
                    message_php(inner, *((const ProtobufCMessage**)member));
                } else if (field->label == PROTOBUF_C_LABEL_REPEATED) {
                    sub_messages = (const ProtobufCMessage**)*((const ProtobufCMessage**)member);
                    for (j=0;j<*num_fields;++j) {
                        MAKE_STD_ZVAL(inner_repeated);
                        array_init(inner_repeated);
                        message_php(inner_repeated, sub_messages[j]);
                        add_next_index_zval(inner, inner_repeated);
                    }
                }

                add_assoc_zval(return_value, (char*)field->name, inner);

            break;
                
            case PROTOBUF_C_TYPE_DOUBLE:
//                double_php(return_value, field->name, *(const uint64_t *)member);
            case PROTOBUF_C_TYPE_FLOAT:
//                float_php(return_value, field->name, *(const uint32_t *)member);
            case PROTOBUF_C_TYPE_SINT32:
//                sint32_php(return_value, field->name, *(const int32_t *)member);
            case PROTOBUF_C_TYPE_FIXED32:
//                fixed32_php(return_value, field->name, *(const uint32_t *)member);
            case PROTOBUF_C_TYPE_SFIXED32:
//                sfixed32_php(return_value, field->name, *(const uint32_t *)member);
            case PROTOBUF_C_TYPE_INT64:
//                int64_php(return_value, field->name, *(const uint64_t *)member);
            case PROTOBUF_C_TYPE_SINT64:
//                sint64_php(return_value, field->name, *(const int64_t *)member);
            case PROTOBUF_C_TYPE_UINT64:
//                uint64_php(return_value, field->name, *(const uint64_t *)member);
            case PROTOBUF_C_TYPE_FIXED64:
//                fixed64_php(return_value, field->name, *(const uint64_t *)member);
            case PROTOBUF_C_TYPE_SFIXED64:
//                sfixed64_php(return_value, field->name, *(const uint64_t *)member);
            // XXX unimplemented XXX
            case PROTOBUF_C_TYPE_ENUM:
            case PROTOBUF_C_TYPE_BYTES:
            default:
                break;
        }
    }
}
Exemple #7
0
/* {{{ apc_iterator_item */
static apc_iterator_item_t* apc_iterator_item_ctor(apc_iterator_t *iterator, slot_t **slot_pp) {
    zval *zvalue;
    char md5str[33];
    slot_t *slot = *slot_pp;
    apc_context_t ctxt = {0, };
    apc_iterator_item_t *item = ecalloc(1, sizeof(apc_iterator_item_t));

    if (slot->key.type == APC_CACHE_KEY_FILE) {
        /* keys should be unique and with stat=1 we could have multiple files with the same name, so use '<device> <inode>' instead */
#ifdef PHP_WIN32
        item->key_len = spprintf(&item->key, 0, "%I64d %I64d", slot->key.data.file.device, slot->key.data.file.inode);
#else
        item->key_len = spprintf(&item->key, 0, "%ld %ld", (ulong)slot->key.data.file.device, (ulong)slot->key.data.file.inode);
#endif
        item->filename_key = estrdup(slot->value->data.file.filename);
    } else if (slot->key.type == APC_CACHE_KEY_USER) {
        item->key = estrndup((char*)slot->key.data.user.identifier, slot->key.data.user.identifier_len);
        item->key_len = slot->key.data.user.identifier_len;
        item->filename_key = item->key; 
    } else if (slot->key.type == APC_CACHE_KEY_FPFILE) {
        item->key = estrndup((char*)slot->key.data.fpfile.fullpath, slot->key.data.fpfile.fullpath_len);
        item->key_len = slot->key.data.fpfile.fullpath_len;
    } else {
        apc_eprint("Internal error, invalid entry type.");
    }

    ALLOC_INIT_ZVAL(item->value);
    array_init(item->value);

    if (APC_ITER_TYPE & iterator->format) {
        if(slot->value->type == APC_CACHE_ENTRY_FILE) {
            add_assoc_string(item->value, "type", "file", 1);
        } else if(slot->value->type == APC_CACHE_ENTRY_USER) {
            add_assoc_string(item->value, "type", "user", 1);
        }
    }
    if (APC_ITER_FILENAME & iterator->format) {
        if(slot->value->type == APC_CACHE_ENTRY_FILE) {
            if (slot->key.type == APC_CACHE_KEY_FILE) {
              add_assoc_string(item->value, "filename", slot->value->data.file.filename, 1);
            } else {  /* APC_CACHE_FPFILE */
              add_assoc_string(item->value, "filename", (char*)slot->key.data.fpfile.fullpath, 1);
            }
        }
    }
    if (APC_ITER_DEVICE & iterator->format) {
        if(slot->key.type == APC_CACHE_KEY_FILE) {
#ifdef PHP_WIN32
			char buf[20];
			sprintf(buf, "%I64d", slot->key.data.file.device);
			add_assoc_string(item->value, "device", buf, 1);
#else
            add_assoc_long(item->value, "device", slot->key.data.file.device);
#endif
        }
    }
    if (APC_ITER_INODE & iterator->format) {
        if(slot->key.type == APC_CACHE_KEY_FILE) {
#ifdef PHP_WIN32
			char buf[20];
			sprintf(buf, "%I64d", slot->key.data.file.device);
			add_assoc_string(item->value, "device", buf, 1);
#else
            add_assoc_long(item->value, "inode", slot->key.data.file.inode);
#endif
        }
    }
    if (APC_ITER_KEY & iterator->format) {
        add_assoc_stringl(item->value, "key", item->key, item->key_len, 1);
    }
    if (APC_ITER_VALUE & iterator->format) {
        if(slot->value->type == APC_CACHE_ENTRY_USER) {

            ctxt.pool = apc_pool_create(APC_UNPOOL, apc_php_malloc, apc_php_free, NULL, NULL);
            ctxt.copy = APC_COPY_OUT_USER;

            MAKE_STD_ZVAL(zvalue);
            apc_cache_fetch_zval(zvalue, slot->value->data.user.val, &ctxt);
            apc_pool_destroy(ctxt.pool);
            add_assoc_zval(item->value, "value", zvalue);
        }
    }
    if (APC_ITER_MD5 & iterator->format) {
        if(slot->value->type == APC_CACHE_ENTRY_FILE) {
            if(slot->key.md5) {
                make_digest(md5str, slot->key.md5);
                add_assoc_string(item->value, "md5", md5str, 1);
            }
        }
    }
    if (APC_ITER_NUM_HITS & iterator->format) {
        add_assoc_long(item->value, "num_hits", slot->num_hits);
    }
    if (APC_ITER_MTIME & iterator->format) {
        add_assoc_long(item->value, "mtime", slot->key.mtime);
    }
    if (APC_ITER_CTIME & iterator->format) {
        add_assoc_long(item->value, "creation_time", slot->creation_time);
    }
    if (APC_ITER_DTIME & iterator->format) {
        add_assoc_long(item->value, "deletion_time", slot->deletion_time);
    }
    if (APC_ITER_ATIME & iterator->format) {
        add_assoc_long(item->value, "access_time", slot->access_time);
    }
    if (APC_ITER_REFCOUNT & iterator->format) {
        add_assoc_long(item->value, "ref_count", slot->value->ref_count);
    }
    if (APC_ITER_MEM_SIZE & iterator->format) {
        add_assoc_long(item->value, "mem_size", slot->value->mem_size);
    }
    if (APC_ITER_TTL & iterator->format) {
        if(slot->value->type == APC_CACHE_ENTRY_USER) {
            add_assoc_long(item->value, "ttl", slot->value->data.user.ttl);
        }
    }

    return item;
}
Exemple #8
0
/* event must be initialized with MAKE_STD_ZVAL or similar and array_init before sending here */
void php_jam_capture_error_ex(zval *event, int type, const char *error_filename, const uint error_lineno, zend_bool free_event, const char *format, va_list args TSRMLS_DC)
{
	zval **ppzval;
	va_list args_cp;
	int len;
	char *buffer;
	char uuid_str[PHP_JAM_UUID_LEN + 1];
	
	TSRMLS_FETCH();
	
	/* Generate unique identifier */
	if (!php_jam_generate_uuid(uuid_str)) {
		php_jam_original_error_cb(E_WARNING TSRMLS_CC, "Failed to generate uuid");
		return;
	}

	/* Capture superglobals */
	if (JAM_G(log_get)) {
		_add_assoc_zval_helper(event, "_GET", sizeof("_GET") TSRMLS_CC);
	}
	
	if (JAM_G(log_post)) {
		_add_assoc_zval_helper(event, "_POST", sizeof("_POST") TSRMLS_CC);
	}
	
	if (JAM_G(log_cookie)) {
		_add_assoc_zval_helper(event, "_COOKIE", sizeof("_COOKIE") TSRMLS_CC);
	}
	
	if (JAM_G(log_session)) {
		_add_assoc_zval_helper(event, "_SESSION", sizeof("_SESSION") TSRMLS_CC);
	}
	
	if (JAM_G(log_server)) {
		_add_assoc_zval_helper(event, "_SERVER", sizeof("_SERVER") TSRMLS_CC);
	}
	
	if (JAM_G(log_env)) {
		_add_assoc_zval_helper(event, "_ENV", sizeof("_ENV") TSRMLS_CC);
	}
	
	if (JAM_G(log_files)) {
		_add_assoc_zval_helper(event, "_FILES", sizeof("_FILES") TSRMLS_CC);
	}
	
	/* Capture backtrace */
	if (JAM_G(log_backtrace)) {
		zval *btrace;
		ALLOC_INIT_ZVAL(btrace);
#if PHP_API_VERSION <= PHP_5_3_X_API_NO
		zend_fetch_debug_backtrace(btrace, 0, 0 TSRMLS_CC);
#else
// TODO: introduce a directive for the amount of stack frames returned instead of hard coded 1000?
		zend_fetch_debug_backtrace(btrace, 0, 0 TSRMLS_CC,1000);
#endif
		add_assoc_zval(event, "backtrace", btrace);
	}
	
	va_copy(args_cp, args);
	len = vspprintf(&buffer, PG(log_errors_max_len), format, args_cp);
	va_end(args_cp);

	add_assoc_string(event,	"error_message", buffer, 0);
	add_assoc_string(event,	"filename",	(char *)error_filename, 1);
	
	add_assoc_long(event, "line_number", error_lineno);
	add_assoc_long(event, "error_type", type);
	
	/*
		Set the last logged uuid into _SERVER
	*/
	add_assoc_string(event, "jam_event_uuid", uuid_str, 1);
	add_assoc_long(event, "jam_event_time", time(NULL));

	/*
		Set the last logged uuid into _SERVER
	*/
	if (zend_hash_find(&EG(symbol_table), "_SERVER", sizeof("_SERVER"), (void **) &ppzval) == SUCCESS) {
		add_assoc_string(*ppzval, "jam_last_uuid", uuid_str, 1);
	}

	/* Send to backend */
	php_jam_storage_store_all(uuid_str, event, type, error_filename, error_lineno TSRMLS_CC);
	
	if (free_event) {
		zval_dtor(event);
		FREE_ZVAL(event);
	}
}
/* {{{ php_parsekit_parse_node */
static void php_parsekit_parse_node(zval *return_value, zend_op_array *op_array, znode *node, long flags, long options TSRMLS_DC)
{
	array_init(return_value);
	add_assoc_long(return_value, "type", node->op_type);
	add_assoc_string(return_value, "type_name", php_parsekit_define_name(node->op_type, php_parsekit_nodetype_names, PHP_PARSEKIT_NODETYPE_UNKNOWN), 1);
	if (node->op_type == IS_CONST) {
		zval *tmpzval;
		MAKE_STD_ZVAL(tmpzval);
		*tmpzval = node->u.constant;
		zval_copy_ctor(tmpzval);
		Z_SET_REFCOUNT_P(tmpzval, 1);
		add_assoc_zval(return_value, "constant", tmpzval);
#ifdef IS_CV
/* PHP >= 5.1 */
	} else if (node->op_type == IS_CV) {
		add_assoc_long(return_value, "var", node->u.var);
		add_assoc_stringl(return_value, "varname", op_array->vars[node->u.var].name, op_array->vars[node->u.var].name_len, 1);
#endif
	} else {
		/* IS_VAR || IS_TMP_VAR || IS_UNUSED */
		char sop[(sizeof(void *) * 2) + 1];

		snprintf(sop, (sizeof(void *) * 2) + 1, "%X", (unsigned int)node->u.var); 

		if ((flags & PHP_PARSEKIT_VAR) ||
			(options & PHP_PARSEKIT_ALL_ELEMENTS)) {
			add_assoc_long(return_value, "var", node->u.var / sizeof(temp_variable));
		} else if (options & PHP_PARSEKIT_ALWAYS_SET) {
			add_assoc_null(return_value, "var");
		}

		if ((flags & PHP_PARSEKIT_OPLINE) ||
			(options & PHP_PARSEKIT_ALL_ELEMENTS)) {
			add_assoc_string(return_value, "opline_num", sop, 1);
		} else if (options & PHP_PARSEKIT_ALWAYS_SET) {
			add_assoc_null(return_value, "opline_num");
		}

		if ((flags & PHP_PARSEKIT_OPARRAY) ||
			(options & PHP_PARSEKIT_ALL_ELEMENTS)) {
			add_assoc_string(return_value, "op_array", sop, 1);
		} else if (options & PHP_PARSEKIT_ALWAYS_SET) {
			add_assoc_null(return_value, "op_array");
		}

#ifdef ZEND_ENGINE_2
/* ZE2 Only */
		if ((flags & PHP_PARSEKIT_JMP_ADDR) ||
			(options & PHP_PARSEKIT_ALL_ELEMENTS)) {
			add_assoc_string(return_value, "jmp_addr", sop, 1);
			snprintf(sop, sizeof(sop)-1, "%u",
					((unsigned int)((char*)node->u.var - (char*)op_array->opcodes))/sizeof(zend_op));
			add_assoc_string(return_value, "jmp_offset", sop, 1); 
		} else if (options & PHP_PARSEKIT_ALWAYS_SET) {
			add_assoc_null(return_value, "jmp_addr");
		}
#endif

		if ((flags & PHP_PARSEKIT_EA_TYPE) ||
			(options & PHP_PARSEKIT_ALL_ELEMENTS)) {
			add_assoc_long(return_value, "EA.type", node->u.EA.type);
		} else if (options & PHP_PARSEKIT_ALWAYS_SET) {
			add_assoc_null(return_value, "EA.type");
		}
	}
}
Exemple #10
0
bool ssdb_geo_neighbours(
		SSDBSock *ssdb_sock, char *key,
		int key_len,
		char *member_key,
		int member_key_len,
		double radius_meters,
		long return_limit,
		long offset_limit,
		long zscan_limit,
		INTERNAL_FUNCTION_PARAMETERS) {
	double latlong[2] = {0};
	if (!ssdb_geo_member(ssdb_sock, key, key_len, member_key, member_key_len, (double *)latlong)) {
		return false;
	}

	SSDBGeoObj *ssdb_geo_obj = emalloc(sizeof(SSDBGeoObj));

	ssdb_geo_obj->ssdb_sock      = ssdb_sock;
	ssdb_geo_obj->key            = key;
	ssdb_geo_obj->key_len        = key_len;
	ssdb_geo_obj->member_key     = member_key;
	ssdb_geo_obj->member_key_len = member_key_len;
	ssdb_geo_obj->limit_str      = NULL;
	ssdb_geo_obj->limit_str_len  = spprintf(&ssdb_geo_obj->limit_str, 0, "%ld", zscan_limit);

	GeoHashRadius georadius = geohashGetAreasByRadiusWGS84(latlong[0], latlong[1], radius_meters);
	SSDBGeoList *l = ssdb_geo_members(ssdb_geo_obj, georadius, latlong[0], latlong[1], radius_meters);

	efree(ssdb_geo_obj->limit_str);
	efree(ssdb_geo_obj);
	if (l == NULL) {
		return false;
	}

	return_limit = return_limit <= 0 ? l->num : return_limit;

	int i = 0;
	SSDBGeoPoint *p_l = malloc(sizeof(SSDBGeoPoint) * l->num);
	SSDBGeoPoint *p;
	SSDBGeoNode *n = l->head;
	while (n != NULL) {
		p = (SSDBGeoPoint *)n->data;

		p_l[i].member    = p->member;
		p_l[i].latitude  = p->latitude;
		p_l[i].longitude = p->longitude;
		p_l[i].dist      = p->dist;

		n = n->next;
		i++;
	}

	qsort(p_l, l->num, sizeof(SSDBGeoPoint), ssdb_geo_point_sort_asc);

	zval *temp;
	int return_num = 0;
	array_init(return_value);
	offset_limit = offset_limit < 0 ? 0 : offset_limit; 
	for (i = 0; i < l->num; i++) {
		if (i >= offset_limit && return_num < return_limit) {
			MAKE_STD_ZVAL(temp);
			array_init_size(temp, 3);
			add_assoc_double_ex(temp, ZEND_STRS("latitude"),  p_l[i].latitude);
			add_assoc_double_ex(temp, ZEND_STRS("longitude"), p_l[i].longitude);
			add_assoc_double_ex(temp, ZEND_STRS("distance"),  p_l[i].dist);
			add_assoc_zval(return_value, p_l[i].member, temp);
			return_num++;
		}
		efree(p_l[i].member);
	}

	free(p_l);
	ssdb_geo_list_destory(l);

	return true;
}
/* {{{ php_parsekit_parse_op_array */
static void php_parsekit_parse_op_array(zval *return_value, zend_op_array *ops, long options TSRMLS_DC)
{
	zend_op *op;
	zval *tmpzval;
	int i = 0;

	/* TODO: Reorder / Organize */

	array_init(return_value);

	add_assoc_long(return_value, "type", (long)(ops->type));
	add_assoc_string(return_value, "type_name", php_parsekit_define_name(ops->type, php_parsekit_function_types, PHP_PARSEKIT_FUNCTYPE_UNKNOWN), 1);
	if (ops->function_name) {
		add_assoc_string(return_value, "function_name", ops->function_name, 1);
	} else if (options & PHP_PARSEKIT_ALWAYS_SET) {
		add_assoc_null(return_value, "function_name");
	}

#ifdef ZEND_ENGINE_2
/* ZE2 op_array members */
	if (ops->scope && ops->scope->name) {
		add_assoc_stringl(return_value, "scope", ops->scope->name, ops->scope->name_length, 1);
	} else if (options & PHP_PARSEKIT_ALWAYS_SET) {
		add_assoc_null(return_value, "scope");
	}
	add_assoc_long(return_value, "fn_flags", ops->fn_flags);
	if (ops->function_name && ops->prototype) {
		MAKE_STD_ZVAL(tmpzval);
		array_init(tmpzval);
		add_assoc_long(tmpzval, "type", ops->prototype->type);
		add_assoc_string(return_value, "type_name", php_parsekit_define_name(ops->prototype->type, php_parsekit_function_types, PHP_PARSEKIT_FUNCTYPE_UNKNOWN), 1);
		if (ops->prototype->common.function_name) {
			add_assoc_string(tmpzval, "function_name", ops->prototype->common.function_name, 1);
		} else if (options & PHP_PARSEKIT_ALWAYS_SET) {
			add_assoc_null(tmpzval, "function_name");
		}
		if (ops->prototype->common.scope && ops->prototype->common.scope->name) {
			add_assoc_stringl(tmpzval, "scope", ops->prototype->common.scope->name, ops->prototype->common.scope->name_length, 1);
		} else if (options & PHP_PARSEKIT_ALWAYS_SET) {
			add_assoc_null(tmpzval, "scope");
		}
		add_assoc_zval(return_value, "prototype", tmpzval);		
	} else if (options & PHP_PARSEKIT_ALWAYS_SET) {
		add_assoc_null(return_value, "prototype");
	}
	add_assoc_long(return_value, "num_args", ops->num_args);
	add_assoc_long(return_value, "required_num_args", ops->required_num_args);
	add_assoc_bool(return_value, "pass_rest_by_reference", ops->pass_rest_by_reference);

	if (ops->num_args && ops->arg_info) {
		MAKE_STD_ZVAL(tmpzval);
		php_parsekit_parse_arginfo(tmpzval, ops->num_args, ops->arg_info, options TSRMLS_CC);
		add_assoc_zval(return_value, "arg_info", tmpzval);
	} else if (options & PHP_PARSEKIT_ALWAYS_SET) {
		add_assoc_null(return_value, "arg_info");
	}

	if (ops->last_try_catch > 0) {
		MAKE_STD_ZVAL(tmpzval);
		array_init(tmpzval);
		for(i = 0; i < ops->last_try_catch; i++) {
			zval *tmp_zval;

			MAKE_STD_ZVAL(tmp_zval);
			array_init(tmp_zval);
			add_assoc_long(tmp_zval, "try_op", ops->try_catch_array[i].try_op);
			add_assoc_long(tmp_zval, "catch_op", ops->try_catch_array[i].catch_op);
			add_index_zval(tmpzval, i, tmp_zval);
		}
		add_assoc_zval(return_value, "try_catch_array", tmpzval);
	} else if (options & PHP_PARSEKIT_ALWAYS_SET) {
		add_assoc_null(return_value, "try_catch_array");
	}

#ifndef ZEND_ACC_CLOSURE
/* PHP<5.3 */
	add_assoc_bool(return_value, "uses_this", ops->uses_this);
#endif
	add_assoc_long(return_value, "line_start", ops->line_start);
	add_assoc_long(return_value, "line_end", ops->line_end);

	if (ops->doc_comment && ops->doc_comment_len) {
		add_assoc_stringl(return_value, "doc_comment", ops->doc_comment, ops->doc_comment_len, 1);
	} else if (options & PHP_PARSEKIT_ALWAYS_SET) {
		add_assoc_null(return_value, "doc_comment");
	}

#else
/* ZE1 op_array members */

	if (ops->arg_types) {
		zend_uchar *arg_types = ops->arg_types;
		int numargs = *(ops->arg_types);

		MAKE_STD_ZVAL(tmpzval);
		array_init(tmpzval);
		add_assoc_long(tmpzval, "arg_count", numargs);

		for(i = 0; i < numargs; i++) {
			add_next_index_long(tmpzval, arg_types[i+1]);
		}

		add_assoc_zval(return_value, "arg_types", tmpzval);

		/* Emulated arg_info */
		MAKE_STD_ZVAL(tmpzval);
		php_parsekit_derive_arginfo(tmpzval, ops, options TSRMLS_CC);
		add_assoc_zval(return_value, "arg_info", tmpzval);
	} else {
		MAKE_STD_ZVAL(tmpzval);
		array_init(tmpzval);
		add_assoc_long(tmpzval, "arg_count", 0);

		add_assoc_zval(return_value, "arg_types", tmpzval);
		add_assoc_null(return_value, "arg_info");
	}

	add_assoc_bool(return_value, "uses_global", ops->uses_globals);
#endif
/* ZE1 and ZE2 */

	add_assoc_bool(return_value, "return_reference", ops->return_reference);
	add_assoc_long(return_value, "refcount", *(ops->refcount));
	add_assoc_long(return_value, "last", ops->last);
	add_assoc_long(return_value, "size", ops->size);
	add_assoc_long(return_value, "T", ops->T);
	add_assoc_long(return_value, "last_brk_cont", ops->last_brk_cont);
	add_assoc_long(return_value, "current_brk_cont", ops->current_brk_cont);
	add_assoc_long(return_value, "backpatch_count", ops->backpatch_count);
	add_assoc_bool(return_value, "done_pass_two", ops->done_pass_two);

	if (ops->last_brk_cont > 0) {
		MAKE_STD_ZVAL(tmpzval);
		array_init(tmpzval);
		for(i = 0; i < ops->last_brk_cont; i++) {
			zval *tmp_zval;

			MAKE_STD_ZVAL(tmp_zval);
			array_init(tmp_zval);
			add_assoc_long(tmp_zval, "cont", ops->brk_cont_array[i].cont);
			add_assoc_long(tmp_zval, "brk", ops->brk_cont_array[i].brk);
			add_assoc_long(tmp_zval, "parent", ops->brk_cont_array[i].parent);
			add_index_zval(tmpzval, i, tmp_zval);
		}
		add_assoc_zval(return_value, "brk_cont_array", tmpzval);
	} else if (options & PHP_PARSEKIT_ALWAYS_SET) {
		add_assoc_null(return_value, "brk_cont_array");
	}

	if (ops->static_variables) {
		zval *tmp_zval;

		MAKE_STD_ZVAL(tmpzval);
		array_init(tmpzval);
		zend_hash_copy(HASH_OF(tmpzval), ops->static_variables, (copy_ctor_func_t) zval_add_ref, (void *) &tmp_zval, sizeof(zval *));
		add_assoc_zval(return_value, "static_variables", tmpzval);
	} else if (options & PHP_PARSEKIT_ALWAYS_SET) {
		add_assoc_null(return_value, "static_variables");
	}

	if (ops->start_op) {
		char sop[(sizeof(void *) * 2) + 1];

		snprintf(sop, sizeof(sop), "%X", (unsigned int)ops->start_op); 
		add_assoc_string(return_value, "start_op", sop, 1);
	} else if (options & PHP_PARSEKIT_ALWAYS_SET) {
		add_assoc_null(return_value, "start_op");
	}

	if (ops->filename) {
		add_assoc_string(return_value, "filename", ops->filename, 1);
	} else {
		add_assoc_null(return_value, "filename");
	}

	/* Leave this last, it simplifies readability */
	MAKE_STD_ZVAL(tmpzval);
	array_init(tmpzval);
	for(op = ops->opcodes, i = 0; op && i < ops->size; op++, i++) {
		zval *zop;

		MAKE_STD_ZVAL(zop);
		php_parsekit_parse_op(zop, ops, op, options TSRMLS_CC);
		add_next_index_zval(tmpzval, zop);
	}	
	add_assoc_zval(return_value, "opcodes", tmpzval);

}
/* {{{ MongoCursor->__construct
 */
PHP_METHOD(MongoCursor, __construct) {
  zval *zlink = 0, *zns = 0, *zquery = 0, *zfields = 0, *empty, *q, *slave_okay;
  zval **data;
  mongo_cursor *cursor;
  mongo_link *link;

  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|zz", &zlink, &zns, &zquery, &zfields) == FAILURE) {
    return;
  }

  // if query or fields weren't passed, make them default to an empty array
  MAKE_STD_ZVAL(empty);
  object_init(empty);

  // these are both initialized to the same zval, but that's okay because 
  // there's no way to change them without creating a new cursor
  if (!zquery) {
    zquery = empty;
  }
  if (!zfields) {
    zfields = empty;
  }

  cursor = (mongo_cursor*)zend_object_store_get_object(getThis() TSRMLS_CC);
 
  // db connection
  cursor->resource = zlink;
  zval_add_ref(&zlink);

  // db connection resource
  ZEND_FETCH_RESOURCE2(link, mongo_link*, &zlink, -1, PHP_CONNECTION_RES_NAME, le_connection, le_pconnection); 
  cursor->link = link;

  // change ['x', 'y', 'z'] into {'x' : 1, 'y' : 1, 'z' : 1}
  if (Z_TYPE_P(zfields) == IS_ARRAY) {
    HashPosition pointer;
    zval *fields;

    MAKE_STD_ZVAL(fields);
    object_init(fields);

    // fields to return
    for(zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(zfields), &pointer); 
        zend_hash_get_current_data_ex(Z_ARRVAL_P(zfields), (void**) &data, &pointer) == SUCCESS; 
        zend_hash_move_forward_ex(Z_ARRVAL_P(zfields), &pointer)) {
      int key_type, key_len;
      ulong index;
      char *key;
      
      key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(zfields), &key, (uint*)&key_len, &index, NO_DUP, &pointer);

      if (key_type == HASH_KEY_IS_LONG &&
          Z_TYPE_PP(data) == IS_STRING) {
        add_property_long(fields, Z_STRVAL_PP(data), 1);
      }
      else {
        add_property_long(fields, key, 1);
      }
    }
    cursor->fields = fields;
  }
  // if it's already an object, we don't have to worry
  else {
    cursor->fields = zfields;
    zval_add_ref(&zfields);
  }

  // ns
  convert_to_string(zns);
  cursor->ns = estrdup(Z_STRVAL_P(zns));

  // query
  MAKE_STD_ZVAL(q);
  array_init(q);

  add_assoc_zval(q, "query", zquery);
  zval_add_ref(&zquery);
  cursor->query = q;

  // reset iteration pointer, just in case
  MONGO_METHOD(MongoCursor, reset)(INTERNAL_FUNCTION_PARAM_PASSTHRU);

  cursor->at = 0;
  cursor->num = 0;

  slave_okay = zend_read_static_property(mongo_ce_Cursor, "slaveOkay", strlen("slaveOkay"), NOISY TSRMLS_CC);
  cursor->opts = Z_BVAL_P(slave_okay) ? (1 << 2) : 0;

  // get rid of extra ref
  zval_ptr_dtor(&empty);
}
Exemple #13
0
/* {{{ proto Util::array_pluck(array $array, string $field[, bool $preserve_keys, bool $remove_nomatches])
   Replaces each value in an array with the specified field of the array or object that used to be the value. Very useful when you have an array of objects or arrays from a database, and you only want one specific field. For example, you want an array of emails from an array of users. */
ZEND_METHOD(util, array_pluck)
{
	zval *arr;
	char *key;
	uint keylen;
	zend_bool preserve_keys = 1;
	zend_bool remove_nomatches = 1;
	zend_bool silent = 1;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "as|bb", &arr, &key, &keylen, &preserve_keys, &remove_nomatches) == FAILURE) {
		RETURN_NULL();
	}

	zval **item;
	HashPosition pointer;
	HashTable* arr_hash = Z_ARRVAL_P(arr);
	array_init(return_value);

	zend_hash_internal_pointer_reset_ex(arr_hash, &pointer);
	while (zend_hash_get_current_data_ex(arr_hash, (void**) &item, &pointer) == SUCCESS) {
		zval *zvalue;
		MAKE_STD_ZVAL(zvalue);
		ZVAL_NULL(zvalue);
		zval *temp;
		MAKE_STD_ZVAL(temp);
		*temp = **item;
		zval_copy_ctor(temp);

		if (Z_TYPE_P(temp) == IS_OBJECT) {
			zend_class_entry *object;
			object = Z_OBJCE_P(temp);
			zval *temp_data;
			temp_data = zend_read_property(object, temp, key, keylen, silent TSRMLS_CC);
			*zvalue = *temp_data;
		} else {
			zval **temp_data;
			if (zend_hash_find(Z_ARRVAL_P(temp), key, keylen + 1, (void**) &temp_data) == SUCCESS) {
				*zvalue = **temp_data;
			}
		}

		char *type_key;
		uint type_keylen;
		ulong idx;

		if (Z_TYPE_P(zvalue) != IS_NULL) {
			if (preserve_keys) {
				int type = zend_hash_get_current_key_ex(arr_hash, &type_key, &type_keylen, &idx, 0, &pointer);
				if (type == HASH_KEY_IS_LONG) {
					add_index_zval(return_value, idx, zvalue);
				} else {
					add_assoc_zval(return_value, type_key, zvalue);
				}
			} else {
				add_next_index_zval(return_value, zvalue);
			}
		} else if (!remove_nomatches) {
			int type = zend_hash_get_current_key_ex(arr_hash, &type_key, &type_keylen, &idx, 0, &pointer);
			if (type == HASH_KEY_IS_LONG) {
				add_index_zval(return_value, idx, temp);
			} else {
				add_assoc_zval(return_value, type_key, temp);
			}
		}
		zend_hash_move_forward_ex(arr_hash, &pointer);
	}
	return;
}
/* {{{ proto string MongoGridFSFile::getBytes()
   Returns this file's contents as a string of bytes */
PHP_METHOD(MongoGridFSFile, getBytes)
{
	zval *file, *gridfs, *chunks, *query, *cursor, *sort, *temp;
	zval **id, **size;
	char *str, *str_ptr;
	int len;
	mongo_cursor *cursorobj;
	zval *flags;

	file = zend_read_property(mongo_ce_GridFSFile, getThis(), "file", strlen("file"), NOISY TSRMLS_CC);
	zend_hash_find(HASH_P(file), "_id", strlen("_id") + 1, (void**)&id);

	if (zend_hash_find(HASH_P(file), "length", strlen("length") + 1, (void**)&size) == FAILURE) {
		zend_throw_exception(mongo_ce_GridFSException, "couldn't find file size", 14 TSRMLS_CC);
		return;
	}

	/* make sure that there's an index on chunks so we can sort by chunk num */
	gridfs = zend_read_property(mongo_ce_GridFSFile, getThis(), "gridfs", strlen("gridfs"), NOISY TSRMLS_CC);
	chunks = zend_read_property(mongo_ce_GridFS, gridfs, "chunks", strlen("chunks"), NOISY TSRMLS_CC);

	MAKE_STD_ZVAL(temp);
	php_mongo_ensure_gridfs_index(temp, chunks TSRMLS_CC);
	zval_dtor(temp);

	/* query for chunks */
	MAKE_STD_ZVAL(query);
	array_init(query);
	zval_add_ref(id);
	add_assoc_zval(query, "files_id", *id);

	MAKE_STD_ZVAL(cursor);
	MONGO_METHOD1(MongoCollection, find, cursor, chunks, query);

	/* Copy the flags from the original cursor and apply it to this one */
	flags = zend_read_property(mongo_ce_GridFSFile, getThis(), "flags", strlen("flags"), NOISY TSRMLS_CC);
	cursorobj = (mongo_cursor*)zend_object_store_get_object(cursor TSRMLS_CC);
	convert_to_long(flags);
	cursorobj->opts = Z_LVAL_P(flags);

	MAKE_STD_ZVAL(sort);
	array_init(sort);
	add_assoc_long(sort, "n", 1);

	MONGO_METHOD1(MongoCursor, sort, temp, cursor, sort);
	zval_ptr_dtor(&temp);

	zval_ptr_dtor(&query);
	zval_ptr_dtor(&sort);

	if (Z_TYPE_PP(size) == IS_DOUBLE) {
		len = (int)Z_DVAL_PP(size);
	} else if (Z_TYPE_PP(size) == IS_LONG) {
		len = Z_LVAL_PP(size);
	} else if (Z_TYPE_PP(size) == IS_OBJECT && (Z_OBJCE_PP(size) == mongo_ce_Int32 || Z_OBJCE_PP(size) == mongo_ce_Int64)) {
		zval *sizet = zend_read_property(mongo_ce_Int64, *size, "value", strlen("value"), NOISY TSRMLS_CC);
		if (Z_TYPE_P(sizet) != IS_STRING) {
			zval_ptr_dtor(&cursor);
			zend_throw_exception(mongo_ce_GridFSException, "couldn't find file size, value object broken", 0 TSRMLS_CC);
			return;
		}
		len = atoi(Z_STRVAL_P(sizet));
	} else {
		zval_ptr_dtor(&cursor);
		zend_throw_exception(mongo_ce_GridFSException, "couldn't find file size, property invalid", 0 TSRMLS_CC);
		return;
	}

	str = (char *)ecalloc(len + 1, 1);
	str_ptr = str;

	if (apply_to_cursor(cursor, copy_bytes, &str, len + 1 TSRMLS_CC) == FAILURE) {
		zval_ptr_dtor(&cursor);
		efree(str_ptr);

		if (EG(exception)) {
			return;
		}
		zend_throw_exception(mongo_ce_GridFSException, "error reading chunk of file", 17 TSRMLS_CC);
		return;
	}

	zval_ptr_dtor(&cursor);

	str_ptr[len] = '\0';

	RETURN_STRINGL(str_ptr, len, 0);
}
Exemple #15
0
/* {{{ apc_cache_info */
PHP_APCU_API zval apc_cache_info(apc_cache_t* cache, zend_bool limited)
{
    zval info;
    zval list;
    zval gc;
    zval slots;
    apc_cache_slot_t* p;
    zend_ulong i, j;

    if (!cache) {
		ZVAL_NULL(&info);

        return info;
    }

    /* read lock header */
    APC_RLOCK(cache->header);

    array_init(&info);
    add_assoc_long(&info, "num_slots", cache->nslots);
    add_assoc_long(&info, "ttl", cache->ttl);
    add_assoc_double(&info, "num_hits", (double)cache->header->nhits);
    add_assoc_double(&info, "num_misses", (double)cache->header->nmisses);
    add_assoc_double(&info, "num_inserts", (double)cache->header->ninserts);
    add_assoc_long(&info,   "num_entries", cache->header->nentries);
    add_assoc_double(&info, "expunges", (double)cache->header->nexpunges);
    add_assoc_long(&info, "start_time", cache->header->stime);
    add_assoc_double(&info, "mem_size", (double)cache->header->mem_size);

#if APC_MMAP
    add_assoc_stringl(&info, "memory_type", "mmap", sizeof("mmap")-1);
#else
    add_assoc_stringl(&info, "memory_type", "IPC shared", sizeof("IPC shared")-1);
#endif

    if (!limited) {
        /* For each hashtable slot */
        array_init(&list);
        array_init(&slots);

        for (i = 0; i < cache->nslots; i++) {
            p = cache->slots[i];
            j = 0;
            for (; p != NULL; p = p->next) {
                zval link = apc_cache_link_info(cache, p);
                add_next_index_zval(&list, &link);
                j++;
            }
            if(j != 0) {
                add_index_long(&slots, (ulong)i, j);
            }
        }

        /* For each slot pending deletion */
        array_init(&gc);

        for (p = cache->header->gc; p != NULL; p = p->next) {
            zval link = apc_cache_link_info(cache, p);
            add_next_index_zval(&gc, &link);
        }
        
        add_assoc_zval(&info, "cache_list", &list);
        add_assoc_zval(&info, "deleted_list", &gc);
        add_assoc_zval(&info, "slot_distribution", &slots);
    }
	
	/* unlock header */
	APC_RUNLOCK(cache->header);

    return info;
}
/* {{{ proto int MongoGridFSFile::write([string filename = null])
   Writes this file to the filesystem */
PHP_METHOD(MongoGridFSFile, write)
{
	char *filename = 0;
	int filename_len, total = 0;
	zval *gridfs, *file, *chunks, *query, *cursor, *sort, tmp;
	zval **id, **size;
	int len;
	FILE *fp;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &filename, &filename_len) == FAILURE) {
		return;
	}

	gridfs = zend_read_property(mongo_ce_GridFSFile, getThis(), "gridfs", strlen("gridfs"), NOISY TSRMLS_CC);
	file = zend_read_property(mongo_ce_GridFSFile, getThis(), "file", strlen("file"), NOISY TSRMLS_CC);

	if (zend_hash_find(HASH_P(file), "length", strlen("length") + 1, (void**)&size) == FAILURE) {
		zend_throw_exception(mongo_ce_GridFSException, "couldn't find file size", 14 TSRMLS_CC);
		return;
	}

	if (Z_TYPE_PP(size) == IS_DOUBLE) {
		len = (int)Z_DVAL_PP(size);
	} else if (Z_TYPE_PP(size) == IS_LONG) {
		len = Z_LVAL_PP(size);
	} else if (Z_TYPE_PP(size) == IS_OBJECT && (Z_OBJCE_PP(size) == mongo_ce_Int32 || Z_OBJCE_PP(size) == mongo_ce_Int64)) {
		zval *sizet = zend_read_property(mongo_ce_Int64, *size, "value", strlen("value"), NOISY TSRMLS_CC);
		if (Z_TYPE_P(sizet) != IS_STRING) {
			zval_ptr_dtor(&cursor);
			zend_throw_exception(mongo_ce_GridFSException, "couldn't find file size, value object broken", 0 TSRMLS_CC);
			return;
		}
		len = atoi(Z_STRVAL_P(sizet));
	} else {
		zval_ptr_dtor(&cursor);
		zend_throw_exception(mongo_ce_GridFSException, "couldn't find file size, property invalid", 0 TSRMLS_CC);
		return;
	}

	/* Make sure that there's an index on chunks so we can sort by chunk num */
	chunks = zend_read_property(mongo_ce_GridFS, gridfs, "chunks", strlen("chunks"), NOISY TSRMLS_CC);

	php_mongo_ensure_gridfs_index(&tmp, chunks TSRMLS_CC);
	zval_dtor(&tmp);

	if (!filename) {
		zval **temp;
		if (zend_hash_find(HASH_P(file), "filename", strlen("filename") + 1, (void**) &temp) == SUCCESS) {
			convert_to_string_ex(temp);
			filename = Z_STRVAL_PP(temp);
		} else {
			zend_throw_exception(mongo_ce_GridFSException, "Cannot find filename", 15 TSRMLS_CC);
			return;
		}
	}

	fp = fopen(filename, "wb");
	if (!fp) {
		zend_throw_exception_ex(mongo_ce_GridFSException, 16 TSRMLS_CC, "could not open destination file %s", filename);
		return;
	}

	zend_hash_find(HASH_P(file), "_id", strlen("_id") + 1, (void**)&id);

	MAKE_STD_ZVAL(query);
	array_init(query);
	zval_add_ref(id);
	add_assoc_zval(query, "files_id", *id);

	MAKE_STD_ZVAL(cursor);
	MONGO_METHOD1(MongoCollection, find, cursor, chunks, query);

	MAKE_STD_ZVAL(sort);
	array_init(sort);
	add_assoc_long(sort, "n", 1);

	MONGO_METHOD1(MongoCursor, sort, cursor, cursor, sort);

	if ((total = apply_to_cursor(cursor, copy_file, fp, len TSRMLS_CC)) == FAILURE) {
		zend_throw_exception(mongo_ce_GridFSException, "error reading chunk of file", 17 TSRMLS_CC);
	}

	fclose(fp);

	zval_ptr_dtor(&cursor);
	zval_ptr_dtor(&sort);
	zval_ptr_dtor(&query);

	RETURN_LONG(total);
}
Exemple #17
0
PHP_METHOD(air_mysql_waiter, step_0) {
	AIR_INIT_THIS;
	zval *services = zend_read_property(Z_OBJCE_P(self), self, ZEND_STRL("_services"), 0 TSRMLS_CC);
	zval *responses = zend_read_property(Z_OBJCE_P(self), self, ZEND_STRL("_responses"), 0 TSRMLS_CC);
	zval *context = zend_read_property(Z_OBJCE_P(self), self, ZEND_STRL("_context"), 0 TSRMLS_CC);
	zend_class_entry *mysqli_ce = air_get_ce(ZEND_STRL("mysqli") TSRMLS_CC);
	zval *async;
	MAKE_STD_ZVAL(async);
	ZVAL_LONG(async, MYSQLI_ASYNC);

	zval *wait_pool, *m2s;
	MAKE_STD_ZVAL(wait_pool);
	array_init(wait_pool);
	MAKE_STD_ZVAL(m2s);
	array_init(m2s);

	zval *service;
	ulong idx;
	uint _idx, key_len;
	char *key;
	zval *mysqli = NULL;
	HashTable *ah = Z_ARRVAL_P(services);
	for(zend_hash_internal_pointer_reset(ah);
			zend_hash_has_more_elements(ah) == SUCCESS;){
		zval **___tmp;
		if (zend_hash_get_current_data(ah, (void**)&___tmp) == FAILURE) {
			continue;
		}
		if(zend_hash_get_current_key_ex(ah, &key, &key_len, &idx, 0, NULL) != HASH_KEY_IS_STRING) {
			key = NULL; key_len = 0;
		}
		service = *___tmp;
		if(Z_TYPE_P(service) == IS_NULL){
			zend_hash_index_del(ah, idx);
			continue;
		}
		zval *service_id = zend_read_property(air_async_service_ce, service, ZEND_STRL("_id"), 1 TSRMLS_CC);
		zval *mysql = zend_read_property(air_async_service_ce, service, ZEND_STRL("_request"), 1 TSRMLS_CC);
		zval *status = zend_read_property(air_mysql_ce, mysql, ZEND_STRL("_status"), 0 TSRMLS_CC);
		if(Z_LVAL_P(status)){
			//ignore if the mysql's been executed
			zend_hash_index_del(ah, idx);
			continue;
		}
		zval *mysql_config = zend_read_property(air_mysql_ce, mysql, ZEND_STRL("_config"), 1 TSRMLS_CC);
		zval *mode = zend_read_property(air_mysql_ce, mysql, ZEND_STRL("_mode"), 1 TSRMLS_CC);
		if(Z_TYPE_P(mode) == IS_NULL){
			air_mysql_auto_mode(mysql TSRMLS_CC);
			mode = zend_read_property(air_mysql_ce, mysql, ZEND_STRL("_mode"), 1 TSRMLS_CC);
		}
		zval **acquire_params[2] = {&mysql_config, &mode};
		mysqli = NULL;
		air_call_static_method(air_mysql_keeper_ce, "acquire", &mysqli, 2, acquire_params);
		if(Z_TYPE_P(mysqli) != IS_NULL){
			zval **build_params[1] = {&mysqli};
			zval *sql = NULL;
			air_call_method(&mysql, air_mysql_ce, NULL, ZEND_STRL("build"), &sql, 1, build_params TSRMLS_CC);
			if(sql){
				zval **query_params[2] = {&sql, &async};
				air_call_method(&mysqli, mysqli_ce, NULL, ZEND_STRL("query"), NULL, 2, query_params TSRMLS_CC);
				add_next_index_zval(wait_pool, mysqli);
				Z_ADDREF_P(service_id);
				add_index_zval(m2s, air_mysqli_get_id(mysqli TSRMLS_CC), service_id);
				zval_ptr_dtor(&sql);
			}else{
				//should not happen
				php_error(E_ERROR, "sql not found");
				zval_ptr_dtor(&mysqli);
			}
		}else{
			zval_ptr_dtor(&mysqli);
		}
		zend_hash_move_forward(ah);
	}
	zval_ptr_dtor(&async);
	add_assoc_zval(context, "pool", wait_pool);
	add_assoc_zval(context, "m2s", m2s);
	add_assoc_long(context, "waited", zend_hash_num_elements(Z_ARRVAL_P(wait_pool)));
	add_assoc_long(context, "processed", 0);
	add_assoc_long(context, "step", 1);
}
Exemple #18
0
ZEND_METHOD( alinq_class , GroupBy )
{
    zend_fcall_info fci;
    zend_fcall_info_cache fci_cache;
    zend_class_entry *ce;
    ce = Z_OBJCE_P(getThis());
    zval * reVal;
    zval * resultArray;
    MAKE_STD_ZVAL(resultArray);
    array_init(resultArray);
    zval *retval_ptr = NULL;
    zval *returnObj;  
    zval *dataSource, **tmpns;


    char aReturnType;
    int aReturnTypeLen; 

    // aReturnType = 'bool';
     //取得数组
    dataSource = zend_read_property(ce, getThis(), "dataSource", sizeof("dataSource")-1, 0 TSRMLS_DC);

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "f", &fci, &fci_cache) == FAILURE) {
        return;
    }     

    while (zend_hash_get_current_data(Z_ARRVAL_P(dataSource), (void **)&tmpns) == SUCCESS) {
        char *key;
        uint keylen;
        ulong idx;
        int type;
        zval **ppzval, tmpcopy;
        zval **item,*item1;
        MAKE_STD_ZVAL(item1);
        array_init(item1);
        item = &item1;
        // php_printf("step-\n");
        // if(count>0 && i>=count){        //只循环count次
        //     break;
        // }

        type = zend_hash_get_current_key_ex(Z_ARRVAL_P(dataSource), &key, &keylen,&idx, 0, NULL);

        //重新copy一个zval,防止破坏原数据
        tmpcopy = **tmpns;
        zval_copy_ctor(&tmpcopy);
        INIT_PZVAL(&tmpcopy);
         // convert_to_string(&tmpcopy);
        

        walu_call_anony_function(&retval_ptr, NULL, fci, "sz", key, keylen,&tmpcopy); 

        if(zend_hash_find(Z_ARRVAL_P(resultArray), Z_STRVAL_P(retval_ptr),sizeof(Z_STRVAL_P(retval_ptr)), (void **)&item) == FAILURE && IS_STRING==Z_TYPE_P(retval_ptr)) {
            // php_printf("step0\n");
            // zend_error(E_ERROR, "element not found");
            // MAKE_STD_ZVAL(item);
            // array_init(item);
            add_assoc_zval(resultArray, Z_STRVAL_P(retval_ptr), *item); 
        }
        // PHPWRITE(Z_STRVAL_P(retval_ptr),strlen(Z_STRVAL_P(retval_ptr)));  
        // php_printf("step1\n");
        if( IS_ARRAY!=Z_TYPE_PP(item)){
            php_printf("not array\n");
            continue;
        }

        // add_assoc_zval(resultArray, retval_ptr, *tmpns);  
        add_next_index_zval(*item,*tmpns);
        // /* Toss out old copy */
        zval_dtor(&tmpcopy);



        zend_hash_move_forward(Z_ARRVAL_P(dataSource));
    }
    
    walu_call_user_function(&returnObj, getThis(), "Instance", "z", resultArray);
    RETURN_ZVAL(returnObj,1,1);    

    return; 

}
zval* appointment_recurrence_pattern_to_zval(struct AppointmentRecurrencePattern *arp)
{
	struct RecurrencePattern   *rp;
	zval			   *zv;
	zval                       *zrp;
	MAKE_STD_ZVAL(zv);
	array_init(zv);

	rp = &(arp->RecurrencePattern);
	MAKE_STD_ZVAL(zrp);
	array_init(zrp);

	switch(rp->RecurFrequency) {
	case 0x200A:
		add_assoc_string(zrp, "RecurFrequency", "daily", 1);
		break;
	case 0x200B:
		add_assoc_string(zrp, "RecurFrequency", "weekly", 1);
		break;
	case 0x200C:
		add_assoc_string(zrp, "RecurFrequency", "monthly", 1);
		break;
	case 0x200D:
		add_assoc_string(zrp, "RecurFrequency", "yearly", 1);
		break;
	default:
		php_error(E_ERROR, "Unknown RecurFrequency: %i", rp->RecurFrequency);

	}


	switch(rp->PatternType) {
	case 0x0:
		add_assoc_string(zrp, "PatternType", "daily", 1);
		break;
	case 0x1:
		add_assoc_string(zrp, "PatternType", "week", 1);
		break;
	case 0x2:
		add_assoc_string(zrp, "PatternType", "month", 1);
		break;
	case 0x3:
		add_assoc_string(zrp, "PatternType", "monthNth", 1);
		break;
	case 0x4:
		add_assoc_string(zrp, "PatternType", "monthEnd", 1);
		break;
	case 0xA:
	case 0xB:
	case 0xC:
		php_error(E_ERROR, "Hijr calendar not supported yet");
	default:
		php_error(E_ERROR, "Invalid time pattern type: %i", rp->PatternType);
	}

	add_assoc_long(zrp, "FirstDateTime", rp->FirstDateTime);
	add_assoc_long(zrp, "Period", rp->Period);
	// PatternTypeSpecific
	switch (rp->EndType) {
	case 0x00002021:
		add_assoc_string(zrp, "EndType", "AFTER_DATE", 1);
		break;
	case 0x00002022:
		add_assoc_string(zrp, "EndType", "AFTER_N", 1);
		break;
	case 0x00002023:
	case 0xFFFFFFFF:
		add_assoc_string(zrp, "EndType", "NEVER", 1);
		break;
	default:
		php_error(E_ERROR, "Unknown EndType %i", rp->EndType);
	}
	if (rp->OccurrenceCount	!= 0X0000000A) {
		add_assoc_long(zrp, "OccurrenceCount", rp->OccurrenceCount);
	}

	add_assoc_long(zrp, "DeletedInstanceCount", rp->DeletedInstanceCount);
	add_assoc_long(zrp, "ModifiedInstanceCount", rp->ModifiedInstanceCount);
	// TODO list of Delted And Modified count

	add_assoc_long(zrp, "StartDate", rp->StartDate);
	if (rp->EndDate != 0x5AE980DF) {
		add_assoc_long(zrp, "EndDate", rp->EndDate);
	}

	add_assoc_zval(zv, "RecurrencePattern", zrp);
	add_assoc_long(zv, "StartTimeOffset", arp->StartTimeOffset);
	add_assoc_long(zv, "EndTimeOffset", arp->EndTimeOffset);


	return zv;
}
/* {{{ clm_get_device_info() */
static zval *clm_get_device_info(cl_device_id device TSRMLS_DC)
{
	const device_info_param_t *param = device_info_list;
	cl_int err = CL_SUCCESS;
	char buf[1024] = { 0 };
	size_t len = 0;
	cl_uint max_work_item_dimensions = 0;
	zval *zinfo;

	err = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS,
	                      sizeof(max_work_item_dimensions),
	                      &max_work_item_dimensions, NULL);
	if (err != CL_SUCCESS) {
		max_work_item_dimensions = 0;
	}

	MAKE_STD_ZVAL(zinfo);
	array_init_size(zinfo, 64);

	while (param->key != NULL) {
		switch (param->type) {
			case PARAM_TYPE_BITFIELD: {
				cl_bitfield val = 0;
				err = clGetDeviceInfo(device, param->name, sizeof(val), &val, NULL);
				if (err == CL_SUCCESS) {
					long lval = (long)val;
					add_assoc_long(zinfo, param->key, lval);
				}
			}
			break;

			case PARAM_TYPE_BOOL: {
				cl_bool val = 0;
				err = clGetDeviceInfo(device, param->name, sizeof(val), &val, NULL);
				if (err == CL_SUCCESS) {
					zend_bool bval = (zend_bool)val;
					add_assoc_bool(zinfo, param->key, bval);
				}
			}
			break;

			case PARAM_TYPE_SIZE: {
				size_t val = 0;
				err = clGetDeviceInfo(device, param->name, sizeof(val), &val, NULL);
				if (err == CL_SUCCESS) {
					long lval = (long)val;
					add_assoc_long(zinfo, param->key, lval);
				}
			}
			break;

			case PARAM_TYPE_UINT: {
				cl_uint val = 0;
				err = clGetDeviceInfo(device, param->name, sizeof(val), &val, NULL);
				if (err == CL_SUCCESS) {
					long lval = (long)val;
					add_assoc_long(zinfo, param->key, lval);
				}
			}
			break;

			case PARAM_TYPE_ULONG: {
				cl_ulong val = 0;
				err = clGetDeviceInfo(device, param->name, sizeof(val), &val, NULL);
				if (err == CL_SUCCESS) {
					long lval = (long)val;
					add_assoc_long(zinfo, param->key, lval);
				}
			}
			break;

			case PARAM_TYPE_STRING: {
				err = clGetDeviceInfo(device, param->name, sizeof(buf), buf, &len);
				if (err == CL_SUCCESS) {
					add_assoc_stringl(zinfo, param->key, buf, len, 1);
				}
			}
			break;

			case PARAM_TYPE_PLATFORM: {
				cl_platform_id platform;
				err = clGetDeviceInfo(device, param->name, sizeof(platform), &platform, NULL);
				if (err == CL_SUCCESS) {
					zval *pinfo = clm_get_platform_info(platform TSRMLS_CC);
					add_assoc_zval(zinfo, param->key, pinfo);
				}
			}
			break;

			case PARAM_TYPE_MAX_WORK_ITEM_SIZES: {
				size_t siz = sizeof(size_t) * max_work_item_dimensions;
				size_t *sizes = ecalloc(max_work_item_dimensions, sizeof(size_t));
				if (!sizes) {
					break;
				}

				err = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_SIZES, siz, sizes, NULL);
				if (err == CL_SUCCESS) {
					cl_uint i;
					zval *zsizes;
					MAKE_STD_ZVAL(zsizes);
					array_init_size(zsizes, max_work_item_dimensions);
					for (i = 0; i < max_work_item_dimensions; i++) {
						long lval = (long)sizes[i];
						add_next_index_long(zsizes, lval);
					}
					add_assoc_zval(zinfo, param->key, zsizes);
				}

				efree(sizes);
			}
			break;
		}

		if (err != CL_SUCCESS) {
			add_assoc_null(zinfo, param->key);
		}

		param++;
	}

	return zinfo;
}
Exemple #21
0
static int process_stream_onRead(swReactor *reactor, swEvent *event)
{
    SWOOLE_GET_TSRMLS;

    process_stream *ps = event->socket->object;
    char *buf = ps->buffer->str + ps->buffer->length;
    size_t len = ps->buffer->size - ps->buffer->length;

    int ret = read(event->fd, buf, len);
    if (ret > 0)
    {
        ps->buffer->length += ret;
        if (ps->buffer->length == ps->buffer->size)
        {
            swString_extend(ps->buffer, ps->buffer->size * 2);
        }
        return SW_OK;
    }
    else if (ret < 0)
    {
        swSysError("read() failed.");
        return SW_OK;
    }

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

    zval *zdata;
    SW_MAKE_STD_ZVAL(zdata);
    SW_ZVAL_STRINGL(zdata, ps->buffer->str, ps->buffer->length, 1);

    SwooleG.main_reactor->del(SwooleG.main_reactor, ps->fd);

    swString_free(ps->buffer);
    args[0] = &zdata;

    int status;
    zval *zstatus;
    SW_MAKE_STD_ZVAL(zstatus);

    pid_t pid = swWaitpid(ps->pid, &status, WNOHANG);
    if (pid > 0)
    {
        array_init(zstatus);
        add_assoc_long(zstatus, "code", WEXITSTATUS(status));
        add_assoc_long(zstatus, "signal", WTERMSIG(status));
    }
    else
    {
        ZVAL_FALSE(zstatus);
    }

    args[1] = &zstatus;

    zval *zcallback = ps->callback;

    if (zcallback)
    {
        if (sw_call_user_function_ex(EG(function_table), NULL, zcallback, &retval, 2, args, 0, NULL TSRMLS_CC) == FAILURE)
        {
            swoole_php_fatal_error(E_WARNING, "swoole_async: onAsyncComplete handler error");
        }
        sw_zval_free(zcallback);
    }
    else
    {
#ifdef SW_COROUTINE
        php_context *context = ps->context;
        sw_zval_add_ref(&zdata);
        add_assoc_zval(zstatus, "output", zdata);
        int ret = coro_resume(context, zstatus, &retval);
        if (ret == CORO_END && retval)
        {
            sw_zval_ptr_dtor(&retval);
        }
        efree(context);
#else
        return SW_OK;
#endif
    }

    if (EG(exception))
    {
        zend_exception_error(EG(exception), E_ERROR TSRMLS_CC);
    }
    if (retval != NULL)
    {
        sw_zval_ptr_dtor(&retval);
    }
    sw_zval_ptr_dtor(&zdata);
    sw_zval_ptr_dtor(&zstatus);
    close(ps->fd);
    efree(ps);

    return SW_OK;
}
Exemple #22
0
/* {{{ php_parserr */
static void php_parserr(PDNS_RECORD pRec, int type_to_fetch, int store, int raw, zval *subarray)
{
	int type;
	u_long ttl;

	type = pRec->wType;
	ttl = pRec->dwTtl;

	if (type_to_fetch != DNS_TYPE_ANY && type != type_to_fetch) {
		return;
	}

	if (!store) {
		return;
	}

	array_init(subarray);

	add_assoc_string(subarray, "host", pRec->pName);
	add_assoc_string(subarray, "class", "IN");
	add_assoc_long(subarray, "ttl", ttl);

	if (raw) {
		add_assoc_long(subarray, "type", type);
		add_assoc_stringl(subarray, "data", (char*) &pRec->Data, (uint) pRec->wDataLength);
		return;
	}

	switch (type) {
		case DNS_TYPE_A: {
			IN_ADDR ipaddr;
			ipaddr.S_un.S_addr = (pRec->Data.A.IpAddress);
			add_assoc_string(subarray, "type", "A");
			add_assoc_string(subarray, "ip", inet_ntoa(ipaddr));
			break;
		}

		case DNS_TYPE_MX:
			add_assoc_string(subarray, "type", "MX");
			add_assoc_long(subarray, "pri", pRec->Data.Srv.wPriority);
			/* no break; */

		case DNS_TYPE_CNAME:
			if (type == DNS_TYPE_CNAME) {
				add_assoc_string(subarray, "type", "CNAME");
			}
			/* no break; */

		case DNS_TYPE_NS:
			if (type == DNS_TYPE_NS) {
				add_assoc_string(subarray, "type", "NS");
			}
			/* no break; */

		case DNS_TYPE_PTR:
			if (type == DNS_TYPE_PTR) {
				add_assoc_string(subarray, "type", "PTR");
			}
			add_assoc_string(subarray, "target", pRec->Data.MX.pNameExchange);
			break;

		/* Not available on windows, the query is possible but there is no DNS_HINFO_DATA structure */
		case DNS_TYPE_HINFO:
		case DNS_TYPE_TEXT:
			{
				DWORD i = 0;
				DNS_TXT_DATA *data_txt = &pRec->Data.TXT;
				DWORD count = data_txt->dwStringCount;
				zend_string *txt;
				char *txt_dst;
				long txt_len = 0;
				zval entries;

				add_assoc_string(subarray, "type", "TXT");
				
				array_init(&entries);
				
				for (i = 0; i < count; i++) {
					txt_len += strlen(data_txt->pStringArray[i]) + 1;
				}

				txt = zend_string_safe_alloc(txt_len, 2, 0, 0);
				txt_dst = txt->val;
				for (i = 0; i < count; i++) {
					int len = strlen(data_txt->pStringArray[i]);
					memcpy(txt_dst, data_txt->pStringArray[i], len);
					add_next_index_stringl(&entries, data_txt->pStringArray[i], len);
					txt_dst += len;
				}
				txt->len = txt_dst - txt->val;
				add_assoc_str(subarray, "txt", txt);
				add_assoc_zval(subarray, "entries", &entries);
			}
			break;

		case DNS_TYPE_SOA:
			{
				DNS_SOA_DATA *data_soa = &pRec->Data.Soa;

				add_assoc_string(subarray, "type", "SOA");

				add_assoc_string(subarray, "mname", data_soa->pNamePrimaryServer);
				add_assoc_string(subarray, "rname", data_soa->pNameAdministrator);
				add_assoc_long(subarray, "serial", data_soa->dwSerialNo);
				add_assoc_long(subarray, "refresh", data_soa->dwRefresh);
				add_assoc_long(subarray, "retry", data_soa->dwRetry);
				add_assoc_long(subarray, "expire", data_soa->dwExpire);
				add_assoc_long(subarray, "minimum-ttl", data_soa->dwDefaultTtl);
			}
			break;

		case DNS_TYPE_AAAA:
			{
				DNS_AAAA_DATA *data_aaaa = &pRec->Data.AAAA;
				char buf[sizeof("AAAA:AAAA:AAAA:AAAA:AAAA:AAAA:AAAA:AAAA")];
				char *tp = buf;
				int i;
				unsigned short out[8];
				int have_v6_break = 0, in_v6_break = 0;

				for (i = 0; i < 4; ++i) {
					DWORD chunk = data_aaaa->Ip6Address.IP6Dword[i];
					out[i * 2]     = htons(LOWORD(chunk));
					out[i * 2 + 1] = htons(HIWORD(chunk));
				}

				for(i=0; i < 8; i++) {
					if (out[i] != 0) {
						if (tp > (u_char *)buf) {
							in_v6_break = 0;
							tp[0] = ':';
							tp++;
						}
						tp += sprintf((char*)tp,"%x", out[i]);
					} else {
						if (!have_v6_break) {
							have_v6_break = 1;
							in_v6_break = 1;
							tp[0] = ':';
							tp++;
						} else if (!in_v6_break) {
							tp[0] = ':';
							tp++;
							tp[0] = '0';
							tp++;
						}
					}
				}

				if (have_v6_break && in_v6_break) {
					tp[0] = ':';
					tp++;
				}
				tp[0] = '\0';

				add_assoc_string(subarray, "type", "AAAA");
				add_assoc_string(subarray, "ipv6", buf);
			}
			break;

#if 0
		/* Won't be implemented. A6 is deprecated. (Pierre) */
		case DNS_TYPE_A6:
			break;
#endif

		case DNS_TYPE_SRV:
			{
				DNS_SRV_DATA *data_srv = &pRec->Data.Srv;

				add_assoc_string(subarray, "type", "SRV");
				add_assoc_long(subarray, "pri", data_srv->wPriority);
				add_assoc_long(subarray, "weight", data_srv->wWeight);
				add_assoc_long(subarray, "port", data_srv->wPort);
				add_assoc_string(subarray, "target", data_srv->pNameTarget);
			}
			break;

#if _MSC_VER >= 1500
		case DNS_TYPE_NAPTR:
			{
				DNS_NAPTR_DATA * data_naptr = &pRec->Data.Naptr;

				add_assoc_string(subarray, "type", "NAPTR");
				add_assoc_long(subarray, "order", data_naptr->wOrder);
				add_assoc_long(subarray, "pref", data_naptr->wPreference);
				add_assoc_string(subarray, "flags", data_naptr->pFlags);
				add_assoc_string(subarray, "services", data_naptr->pService);
				add_assoc_string(subarray, "regex", data_naptr->pRegularExpression);
				add_assoc_string(subarray, "replacement", data_naptr->pReplacement);
			}
			break;
#endif

		default:
			/* unknown type */
			ZVAL_UNDEF(subarray);
			return;
	}

}
/* {{{ MongoCursor->__construct
 */
PHP_METHOD(MongoCursor, __construct) {
  zval *zlink = 0, *zns = 0, *zquery = 0, *zfields = 0, *empty, *timeout;
  zval **data;
  mongo_cursor *cursor;
  mongo_link *link;

  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Oz|zz", &zlink,
                            mongo_ce_Mongo, &zns, &zquery, &zfields) == FAILURE) {
    return;
  }
  if ((zquery && IS_SCALAR_P(zquery)) || (zfields && IS_SCALAR_P(zfields))) {
    zend_error(E_WARNING, "MongoCursor::__construct() expects parameters 3 and 4 to be arrays or objects");
    return;
  }

  // if query or fields weren't passed, make them default to an empty array
  MAKE_STD_ZVAL(empty);
  object_init(empty);

  // these are both initialized to the same zval, but that's okay because 
  // there's no way to change them without creating a new cursor
  if (!zquery || (Z_TYPE_P(zquery) == IS_ARRAY && zend_hash_num_elements(HASH_P(zquery)) == 0)) {
    zquery = empty;
  }
  if (!zfields) {
    zfields = empty;
  }

  cursor = (mongo_cursor*)zend_object_store_get_object(getThis() TSRMLS_CC);
 
  // db connection
  cursor->resource = zlink;
  zval_add_ref(&zlink);

  // db connection resource
  PHP_MONGO_GET_LINK(zlink);
  cursor->link = link;

  // change ['x', 'y', 'z'] into {'x' : 1, 'y' : 1, 'z' : 1}
  if (Z_TYPE_P(zfields) == IS_ARRAY) {
    HashPosition pointer;
    zval *fields;

    MAKE_STD_ZVAL(fields);
    array_init(fields);

    // fields to return
    for(zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(zfields), &pointer); 
        zend_hash_get_current_data_ex(Z_ARRVAL_P(zfields), (void**) &data, &pointer) == SUCCESS; 
        zend_hash_move_forward_ex(Z_ARRVAL_P(zfields), &pointer)) {
      int key_type, key_len;
      ulong index;
      char *key;
      
      key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(zfields), &key, (uint*)&key_len, &index, NO_DUP, &pointer);

      if (key_type == HASH_KEY_IS_LONG) {
        if (Z_TYPE_PP(data) == IS_STRING) {
          add_assoc_long(fields, Z_STRVAL_PP(data), 1);
        }
        else {
          zval_ptr_dtor(&empty);
          zval_ptr_dtor(&fields);
          zend_throw_exception(mongo_ce_Exception, "field names must be strings", 0 TSRMLS_CC);
          return;
        }
      }
      else {
        add_assoc_zval(fields, key, *data);
        zval_add_ref(data);
      }
    }
    cursor->fields = fields;
  }
  // if it's already an object, we don't have to worry
  else {
    cursor->fields = zfields;
    zval_add_ref(&zfields);
  }

  // ns
  convert_to_string(zns);
  cursor->ns = estrdup(Z_STRVAL_P(zns));

  // query
  cursor->query = zquery;
  zval_add_ref(&zquery);

  // reset iteration pointer, just in case
  MONGO_METHOD(MongoCursor, reset, return_value, getThis());

  cursor->at = 0;
  cursor->num = 0;
  cursor->special = 0;
  cursor->persist = 0;
  
  timeout = zend_read_static_property(mongo_ce_Cursor, "timeout", strlen("timeout"), NOISY TSRMLS_CC);
  cursor->timeout = Z_LVAL_P(timeout);

  cursor->opts = link->slave_okay ? (1 << 2) : 0;
  
  // get rid of extra ref
  zval_ptr_dtor(&empty);
}
/* {{{ proto array accelerator_get_configuration()
   Obtain configuration information */
static ZEND_FUNCTION(opcache_get_configuration)
{
	zval directives, version, blacklist;

	if (zend_parse_parameters_none() == FAILURE) {
		RETURN_FALSE;
	}

	if (!validate_api_restriction()) {
		RETURN_FALSE;
	}

	array_init(return_value);

	/* directives */
	array_init(&directives);
	add_assoc_bool(&directives, "opcache.enable",              ZCG(enabled));
	add_assoc_bool(&directives, "opcache.enable_cli",          ZCG(accel_directives).enable_cli);
	add_assoc_bool(&directives, "opcache.use_cwd",             ZCG(accel_directives).use_cwd);
	add_assoc_bool(&directives, "opcache.validate_timestamps", ZCG(accel_directives).validate_timestamps);
	add_assoc_bool(&directives, "opcache.validate_permission", ZCG(accel_directives).validate_permission);
#ifndef ZEND_WIN32
	add_assoc_bool(&directives, "opcache.validate_root",       ZCG(accel_directives).validate_root);
#endif
	add_assoc_bool(&directives, "opcache.inherited_hack",      ZCG(accel_directives).inherited_hack);
	add_assoc_bool(&directives, "opcache.dups_fix",            ZCG(accel_directives).ignore_dups);
	add_assoc_bool(&directives, "opcache.revalidate_path",     ZCG(accel_directives).revalidate_path);

	add_assoc_long(&directives,   "opcache.log_verbosity_level",    ZCG(accel_directives).log_verbosity_level);
	add_assoc_long(&directives,	 "opcache.memory_consumption",     ZCG(accel_directives).memory_consumption);
	add_assoc_long(&directives,	 "opcache.interned_strings_buffer",ZCG(accel_directives).interned_strings_buffer);
	add_assoc_long(&directives, 	 "opcache.max_accelerated_files",  ZCG(accel_directives).max_accelerated_files);
	add_assoc_double(&directives, "opcache.max_wasted_percentage",  ZCG(accel_directives).max_wasted_percentage);
	add_assoc_long(&directives, 	 "opcache.consistency_checks",     ZCG(accel_directives).consistency_checks);
	add_assoc_long(&directives, 	 "opcache.force_restart_timeout",  ZCG(accel_directives).force_restart_timeout);
	add_assoc_long(&directives, 	 "opcache.revalidate_freq",        ZCG(accel_directives).revalidate_freq);
	add_assoc_string(&directives, "opcache.preferred_memory_model", STRING_NOT_NULL(ZCG(accel_directives).memory_model));
	add_assoc_string(&directives, "opcache.blacklist_filename",     STRING_NOT_NULL(ZCG(accel_directives).user_blacklist_filename));
	add_assoc_long(&directives,   "opcache.max_file_size",          ZCG(accel_directives).max_file_size);
	add_assoc_string(&directives, "opcache.error_log",              STRING_NOT_NULL(ZCG(accel_directives).error_log));

	add_assoc_bool(&directives,   "opcache.protect_memory",         ZCG(accel_directives).protect_memory);
	add_assoc_bool(&directives,   "opcache.save_comments",          ZCG(accel_directives).save_comments);
	add_assoc_bool(&directives,   "opcache.fast_shutdown",          ZCG(accel_directives).fast_shutdown);
	add_assoc_bool(&directives,   "opcache.enable_file_override",   ZCG(accel_directives).file_override_enabled);
	add_assoc_long(&directives, 	 "opcache.optimization_level",     ZCG(accel_directives).optimization_level);

#ifndef ZEND_WIN32
	add_assoc_string(&directives, "opcache.lockfile_path",          STRING_NOT_NULL(ZCG(accel_directives).lockfile_path));
#endif

#ifdef HAVE_OPCACHE_FILE_CACHE
	add_assoc_string(&directives, "opcache.file_cache",                    ZCG(accel_directives).file_cache ? ZCG(accel_directives).file_cache : "");
	add_assoc_bool(&directives,   "opcache.file_cache_only",               ZCG(accel_directives).file_cache_only);
	add_assoc_bool(&directives,   "opcache.file_cache_consistency_checks", ZCG(accel_directives).file_cache_consistency_checks);
#endif

	add_assoc_zval(return_value, "directives", &directives);

	/*version */
	array_init(&version);
	add_assoc_string(&version, "version", PHP_VERSION);
	add_assoc_string(&version, "opcache_product_name", ACCELERATOR_PRODUCT_NAME);
	add_assoc_zval(return_value, "version", &version);

	/* blacklist */
	array_init(&blacklist);
	zend_accel_blacklist_apply(&accel_blacklist, add_blacklist_path, &blacklist);
	add_assoc_zval(return_value, "blacklist", &blacklist);
}
/* {{{ 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);
		}
	}
}
Exemple #26
0
PHP_METHOD(jsonrpc_server, execute)
{
  zval *object;
  zval *func;

  zval **func_params, **exec_params;
  zval *data, *payload, *error, *response;
  zval **payload_method, **payload_params;
  zval **id = NULL;

  sapi_header_line ctr = {0};
  smart_str buf = {0};

  zend_bool response_type = 0; // type:0 =>json type:1 => array

  object = getThis();

  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b",
    &response_type) == FAILURE)
  {
    return ;
  }
  
  payload = zend_read_property(
      php_jsonrpc_server_entry, getThis(), "payload", sizeof("payload")-1, 0 TSRMLS_CC
    );

  MAKE_STD_ZVAL(error);
  array_init(error);

  MAKE_STD_ZVAL(func);

  ZVAL_STRINGL(func, "jsonformat", sizeof("jsonformat") - 1, 0);
  if (call_user_function(NULL, &object, func, return_value, 0, NULL TSRMLS_CC) == FAILURE){
    php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed calling Jsonrpc_Server::jsonformat()");
    return ;
  }
  if (!Z_BVAL_P(return_value)){
    add_assoc_long(error, "code", -32700);
    add_assoc_string(error, "message", "Parse error", 1);
    
    zval_dtor(return_value);
    array_init(return_value);
    add_assoc_string(return_value, "jsonrpc", "2.0", 1);
    add_assoc_zval(return_value, "error", error);
    goto getresponse;
  }


  ZVAL_STRINGL(func, "rpcformat", sizeof("rpcformat") - 1, 0);
  if (call_user_function(NULL, &object, func, return_value, 0, NULL TSRMLS_CC) == FAILURE){
    php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed calling Jsonrpc_Server::rpcformat()");
    return ;
  }

  if (Z_LVAL_P(return_value) == -32600){
    add_assoc_long(error, "code", -32600);
    add_assoc_string(error, "message", "Invalid Request", 1);
    
    zval_dtor(return_value);
    array_init(return_value);
    add_assoc_string(return_value, "jsonrpc", "2.0", 1);
    add_assoc_zval(return_value, "error", error);
    goto getresponse;
  }else if (Z_LVAL_P(return_value) == -32601){
    add_assoc_long(error, "code", -32601);
    add_assoc_string(error, "message", "Method not found", 1);
   
    zval_dtor(return_value);
    array_init(return_value);
    add_assoc_string(return_value, "jsonrpc", "2.0", 1);
    add_assoc_zval(return_value, "error", error);
    goto getresponse;
  }else if (Z_LVAL_P(return_value) == -32602){
    add_assoc_long(error, "code", -32602);
    add_assoc_string(error, "message", "Invalid params", 1);
    
    zval_dtor(return_value);
    array_init(return_value);
    add_assoc_string(return_value, "jsonrpc", "2.0", 1);
    add_assoc_zval(return_value, "error", error);
    goto getresponse;
  }else if (Z_LVAL_P(return_value) == -32603){
    add_assoc_long(error, "code", -32603);
    add_assoc_string(error, "message", "Internal error", 1);
    
    zval_dtor(return_value);
    array_init(return_value);
    add_assoc_string(return_value, "jsonrpc", "2.0", 1);
    add_assoc_zval(return_value, "error", error);
    goto getresponse;
  }

  exec_params = emalloc(sizeof(zval *) * 2);
  payload = zend_read_property(
      php_jsonrpc_server_entry, getThis(), "payload", sizeof("payload")-1, 0 TSRMLS_CC
    );
  if (zend_hash_find(Z_ARRVAL_P(payload), "method", strlen("method")+1, (void **)&payload_method) == FAILURE)
  {
    php_error_docref(NULL TSRMLS_CC, E_WARNING, "method is not find");
    return ;
  }
  //jsr_dump_zval(*payload_method);
  exec_params[0] = *payload_method;

  if (zend_hash_find(Z_ARRVAL_P(payload), "params", strlen("params")+1, (void **)&payload_params) == FAILURE)
  {
    php_error_docref(NULL TSRMLS_CC, E_WARNING, "params is not find");
    return ;
  }
  //shurrik_dump_zval(*payload_params);
  exec_params[1] = *payload_params;

  MAKE_STD_ZVAL(data);
  ZVAL_STRINGL(func, "executeprocedure", sizeof("executeprocedure") - 1, 0);
  if (call_user_function(NULL, &object, func, data, 2, exec_params TSRMLS_CC) == FAILURE){
    php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed calling Jsonrpc_Server::executeprocedure()");
    return ;
  }

  efree(exec_params);

  if (Z_LVAL_P(data) == -32601){
    add_assoc_long(error, "code", -32601);
    add_assoc_string(error, "message", "Method not found", 1);

    zval_dtor(return_value);
    array_init(return_value);
    add_assoc_string(return_value, "jsonrpc", "2.0", 1);
    add_assoc_zval(return_value, "error", error);
    goto getresponse;
  }

  zval_dtor(return_value);
  array_init(return_value);
  add_assoc_string(return_value, "jsonrpc", "2.0", 1);
  add_assoc_zval(return_value, "result", data);
  goto getresponse;

  return ;

getresponse:
  
  if (Z_TYPE_P(payload) == IS_ARRAY){
    if (!zend_symtable_exists(Z_ARRVAL_P(payload), "id", strlen("id")+1))
    {
    }else {
      
      if (zend_hash_find(Z_ARRVAL_P(payload), "id", strlen("id")+1, (void **)&id ) == FAILURE)
      {
        //php_error_docref(NULL TSRMLS_CC, E_WARNING, "closeure is not expected to be a valid callback");
        //return ;
      }

      if (Z_TYPE_PP(id) == IS_NULL){
        add_assoc_null(return_value, "id");
      }else if(Z_TYPE_PP(id) == IS_STRING){
        convert_to_string(*id);
        add_assoc_string(return_value, "id", Z_STRVAL_PP(id), 0);
      }else if (Z_TYPE_PP(id) == IS_LONG){
        convert_to_long(*id);
        add_assoc_long(return_value, "id", Z_LVAL_PP(id));
      }
    }
  }else {
    add_assoc_null(return_value, "id");
  }
  

  ctr.line = "Content-Type: application/json";
  ctr.line_len = strlen(ctr.line);
  sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);

  /*if (!response_type){
    php_json_encode(&buf, return_value, 0 TSRMLS_CC);
    zval_dtor(return_value);
    zval_dtor(error);

    ZVAL_STRINGL(return_value, buf.c, buf.len, 1);
    smart_str_free(&buf);
  }*/

  if (!response_type){
    exec_params = emalloc(sizeof(zval *) * 1);
    exec_params[0] = return_value;

    ZVAL_STRINGL(func, "Jsonrpc_Yajl::generate", sizeof("Jsonrpc_Yajl::generate") - 1, 0);
    if (call_user_function(EG(function_table), NULL, func, return_value, 1, exec_params TSRMLS_CC) == FAILURE)
    {
      php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed calling Jsonrpc_Yajl::generate()");
      return ;
    }

    //ZVAL_STRINGL(return_value, Z_STRVAL_P(return_value), Z_STRLEN_P(return_value), 1);

    zval_dtor(error);
    efree(exec_params);

  }

  efree(func);

  return ;

}
void uri_template_parse(char *tpl, zval *return_value, zval *vars, zval *capture)
{
	smart_str result = {0};
	zval *expressions = NULL;
	zval  vars_ptr;
	unsigned char c;
	char *start;
	int state = URI_TEMPLATE_ERROR_NONE;

	if (capture != NULL) {
		MAKE_STD_ZVAL(expressions);
		array_init(expressions);
	}

	vars_ptr = *vars;
	zval_copy_ctor(&vars_ptr);

	while (*tpl) {
		if (*tpl == '{') {
			start = tpl + 1;

			while (*(tpl++) && *tpl != '}' && *tpl != '{');

			if (*tpl == '}') {
				if (tpl - start > 0) {
					uri_template_expr *expr = build_expr(start, tpl - start);

					if (expr->error) {
						append_malformed_expr(&result, start, tpl - start);

						if (state == URI_TEMPLATE_ERROR_NONE) {
							state = URI_TEMPLATE_ERROR_EXPRESSION;
						}
					} else {
						uri_template_process(expr, &vars_ptr, &result);
					}

					if (expressions != NULL) {
						add_expr_to_array(expressions, expr);
					}

					uri_template_expr_free(expr);
				} else {
					smart_str_appends(&result, "{}");
				}
			} else if (*tpl == '{') {
				smart_str_appendl(&result, start - 1, tpl - start + 1);
				state = URI_TEMPLATE_ERROR_SYNTAX;
				tpl--;
			} else {
				smart_str_appendc(&result, '{');
				smart_str_appendl(&result, start, tpl - start);
				state = URI_TEMPLATE_ERROR_SYNTAX;
			}
		} else {
			c = *tpl;

			if (c == '}') {
				smart_str_appendc(&result, '}');
				state = URI_TEMPLATE_ERROR_SYNTAX;
			} else if (c == '%' && isxdigit(*(tpl + 1)) && isxdigit(*(tpl + 2))) {
				smart_str_appendc(&result, '%');
				smart_str_appendc(&result, *(++tpl));
				smart_str_appendc(&result, *(++tpl));
			} else {
				int result_len = result.len;
				int distance = 0;

				uri_template_substr_copy(&result, tpl, 1, URI_TEMPLATE_ALLOW_RESERVED);
        
				distance = result.len - result_len;
				tpl += (distance % 3 ? 1 : distance / 3) - 1;
			}
		}

		tpl++;
	}

	smart_str_0(&result);
	ZVAL_STRING(return_value, result.c ? result.c : "", 1);

	if (capture != NULL) {
		add_assoc_string(capture, "result", result.c ? result.c : "", 1);
		add_assoc_long(capture, "state", state);
		add_assoc_zval(capture, "expressions", expressions);
	}
	
	zval_dtor(&vars_ptr);
	smart_str_free(&result);
}