v8js_convert.cc 38 KB

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