PageRenderTime 54ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/common/xajax/xajax.inc.php

https://bitbucket.org/wildanm/orangehrm
PHP | 979 lines | 676 code | 95 blank | 208 comment | 166 complexity | a289895d67fb777cbaa526e50fa3b616 MD5 | raw file
Possible License(s): CC-BY-SA-3.0, AGPL-3.0, BSD-3-Clause, AGPL-1.0, GPL-2.0, LGPL-2.1, LGPL-3.0
  1. <?php
  2. ///////////////////////////////////////////////////////////////////////////////
  3. // xajax.inc.php :: Main xajax class and setup file
  4. //
  5. // xajax version 0.2.3
  6. // copyright (c) 2005 by Jared White & J. Max Wilson
  7. // http://xajax.sourceforge.net
  8. //
  9. // xajax is an open source PHP class library for easily creating powerful
  10. // PHP-driven, web-based AJAX Applications. Using xajax, you can asynchronously
  11. // call PHP functions and update the content of your your webpage without
  12. // reloading the page.
  13. //
  14. // xajax is released under the terms of the LGPL license
  15. // http://www.gnu.org/copyleft/lesser.html#SEC3
  16. //
  17. // This library is free software; you can redistribute it and/or
  18. // modify it under the terms of the GNU Lesser General Public
  19. // License as published by the Free Software Foundation; either
  20. // version 2.1 of the License, or (at your option) any later version.
  21. //
  22. // This library is distributed in the hope that it will be useful,
  23. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  25. // Lesser General Public License for more details.
  26. //
  27. // You should have received a copy of the GNU Lesser General Public
  28. // License along with this library; if not, write to the Free Software
  29. // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  30. ///////////////////////////////////////////////////////////////////////////////
  31. /* Modifications done by OrangeHRM:
  32. *
  33. * 1. Function getJavascriptInclude().
  34. * Default URI and file paths were changed to match OrangeHRM needs.
  35. * Changed to validate as XHTML
  36. * 2. Fixed a bug in buffer cleaning - 2007/06/30
  37. * 3. Enabled buffer cleaning - 2007/06/30
  38. */
  39. // Define XAJAX_DEFAULT_CHAR_ENCODING that is used by both
  40. // the xajax and xajaxResponse classes
  41. if (!defined ('XAJAX_DEFAULT_CHAR_ENCODING'))
  42. {
  43. define ('XAJAX_DEFAULT_CHAR_ENCODING', 'utf-8' );
  44. }
  45. require_once("xajaxResponse.inc.php");
  46. // Communication Method Defines
  47. if (!defined ('XAJAX_GET'))
  48. {
  49. define ('XAJAX_GET', 0);
  50. }
  51. if (!defined ('XAJAX_POST'))
  52. {
  53. define ('XAJAX_POST', 1);
  54. }
  55. // the xajax class generates the xajax javascript for your page including the
  56. // javascript wrappers for the PHP functions that you want to call from your page.
  57. // It also handles processing and executing the command messages in the xml responses
  58. // sent back to your page from your PHP functions.
  59. class xajax
  60. {
  61. var $aFunctions; // Array of PHP functions that will be callable through javascript wrappers
  62. var $aObjects; // Array of object callbacks that will allow Javascript to call PHP methods (key=function name)
  63. var $aFunctionRequestTypes; // Array of RequestTypes to be used with each function (key=function name)
  64. var $aFunctionIncludeFiles; // Array of Include Files for any external functions (key=function name)
  65. var $sCatchAllFunction; // Name of the PHP function to call if no callable function was found
  66. var $sPreFunction; // Name of the PHP function to call before any other function
  67. var $sRequestURI; // The URI for making requests to the xajax object
  68. var $sWrapperPrefix; // The prefix to prepend to the javascript wraper function name
  69. var $bDebug; // Show debug messages (true/false)
  70. var $bStatusMessages; // Show debug messages (true/false)
  71. var $bExitAllowed; // Allow xajax to exit after processing a request (true/false)
  72. var $bWaitCursor; // Use wait cursor in browser (true/false)
  73. var $bErrorHandler; // Use an special xajax error handler so the errors are sent to the browser properly
  74. var $sLogFile; // Specify if xajax should log errors (and more information in a future release)
  75. var $bCleanBuffer; // Clean all output buffers before outputting response (true/false)
  76. var $sEncoding; // String containing the character encoding used.
  77. var $bDecodeUTF8Input; // Decode input request args from UTF-8 (true/false)
  78. var $bOutputEntities; // Convert special characters to HTML entities (true/false)
  79. var $aObjArray; // Array for parsing complex objects
  80. var $iPos; // Position in $aObjArray
  81. // Contructor
  82. // $sRequestURI - defaults to the current page
  83. // $sWrapperPrefix - defaults to "xajax_";
  84. // $sEncoding - defaults to XAJAX_DEFAULT_CHAR_ENCODING defined above
  85. // $bDebug Mode - defaults to false
  86. // usage: $xajax = new xajax();
  87. function xajax($sRequestURI="",$sWrapperPrefix="xajax_",$sEncoding=XAJAX_DEFAULT_CHAR_ENCODING,$bDebug=false)
  88. {
  89. $this->aFunctions = array();
  90. $this->aObjects = array();
  91. $this->aFunctionIncludeFiles = array();
  92. $this->sRequestURI = $sRequestURI;
  93. if ($this->sRequestURI == "")
  94. $this->sRequestURI = $this->_detectURI();
  95. $this->sWrapperPrefix = $sWrapperPrefix;
  96. $this->bDebug = $bDebug;
  97. $this->bStatusMessages = false;
  98. $this->bWaitCursor = true;
  99. $this->bExitAllowed = true;
  100. $this->bErrorHandler = false;
  101. $this->sLogFile = "";
  102. $this->bCleanBuffer = true;
  103. $this->setCharEncoding($sEncoding);
  104. $this->bDecodeUTF8Input = false;
  105. $this->bOutputEntities = false;
  106. }
  107. // setRequestURI() sets the URI to which requests will be made
  108. // usage: $xajax->setRequestURI("http://xajax.sourceforge.net");
  109. function setRequestURI($sRequestURI)
  110. {
  111. $this->sRequestURI = $sRequestURI;
  112. }
  113. // setWrapperPrefix() sets the prefix that will be appended to the Javascript
  114. // wrapper functions (default is "xajax_").
  115. function setWrapperPrefix($sPrefix)
  116. {
  117. $this->sWrapperPrefix = $sPrefix;
  118. }
  119. // debugOn() enables debug messages for xajax
  120. function debugOn()
  121. {
  122. $this->bDebug = true;
  123. }
  124. // debugOff() disables debug messages for xajax (default behavior)
  125. function debugOff()
  126. {
  127. $this->bDebug = false;
  128. }
  129. // statusMessagesOn() enables messages in the statusbar for xajax
  130. function statusMessagesOn()
  131. {
  132. $this->bStatusMessages = true;
  133. }
  134. // statusMessagesOff() disables messages in the statusbar for xajax (default behavior)
  135. function statusMessagesOff()
  136. {
  137. $this->bStatusMessages = false;
  138. }
  139. // waitCursor() enables the wait cursor to be displayed in the browser (default behavior)
  140. function waitCursorOn()
  141. {
  142. $this->bWaitCursor = true;
  143. }
  144. // waitCursorOff() disables the wait cursor to be displayed in the browser
  145. function waitCursorOff()
  146. {
  147. $this->bWaitCursor = false;
  148. }
  149. // exitAllowedOn() enables xajax to exit immediately after processing a request
  150. // and sending the response back to the browser (default behavior)
  151. function exitAllowedOn()
  152. {
  153. $this->bExitAllowed = true;
  154. }
  155. // exitAllowedOff() disables xajax's default behavior of exiting immediately
  156. // after processing a request and sending the response back to the browser
  157. function exitAllowedOff()
  158. {
  159. $this->bExitAllowed = false;
  160. }
  161. // errorHandlerOn() turns on xajax's error handling system so that PHP errors
  162. // that occur during a request are trapped and pushed to the browser in the
  163. // form of a Javascript alert
  164. function errorHandlerOn()
  165. {
  166. $this->bErrorHandler = true;
  167. }
  168. // errorHandlerOff() turns off xajax's error handling system (default behavior)
  169. function errorHandlerOff()
  170. {
  171. $this->bErrorHandler = false;
  172. }
  173. // setLogFile() specifies a log file that will be written to by xajax during
  174. // a request (used only by the error handling system at present). If you don't
  175. // invoke this method, or you pass in "", then no log file will be written to.
  176. // usage: $xajax->setLogFile("/xajax_logs/errors.log");
  177. function setLogFile($sFilename)
  178. {
  179. $this->sLogFile = $sFilename;
  180. }
  181. // cleanBufferOn() causes xajax to clean out all output buffers before outputting
  182. // a response (default behavior)
  183. function cleanBufferOn()
  184. {
  185. $this->bCleanBuffer = true;
  186. }
  187. // cleanBufferOff() turns off xajax's output buffer cleaning
  188. function cleanBufferOff()
  189. {
  190. $this->bCleanBuffer = false;
  191. }
  192. // setCharEncoding() sets the character encoding to be used by xajax
  193. // usage: $xajax->setCharEncoding("utf-8");
  194. // *Note: to change the default character encoding for all xajax responses, set
  195. // the XAJAX_DEFAULT_CHAR_ENCODING constant near the beginning of the xajax.inc.php file
  196. function setCharEncoding($sEncoding)
  197. {
  198. $this->sEncoding = $sEncoding;
  199. }
  200. // decodeUTF8InputOn() causes xajax to decode the input request args from UTF-8 to the
  201. // current encoding.
  202. function decodeUTF8InputOn()
  203. {
  204. $this->bDecodeUTF8Input = true;
  205. }
  206. // decodeUTF8InputOff() turns off decoding the input request args from UTF-8.
  207. // (default behavior)
  208. function decodeUTF8InputOff()
  209. {
  210. $this->bDecodeUTF8Input = false;
  211. }
  212. // outputEntitiesOn() tells the response object to convert special characters to
  213. // HTML entities automatically (only works if the mb_string extension is available).
  214. function outputEntitiesOn()
  215. {
  216. $this->bOutputEntities = true;
  217. }
  218. // outputEntitiesOff() tells the response object to output special characters
  219. // intact. (default behavior)
  220. function outputEntitiesOff()
  221. {
  222. $this->bOutputEntities = false;
  223. }
  224. // registerFunction() registers a PHP function or method to be callable through
  225. // xajax in your Javascript. If you want to register a function, pass in the name
  226. // of that function. If you want to register a static class method, pass in an array
  227. // like so:
  228. // array("myFunctionName", "myClass", "myMethod")
  229. // For an object instance method, use an object variable for the second array element
  230. // (and in PHP 4 make sure you put an & before the variable to pass the object by
  231. // reference). Note: the function name is what you call via Javascript, so it can be
  232. // anything as long as it doesn't conflict with any other registered function name.
  233. //
  234. // $mFunction is a string containing the function name or an object callback array
  235. // $sRequestType is the RequestType (XAJAX_GET/XAJAX_POST) that should be used
  236. // for this function. Defaults to XAJAX_POST.
  237. // usage: $xajax->registerFunction("myFunction");
  238. // or: $xajax->registerFunction(array("myFunctionName", &$myObject, "myMethod"));
  239. function registerFunction($mFunction,$sRequestType=XAJAX_POST)
  240. {
  241. if (is_array($mFunction)) {
  242. $this->aFunctions[$mFunction[0]] = 1;
  243. $this->aFunctionRequestTypes[$mFunction[0]] = $sRequestType;
  244. $this->aObjects[$mFunction[0]] = array_slice($mFunction, 1);
  245. }
  246. else {
  247. $this->aFunctions[$mFunction] = 1;
  248. $this->aFunctionRequestTypes[$mFunction] = $sRequestType;
  249. }
  250. }
  251. // registerExternalFunction() registers a PHP function to be callable through xajax
  252. // which is located in some other file. If the function is requested the external
  253. // file will be included to define the function before the function is called
  254. // $mFunction is a string containing the function name or an object callback array
  255. // see registerFunction() for more info on object callback arrays
  256. // $sIncludeFile is a string containing the path and filename of the include file
  257. // $sRequestType is the RequestType (XAJAX_GET/XAJAX_POST) that should be used
  258. // for this function. Defaults to XAJAX_POST.
  259. // usage: $xajax->registerExternalFunction("myFunction","myFunction.inc.php",XAJAX_POST);
  260. function registerExternalFunction($mFunction,$sIncludeFile,$sRequestType=XAJAX_POST)
  261. {
  262. $this->registerFunction($mFunction, $sRequestType);
  263. if (is_array($mFunction)) {
  264. $this->aFunctionIncludeFiles[$mFunction[0]] = $sIncludeFile;
  265. }
  266. else {
  267. $this->aFunctionIncludeFiles[$mFunction] = $sIncludeFile;
  268. }
  269. }
  270. // registerCatchAllFunction() registers a PHP function to be called when xajax cannot
  271. // find the function being called via Javascript. Because this is technically
  272. // impossible when using "wrapped" functions, the catch-all feature is only useful
  273. // when you're directly using the xajax.call() Javascript method. Use the catch-all
  274. // feature when you want more dynamic ability to intercept unknown calls and handle
  275. // them in a custom way.
  276. // $mFunction is a string containing the function name or an object callback array
  277. // see registerFunction() for more info on object callback arrays
  278. // usage: $xajax->registerCatchAllFunction("myCatchAllFunction");
  279. function registerCatchAllFunction($mFunction)
  280. {
  281. if (is_array($mFunction)) {
  282. $this->sCatchAllFunction = $mFunction[0];
  283. $this->aObjects[$mFunction[0]] = array_slice($mFunction, 1);
  284. }
  285. else {
  286. $this->sCatchAllFunction = $mFunction;
  287. }
  288. }
  289. // registerPreFunction() registers a PHP function to be called before xajax calls
  290. // the requested function. xajax will automatically add the request function's response
  291. // to the pre-function's response to create a single response. Another feature is
  292. // the ability to return not just a response, but an array with the first element
  293. // being false (a boolean) and the second being the response. In this case, the
  294. // pre-function's response will be returned to the browser without xajax calling
  295. // the requested function.
  296. // $mFunction is a string containing the function name or an object callback array
  297. // see registerFunction() for more info on object callback arrays
  298. // usage $xajax->registerPreFunction("myPreFunction");
  299. function registerPreFunction($mFunction)
  300. {
  301. if (is_array($mFunction)) {
  302. $this->sPreFunction = $mFunction[0];
  303. $this->aObjects[$mFunction[0]] = array_slice($mFunction, 1);
  304. }
  305. else {
  306. $this->sPreFunction = $mFunction;
  307. }
  308. }
  309. // returns true if xajax can process the request, false if otherwise
  310. // you can use this to determine if xajax needs to process the request or not
  311. function canProcessRequests()
  312. {
  313. if ($this->getRequestMode() != -1) return true;
  314. return false;
  315. }
  316. // returns the current request mode, or -1 if there is none
  317. function getRequestMode()
  318. {
  319. if (!empty($_GET["xajax"]))
  320. return XAJAX_GET;
  321. if (!empty($_POST["xajax"]))
  322. return XAJAX_POST;
  323. return -1;
  324. }
  325. // processRequests() is the main communications engine of xajax
  326. // The engine handles all incoming xajax requests, calls the apporiate PHP functions
  327. // and passes the xml responses back to the javascript response handler
  328. // if your RequestURI is the same as your web page then this function should
  329. // be called before any headers or html has been sent.
  330. // usage: $xajax->processRequests()
  331. function processRequests()
  332. {
  333. $requestMode = -1;
  334. $sFunctionName = "";
  335. $bFoundFunction = true;
  336. $bFunctionIsCatchAll = false;
  337. $sFunctionNameForSpecial = "";
  338. $aArgs = array();
  339. $sPreResponse = "";
  340. $bEndRequest = false;
  341. $sResponse = "";
  342. $requestMode = $this->getRequestMode();
  343. if ($requestMode == -1) return;
  344. if ($requestMode == XAJAX_POST)
  345. {
  346. $sFunctionName = $_POST["xajax"];
  347. if (!empty($_POST["xajaxargs"]))
  348. $aArgs = $_POST["xajaxargs"];
  349. }
  350. else
  351. {
  352. header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  353. header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  354. header ("Cache-Control: no-cache, must-revalidate");
  355. header ("Pragma: no-cache");
  356. $sFunctionName = $_GET["xajax"];
  357. if (!empty($_GET["xajaxargs"]))
  358. $aArgs = $_GET["xajaxargs"];
  359. }
  360. // Use xajax error handler if necessary
  361. if ($this->bErrorHandler) {
  362. $GLOBALS['xajaxErrorHandlerText'] = "";
  363. set_error_handler("xajaxErrorHandler");
  364. }
  365. if ($this->sPreFunction) {
  366. if (!$this->_isFunctionCallable($this->sPreFunction)) {
  367. $bFoundFunction = false;
  368. $objResponse = new xajaxResponse();
  369. $objResponse->addAlert("Unknown Pre-Function ". $this->sPreFunction);
  370. $sResponse = $objResponse->getXML();
  371. }
  372. }
  373. //include any external dependencies associated with this function name
  374. if (array_key_exists($sFunctionName,$this->aFunctionIncludeFiles))
  375. {
  376. ob_start();
  377. include_once($this->aFunctionIncludeFiles[$sFunctionName]);
  378. ob_end_clean();
  379. }
  380. if ($bFoundFunction) {
  381. $sFunctionNameForSpecial = $sFunctionName;
  382. if (!array_key_exists($sFunctionName, $this->aFunctions))
  383. {
  384. if ($this->sCatchAllFunction) {
  385. $sFunctionName = $this->sCatchAllFunction;
  386. $bFunctionIsCatchAll = true;
  387. }
  388. else {
  389. $bFoundFunction = false;
  390. $objResponse = new xajaxResponse();
  391. $objResponse->addAlert("Unknown Function $sFunctionName.");
  392. $sResponse = $objResponse->getXML();
  393. }
  394. }
  395. else if ($this->aFunctionRequestTypes[$sFunctionName] != $requestMode)
  396. {
  397. $bFoundFunction = false;
  398. $objResponse = new xajaxResponse();
  399. $objResponse->addAlert("Incorrect Request Type.");
  400. $sResponse = $objResponse->getXML();
  401. }
  402. }
  403. if ($bFoundFunction)
  404. {
  405. for ($i = 0; $i < sizeof($aArgs); $i++)
  406. {
  407. // If magic quotes is on, then we need to strip the slashes from the args
  408. if (get_magic_quotes_gpc() == 1 && is_string($aArgs[$i])) {
  409. $aArgs[$i] = stripslashes($aArgs[$i]);
  410. }
  411. if (stristr($aArgs[$i],"<xjxobj>") != false)
  412. {
  413. $aArgs[$i] = $this->_xmlToArray("xjxobj",$aArgs[$i]);
  414. }
  415. else if (stristr($aArgs[$i],"<xjxquery>") != false)
  416. {
  417. $aArgs[$i] = $this->_xmlToArray("xjxquery",$aArgs[$i]);
  418. }
  419. else if ($this->bDecodeUTF8Input)
  420. {
  421. $aArgs[$i] = $this->_decodeUTF8Data($aArgs[$i]);
  422. }
  423. }
  424. if ($this->sPreFunction) {
  425. $mPreResponse = $this->_callFunction($this->sPreFunction, array($sFunctionNameForSpecial, $aArgs));
  426. if (is_array($mPreResponse) && $mPreResponse[0] === false) {
  427. $bEndRequest = true;
  428. $sPreResponse = $mPreResponse[1];
  429. }
  430. else {
  431. $sPreResponse = $mPreResponse;
  432. }
  433. if (is_a($sPreResponse, "xajaxResponse")) {
  434. $sPreResponse = $sPreResponse->getXML();
  435. }
  436. if ($bEndRequest) $sResponse = $sPreResponse;
  437. }
  438. if (!$bEndRequest) {
  439. if (!$this->_isFunctionCallable($sFunctionName)) {
  440. $objResponse = new xajaxResponse();
  441. $objResponse->addAlert("The Registered Function $sFunctionName Could Not Be Found.");
  442. $sResponse = $objResponse->getXML();
  443. }
  444. else {
  445. if ($bFunctionIsCatchAll) {
  446. $aArgs = array($sFunctionNameForSpecial, $aArgs);
  447. }
  448. $sResponse = $this->_callFunction($sFunctionName, $aArgs);
  449. }
  450. if (is_a($sResponse, "xajaxResponse")) {
  451. $sResponse = $sResponse->getXML();
  452. }
  453. if (!is_string($sResponse) || strpos($sResponse, "<xjx>") === FALSE) {
  454. $objResponse = new xajaxResponse();
  455. $objResponse->addAlert("No XML Response Was Returned By Function $sFunctionName.");
  456. $sResponse = $objResponse->getXML();
  457. }
  458. else if ($sPreResponse != "") {
  459. $sNewResponse = new xajaxResponse($this->sEncoding, $this->bOutputEntities);
  460. $sNewResponse->loadXML($sPreResponse);
  461. $sNewResponse->loadXML($sResponse);
  462. $sResponse = $sNewResponse->getXML();
  463. }
  464. }
  465. }
  466. $sContentHeader = "Content-type: text/xml;";
  467. if ($this->sEncoding && strlen(trim($this->sEncoding)) > 0)
  468. $sContentHeader .= " charset=".$this->sEncoding;
  469. header($sContentHeader);
  470. if ($this->bErrorHandler && !empty( $GLOBALS['xajaxErrorHandlerText'] )) {
  471. $sErrorResponse = new xajaxResponse();
  472. $sErrorResponse->addAlert("** PHP Error Messages: **" . $GLOBALS['xajaxErrorHandlerText']);
  473. if ($this->sLogFile) {
  474. $fH = @fopen($this->sLogFile, "a");
  475. if (!$fH) {
  476. $sErrorResponse->addAlert("** Logging Error **\n\nxajax was unable to write to the error log file:\n" . $this->sLogFile);
  477. }
  478. else {
  479. fwrite($fH, "** xajax Error Log - " . strftime("%b %e %Y %I:%M:%S %p") . " **" . $GLOBALS['xajaxErrorHandlerText'] . "\n\n\n");
  480. fclose($fH);
  481. }
  482. }
  483. $sErrorResponse->loadXML($sResponse);
  484. $sResponse = $sErrorResponse->getXML();
  485. }
  486. if ($this->bCleanBuffer) @ob_get_clean();
  487. print $sResponse;
  488. if ($this->bErrorHandler) restore_error_handler();
  489. if ($this->bExitAllowed)
  490. exit();
  491. }
  492. // printJavascript() prints the xajax javascript code into your page by printing
  493. // the output of the getJavascript() method. It should only be called between the
  494. // <head> </head> tags in your HTML page. Remember, if you only want to obtain the
  495. // result of this function, use getJavascript() instead.
  496. // $sJsURI is the relative address of the folder where xajax has been installed.
  497. // For instance, if your PHP file is "http://www.myserver.com/myfolder/mypage.php"
  498. // and xajax was installed in "http://www.myserver.com/anotherfolder", then
  499. // $sJsURI should be set to "../anotherfolder". Defaults to assuming xajax is in
  500. // the same folder as your PHP file.
  501. // $sJsFile is the relative folder/file pair of the xajax Javascript engine located
  502. // within the xajax installation folder. Defaults to xajax_js/xajax.js.
  503. // usage:
  504. // <head>
  505. // ...
  506. // < ?php $xajax->printJavascript(); ? >
  507. function printJavascript($sJsURI="", $sJsFile=NULL)
  508. {
  509. print $this->getJavascript($sJsURI, $sJsFile);
  510. }
  511. // getJavascript() returns the xajax javascript code that should be added to
  512. // your HTML page between the <head> </head> tags. See printJavascript()
  513. // for information about the function arguments.
  514. // usage:
  515. // < ?php $xajaxJSHead = $xajax->getJavascript(); ? >
  516. // <head>
  517. // ...
  518. // < ?php echo $xajaxJSHead; ? >
  519. function getJavascript($sJsURI="", $sJsFile=NULL)
  520. {
  521. $html = $this->getJavascriptConfig();
  522. $html .= $this->getJavascriptInclude($sJsURI, $sJsFile);
  523. return $html;
  524. }
  525. // getJavascriptConfig() returns a string containing inline Javascript that sets
  526. // up the xajax runtime
  527. function getJavascriptConfig()
  528. {
  529. $html = "\t<script type=\"text/javascript\"><!--//--><![CDATA[//><!--\n";
  530. $html .= "var xajaxRequestUri=\"".$this->sRequestURI."\";\n";
  531. $html .= "var xajaxDebug=".($this->bDebug?"true":"false").";\n";
  532. $html .= "var xajaxStatusMessages=".($this->bStatusMessages?"true":"false").";\n";
  533. $html .= "var xajaxWaitCursor=".($this->bWaitCursor?"true":"false").";\n";
  534. $html .= "var xajaxDefinedGet=".XAJAX_GET.";\n";
  535. $html .= "var xajaxDefinedPost=".XAJAX_POST.";\n";
  536. $html .= "var xajaxLoaded=false;\n";
  537. foreach($this->aFunctions as $sFunction => $bExists) {
  538. $html .= $this->_wrap($sFunction,$this->aFunctionRequestTypes[$sFunction]);
  539. }
  540. $html .= "\t//--><!]]></script>\n";
  541. return $html;
  542. }
  543. // getJavascriptInclude() returns a string containing a Javascript include of the
  544. // xajax.js file along with a check to see if the file loaded after six seconds
  545. function getJavascriptInclude($sJsURI="./xajax/", $sJsFile=NULL)
  546. {
  547. if ($sJsFile == NULL) $sJsFile = "../../lib/common/xajax/xajax_js/xajax.js";
  548. // \ajax\xajax\xajax_js
  549. //if ($sJsURI != "" && substr($sJsURI, -1) != "/") $sJsURI .= "xajax/";
  550. //$html = "\t<script type=\"text/javascript\" src=\"" . $sJsURI . $sJsFile . "\"></script>\n";
  551. $html = "\t<script type=\"text/javascript\" src=\"../../lib/common/xajax/xajax_js/xajax.js\"></script>\n";
  552. $html .= "\t<script type=\"text/javascript\"><!--//--><![CDATA[//><!--\n";
  553. $html .= "window.setTimeout(function () { if (!xajaxLoaded) { alert('Error: the xajax Javascript file could not be included. Perhaps the URL is incorrect?\\nURL: {$sJsURI}{$sJsFile}'); } }, 4000);\n";
  554. $html .= "\t//--><!]]></script>\n";
  555. return $html;
  556. }
  557. // autoCompressJavascript() can be used to create a new xajax.js file out of the
  558. // xajax_uncompressed.js file (which will only happen if xajax.js doesn't already
  559. // exist on the filesystem).
  560. // $sJsFullFilename is an optional argument containing the full server file path
  561. // of xajax.js.
  562. function autoCompressJavascript($sJsFullFilename=NULL)
  563. {
  564. $sJsFile = "xajax_js/xajax.js";
  565. if ($sJsFullFilename) {
  566. $realJsFile = $sJsFullFilename;
  567. }
  568. else {
  569. $realPath = realpath(dirname(__FILE__));
  570. $realJsFile = $realPath . "/". $sJsFile;
  571. }
  572. // Create a compressed file if necessary
  573. if (!file_exists($realJsFile)) {
  574. $srcFile = str_replace(".js", "_uncompressed.js", $realJsFile);
  575. if (!file_exists($srcFile)) {
  576. trigger_error("The xajax uncompressed Javascript file could not be found in the <b>" . dirname($realJsFile) . "</b> folder. Error ", E_USER_ERROR);
  577. }
  578. require("xajaxCompress.php");
  579. $javaScript = implode('', file($srcFile));
  580. $compressedScript = xajaxCompressJavascript($javaScript);
  581. $fH = @fopen($realJsFile, "w");
  582. if (!$fH) {
  583. trigger_error("The xajax compressed javascript file could not be written in the <b>" . dirname($realJsFile) . "</b> folder. Error ", E_USER_ERROR);
  584. }
  585. else {
  586. fwrite($fH, $compressedScript);
  587. fclose($fH);
  588. }
  589. }
  590. }
  591. // _detectURL() returns the current URL based upon the SERVER vars
  592. // used internally
  593. function _detectURI() {
  594. $aURL = array();
  595. // Try to get the request URL
  596. if (!empty($_SERVER['REQUEST_URI'])) {
  597. $aURL = parse_url($_SERVER['REQUEST_URI']);
  598. }
  599. // Fill in the empty values
  600. if (empty($aURL['scheme'])) {
  601. if (!empty($_SERVER['HTTP_SCHEME'])) {
  602. $aURL['scheme'] = $_SERVER['HTTP_SCHEME'];
  603. } else {
  604. $aURL['scheme'] = (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') ? 'https' : 'http';
  605. }
  606. }
  607. if (empty($aURL['host'])) {
  608. if (!empty($_SERVER['HTTP_HOST'])) {
  609. if (strpos($_SERVER['HTTP_HOST'], ':') > 0) {
  610. list($aURL['host'], $aURL['port']) = explode(':', $_SERVER['HTTP_HOST']);
  611. } else {
  612. $aURL['host'] = $_SERVER['HTTP_HOST'];
  613. }
  614. } else if (!empty($_SERVER['SERVER_NAME'])) {
  615. $aURL['host'] = $_SERVER['SERVER_NAME'];
  616. } else {
  617. print "xajax Error: xajax failed to automatically identify your Request URI.";
  618. print "Please set the Request URI explicitly when you instantiate the xajax object.";
  619. exit();
  620. }
  621. }
  622. if (empty($aURL['port']) && !empty($_SERVER['SERVER_PORT'])) {
  623. $aURL['port'] = $_SERVER['SERVER_PORT'];
  624. }
  625. if (empty($aURL['path'])) {
  626. if (!empty($_SERVER['PATH_INFO'])) {
  627. $sPath = parse_url($_SERVER['PATH_INFO']);
  628. } else {
  629. $sPath = parse_url($_SERVER['PHP_SELF']);
  630. }
  631. $aURL['path'] = $sPath['path'];
  632. unset($sPath);
  633. }
  634. if (!empty($aURL['query'])) {
  635. $aURL['query'] = '?'.$aURL['query'];
  636. }
  637. // Build the URL: Start with scheme, user and pass
  638. $sURL = $aURL['scheme'].'://';
  639. if (!empty($aURL['user'])) {
  640. $sURL.= $aURL['user'];
  641. if (!empty($aURL['pass'])) {
  642. $sURL.= ':'.$aURL['pass'];
  643. }
  644. $sURL.= '@';
  645. }
  646. // Add the host
  647. $sURL.= $aURL['host'];
  648. // Add the port if needed
  649. if (!empty($aURL['port']) && (($aURL['scheme'] == 'http' && $aURL['port'] != 80) || ($aURL['scheme'] == 'https' && $aURL['port'] != 443))) {
  650. $sURL.= ':'.$aURL['port'];
  651. }
  652. // Add the path and the query string
  653. $sURL.= $aURL['path'].@$aURL['query'];
  654. // Clean up
  655. unset($aURL);
  656. return $sURL;
  657. }
  658. // returns true if the function name is associated with an object callback,
  659. // false if not.
  660. // user internally
  661. function _isObjectCallback($sFunction)
  662. {
  663. if (array_key_exists($sFunction, $this->aObjects)) return true;
  664. return false;
  665. }
  666. // return true if the function or object callback can be called, false if not
  667. // user internally
  668. function _isFunctionCallable($sFunction)
  669. {
  670. if ($this->_isObjectCallback($sFunction)) {
  671. if (is_object($this->aObjects[$sFunction][0])) {
  672. return method_exists($this->aObjects[$sFunction][0], $this->aObjects[$sFunction][1]);
  673. }
  674. else {
  675. return is_callable($this->aObjects[$sFunction]);
  676. }
  677. }
  678. else {
  679. return function_exists($sFunction);
  680. }
  681. }
  682. // calls the function, class method, or object method with the supplied arguments
  683. // user internally
  684. function _callFunction($sFunction, $aArgs)
  685. {
  686. if ($this->_isObjectCallback($sFunction)) {
  687. $mReturn = call_user_func_array($this->aObjects[$sFunction], $aArgs);
  688. }
  689. else {
  690. $mReturn = call_user_func_array($sFunction, $aArgs);
  691. }
  692. return $mReturn;
  693. }
  694. // generates the javascript wrapper for the specified PHP function
  695. // used internally
  696. function _wrap($sFunction,$sRequestType=XAJAX_POST)
  697. {
  698. $js = "function ".$this->sWrapperPrefix."$sFunction(){return xajax.call(\"$sFunction\", arguments, ".$sRequestType.");}\n";
  699. return $js;
  700. }
  701. // _xmlToArray() takes a string containing xajax xjxobj xml or xjxquery xml
  702. // and builds an array representation of it to pass as an argument to
  703. // the php function being called. Returns an array.
  704. // used internally
  705. function _xmlToArray($rootTag, $sXml)
  706. {
  707. $aArray = array();
  708. $sXml = str_replace("<$rootTag>","<$rootTag>|~|",$sXml);
  709. $sXml = str_replace("</$rootTag>","</$rootTag>|~|",$sXml);
  710. $sXml = str_replace("<e>","<e>|~|",$sXml);
  711. $sXml = str_replace("</e>","</e>|~|",$sXml);
  712. $sXml = str_replace("<k>","<k>|~|",$sXml);
  713. $sXml = str_replace("</k>","|~|</k>|~|",$sXml);
  714. $sXml = str_replace("<v>","<v>|~|",$sXml);
  715. $sXml = str_replace("</v>","|~|</v>|~|",$sXml);
  716. $sXml = str_replace("<q>","<q>|~|",$sXml);
  717. $sXml = str_replace("</q>","|~|</q>|~|",$sXml);
  718. $this->aObjArray = explode("|~|",$sXml);
  719. $this->iPos = 0;
  720. $aArray = $this->_parseObjXml($rootTag);
  721. if ($this->bDecodeUTF8Input)
  722. {
  723. foreach ($aArray as $sKey => $sValue)
  724. {
  725. $aArray[$sKey] = $this->_decodeUTF8Data($sValue);
  726. }
  727. }
  728. return $aArray;
  729. }
  730. // _parseObjXml() is a recursive function that generates an array from the
  731. // contents of $this->aObjArray. Returns an array.
  732. // used internally
  733. function _parseObjXml($rootTag)
  734. {
  735. $aArray = array();
  736. if ($rootTag == "xjxobj")
  737. {
  738. while(!stristr($this->aObjArray[$this->iPos],"</xjxobj>"))
  739. {
  740. $this->iPos++;
  741. if(stristr($this->aObjArray[$this->iPos],"<e>"))
  742. {
  743. $key = "";
  744. $value = null;
  745. $this->iPos++;
  746. while(!stristr($this->aObjArray[$this->iPos],"</e>"))
  747. {
  748. if(stristr($this->aObjArray[$this->iPos],"<k>"))
  749. {
  750. $this->iPos++;
  751. while(!stristr($this->aObjArray[$this->iPos],"</k>"))
  752. {
  753. $key .= $this->aObjArray[$this->iPos];
  754. $this->iPos++;
  755. }
  756. }
  757. if(stristr($this->aObjArray[$this->iPos],"<v>"))
  758. {
  759. $this->iPos++;
  760. while(!stristr($this->aObjArray[$this->iPos],"</v>"))
  761. {
  762. if(stristr($this->aObjArray[$this->iPos],"<xjxobj>"))
  763. {
  764. $value = $this->_parseObjXml("xjxobj");
  765. $this->iPos++;
  766. }
  767. else
  768. {
  769. $value .= $this->aObjArray[$this->iPos];
  770. }
  771. $this->iPos++;
  772. }
  773. }
  774. $this->iPos++;
  775. }
  776. $aArray[$key]=$value;
  777. }
  778. }
  779. }
  780. if ($rootTag == "xjxquery")
  781. {
  782. $sQuery = "";
  783. $this->iPos++;
  784. while(!stristr($this->aObjArray[$this->iPos],"</xjxquery>"))
  785. {
  786. if (stristr($this->aObjArray[$this->iPos],"<q>") || stristr($this->aObjArray[$this->iPos],"</q>"))
  787. {
  788. $this->iPos++;
  789. continue;
  790. }
  791. $sQuery .= $this->aObjArray[$this->iPos];
  792. $this->iPos++;
  793. }
  794. parse_str($sQuery, $aArray);
  795. // If magic quotes is on, then we need to strip the slashes from the
  796. // array values because of the parse_str pass which adds slashes
  797. if (get_magic_quotes_gpc() == 1) {
  798. $newArray = array();
  799. foreach ($aArray as $sKey => $sValue) {
  800. if (is_string($sValue))
  801. $newArray[$sKey] = stripslashes($sValue);
  802. else
  803. $newArray[$sKey] = $sValue;
  804. }
  805. $aArray = $newArray;
  806. }
  807. }
  808. return $aArray;
  809. }
  810. function _decodeUTF8Data($sData)
  811. {
  812. $sValue = $sData;
  813. if ($this->bDecodeUTF8Input)
  814. {
  815. $sFuncToUse = NULL;
  816. if (function_exists('iconv'))
  817. {
  818. $sFuncToUse = "iconv";
  819. }
  820. else if (function_exists('mb_convert_encoding'))
  821. {
  822. $sFuncToUse = "mb_convert_encoding";
  823. }
  824. else if ($this->sEncoding == "ISO-8859-1")
  825. {
  826. $sFuncToUse = "utf8_decode";
  827. }
  828. else
  829. {
  830. trigger_error("The incoming xajax data could not be converted from UTF-8", E_USER_NOTICE);
  831. }
  832. if ($sFuncToUse)
  833. {
  834. if (is_string($sValue))
  835. {
  836. if ($sFuncToUse == "iconv")
  837. {
  838. $sValue = iconv("UTF-8", $this->sEncoding.'//TRANSLIT', $sValue);
  839. }
  840. else if ($sFuncToUse == "mb_convert_encoding")
  841. {
  842. $sValue = mb_convert_encoding($sValue, $this->sEncoding, "UTF-8");
  843. }
  844. else
  845. {
  846. $sValue = utf8_decode($sValue);
  847. }
  848. }
  849. }
  850. }
  851. return $sValue;
  852. }
  853. }// end class xajax
  854. // xajaxErrorHandler() is registered with PHP's set_error_handler() function if
  855. // the xajax error handling system is turned on
  856. // used by the xajax class
  857. function xajaxErrorHandler($errno, $errstr, $errfile, $errline)
  858. {
  859. $errorReporting = error_reporting();
  860. if (($errno & $errorReporting) == 0) return;
  861. if ($errno == E_NOTICE) {
  862. $errTypeStr = "NOTICE";
  863. }
  864. else if ($errno == E_WARNING) {
  865. $errTypeStr = "WARNING";
  866. }
  867. else if ($errno == E_USER_NOTICE) {
  868. $errTypeStr = "USER NOTICE";
  869. }
  870. else if ($errno == E_USER_WARNING) {
  871. $errTypeStr = "USER WARNING";
  872. }
  873. else if ($errno == E_USER_ERROR) {
  874. $errTypeStr = "USER FATAL ERROR";
  875. }
  876. else if ($errno == E_STRICT) {
  877. return;
  878. }
  879. else {
  880. $errTypeStr = "UNKNOWN: $errno";
  881. }
  882. $GLOBALS['xajaxErrorHandlerText'] .= "\n----\n[$errTypeStr] $errstr\nerror in line $errline of file $errfile";
  883. }
  884. ?>