v8js_convert.cc 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 5 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2013 The PHP Group |
  6. +----------------------------------------------------------------------+
  7. | http://www.opensource.org/licenses/mit-license.php MIT License |
  8. +----------------------------------------------------------------------+
  9. | Author: Jani Taskinen <[email protected]> |
  10. | Author: Patrick Reilly <[email protected]> |
  11. +----------------------------------------------------------------------+
  12. */
  13. /* $Id$ */
  14. #ifdef HAVE_CONFIG_H
  15. #include "config.h"
  16. #endif
  17. extern "C" {
  18. #include "php.h"
  19. #include "ext/date/php_date.h"
  20. #include "ext/standard/php_string.h"
  21. #include "zend_interfaces.h"
  22. #include "zend_closures.h"
  23. }
  24. #include "php_v8js_macros.h"
  25. #include <v8.h>
  26. #include <stdexcept>
  27. #include <limits>
  28. /* Callback for PHP's zend_error_cb; catching any fatal PHP error.
  29. * The callback is installed in the lowest (stack wise) php_v8js_call_php_func
  30. * frame. Just store the error message and jump right back there and fall
  31. * back into V8 context. */
  32. static void php_v8js_error_handler(int error_num, const char *error_filename,
  33. const uint error_lineno, const char *format,
  34. va_list args) /* {{{ */
  35. {
  36. char *buffer;
  37. int buffer_len;
  38. switch (error_num)
  39. {
  40. case E_ERROR:
  41. case E_CORE_ERROR:
  42. case E_USER_ERROR:
  43. buffer_len = vspprintf(&buffer, PG(log_errors_max_len), format, args);
  44. V8JSG(fatal_error_abort) = true;
  45. V8JSG(error_num) = error_num;
  46. V8JSG(error_message) = buffer;
  47. longjmp(*V8JSG(unwind_env), 1);
  48. break;
  49. default:
  50. V8JSG(old_error_handler)(error_num, error_filename, error_lineno, format, args);
  51. break;
  52. }
  53. }
  54. /* }}} */
  55. static void php_v8js_weak_object_callback(const v8::WeakCallbackData<v8::Object, zval> &data);
  56. /* Callback for PHP methods and functions */
  57. static void php_v8js_call_php_func(zval *value, zend_class_entry *ce, zend_function *method_ptr, v8::Isolate *isolate, const v8::FunctionCallbackInfo<v8::Value>& info TSRMLS_DC) /* {{{ */
  58. {
  59. v8::Handle<v8::Value> return_value;
  60. zend_fcall_info fci;
  61. zend_fcall_info_cache fcc;
  62. zval fname, *retval_ptr = NULL, **argv = NULL;
  63. zend_uint argc = info.Length(), min_num_args = 0, max_num_args = 0;
  64. char *error;
  65. int error_len, i, flags = V8JS_FLAG_NONE;
  66. #if PHP_V8_API_VERSION <= 3023008
  67. /* Until V8 3.23.8 Isolate could only take one external pointer. */
  68. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData();
  69. #else
  70. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
  71. #endif
  72. /* Set parameter limits */
  73. min_num_args = method_ptr->common.required_num_args;
  74. max_num_args = method_ptr->common.num_args;
  75. /* Function name to call */
  76. INIT_ZVAL(fname);
  77. ZVAL_STRING(&fname, method_ptr->common.function_name, 0);
  78. /* zend_fcall_info */
  79. fci.size = sizeof(fci);
  80. fci.function_table = &ce->function_table;
  81. fci.function_name = &fname;
  82. fci.symbol_table = NULL;
  83. fci.object_ptr = value;
  84. fci.retval_ptr_ptr = &retval_ptr;
  85. fci.param_count = 0;
  86. /* Check for passed vs required number of arguments */
  87. if (argc < min_num_args)
  88. {
  89. error_len = spprintf(&error, 0,
  90. "%s::%s() expects %s %d parameter%s, %d given",
  91. ce->name,
  92. method_ptr->common.function_name,
  93. min_num_args == max_num_args ? "exactly" : argc < min_num_args ? "at least" : "at most",
  94. argc < min_num_args ? min_num_args : max_num_args,
  95. (argc < min_num_args ? min_num_args : max_num_args) == 1 ? "" : "s",
  96. argc);
  97. return_value = V8JS_THROW(isolate, TypeError, error, error_len);
  98. if (ce == zend_ce_closure) {
  99. efree(const_cast<char*>(method_ptr->internal_function.function_name));
  100. efree(method_ptr);
  101. }
  102. efree(error);
  103. info.GetReturnValue().Set(return_value);
  104. return;
  105. }
  106. /* Convert parameters passed from V8 */
  107. if (argc) {
  108. flags = V8JS_GLOBAL_GET_FLAGS(isolate);
  109. fci.params = (zval ***) safe_emalloc(argc, sizeof(zval **), 0);
  110. argv = (zval **) safe_emalloc(argc, sizeof(zval *), 0);
  111. for (i = 0; i < argc; i++) {
  112. v8::Local<v8::Value> php_object;
  113. if (info[i]->IsObject()) {
  114. php_object = v8::Local<v8::Object>::Cast(info[i])->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY));
  115. }
  116. if (!php_object.IsEmpty()) {
  117. /* This is a PHP object, passed to JS and back. */
  118. argv[i] = reinterpret_cast<zval *>(v8::External::Cast(*php_object)->Value());
  119. Z_ADDREF_P(argv[i]);
  120. } else {
  121. MAKE_STD_ZVAL(argv[i]);
  122. if (v8js_to_zval(info[i], argv[i], flags, isolate TSRMLS_CC) == FAILURE) {
  123. fci.param_count++;
  124. error_len = spprintf(&error, 0, "converting parameter #%d passed to %s() failed", i + 1, method_ptr->common.function_name);
  125. return_value = V8JS_THROW(isolate, Error, error, error_len);
  126. efree(error);
  127. goto failure;
  128. }
  129. }
  130. fci.params[fci.param_count++] = &argv[i];
  131. }
  132. } else {
  133. fci.params = NULL;
  134. }
  135. fci.no_separation = 1;
  136. {
  137. isolate->Exit();
  138. v8::Unlocker unlocker(isolate);
  139. /* zend_fcall_info_cache */
  140. fcc.initialized = 1;
  141. fcc.function_handler = method_ptr;
  142. fcc.calling_scope = ce;
  143. fcc.called_scope = ce;
  144. fcc.object_ptr = value;
  145. jmp_buf env;
  146. int val = 0;
  147. bool installed_handler = false;
  148. /* If this is the first level call from V8 back to PHP, install a
  149. * handler for fatal errors; we must fall back through V8 to keep
  150. * it from crashing. */
  151. if (V8JSG(unwind_env) == NULL) {
  152. installed_handler = true;
  153. V8JSG(old_error_handler) = zend_error_cb;
  154. zend_error_cb = php_v8js_error_handler;
  155. val = setjmp (env);
  156. V8JSG(unwind_env) = &env;
  157. }
  158. if (!val) {
  159. /* Call the method */
  160. zend_call_function(&fci, &fcc TSRMLS_CC);
  161. }
  162. if (installed_handler) {
  163. zend_error_cb = V8JSG(old_error_handler);
  164. V8JSG(unwind_env) = NULL;
  165. }
  166. }
  167. isolate->Enter();
  168. if (V8JSG(fatal_error_abort)) {
  169. v8::V8::TerminateExecution(isolate);
  170. info.GetReturnValue().Set(V8JS_NULL);
  171. return;
  172. }
  173. failure:
  174. /* Cleanup */
  175. if (argc) {
  176. for (i = 0; i < fci.param_count; i++) {
  177. zval_ptr_dtor(&argv[i]);
  178. }
  179. efree(argv);
  180. efree(fci.params);
  181. }
  182. if (retval_ptr != NULL) {
  183. return_value = zval_to_v8js(retval_ptr, isolate TSRMLS_CC);
  184. zval_ptr_dtor(&retval_ptr);
  185. } else {
  186. return_value = V8JS_NULL;
  187. }
  188. info.GetReturnValue().Set(return_value);
  189. }
  190. /* }}} */
  191. /* Callback for PHP methods and functions */
  192. static void php_v8js_php_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  193. {
  194. v8::Isolate *isolate = info.GetIsolate();
  195. v8::Local<v8::Object> self = info.Holder();
  196. V8JS_TSRMLS_FETCH();
  197. zval *value = reinterpret_cast<zval *>(v8::External::Cast(*self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY)))->Value());
  198. zend_function *method_ptr;
  199. zend_class_entry *ce = Z_OBJCE_P(value);
  200. /* Set method_ptr from v8::External or fetch the closure invoker */
  201. if (!info.Data().IsEmpty() && info.Data()->IsExternal()) {
  202. method_ptr = static_cast<zend_function *>(v8::External::Cast(*info.Data())->Value());
  203. } else {
  204. method_ptr = zend_get_closure_invoke_method(value TSRMLS_CC);
  205. }
  206. return php_v8js_call_php_func(value, ce, method_ptr, isolate, info TSRMLS_CC);
  207. }
  208. /* Callback for PHP constructor calls */
  209. static void php_v8js_construct_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  210. {
  211. v8::Isolate *isolate = info.GetIsolate();
  212. info.GetReturnValue().Set(V8JS_UNDEFINED);
  213. // @todo assert constructor call
  214. v8::Handle<v8::Object> newobj = info.This();
  215. v8::Local<v8::External> php_object;
  216. zval *value;
  217. if (!info.IsConstructCall()) {
  218. return;
  219. }
  220. v8::Local<v8::Array> cons_data = v8::Local<v8::Array>::Cast(info.Data());
  221. v8::Local<v8::External> ext_tmpl = v8::Local<v8::External>::Cast(cons_data->Get(0));
  222. v8::Local<v8::External> ext_ce = v8::Local<v8::External>::Cast(cons_data->Get(1));
  223. if (info[0]->IsExternal()) {
  224. // Object created by v8js in php_v8js_hash_to_jsobj, PHP object passed as v8::External.
  225. php_object = v8::Local<v8::External>::Cast(info[0]);
  226. value = reinterpret_cast<zval *>(php_object->Value());
  227. // Increase the reference count of this value because we're storing it internally for use later
  228. // See https://github.com/preillyme/v8js/issues/6
  229. Z_ADDREF_P(value);
  230. } else {
  231. // Object created from JavaScript context. Need to create PHP object first.
  232. V8JS_TSRMLS_FETCH();
  233. zend_class_entry *ce = static_cast<zend_class_entry *>(ext_ce->Value());
  234. zend_function *ctor_ptr = ce->constructor;
  235. // Check access on __construct function, if any
  236. if (ctor_ptr != NULL && (ctor_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0) {
  237. info.GetReturnValue().Set(isolate->ThrowException(V8JS_SYM("Call to protected __construct() not allowed")));
  238. return;
  239. }
  240. MAKE_STD_ZVAL(value);
  241. object_init_ex(value, ce);
  242. // Call __construct function
  243. if (ctor_ptr != NULL) {
  244. php_v8js_call_php_func(value, ce, ctor_ptr, isolate, info TSRMLS_CC);
  245. }
  246. php_object = V8JS_NEW(v8::External, isolate, value);
  247. }
  248. newobj->SetAlignedPointerInInternalField(0, ext_tmpl->Value());
  249. newobj->SetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY), php_object);
  250. #if PHP_V8_API_VERSION <= 3023008
  251. /* Until V8 3.23.8 Isolate could only take one external pointer. */
  252. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData();
  253. #else
  254. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
  255. #endif
  256. // Since we got to decrease the reference count again, in case v8 garbage collector
  257. // decides to dispose the JS object, we add a weak persistent handle and register
  258. // a callback function that removes the reference.
  259. ctx->weak_objects[value].Reset(isolate, newobj);
  260. ctx->weak_objects[value].SetWeak(value, php_v8js_weak_object_callback);
  261. // Just tell v8 that we're allocating some external memory
  262. // (for the moment we just always tell 1k instead of trying to find out actual values)
  263. isolate->AdjustAmountOfExternalAllocatedMemory(1024);
  264. }
  265. /* }}} */
  266. static int _php_v8js_is_assoc_array(HashTable *myht TSRMLS_DC) /* {{{ */
  267. {
  268. int i;
  269. char *key;
  270. ulong index, idx = 0;
  271. uint key_len;
  272. HashPosition pos;
  273. zend_hash_internal_pointer_reset_ex(myht, &pos);
  274. for (;; zend_hash_move_forward_ex(myht, &pos)) {
  275. i = zend_hash_get_current_key_ex(myht, &key, &key_len, &index, 0, &pos);
  276. if (i == HASH_KEY_NON_EXISTANT)
  277. break;
  278. if (i == HASH_KEY_IS_STRING || index != idx) {
  279. return 1;
  280. }
  281. idx++;
  282. }
  283. return 0;
  284. }
  285. /* }}} */
  286. static void php_v8js_weak_object_callback(const v8::WeakCallbackData<v8::Object, zval> &data) {
  287. v8::Isolate *isolate = data.GetIsolate();
  288. zval *value = data.GetParameter();
  289. zval_ptr_dtor(&value);
  290. #if PHP_V8_API_VERSION <= 3023008
  291. /* Until V8 3.23.8 Isolate could only take one external pointer. */
  292. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData();
  293. #else
  294. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
  295. #endif
  296. ctx->weak_objects.at(value).Reset();
  297. ctx->weak_objects.erase(value);
  298. isolate->AdjustAmountOfExternalAllocatedMemory(-1024);
  299. }
  300. static void php_v8js_weak_closure_callback(const v8::WeakCallbackData<v8::Object, v8js_tmpl_t> &data) {
  301. v8::Isolate *isolate = data.GetIsolate();
  302. v8js_tmpl_t *persist_tpl_ = data.GetParameter();
  303. persist_tpl_->Reset();
  304. delete persist_tpl_;
  305. #if PHP_V8_API_VERSION <= 3023008
  306. /* Until V8 3.23.8 Isolate could only take one external pointer. */
  307. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData();
  308. #else
  309. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
  310. #endif
  311. ctx->weak_closures.at(persist_tpl_).Reset();
  312. ctx->weak_closures.erase(persist_tpl_);
  313. };
  314. /* These are not defined by Zend */
  315. #define ZEND_WAKEUP_FUNC_NAME "__wakeup"
  316. #define ZEND_SLEEP_FUNC_NAME "__sleep"
  317. #define ZEND_SET_STATE_FUNC_NAME "__set_state"
  318. #define IS_MAGIC_FUNC(mname) \
  319. ((key_len == sizeof(mname)) && \
  320. !strncasecmp(key, mname, key_len - 1))
  321. #define PHP_V8JS_CALLBACK(isolate, mptr, tmpl) \
  322. V8JS_NEW(v8::FunctionTemplate, (isolate), php_v8js_php_callback, V8JS_NEW(v8::External, (isolate), mptr), V8JS_NEW(v8::Signature, (isolate), tmpl))->GetFunction()
  323. static void php_v8js_named_property_enumerator(const v8::PropertyCallbackInfo<v8::Array> &info) /* {{{ */
  324. {
  325. // note: 'special' properties like 'constructor' are not enumerated.
  326. v8::Isolate *isolate = info.GetIsolate();
  327. v8::Local<v8::Object> self = info.Holder();
  328. v8::Local<v8::Array> result = V8JS_NEW(v8::Array, isolate, 0);
  329. uint32_t result_len = 0;
  330. V8JS_TSRMLS_FETCH();
  331. zend_class_entry *ce;
  332. zend_function *method_ptr;
  333. HashTable *proptable;
  334. HashPosition pos;
  335. char *key = NULL;
  336. uint key_len;
  337. ulong index;
  338. zval *object = reinterpret_cast<zval *>(v8::External::Cast(*self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY)))->Value());
  339. ce = Z_OBJCE_P(object);
  340. /* enumerate all methods */
  341. zend_hash_internal_pointer_reset_ex(&ce->function_table, &pos);
  342. for (;; zend_hash_move_forward_ex(&ce->function_table, &pos)) {
  343. if (zend_hash_get_current_key_ex(&ce->function_table, &key, &key_len, &index, 0, &pos) != HASH_KEY_IS_STRING ||
  344. zend_hash_get_current_data_ex(&ce->function_table, (void **) &method_ptr, &pos) == FAILURE
  345. ) {
  346. break;
  347. }
  348. if ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0) {
  349. /* Allow only public methods */
  350. continue;
  351. }
  352. if ((method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR|ZEND_ACC_CLONE)) != 0) {
  353. /* no __construct, __destruct(), or __clone() functions */
  354. continue;
  355. }
  356. // hide (do not enumerate) other PHP magic functions
  357. if (IS_MAGIC_FUNC(ZEND_CALLSTATIC_FUNC_NAME) ||
  358. IS_MAGIC_FUNC(ZEND_SLEEP_FUNC_NAME) ||
  359. IS_MAGIC_FUNC(ZEND_WAKEUP_FUNC_NAME) ||
  360. IS_MAGIC_FUNC(ZEND_SET_STATE_FUNC_NAME) ||
  361. IS_MAGIC_FUNC(ZEND_GET_FUNC_NAME) ||
  362. IS_MAGIC_FUNC(ZEND_SET_FUNC_NAME) ||
  363. IS_MAGIC_FUNC(ZEND_UNSET_FUNC_NAME) ||
  364. IS_MAGIC_FUNC(ZEND_CALL_FUNC_NAME) ||
  365. IS_MAGIC_FUNC(ZEND_INVOKE_FUNC_NAME) ||
  366. IS_MAGIC_FUNC(ZEND_ISSET_FUNC_NAME)) {
  367. continue;
  368. }
  369. v8::Local<v8::String> method_name = V8JS_STR(method_ptr->common.function_name);
  370. // rename PHP special method names to JS equivalents.
  371. if (IS_MAGIC_FUNC(ZEND_TOSTRING_FUNC_NAME)) {
  372. method_name = V8JS_SYM("toString");
  373. }
  374. result->Set(result_len++, method_name);
  375. }
  376. /* enumerate all properties */
  377. /* Z_OBJPROP uses the get_properties handler */
  378. proptable = Z_OBJPROP_P(object);
  379. zend_hash_internal_pointer_reset_ex(proptable, &pos);
  380. for (;; zend_hash_move_forward_ex(proptable, &pos)) {
  381. int i = zend_hash_get_current_key_ex(proptable, &key, &key_len, &index, 0, &pos);
  382. if (i == HASH_KEY_NON_EXISTANT)
  383. break;
  384. // for consistency with the 'in' operator, skip properties whose
  385. // value IS_NULL (like isset does)
  386. zval **data;
  387. if (zend_hash_get_current_data_ex(proptable, (void **) &data, &pos) == SUCCESS &&
  388. ZVAL_IS_NULL(*data))
  389. continue;
  390. if (i == HASH_KEY_IS_STRING) {
  391. /* skip protected and private members */
  392. if (key[0] == '\0') {
  393. continue;
  394. }
  395. // prefix enumerated property names with '$' so they can be
  396. // dereferenced unambiguously (ie, don't conflict with method
  397. // names)
  398. char prefixed[key_len + 1];
  399. prefixed[0] = '$';
  400. strncpy(prefixed + 1, key, key_len);
  401. result->Set(result_len++, V8JS_STRL(prefixed, key_len));
  402. } else {
  403. // even numeric indices are enumerated as strings in JavaScript
  404. result->Set(result_len++, V8JS_FLOAT((double) index)->ToString());
  405. }
  406. }
  407. /* done */
  408. info.GetReturnValue().Set(result);
  409. }
  410. /* }}} */
  411. static void php_v8js_invoke_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  412. {
  413. v8::Isolate *isolate = info.GetIsolate();
  414. v8::Local<v8::Object> self = info.Holder();
  415. v8::Local<v8::Function> cb = v8::Local<v8::Function>::Cast(info.Data());
  416. int argc = info.Length(), i;
  417. v8::Local<v8::Value> argv[argc];
  418. v8::Local<v8::Value> result;
  419. for (i=0; i<argc; i++) {
  420. argv[i] = info[i];
  421. }
  422. if (info.IsConstructCall()) {
  423. #if PHP_V8_API_VERSION <= 3023008
  424. /* Until V8 3.23.8 Isolate could only take one external pointer. */
  425. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData();
  426. #else
  427. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
  428. #endif
  429. v8::String::Utf8Value str(self->GetConstructorName()->ToString());
  430. const char *constructor_name = ToCString(str);
  431. zend_class_entry *ce = zend_fetch_class_by_name(constructor_name, str.length(), NULL, 0);
  432. v8::Local<v8::FunctionTemplate> new_tpl;
  433. new_tpl = v8::Local<v8::FunctionTemplate>::New
  434. (isolate, ctx->template_cache.at(ce->name));
  435. result = new_tpl->GetFunction()->NewInstance(argc, argv);
  436. } else {
  437. result = cb->Call(self, argc, argv);
  438. }
  439. info.GetReturnValue().Set(result);
  440. }
  441. /* }}} */
  442. // this is a magic '__call' implementation for PHP classes which don't actually
  443. // have a '__call' magic function. This way we can always force a method
  444. // call (as opposed to a property get) from JavaScript using __call.
  445. static void php_v8js_fake_call_impl(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  446. {
  447. v8::Isolate *isolate = info.GetIsolate();
  448. v8::Local<v8::Object> self = info.Holder();
  449. v8::Handle<v8::Value> return_value;
  450. char *error;
  451. int error_len;
  452. V8JS_TSRMLS_FETCH();
  453. zend_class_entry *ce;
  454. zval *object = reinterpret_cast<zval *>(v8::External::Cast(*self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY)))->Value());
  455. ce = Z_OBJCE_P(object);
  456. // first arg is method name, second arg is array of args.
  457. if (info.Length() < 2) {
  458. error_len = spprintf(&error, 0,
  459. "%s::__call expects 2 parameters, %d given",
  460. ce->name, (int) info.Length());
  461. return_value = V8JS_THROW(isolate, TypeError, error, error_len);
  462. efree(error);
  463. info.GetReturnValue().Set(return_value);
  464. return;
  465. }
  466. if (!info[1]->IsArray()) {
  467. error_len = spprintf(&error, 0,
  468. "%s::__call expects 2nd parameter to be an array",
  469. ce->name);
  470. return_value = V8JS_THROW(isolate, TypeError, error, error_len);
  471. efree(error);
  472. info.GetReturnValue().Set(return_value);
  473. return;
  474. }
  475. v8::String::Utf8Value str(info[0]->ToString());
  476. const char *method_name = ToCString(str);
  477. uint method_name_len = strlen(method_name);
  478. v8::Local<v8::Array> args = v8::Local<v8::Array>::Cast(info[1]);
  479. if (args->Length() > 1000000) {
  480. // prevent overflow, since args->Length() is a uint32_t and args
  481. // in the Function->Call method below is a (signed) int.
  482. error_len = spprintf(&error, 0,
  483. "%s::__call expects fewer than a million arguments",
  484. ce->name);
  485. return_value = V8JS_THROW(isolate, TypeError, error, error_len);
  486. efree(error);
  487. info.GetReturnValue().Set(return_value);
  488. return;
  489. }
  490. // okay, look up the method name and manually invoke it.
  491. const zend_object_handlers *h = Z_OBJ_HT_P(object);
  492. zend_function *method_ptr =
  493. h->get_method(&object, (char*)method_name, method_name_len
  494. ZEND_HASH_KEY_NULL TSRMLS_CC);
  495. if (method_ptr == NULL ||
  496. (method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0 ||
  497. (method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR|ZEND_ACC_CLONE)) != 0) {
  498. error_len = spprintf(&error, 0,
  499. "%s::__call to %s method %s", ce->name,
  500. (method_ptr == NULL) ? "undefined" : "non-public", method_name);
  501. return_value = V8JS_THROW(isolate, TypeError, error, error_len);
  502. efree(error);
  503. info.GetReturnValue().Set(return_value);
  504. return;
  505. }
  506. v8::Local<v8::FunctionTemplate> tmpl =
  507. v8::Local<v8::FunctionTemplate>::New
  508. (isolate, *reinterpret_cast<v8js_tmpl_t *>(self->GetAlignedPointerFromInternalField(0)));
  509. // use php_v8js_php_callback to actually execute the method
  510. v8::Local<v8::Function> cb = PHP_V8JS_CALLBACK(isolate, method_ptr, tmpl);
  511. uint32_t i, argc = args->Length();
  512. v8::Local<v8::Value> argv[argc];
  513. for (i=0; i<argc; i++) {
  514. argv[i] = args->Get(i);
  515. }
  516. return_value = cb->Call(info.This(), (int) argc, argv);
  517. info.GetReturnValue().Set(return_value);
  518. }
  519. /* }}} */
  520. typedef enum {
  521. V8JS_PROP_GETTER,
  522. V8JS_PROP_SETTER,
  523. V8JS_PROP_QUERY,
  524. V8JS_PROP_DELETER
  525. } property_op_t;
  526. /* This method handles named property and method get/set/query/delete. */
  527. template<typename T>
  528. static inline v8::Local<v8::Value> php_v8js_named_property_callback(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<T> &info, property_op_t callback_type, v8::Local<v8::Value> set_value = v8::Local<v8::Value>()) /* {{{ */
  529. {
  530. v8::Isolate *isolate = info.GetIsolate();
  531. v8::String::Utf8Value cstr(property);
  532. const char *name = ToCString(cstr);
  533. uint name_len = strlen(name);
  534. char *lower = estrndup(name, name_len);
  535. const char *method_name;
  536. uint method_name_len;
  537. v8::Local<v8::Object> self = info.Holder();
  538. v8::Local<v8::Value> ret_value;
  539. v8::Local<v8::Function> cb;
  540. V8JS_TSRMLS_FETCH();
  541. zend_class_entry *scope, *ce;
  542. zend_function *method_ptr = NULL;
  543. zval *php_value;
  544. zval *object = reinterpret_cast<zval *>(v8::External::Cast(*self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY)))->Value());
  545. v8::Local<v8::FunctionTemplate> tmpl =
  546. v8::Local<v8::FunctionTemplate>::New
  547. (isolate, *reinterpret_cast<v8js_tmpl_t *>(self->GetAlignedPointerFromInternalField(0)));
  548. ce = scope = Z_OBJCE_P(object);
  549. /* First, check the (case-insensitive) method table */
  550. php_strtolower(lower, name_len);
  551. method_name = lower;
  552. method_name_len = name_len;
  553. // toString() -> __tostring()
  554. if (name_len == 8 && strcmp(name, "toString") == 0) {
  555. method_name = ZEND_TOSTRING_FUNC_NAME;
  556. method_name_len = sizeof(ZEND_TOSTRING_FUNC_NAME) - 1;
  557. }
  558. bool is_constructor = (name_len == 11 && strcmp(name, "constructor") == 0);
  559. bool is_magic_call = (method_name_len == 6 && strcmp(method_name, "__call") == 0);
  560. if (is_constructor ||
  561. (name[0] != '$' /* leading '$' means property, not method */ &&
  562. zend_hash_find(&ce->function_table, method_name, method_name_len + 1, (void**)&method_ptr) == SUCCESS &&
  563. ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) != 0) && /* Allow only public methods */
  564. ((method_ptr->common.fn_flags & (ZEND_ACC_CTOR|ZEND_ACC_DTOR|ZEND_ACC_CLONE)) == 0) /* no __construct, __destruct(), or __clone() functions */
  565. ) || (method_ptr=NULL, is_magic_call)
  566. ) {
  567. if (callback_type == V8JS_PROP_GETTER) {
  568. if (is_constructor) {
  569. ret_value = self->GetConstructor();
  570. } else {
  571. if (is_magic_call && method_ptr==NULL) {
  572. // Fake __call implementation
  573. // (only use this if method_ptr==NULL, which means
  574. // there is no actual PHP __call() implementation)
  575. v8::Local<v8::Function> cb =
  576. V8JS_NEW(v8::FunctionTemplate, isolate,
  577. php_v8js_fake_call_impl, V8JS_NULL,
  578. V8JS_NEW(v8::Signature, isolate, tmpl))->GetFunction();
  579. cb->SetName(property);
  580. ret_value = cb;
  581. } else {
  582. ret_value = PHP_V8JS_CALLBACK(isolate, method_ptr, tmpl);
  583. }
  584. }
  585. } else if (callback_type == V8JS_PROP_QUERY) {
  586. // methods are not enumerable
  587. ret_value = V8JS_UINT(v8::ReadOnly|v8::DontEnum|v8::DontDelete);
  588. } else if (callback_type == V8JS_PROP_SETTER) {
  589. ret_value = set_value; // lie. this field is read-only.
  590. } else if (callback_type == V8JS_PROP_DELETER) {
  591. ret_value = V8JS_BOOL(false);
  592. } else {
  593. /* shouldn't reach here! but bail safely */
  594. ret_value = v8::Handle<v8::Value>();
  595. }
  596. } else {
  597. if (name[0]=='$') {
  598. // this is a property (not a method)
  599. name++; name_len--;
  600. }
  601. if (callback_type == V8JS_PROP_GETTER) {
  602. /* Nope, not a method -- must be a (case-sensitive) property */
  603. zval zname;
  604. INIT_ZVAL(zname);
  605. ZVAL_STRINGL(&zname, name, name_len, 0);
  606. zend_property_info *property_info = zend_get_property_info(ce, &zname, 1 TSRMLS_CC);
  607. if(property_info && property_info->flags & ZEND_ACC_PUBLIC) {
  608. php_value = zend_read_property(NULL, object, V8JS_CONST name, name_len, true TSRMLS_CC);
  609. // special case uninitialized_zval_ptr and return an empty value
  610. // (indicating that we don't intercept this property) if the
  611. // property doesn't exist.
  612. if (php_value == EG(uninitialized_zval_ptr)) {
  613. ret_value = v8::Handle<v8::Value>();
  614. } else {
  615. // wrap it
  616. ret_value = zval_to_v8js(php_value, isolate TSRMLS_CC);
  617. /* We don't own the reference to php_value... unless the
  618. * returned refcount was 0, in which case the below code
  619. * will free it. */
  620. zval_add_ref(&php_value);
  621. zval_ptr_dtor(&php_value);
  622. }
  623. }
  624. else if (zend_hash_find(&ce->function_table, "__get", 6, (void**)&method_ptr) == SUCCESS
  625. /* Allow only public methods */
  626. && ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) != 0)) {
  627. /* Okay, let's call __get. */
  628. zend_fcall_info fci;
  629. zval fmember;
  630. INIT_ZVAL(fmember);
  631. ZVAL_STRING(&fmember, "__get", 0);
  632. fci.size = sizeof(fci);
  633. fci.function_table = &ce->function_table;
  634. fci.function_name = &fmember;
  635. fci.symbol_table = NULL;
  636. fci.retval_ptr_ptr = &php_value;
  637. zval *zname_ptr = &zname;
  638. zval **zname_ptr_ptr = &zname_ptr;
  639. fci.param_count = 1;
  640. fci.params = &zname_ptr_ptr;
  641. fci.object_ptr = object;
  642. fci.no_separation = 0;
  643. zend_call_function(&fci, NULL TSRMLS_CC);
  644. ret_value = zval_to_v8js(php_value, isolate TSRMLS_CC);
  645. /* We don't own the reference to php_value... unless the
  646. * returned refcount was 0, in which case the below code
  647. * will free it. */
  648. zval_add_ref(&php_value);
  649. zval_ptr_dtor(&php_value);
  650. }
  651. } else if (callback_type == V8JS_PROP_SETTER) {
  652. MAKE_STD_ZVAL(php_value);
  653. if (v8js_to_zval(set_value, php_value, 0, isolate TSRMLS_CC) != SUCCESS) {
  654. ret_value = v8::Handle<v8::Value>();
  655. }
  656. else {
  657. zval zname;
  658. INIT_ZVAL(zname);
  659. ZVAL_STRINGL(&zname, name, name_len, 0);
  660. zend_property_info *property_info = zend_get_property_info(ce, &zname, 1 TSRMLS_CC);
  661. if(property_info && property_info->flags & ZEND_ACC_PUBLIC) {
  662. zend_update_property(scope, object, V8JS_CONST name, name_len, php_value TSRMLS_CC);
  663. ret_value = set_value;
  664. }
  665. else if (zend_hash_find(&ce->function_table, "__set", 6, (void**)&method_ptr) == SUCCESS
  666. /* Allow only public methods */
  667. && ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) != 0)) {
  668. /* Okay, let's call __set. */
  669. zend_fcall_info fci;
  670. zval fmember;
  671. INIT_ZVAL(fmember);
  672. ZVAL_STRING(&fmember, "__set", 0);
  673. zval *php_ret_value;
  674. fci.size = sizeof(fci);
  675. fci.function_table = &ce->function_table;
  676. fci.function_name = &fmember;
  677. fci.symbol_table = NULL;
  678. fci.retval_ptr_ptr = &php_ret_value;
  679. zval *zname_ptr = &zname;
  680. zval **params[2];
  681. fci.param_count = 2;
  682. fci.params = params;
  683. fci.params[0] = &zname_ptr;
  684. fci.params[1] = &php_value;
  685. fci.object_ptr = object;
  686. fci.no_separation = 1;
  687. zend_call_function(&fci, NULL TSRMLS_CC);
  688. ret_value = zval_to_v8js(php_ret_value, isolate TSRMLS_CC);
  689. /* We don't own the reference to php_ret_value... unless the
  690. * returned refcount was 0, in which case the below code
  691. * will free it. */
  692. zval_add_ref(&php_ret_value);
  693. zval_ptr_dtor(&php_ret_value);
  694. }
  695. }
  696. // if PHP wanted to hold on to this value, update_property would
  697. // have bumped the refcount
  698. zval_ptr_dtor(&php_value);
  699. } else if (callback_type == V8JS_PROP_QUERY ||
  700. callback_type == V8JS_PROP_DELETER) {
  701. const zend_object_handlers *h = Z_OBJ_HT_P(object);
  702. zval *prop;
  703. MAKE_STD_ZVAL(prop);
  704. ZVAL_STRINGL(prop, name, name_len, 1);
  705. if (callback_type == V8JS_PROP_QUERY) {
  706. if (h->has_property(object, prop, 0 ZEND_HASH_KEY_NULL TSRMLS_CC)) {
  707. ret_value = V8JS_UINT(v8::None);
  708. } else {
  709. ret_value = v8::Handle<v8::Value>(); // empty handle
  710. }
  711. } else {
  712. zend_property_info *property_info = zend_get_property_info(ce, prop, 1 TSRMLS_CC);
  713. if(property_info && property_info->flags & ZEND_ACC_PUBLIC) {
  714. h->unset_property(object, prop ZEND_HASH_KEY_NULL TSRMLS_CC);
  715. ret_value = V8JS_BOOL(true);
  716. }
  717. else {
  718. ret_value = v8::Handle<v8::Value>(); // empty handle
  719. }
  720. }
  721. zval_ptr_dtor(&prop);
  722. } else {
  723. /* shouldn't reach here! but bail safely */
  724. ret_value = v8::Handle<v8::Value>();
  725. }
  726. }
  727. efree(lower);
  728. return ret_value;
  729. }
  730. /* }}} */
  731. static void php_v8js_named_property_getter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
  732. {
  733. info.GetReturnValue().Set(php_v8js_named_property_callback(property, info, V8JS_PROP_GETTER));
  734. }
  735. /* }}} */
  736. static void php_v8js_named_property_setter(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
  737. {
  738. info.GetReturnValue().Set(php_v8js_named_property_callback(property, info, V8JS_PROP_SETTER, value));
  739. }
  740. /* }}} */
  741. static void php_v8js_named_property_query(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Integer> &info) /* {{{ */
  742. {
  743. v8::Local<v8::Value> r = php_v8js_named_property_callback(property, info, V8JS_PROP_QUERY);
  744. if (!r.IsEmpty()) {
  745. info.GetReturnValue().Set(r->ToInteger());
  746. }
  747. }
  748. /* }}} */
  749. static void php_v8js_named_property_deleter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Boolean> &info) /* {{{ */
  750. {
  751. v8::Local<v8::Value> r = php_v8js_named_property_callback(property, info, V8JS_PROP_DELETER);
  752. if (!r.IsEmpty()) {
  753. info.GetReturnValue().Set(r->ToBoolean());
  754. }
  755. }
  756. /* }}} */
  757. static v8::Handle<v8::Value> php_v8js_hash_to_jsobj(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  758. {
  759. v8::Handle<v8::Object> newobj;
  760. int i;
  761. char *key = NULL;
  762. ulong index;
  763. uint key_len;
  764. HashTable *myht;
  765. HashPosition pos;
  766. zend_class_entry *ce = NULL;
  767. if (Z_TYPE_P(value) == IS_ARRAY) {
  768. myht = HASH_OF(value);
  769. } else {
  770. myht = Z_OBJPROP_P(value);
  771. ce = Z_OBJCE_P(value);
  772. }
  773. /* Prevent recursion */
  774. if (myht && myht->nApplyCount > 1) {
  775. return V8JS_NULL;
  776. }
  777. /* Object methods */
  778. if (ce == php_ce_v8_function) {
  779. php_v8js_object *c = (php_v8js_object *) zend_object_store_get_object(value TSRMLS_CC);
  780. v8::Local<v8::Value> v8obj = v8::Local<v8::Value>::New(isolate, c->v8obj);
  781. return v8obj;
  782. } else if (ce) {
  783. #if PHP_V8_API_VERSION <= 3023008
  784. /* Until V8 3.23.8 Isolate could only take one external pointer. */
  785. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData();
  786. #else
  787. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData(0);
  788. #endif
  789. v8::Local<v8::FunctionTemplate> new_tpl;
  790. v8js_tmpl_t *persist_tpl_;
  791. try {
  792. new_tpl = v8::Local<v8::FunctionTemplate>::New
  793. (isolate, ctx->template_cache.at(ce->name));
  794. }
  795. catch (const std::out_of_range &) {
  796. /* No cached v8::FunctionTemplate available as of yet, create one. */
  797. new_tpl = V8JS_NEW(v8::FunctionTemplate, isolate, 0);
  798. new_tpl->SetClassName(V8JS_STRL(ce->name, ce->name_length));
  799. new_tpl->InstanceTemplate()->SetInternalFieldCount(1);
  800. if (ce == zend_ce_closure) {
  801. /* Got a closure, mustn't cache ... */
  802. persist_tpl_ = new v8js_tmpl_t(isolate, new_tpl);
  803. /* We'll free persist_tpl_ via php_v8js_weak_closure_callback, below */
  804. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(php_v8js_php_callback);
  805. } else {
  806. /* Add new v8::FunctionTemplate to tpl_map, as long as it is not a closure. */
  807. persist_tpl_ = &ctx->template_cache[ce->name];
  808. persist_tpl_->Reset(isolate, new_tpl);
  809. /* We'll free persist_tpl_ when template_cache is destroyed */
  810. // Finish setup of new_tpl
  811. new_tpl->InstanceTemplate()->SetNamedPropertyHandler
  812. (php_v8js_named_property_getter, /* getter */
  813. php_v8js_named_property_setter, /* setter */
  814. php_v8js_named_property_query, /* query */
  815. php_v8js_named_property_deleter, /* deleter */
  816. php_v8js_named_property_enumerator, /* enumerator */
  817. V8JS_NULL /* data */
  818. );
  819. // add __invoke() handler
  820. zend_function *invoke_method_ptr;
  821. if (zend_hash_find(&ce->function_table, ZEND_INVOKE_FUNC_NAME,
  822. sizeof(ZEND_INVOKE_FUNC_NAME),
  823. (void**)&invoke_method_ptr) == SUCCESS &&
  824. invoke_method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) {
  825. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(php_v8js_invoke_callback, PHP_V8JS_CALLBACK(isolate, invoke_method_ptr, new_tpl));
  826. }
  827. }
  828. v8::Local<v8::Array> call_handler_data = V8JS_NEW(v8::Array, isolate, 2);
  829. call_handler_data->Set(0, V8JS_NEW(v8::External, isolate, persist_tpl_));
  830. call_handler_data->Set(1, V8JS_NEW(v8::External, isolate, ce));
  831. new_tpl->SetCallHandler(php_v8js_construct_callback, call_handler_data);
  832. }
  833. // Create v8 wrapper object
  834. v8::Handle<v8::Value> external = V8JS_NEW(v8::External, isolate, value);
  835. newobj = new_tpl->GetFunction()->NewInstance(1, &external);
  836. if (ce == zend_ce_closure) {
  837. // free uncached function template when object is freed
  838. ctx->weak_closures[persist_tpl_].Reset(isolate, newobj);
  839. ctx->weak_closures[persist_tpl_].SetWeak(persist_tpl_, php_v8js_weak_closure_callback);
  840. }
  841. } else {
  842. // @todo re-use template likewise
  843. v8::Local<v8::FunctionTemplate> new_tpl = V8JS_NEW(v8::FunctionTemplate, isolate, 0);
  844. new_tpl->SetClassName(V8JS_SYM("Array"));
  845. newobj = new_tpl->InstanceTemplate()->NewInstance();
  846. }
  847. /* Object properties */
  848. i = myht ? zend_hash_num_elements(myht) : 0;
  849. if (i > 0 && !ce)
  850. {
  851. zval **data;
  852. HashTable *tmp_ht;
  853. zend_hash_internal_pointer_reset_ex(myht, &pos);
  854. for (;; zend_hash_move_forward_ex(myht, &pos)) {
  855. i = zend_hash_get_current_key_ex(myht, &key, &key_len, &index, 0, &pos);
  856. if (i == HASH_KEY_NON_EXISTANT)
  857. break;
  858. if (zend_hash_get_current_data_ex(myht, (void **) &data, &pos) == SUCCESS)
  859. {
  860. tmp_ht = HASH_OF(*data);
  861. if (tmp_ht) {
  862. tmp_ht->nApplyCount++;
  863. }
  864. if (i == HASH_KEY_IS_STRING)
  865. {
  866. if (key[0] == '\0' && Z_TYPE_P(value) == IS_OBJECT) {
  867. /* Skip protected and private members. */
  868. if (tmp_ht) {
  869. tmp_ht->nApplyCount--;
  870. }
  871. continue;
  872. }
  873. newobj->Set(V8JS_STRL(key, key_len - 1), zval_to_v8js(*data, isolate TSRMLS_CC));
  874. } else {
  875. newobj->Set(index, zval_to_v8js(*data, isolate TSRMLS_CC));
  876. }
  877. if (tmp_ht) {
  878. tmp_ht->nApplyCount--;
  879. }
  880. }
  881. }
  882. }
  883. return newobj;
  884. }
  885. /* }}} */
  886. static v8::Handle<v8::Value> php_v8js_hash_to_jsarr(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  887. {
  888. HashTable *myht = HASH_OF(value);
  889. int i = myht ? zend_hash_num_elements(myht) : 0;
  890. /* Return object if dealing with assoc array */
  891. if (i > 0 && _php_v8js_is_assoc_array(myht TSRMLS_CC)) {
  892. return php_v8js_hash_to_jsobj(value, isolate TSRMLS_CC);
  893. }
  894. v8::Local<v8::Array> newarr;
  895. /* Prevent recursion */
  896. if (myht && myht->nApplyCount > 1) {
  897. return V8JS_NULL;
  898. }
  899. newarr = V8JS_NEW(v8::Array, isolate, i);
  900. if (i > 0)
  901. {
  902. zval **data;
  903. ulong index = 0;
  904. HashTable *tmp_ht;
  905. HashPosition pos;
  906. for (zend_hash_internal_pointer_reset_ex(myht, &pos);
  907. SUCCESS == zend_hash_get_current_data_ex(myht, (void **) &data, &pos);
  908. zend_hash_move_forward_ex(myht, &pos)
  909. ) {
  910. tmp_ht = HASH_OF(*data);
  911. if (tmp_ht) {
  912. tmp_ht->nApplyCount++;
  913. }
  914. newarr->Set(index++, zval_to_v8js(*data, isolate TSRMLS_CC));
  915. if (tmp_ht) {
  916. tmp_ht->nApplyCount--;
  917. }
  918. }
  919. }
  920. return newarr;
  921. }
  922. /* }}} */
  923. v8::Handle<v8::Value> zval_to_v8js(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  924. {
  925. v8::Handle<v8::Value> jsValue;
  926. long v;
  927. zend_class_entry *ce;
  928. switch (Z_TYPE_P(value))
  929. {
  930. case IS_ARRAY:
  931. jsValue = php_v8js_hash_to_jsarr(value, isolate TSRMLS_CC);
  932. break;
  933. case IS_OBJECT:
  934. if (V8JSG(use_date)) {
  935. ce = php_date_get_date_ce();
  936. if (instanceof_function(Z_OBJCE_P(value), ce TSRMLS_CC)) {
  937. zval *dtval;
  938. zend_call_method_with_0_params(&value, NULL, NULL, "getTimestamp", &dtval);
  939. if (dtval)
  940. jsValue = V8JS_DATE(((double)Z_LVAL_P(dtval) * 1000.0));
  941. else
  942. jsValue = V8JS_NULL;
  943. } else
  944. jsValue = php_v8js_hash_to_jsobj(value, isolate TSRMLS_CC);
  945. } else
  946. jsValue = php_v8js_hash_to_jsobj(value, isolate TSRMLS_CC);
  947. break;
  948. case IS_STRING:
  949. jsValue = V8JS_STRL(Z_STRVAL_P(value), Z_STRLEN_P(value));
  950. break;
  951. case IS_LONG:
  952. v = Z_LVAL_P(value);
  953. if (v < - std::numeric_limits<int32_t>::min() || v > std::numeric_limits<int32_t>::max()) {
  954. jsValue = V8JS_FLOAT((double)v);
  955. } else {
  956. jsValue = V8JS_INT(v);
  957. }
  958. break;
  959. case IS_DOUBLE:
  960. jsValue = V8JS_FLOAT(Z_DVAL_P(value));
  961. break;
  962. case IS_BOOL:
  963. jsValue = V8JS_BOOL(Z_BVAL_P(value));
  964. break;
  965. default:
  966. case IS_NULL:
  967. jsValue = V8JS_NULL;
  968. break;
  969. }
  970. return jsValue;
  971. }
  972. /* }}} */
  973. int v8js_to_zval(v8::Handle<v8::Value> jsValue, zval *return_value, int flags, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  974. {
  975. if (jsValue->IsString())
  976. {
  977. v8::String::Utf8Value str(jsValue);
  978. const char *cstr = ToCString(str);
  979. RETVAL_STRINGL(cstr, jsValue->ToString()->Utf8Length(), 1);
  980. // RETVAL_STRING(cstr, 1);
  981. }
  982. else if (jsValue->IsBoolean())
  983. {
  984. RETVAL_BOOL(jsValue->Uint32Value());
  985. }
  986. else if (jsValue->IsInt32() || jsValue->IsUint32())
  987. {
  988. RETVAL_LONG((long) jsValue->IntegerValue());
  989. }
  990. else if (jsValue->IsNumber())
  991. {
  992. RETVAL_DOUBLE(jsValue->NumberValue());
  993. }
  994. else if (jsValue->IsDate()) /* Return as a PHP DateTime object */
  995. {
  996. v8::String::Utf8Value str(jsValue);
  997. const char *cstr = ToCString(str);
  998. zend_class_entry *ce = php_date_get_date_ce();
  999. #if PHP_VERSION_ID < 50304
  1000. zval *param;
  1001. MAKE_STD_ZVAL(param);
  1002. ZVAL_STRING(param, cstr, 1);
  1003. object_init_ex(return_value, ce TSRMLS_CC);
  1004. zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, param);
  1005. zval_ptr_dtor(&param);
  1006. if (EG(exception)) {
  1007. return FAILURE;
  1008. }
  1009. #else
  1010. php_date_instantiate(ce, return_value TSRMLS_CC);
  1011. if (!php_date_initialize((php_date_obj *) zend_object_store_get_object(return_value TSRMLS_CC), (char *) cstr, strlen(cstr), NULL, NULL, 0 TSRMLS_CC)) {
  1012. return FAILURE;
  1013. }
  1014. #endif
  1015. }
  1016. else if (jsValue->IsObject())
  1017. {
  1018. v8::Handle<v8::Object> self = v8::Handle<v8::Object>::Cast(jsValue);
  1019. // if this is a wrapped PHP object, then just unwrap it.
  1020. v8::Local<v8::Value> php_object = self->GetHiddenValue(V8JS_SYM(PHPJS_OBJECT_KEY));
  1021. if (!php_object.IsEmpty()) {
  1022. zval *object = reinterpret_cast<zval *>(v8::External::Cast(*php_object)->Value());
  1023. RETVAL_ZVAL(object, 1, 0);
  1024. return SUCCESS;
  1025. }
  1026. if ((flags & V8JS_FLAG_FORCE_ARRAY) || jsValue->IsArray()) {
  1027. array_init(return_value);
  1028. return php_v8js_v8_get_properties_hash(jsValue, Z_ARRVAL_P(return_value), flags, isolate TSRMLS_CC);
  1029. } else {
  1030. php_v8js_create_v8(return_value, jsValue, flags, isolate TSRMLS_CC);
  1031. return SUCCESS;
  1032. }
  1033. }
  1034. else /* types External, RegExp, Undefined and Null are considered NULL */
  1035. {
  1036. RETVAL_NULL();
  1037. }
  1038. return SUCCESS;
  1039. }
  1040. /* }}} */
  1041. /*
  1042. * Local variables:
  1043. * tab-width: 4
  1044. * c-basic-offset: 4
  1045. * End:
  1046. * vim600: noet sw=4 ts=4 fdm=marker
  1047. * vim<600: noet sw=4 ts=4
  1048. */