v8js_convert.cc 37 KB

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