v8js_convert.cc 38 KB

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