[ Index ]
 

Code source de eGroupWare 1.2.106-2

Accédez au Source d'autres logiciels libresSoutenez Angelica Josefina !

title

Body

[fermer]

/phpgwapi/inc/ -> xajax.inc.php (source)

   1  <?php
   2  ///////////////////////////////////////////////////////////////////////////////
   3  // xajax version 0.1 beta4
   4  // copyright (c) 2005 by J. Max Wilson
   5  // http://xajax.sourceforge.net
   6  //
   7  //
   8  // xajax is an open source PHP class library for easily creating powerful
   9  // PHP-driven, web-based AJAX Applications. Using xajax, you can asynchronously
  10  // call PHP functions and update the content of your your webpage without
  11  // reloading the page.
  12  //
  13  // xajax is released under the terms of the LGPL license
  14  // http://www.gnu.org/copyleft/lesser.html#SEC3
  15  //
  16  // This library is free software; you can redistribute it and/or
  17  // modify it under the terms of the GNU Lesser General Public
  18  // License as published by the Free Software Foundation; either
  19  // version 2.1 of the License, or (at your option) any later version.
  20  //
  21  // This library is distributed in the hope that it will be useful,
  22  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  23  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  24  // Lesser General Public License for more details.
  25  // 
  26  // You should have received a copy of the GNU Lesser General Public
  27  // License along with this library; if not, write to the Free Software
  28  // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  29  ///////////////////////////////////////////////////////////////////////////////
  30  
  31  // The xajaxResponse class is used to created responses to be sent back to your
  32  // webpage.  A response contains one or more command messages for updating your page.
  33  // Currently xajax supports five kinds of command messages:
  34  // * Assign - sets the specified attribute of an element in your page
  35  // * Append - appends data to the end of the specified attribute of an element in your page
  36  // * Prepend - prepends data to teh beginning of the specified attribute of an element in your page
  37  // * Replace - searches for and replaces data in the specified attribute of an element in your page
  38  // * Script - runs JavaScript
  39  // * Alert - shows an alert box with the suplied message text
  40  // elements are identified by their HTML id
  41  class xajaxResponse
  42  {
  43      var $xml;
  44  
  45      // Constructor
  46  	function xajaxResponse()
  47      {
  48          $this->charset = is_object($GLOBALS['egw']->translation) ? $GLOBALS['egw']->translation->charset() : 'UTF-8';
  49          //error_log("xajaxResponse: charset=$this->charset");
  50          $this->xml = "<?xml version=\"1.0\" encoding=\"$this->charset\"?>";
  51          $this->xml .= "<xajax>";
  52      }
  53      
  54      // addAssign() adds an assign command message to your xml response
  55      // $sTarget is a string containing the id of an HTML element
  56      // $sAttribute is the part of the element you wish to modify ("innerHTML", "value", etc.)
  57      // $sData is the data you want to set the attribute to
  58      // usage: $objResponse->addAssign("contentDiv","innerHTML","Some Text");
  59  	function addAssign($sTarget,$sAttribute,$sData)
  60      {
  61          $this->xml .= "<update action=\"assign\">";
  62          $this->xml .= "<target attribute=\"$sAttribute\">$sTarget</target>";
  63          $this->xml .= "<data><![CDATA[$sData]]></data>";
  64          $this->xml .= "</update>";
  65      }
  66      
  67      // addAppend() adds an append command message to your xml response
  68      // $sTarget is a string containing the id of an HTML element
  69      // $sAttribute is the part of the element you wish to modify ("innerHTML", "value", etc.)
  70      // $sData is the data you want to append to the end of the attribute
  71      // usage: $objResponse->addAppend("contentDiv","innerHTML","Some Text");
  72  	function addAppend($sTarget,$sAttribute,$sData)
  73      {
  74          $this->xml .= "<update action=\"append\">";
  75          $this->xml .= "<target attribute=\"$sAttribute\">$sTarget</target>";
  76          $this->xml .= "<data><![CDATA[$sData]]></data>";
  77          $this->xml .= "</update>";
  78      }
  79      
  80      // addPrepend() adds an prepend command message to your xml response
  81      // $sTarget is a string containing the id of an HTML element
  82      // $sAttribute is the part of the element you wish to modify ("innerHTML", "value", etc.)
  83      // $sData is the data you want to prepend to the beginning of the attribute
  84      // usage: $objResponse->addPrepend("contentDiv","innerHTML","Some Text");
  85  	function addPrepend($sTarget,$sAttribute,$sData)
  86      {
  87          $this->xml .= "<update action=\"prepend\">";
  88          $this->xml .= "<target attribute=\"$sAttribute\">$sTarget</target>";
  89          $this->xml .= "<data><![CDATA[$sData]]></data>";
  90          $this->xml .= "</update>";
  91      }
  92      
  93      // addReplace() adds an replace command message to your xml response
  94      // $sTarget is a string containing the id of an HTML element
  95      // $sAttribute is the part of the element you wish to modify ("innerHTML", "value", etc.)
  96      // $sSearch is a string to search for
  97      // $sData is a string to replace the search string when found in the attribute
  98      // usage: $objResponse->addReplace("contentDiv","innerHTML","text","<b>text</b>");
  99  	function addReplace($sTarget,$sAttribute,$sSearch,$sData)
 100      {
 101          $this->xml .= "<update action=\"replace\">";
 102          $this->xml .= "<target attribute=\"$sAttribute\">$sTarget</target>";
 103          $this->xml .= "<search><![CDATA[$sSearch]]></search>";
 104          $this->xml .= "<data><![CDATA[$sData]]></data>";
 105          $this->xml .= "</update>";
 106      }
 107      
 108      // addClear() adds an clear command message to your xml response
 109      // $sTarget is a string containing the id of an HTML element
 110      // $sAttribute is the part of the element you wish to clear ("innerHTML", "value", etc.)
 111      // usage: $objResponse->addClear("contentDiv","innerHTML");
 112  	function addClear($sTarget,$sAttribute)
 113      {
 114          $this->xml .= "<update action=\"clear\">";
 115          $this->xml .= "<target attribute=\"$sAttribute\">$sTarget</target>";
 116          $this->xml .= "</update>";
 117      }
 118      
 119      // addAlert() adds an alert command message to your xml response
 120      // $sMsg is a text to be displayed in the alert box
 121      // usage: $objResponse->addAlert("This is some text");
 122  	function addAlert($sMsg)
 123      {
 124          $this->xml .= "<alert><![CDATA[$sMsg]]></alert>";
 125      }
 126  
 127      // addScript() adds a jscript command message to your xml response
 128      // $sJS is a string containing javascript code to be executed
 129      // usage: $objResponse->addAlert("var x = prompt('get some text');");
 130  	function addScript($sJS)
 131      {
 132          $this->xml .= "<jscript><![CDATA[$sJS]]></jscript>";
 133      }
 134      
 135      // addRemove() adds a Remove Element command message to your xml response
 136      // $sTarget is a string containing the id of an HTML element to be removed
 137      // from your page
 138      // usage: $objResponse->addRemove("Div2");
 139  	function addRemove($sTarget)
 140      {
 141          $this->xml .= "<update action=\"remove\">";
 142          $this->xml .= "<target>$sTarget</target>";
 143          $this->xml .= "</update>";
 144      }
 145      
 146  	function addCreate($sParent, $sTag, $sId, $sType="")
 147      {
 148          $this->xml .= "<update action=\"create\">";
 149          $this->xml .= "<target attribute=\"$sTag\">$sParent</target>";
 150          $this->xml .= "<data><![CDATA[$sId]]></data>";
 151          if ($sType != "")
 152              $this->xml .= "<type><![CDATA[$sType]]></type>";
 153          $this->xml .= "</update>";
 154      }
 155      
 156      // getXML() returns the xml to be returned from your function to the xajax
 157      // processor on your page
 158      // usage: $objResponse->getXML();
 159  	function getXML()
 160      {
 161          if (strstr($this->xml,"</xajax>") == false)
 162              $this->xml .= "</xajax>";
 163          
 164          return $this->xml; 
 165      }
 166  }// end class xajaxResponse
 167  
 168  // Communication Method Defines
 169  if (!defined ('GET'))
 170  {
 171      define ('GET', 0);
 172  }
 173  if (!defined ('POST'))
 174  {
 175      define ('POST', 1);
 176  }
 177  
 178  // the xajax class generates the xajax javascript for your page including the 
 179  // javascript wrappers for the PHP functions that you want to call from your page.
 180  // It also handles processing and executing the command messages in the xml responses
 181  // sent back to your page from your PHP functions.
 182  class xajax
 183  {
 184      var $aFunctions;            // Array of PHP functions that will be callable through javascript wrappers
 185      var $aFunctionRequestTypes;    // Array of RequestTypes to be used with each function (key=function name)
 186      var $sRequestURI;            // The URI for making requests to the xajax object
 187      var $bDebug;                // Show debug messages true/false
 188      var $sWrapperPrefix;        // The prefix to prepend to the javascript wraper function name
 189      var $bStatusMessages;        // Show debug messages true/false
 190      var $aObjArray;                // Array for parsing complex objects
 191      var $iPos;                    // Position in $aObjArray
 192      
 193      // Contructor
 194      // $sRequestURI - defaults to the current page
 195      // $bDebug Mode - defaults to false
 196      // $sWrapperPrefix - defaults to "xajax_";
 197      // usage: $xajax = new xajax();
 198  	function xajax($sRequestURI="",$sWrapperPrefix="xajax_",$bDebug=false)
 199      {
 200          $this->aFunctions = array();
 201          $this->sRequestURI = $sRequestURI;
 202          if ($this->sRequestURI == "")
 203              $this->sRequestURI = $this->detectURI();
 204          $this->sWrapperPrefix = $sWrapperPrefix;
 205          $this->bDebug = $bDebug;
 206      }
 207      
 208      // detectURL() returns the current URL based upon the SERVER vars
 209      // used internally
 210  	function detectURI()
 211      {
 212          $aUri = array();
 213  
 214          if (!empty($_SERVER['REQUEST_URI']))
 215          {
 216              $aUri = parse_url($_SERVER['REQUEST_URI']);
 217          }
 218          
 219          if (empty($aUri['scheme']))
 220          {
 221              if (!empty($_SERVER['HTTP_SCHEME']))
 222              {
 223                  $aUri['scheme'] = $_SERVER['HTTP_SCHEME'];
 224              }
 225              else
 226              {
 227                  $aUri['scheme'] = (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') ? 'https' : 'http';
 228              }
 229  
 230              if (!empty($_SERVER['HTTP_HOST']))
 231              {
 232                  if (strpos($_SERVER['HTTP_HOST'], ':') > 0)
 233                  {
 234                      list($aUri['host'], $aUri['port']) = explode(':', $_SERVER['HTTP_HOST']);
 235                  }
 236                  else
 237                  {
 238                      $aUri['host'] = $_SERVER['HTTP_HOST'];
 239                  }
 240              }
 241              else if (!empty($_SERVER['SERVER_NAME']))
 242              {
 243                  $aUri['host'] = $_SERVER['SERVER_NAME'];
 244              }
 245              else
 246              {
 247                  print "xajax Error: xajax failed to automatically identify your Request URI.";
 248                  print "Please set the Request URI explicitly when you instantiate the xajax object.";
 249                  exit();
 250              }
 251  
 252              if (empty($aUri['port']) && !empty($_SERVER['SERVER_PORT']))
 253              {
 254                  $aUri['port'] = $_SERVER['SERVER_PORT'];
 255              }
 256  
 257              if (empty($aUri['path']))
 258              {
 259                  if (!empty($_SERVER['PATH_INFO']))
 260                  {
 261                      $path = parse_url($_SERVER['PATH_INFO']);
 262                  }
 263                  else
 264                  {
 265                      $path = parse_url($_SERVER['PHP_SELF']);
 266                  }
 267                  $aUri['path'] = $path['path'];
 268                  unset($path);
 269              }
 270          }
 271  
 272          $sUri = $aUri['scheme'] . '://';
 273          if (!empty($aUri['user']))
 274          {
 275              $sUri .= $aUri['user'];
 276              if (!empty($aUri['pass']))
 277              {
 278                  $sUri .= ':' . $aUri['pass'];
 279              }
 280              $sUri .= '@';
 281          }
 282          
 283          $sUri .= $aUri['host'];
 284          
 285          if (!empty($aUri['port']) && (($aUri['scheme'] == 'http' && $aUri['port'] != 80) || ($aUri['scheme'] == 'https' && $aUri['port'] != 443)))
 286          {
 287              $sUri .= ':'.$aUri['port'];
 288          }
 289          // And finally path, without script name
 290          $sUri .= substr($aUri['path'], 0, strrpos($aUri['path'], '/') + 1);
 291  
 292          unset($aUri);
 293  
 294          return $sUri.basename($_SERVER['SCRIPT_NAME']);
 295      }
 296      
 297      // setRequestURI() sets the URI to which requests will be made
 298      // usage: $xajax->setRequestURI("http://xajax.sourceforge.net");
 299  	function setRequestURI($sRequestURI)
 300      {
 301          $this->sRequestURI = $sRequestURI;
 302      }
 303      
 304      // debugOn() enables debug messages for xajax
 305      // usage: $xajax->debugOn();
 306  	function debugOn()
 307      {
 308          $this->bDebug = true;
 309      }
 310      
 311      // debugOff() disables debug messages for xajax
 312      // usage: $xajax->debugOff();
 313  	function debugOff()
 314      {
 315          $this->bDebug = false;
 316      }
 317      
 318      // statusMessagesOn() enables messages in the statusbar for xajax
 319      // usage: $xajax->statusMessagesOn();
 320  	function statusMessagesOn()
 321      {
 322          $this->bStatusMessages = true;
 323      }
 324      
 325      // statusMessagesOff() disables messages in the statusbar for xajax
 326      // usage: $xajax->statusMessagesOff();
 327  	function statusMessagesOff()
 328      {
 329          $this->bStatusMessages = false;
 330      }
 331      
 332      // setWrapperPrefix() sets the prefix that will be appended to the javascript
 333      // wraper functions.
 334  	function setWrapperPrefix($sPrefix)
 335      {
 336          $this->sWrapperPrefix = $sPrefix;
 337      }
 338      
 339      //Dpericated.  Use registerFunction();
 340  	function addFunction($sFunction,$sRequestType=POST)
 341      {
 342          trigger_error("xajax: the <b>addFunction()</b> method has been renamed <b>registerFunction()</b>. <br />Please use ->registerFunction('$sFunction'".($sRequestType==GET?",GET":"")."); instead.",E_USER_WARNING);
 343          $this->registerFunction($sFunction,$sRequestType);
 344      }
 345      
 346      // registerFunction() registers a PHP function to be callable through xajax
 347      // $sFunction is a string containing the function name
 348      // $sRequestType is the RequestType (GET/POST) that should be used 
 349      //        for this function.  Defaults to POST.
 350      // usage: $xajax->registerFunction("myfunction",POST);
 351  	function registerFunction($sFunction,$sRequestType=POST)
 352      {
 353          $this->aFunctions[] = $sFunction;
 354          $this->aFunctionRequestTypes[$sFunction] = $sRequestType;
 355      }
 356      
 357      // generates the javascript wrapper for the specified PHP function
 358      // used internally
 359  	function wrap($sFunction,$sRequestType=POST)
 360      {
 361          $js = "function ".$this->sWrapperPrefix."$sFunction(){xajax.call(\"$sFunction\", arguments, ".$sRequestType.");}\n";        
 362          return $js;
 363      }
 364      
 365      // processRequests() is the main communications engine of xajax
 366      // The engine handles all incoming xajax requests, calls the apporiate PHP functions
 367      // and passes the xml responses back to the javascript response handler
 368      // if your RequestURI is the same as your web page then this function should
 369      // be called before any headers or html has been sent.
 370      // usage: $xajax->processRequests()
 371  	function processRequests()
 372      {    
 373          if (!empty($_GET['xajaxjs']))
 374          {
 375              header("Content-type: text/javascript");
 376              print $this->generateJavascript();
 377              exit();
 378              return;
 379          }
 380          
 381          $requestMode = -1;
 382          $sFunctionName = "";
 383          $aArgs = array();
 384          $sResponse = "";
 385          
 386          if (!empty($_GET["xajax"]))
 387              $requestMode = GET;
 388          
 389          if (!empty($_POST["xajax"]))
 390              $requestMode = POST;
 391              
 392          if ($requestMode == -1) 
 393              return;
 394      
 395          if ($requestMode == POST)
 396          {
 397              $sFunctionName = $_POST["xajax"];
 398              
 399              if (!empty($_POST["xajaxargs"])) 
 400                  $aArgs = $_POST["xajaxargs"];
 401          }
 402          else
 403          {    
 404              header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
 405              header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
 406              header ("Cache-Control: no-cache, must-revalidate");
 407              header ("Pragma: no-cache");
 408              header("Content-type: text/xml");
 409              
 410              $sFunctionName = $_GET["xajax"];
 411              
 412              if (!empty($_GET["xajaxargs"])) 
 413                  $aArgs = $_GET["xajaxargs"];
 414          }
 415          
 416          if (!in_array($sFunctionName, $this->aFunctions))
 417          {
 418              $objResponse = new xajaxResponse();
 419              $objResponse->addAlert("Unknown Function $sFunctionName.");
 420              $sResponse = $objResponse->getXML();
 421          }
 422          else if ($this->aFunctionRequestTypes[$sFunctionName] != $requestMode)
 423          {
 424              $objResponse = new xajaxResponse();
 425              $objResponse->addAlert("Incorrect Request Type.");
 426              $sResponse = $objResponse->getXML();
 427          }
 428          else
 429          {
 430              for ($i = 0; $i < sizeof($aArgs); $i++)
 431              {
 432                  if (stristr($aArgs[$i],"<xjxobj>") != false)
 433                  {
 434                      $aArgs[$i] = $this->xmlToArray("xjxobj",$aArgs[$i]);    
 435                  }
 436                  else if (stristr($aArgs[$i],"<xjxquery>") != false)
 437                  {
 438                      $aArgs[$i] = $this->xmlToArray("xjxquery",$aArgs[$i]);    
 439                  }
 440              }
 441              $sResponse = call_user_func_array($sFunctionName, $aArgs);
 442          }
 443          
 444          header("Content-type: text/xml; charset=$this->charset");
 445          print $sResponse;
 446          
 447          exit();
 448      }
 449      
 450      // xmlToArray() takes a string containing xajax xjxobj xml or xjxquery xml
 451      // and builds an array representation of it to pass as an argument to
 452      // the php function being called. Returns an array.
 453      // used internally
 454  	function xmlToArray($rootTag, $sXml)
 455      {
 456          $aArray = array();
 457          $sXml = str_replace("<$rootTag>","<$rootTag>|~|",$sXml);
 458          $sXml = str_replace("</$rootTag>","</$rootTag>|~|",$sXml);
 459          $sXml = str_replace("<e>","<e>|~|",$sXml);
 460          $sXml = str_replace("</e>","</e>|~|",$sXml);
 461          $sXml = str_replace("<k>","<k>|~|",$sXml);
 462          $sXml = str_replace("</k>","|~|</k>|~|",$sXml);
 463          $sXml = str_replace("<v>","<v>|~|",$sXml);
 464          $sXml = str_replace("</v>","|~|</v>|~|",$sXml);
 465          $sXml = str_replace("<q>","<q>|~|",$sXml);
 466          $sXml = str_replace("</q>","|~|</q>|~|",$sXml);
 467          
 468          $this->aObjArray = explode("|~|",$sXml);
 469          
 470          $this->iPos = 0;
 471          $aArray = $this->parseObjXml($rootTag);
 472          
 473          return $aArray;
 474      }
 475      
 476      // parseObjXml() is a recursive function that generates an array from the
 477      // contents of $this->aObjArray. Returns an array.
 478      // used internally
 479  	function parseObjXml($rootTag)
 480      {
 481          $aArray = array();
 482          
 483          if ($rootTag == "xjxobj")
 484          {
 485              while(!stristr($this->aObjArray[$this->iPos],"</xjxobj>"))
 486              {
 487                  $this->iPos++;
 488                  if(stristr($this->aObjArray[$this->iPos],"<e>"))
 489                  {
 490                      $key = "";
 491                      $value = null;
 492                          
 493                      $this->iPos++;
 494                      while(!stristr($this->aObjArray[$this->iPos],"</e>"))
 495                      {
 496                          if(stristr($this->aObjArray[$this->iPos],"<k>"))
 497                          {
 498                              $this->iPos++;
 499                              while(!stristr($this->aObjArray[$this->iPos],"</k>"))
 500                              {
 501                                  $key .= $this->aObjArray[$this->iPos];
 502                                  $this->iPos++;
 503                              }
 504                          }
 505                          if(stristr($this->aObjArray[$this->iPos],"<v>"))
 506                          {
 507                              $this->iPos++;
 508                              while(!stristr($this->aObjArray[$this->iPos],"</v>"))
 509                              {
 510                                  if(stristr($this->aObjArray[$this->iPos],"<xjxobj>"))
 511                                  {
 512                                      $value = $this->parseObjXml("xjxobj");
 513                                      $this->iPos++;
 514                                  }
 515                                  else
 516                                  {
 517                                      $value .= $this->aObjArray[$this->iPos];
 518                                  }
 519                                  $this->iPos++;
 520                              }
 521                          }
 522                          $this->iPos++;
 523                      }
 524                      $aArray[$key]=$value;
 525                  }
 526              }
 527          }
 528          
 529          if ($rootTag == "xjxquery")
 530          {
 531              $sQuery = "";
 532              $this->iPos++;
 533              while(!stristr($this->aObjArray[$this->iPos],"</xjxquery>"))
 534              {
 535                  if (stristr($this->aObjArray[$this->iPos],"<q>") || stristr($this->aObjArray[$this->iPos],"</q>"))
 536                  {
 537                      $this->iPos++;
 538                      continue;
 539                  }
 540                  $sQuery    .= $this->aObjArray[$this->iPos];
 541                  $this->iPos++;
 542              }
 543              parse_str($sQuery, $aArray);
 544          }
 545          
 546          return $aArray;
 547      }
 548      
 549      // Depricated.  Use printJavascript();
 550  	function javascript($sJsURI="")
 551      {
 552          trigger_error("xajax: the <b>javascript()</b> method has been renamed <b>printJavascript()</b>. <br />Please use ->printJavascript(".($sJsURI==""?"":"'$sJsURI'")."); instead.",E_USER_WARNING);
 553          $this->printJavascript($sJsURI);
 554      }
 555      
 556      // printJavascript() prints the xajax javascript code into your page
 557      // it should only be called between the <head> </head> tags
 558      // usage:
 559      //    <head>
 560      //        ...
 561      //        <?php $xajax->printJavascript(); 
 562  	function printJavascript($sJsURI="")
 563      {
 564          print $this->getJavascript($sJsURI);
 565      }
 566      
 567      // getJavascript() returns the xajax javascript code that should be added to
 568      // your page between the <head> </head> tags
 569      // usage:
 570      //    <head>
 571      //        ...
 572      //        <?php $xajax->getJavascript(); 
 573  	function getJavascript($sJsURI="")
 574      {    
 575          if ($sJsURI == "")
 576              $sJsURI = $this->sRequestURI;
 577              
 578          $separator=strpos($sJsURI,'?')==false?'?':'&';
 579          
 580          $html  = "<script type=\"text/javascript\">var xajaxRequestUri=\"".$this->sRequestURI."\";</script>\n";
 581          $html .= "\t<script type=\"text/javascript\" src=\"".$sJsURI.$separator."xajaxjs=xajaxjs\"></script>\n";
 582          
 583          return $html;
 584      }
 585      
 586      // compressJavascript() compresses the javascript code for more efficient delivery
 587      // used internally 
 588      // $sJS is a string containing the javascript code to compress
 589  	function compressJavascript($sJS)
 590      {
 591          //remove windows cariage returns
 592          $sJS = str_replace("\r","",$sJS);
 593          
 594          //array to store replaced literal strings
 595          $literal_strings = array();
 596          
 597          //explode the string into lines
 598          $lines = explode("\n",$sJS);
 599          //loop through all the lines, building a new string at the same time as removing literal strings
 600          $clean = "";
 601          $inComment = false;
 602          $literal = "";
 603          $inQuote = false;
 604          $escaped = false;
 605          $quoteChar = "";
 606          
 607          for($i=0;$i<count($lines);$i++)
 608          {
 609              $line = $lines[$i];
 610              $inNormalComment = false;
 611          
 612              //loop through line's characters and take out any literal strings, replace them with ___i___ where i is the index of this string
 613              for($j=0;$j<strlen($line);$j++)
 614              {
 615                  $c = substr($line,$j,1);
 616                  $d = substr($line,$j,2);
 617          
 618                  //look for start of quote
 619                  if(!$inQuote && !$inComment)
 620                  {
 621                      //is this character a quote or a comment
 622                      if(($c=="\"" || $c=="'") && !$inComment && !$inNormalComment)
 623                      {
 624                          $inQuote = true;
 625                          $inComment = false;
 626                          $escaped = false;
 627                          $quoteChar = $c;
 628                          $literal = $c;
 629                      }
 630                      else if($d=="/*" && !$inNormalComment)
 631                      {
 632                          $inQuote = false;
 633                          $inComment = true;
 634                          $escaped = false;
 635                          $quoteChar = $d;
 636                          $literal = $d;    
 637                          $j++;    
 638                      }
 639                      else if($d=="//") //ignore string markers that are found inside comments
 640                      {
 641                          $inNormalComment = true;
 642                          $clean .= $c;
 643                      }
 644                      else
 645                      {
 646                          $clean .= $c;
 647                      }
 648                  }
 649                  else //allready in a string so find end quote
 650                  {
 651                      if($c == $quoteChar && !$escaped && !$inComment)
 652                      {
 653                          $inQuote = false;
 654                          $literal .= $c;
 655          
 656                          //subsitute in a marker for the string
 657                          $clean .= "___" . count($literal_strings) . "___";
 658          
 659                          //push the string onto our array
 660                          array_push($literal_strings,$literal);
 661          
 662                      }
 663                      else if($inComment && $d=="*/")
 664                      {
 665                          $inComment = false;
 666                          $literal .= $d;
 667          
 668                          //subsitute in a marker for the string
 669                          $clean .= "___" . count($literal_strings) . "___";
 670          
 671                          //push the string onto our array
 672                          array_push($literal_strings,$literal);
 673          
 674                          $j++;
 675                      }
 676                      else if($c == "\\" && !$escaped)
 677                          $escaped = true;
 678                      else
 679                          $escaped = false;
 680          
 681                      $literal .= $c;
 682                  }
 683              }
 684              if($inComment) $literal .= "\n";
 685              $clean .= "\n";
 686          }
 687          //explode the clean string into lines again
 688          $lines = explode("\n",$clean);
 689          
 690          //now process each line at a time
 691          for($i=0;$i<count($lines);$i++)
 692          {
 693              $line = $lines[$i];
 694          
 695              //remove comments
 696              $line = preg_replace("/\/\/(.*)/","",$line);
 697          
 698              //strip leading and trailing whitespace
 699              $line = trim($line);
 700          
 701              //remove all whitespace with a single space
 702              $line = preg_replace("/\s+/"," ",$line);
 703          
 704              //remove any whitespace that occurs after/before an operator
 705              $line = preg_replace("/\s*([!\}\{;,&=\|\-\+\*\/\)\(:])\s*/","\\1",$line);
 706          
 707              $lines[$i] = $line;
 708          }
 709          
 710          //implode the lines
 711          $sJS = implode("\n",$lines);
 712          
 713          //make sure there is a max of 1 \n after each line
 714          $sJS = preg_replace("/[\n]+/","\n",$sJS);
 715          
 716          //strip out line breaks that immediately follow a semi-colon
 717          $sJS = preg_replace("/;\n/",";",$sJS);
 718          
 719          //curly brackets aren't on their own
 720          $sJS = preg_replace("/[\n]*\{[\n]*/","{",$sJS);
 721          
 722          //finally loop through and replace all the literal strings:
 723          for($i=0;$i<count($literal_strings);$i++)
 724              $sJS = str_replace("___".$i."___",$literal_strings[$i],$sJS);
 725          
 726          return $sJS;
 727      }
 728  
 729      // generateJavascript() generates all of the xajax javascript code including the javascript
 730      // wrappers for the PHP functions specified by the registerFunction() method and the response
 731      // xml parser
 732      // used internally
 733  	function generateJavascript()
 734      {
 735          $js  = "";
 736          if ($this->bDebug){ $js .= "var xajaxDebug=".($this->bDebug?"true":"false").";\n"; }
 737          
 738          ob_start();
 739          ?>
 740  		function Xajax()
 741          {
 742              <?php if ($this->bDebug){ ?>this.DebugMessage = function(text){if (xajaxDebug) alert("Xajax Debug:\n " + text)}<?php    } ?>
 743              
 744              this.workId = 'xajaxWork'+ new Date().getTime();
 745              this.depth = 0;
 746              
 747              //Get the XMLHttpRequest Object
 748              this.getRequestObject = function()
 749              {
 750                  <?php if ($this->bDebug){ ?>this.DebugMessage("Initializing Request Object..");<?php } ?>
 751                  var req;
 752                  try
 753                  {
 754                      req=new ActiveXObject("Msxml2.XMLHTTP");
 755                  }
 756                  catch (e)
 757                  {
 758                      try
 759                      {
 760                          req=new ActiveXObject("Microsoft.XMLHTTP");
 761                      }
 762                      catch (e2)
 763                      {
 764                          req=null;
 765                      }
 766                  }
 767                  if(!req && typeof XMLHttpRequest != "undefined")
 768                      req = new XMLHttpRequest();
 769                  
 770                      <?php if ($this->bDebug){ ?>if (!req) this.DebugMessage("Request Object Instantiation failed.");<?php } ?>
 771                      
 772                  return req;
 773              }
 774  
 775              // xajax.$() is shorthand for document.getElementById()
 776              this.$ = function(sId)
 777              {
 778                  return document.getElementById(sId);
 779              }
 780              
 781              // xajax.getFormValues() builds a query string XML message from the elements of a form object
 782              this.getFormValues = function(frm)
 783              {
 784                  var objForm;
 785                  if (typeof(frm) == "string")
 786                      objForm = this.$(frm);
 787                  else
 788                      objForm = frm;
 789                  var sXml = "<xjxquery><q>";
 790                  if (objForm && objForm.tagName == 'FORM')
 791                  {
 792                      var formElements = objForm.elements;
 793                      for( var i=0; i < formElements.length; i++)
 794                      {
 795                          if ((formElements[i].type == 'radio' || formElements[i].type == 'checkbox') && formElements[i].checked == false)
 796                              continue;
 797                          var name = formElements[i].name;
 798                          if (name)
 799                          {
 800                              if (sXml != '<xjxquery><q>')
 801                                  sXml += '&';
 802                              sXml += name+"="+encodeURIComponent(formElements[i].value);
 803                          } 
 804                      }
 805                  }
 806                  
 807                  sXml +="</q></xjxquery>";
 808                  
 809                  return sXml;
 810              }
 811              
 812              // Generates an XML message that xajax can understand from a javascript object
 813              this.objectToXML = function(obj)
 814              {
 815                  var sXml = "<xjxobj>";
 816                  for (i in obj)
 817                  {
 818                      try
 819                      {
 820                          if (i == 'constructor')
 821                              continue;
 822                          if (obj[i] && typeof(obj[i]) == 'function')
 823                              continue;
 824                              
 825                          var key = i;
 826                          var value = obj[i];
 827                          if (value && typeof(value)=="object" && 
 828                              (value.constructor == Array
 829                               ) && this.depth <= 50)
 830                          {
 831                              this.depth++;
 832                              value = this.objectToXML(value);
 833                              this.depth--;
 834                          }
 835                          
 836                          sXml += "<e><k>"+key+"</k><v>"+value+"</v></e>";
 837                          
 838                      }
 839                      catch(e)
 840                      {
 841                          <?php if ($this->bDebug){ ?>this.DebugMessage(e);<?php } ?>
 842                      }
 843                  }
 844                  sXml += "</xjxobj>";
 845              
 846                  return sXml;
 847              }
 848  
 849              // Sends a XMLHttpRequest to call the specified PHP function on the server
 850              this.call = function(sFunction, aArgs, sRequestType)
 851              {
 852                  var i,r,postData;
 853                  if (document.body)
 854                      document.body.style.cursor = 'wait';
 855                  <?php if ($this->bStatusMessages == true){?>window.status = 'Sending Request...';<?php } ?>
 856                  <?php if ($this->bDebug){ ?>this.DebugMessage("Starting xajax...");<?php } ?>
 857                  var xajaxRequestType = sRequestType;
 858                  var uri = xajaxRequestUri;
 859                  var value;
 860                  switch(xajaxRequestType)
 861                  {
 862                      case <?php print GET; ?>:{
 863                          var uriGet = uri.indexOf("?")==-1?"?xajax="+encodeURIComponent(sFunction):"&xajax="+encodeURIComponent(sFunction);
 864                          for (i = 0; i<aArgs.length; i++)
 865                          {
 866                              value = aArgs[i];
 867                              if (typeof(value)=="object")
 868                                  value = this.objectToXML(value);
 869                              uriGet += "&xajaxargs[]="+encodeURIComponent(value);
 870                          }
 871                          uriGet += "&xajaxr=" + new Date().getTime();
 872                          uri += uriGet;
 873                          postData = null;
 874                          } break;
 875                      case <?php print POST; ?>:{
 876                          postData = "xajax="+encodeURIComponent(sFunction);
 877                          postData += "&xajaxr="+new Date().getTime();
 878                          for (i = 0; i <aArgs.length; i++)
 879                          {
 880                              value = aArgs[i];
 881                              if (typeof(value)=="object")
 882                                  value = this.objectToXML(value);
 883                              postData = postData+"&xajaxargs[]="+encodeURIComponent(value);
 884                          }
 885                          } break;
 886                      default:
 887                          alert("Illegal request type: " + xajaxRequestType); return false; break;
 888                  }
 889                  r = this.getRequestObject();
 890                  r.open(xajaxRequestType==<?php print GET; ?>?"GET":"POST", uri, true);
 891                  if (xajaxRequestType == <?php print POST; ?>)
 892                  {
 893                      try
 894                      {
 895                          r.setRequestHeader("Method", "POST " + uri + " HTTP/1.1");
 896                          r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 897                      }
 898                      catch(e)
 899                      {
 900                          alert("Your browser does not appear to  support asynchronous requests using POST.");
 901                          return false;
 902                      }
 903                  }
 904                  r.onreadystatechange = function()
 905                  {
 906                      if (r.readyState != 4)
 907                          return;
 908                      
 909                      if (r.status==200)
 910                      {
 911                          <?php if ($this->bDebug){ ?>xajax.DebugMessage("Received:\n" + r.responseText);<?php } ?>
 912                          var data = r.responseXML;
 913                          if (data)
 914                              xajax.processResponse(data);
 915                      }
 916                  }
 917                  <?php if ($this->bDebug){ ?>this.DebugMessage("Calling "+sFunction +" uri="+uri+" (post:"+ postData +")");<?php } ?>
 918                  r.send(postData);
 919                  <?php if ($this->bStatusMessages == true){?>window.status = 'Waiting for data...';<?php } ?>
 920                  <?php if ($this->bDebug){ ?>this.DebugMessage(sFunction + " waiting..");<?php } ?>
 921                  delete r;
 922                  return true;
 923              }
 924              
 925              // Tests if the new Data is the same as the extant data
 926              this.willChange = function(element, attribute, newData)
 927              {
 928                  var oldData;
 929                  if (attribute == "innerHTML")
 930                  {
 931                      tmpXajax = this.$(this.workId);
 932                      if (tmpXajax == null)
 933                      {
 934                          tmpXajax = document.createElement("div");
 935                          tmpXajax.setAttribute('id',this.workId);
 936                          tmpXajax.style.display = "none";
 937                          tmpXajax.style.visibility = "hidden";
 938                          document.body.appendChild(tmpXajax);
 939                      }
 940                      tmpXajax.innerHTML = newData;
 941                      newData = tmpXajax.innerHTML;
 942                  }
 943                  eval("oldData=document.getElementById('"+element+"')."+attribute);
 944                  if (newData != oldData)
 945                      return true;
 946                      
 947                  return false;
 948              }
 949              
 950              //Process XML xajaxResponses returned from the request
 951              this.processResponse = function(xml)
 952              {
 953                  <?php if ($this->bStatusMessages == true){?> window.status = 'Recieving data...'; <?php } ?>
 954                  var tmpXajax = null;
 955                  xml = xml.documentElement;
 956                  for (i=0; i<xml.childNodes.length; i++)
 957                  {
 958                      if (xml.childNodes[i].nodeName == "alert")
 959                      {
 960                          if (xml.childNodes[i].firstChild)
 961                              alert(xml.childNodes[i].firstChild.nodeValue);
 962                      }
 963                      if (xml.childNodes[i].nodeName == "jscript")
 964                      {
 965                          if (xml.childNodes[i].firstChild)
 966                              eval(xml.childNodes[i].firstChild.nodeValue);
 967                      }
 968                      if (xml.childNodes[i].nodeName == "update")
 969                      {
 970                          var action;
 971                          var element;
 972                          var attribute;
 973                          var search;
 974                          var data;
 975                          var type;
 976                          var objElement;
 977                          
 978                          for (j=0; j<xml.childNodes[i].attributes.length; j++)
 979                          {
 980                              if (xml.childNodes[i].attributes[j].name == "action")
 981                              {
 982                                  action = xml.childNodes[i].attributes[j].value;
 983                              }
 984                          }
 985                          
 986                          var node = xml.childNodes[i];
 987                          for (j=0;j<node.childNodes.length;j++)
 988                          {
 989                              if (node.childNodes[j].nodeName == "target")
 990                              {
 991                                  for (k=0; k<node.childNodes[j].attributes.length; k++)
 992                                  {
 993                                      if (node.childNodes[j].attributes[k].name == "attribute")
 994                                      {
 995                                          attribute = node.childNodes[j].attributes[k].value;
 996                                      }
 997                                  }
 998                                  element = node.childNodes[j].firstChild.nodeValue;
 999                              }
1000                              if (node.childNodes[j].nodeName == "search")
1001                              {
1002                                  if (node.childNodes[j].firstChild)
1003                                      search = node.childNodes[j].firstChild.nodeValue;
1004                                  else
1005                                      search = "";
1006                              }
1007                              if (node.childNodes[j].nodeName == "data")
1008                              {
1009                                  if (node.childNodes[j].firstChild)
1010                                      data = node.childNodes[j].firstChild.nodeValue;
1011                                  else
1012                                      data = "";
1013                              }
1014                              
1015                              if (node.childNodes[j].nodeName == "type")
1016                              {
1017                                  if (node.childNodes[j].firstChild)
1018                                      type = node.childNodes[j].firstChild.nodeValue;
1019                                  else
1020                                      type = "";
1021                              }
1022                          }
1023                          if (action=="assign")
1024                          {
1025                              if (this.willChange(element,attribute,data))
1026                              {
1027                                  eval("document.getElementById('"+element+"')."+attribute+"=data;");
1028                              }
1029                          }
1030                          if (action=="append")
1031                              eval("document.getElementById('"+element+"')."+attribute+"+=data;");
1032                          if (action=="prepend")
1033                              eval("document.getElementById('"+element+"')."+attribute+"=data+document.getElementById('"+element+"')."+attribute);
1034                          if (action=="replace")
1035                          {
1036                              eval("var v=document.getElementById('"+element+"')."+attribute);
1037                              var v2 = v.indexOf(search)==-1?v:"";
1038                              while (v.indexOf(search) > -1)
1039                              {
1040                                  x = v.indexOf(search)+search.length+1;
1041                                  v2 += v.substr(0,x).replace(search,data);
1042                                  v = v.substr(x,v.length-x);
1043                              }
1044                              if (this.willChange(element,attribute,v2))
1045                                  eval('document.getElementById("'+element+'").'+attribute+'=v2;');
1046                          }
1047                          if (action=="clear")
1048                              eval("document.getElementById('"+element+"')."+attribute+"='';");
1049                          if (action=="remove")
1050                          {
1051                              objElement = this.$(element);
1052                              if (objElement.parentNode && objElement.parentNode.removeChild)
1053                              {
1054                                  objElement.parentNode.removeChild(objElement);
1055                              }
1056                          }
1057                          if (action=="create")
1058                          {
1059                              var objParent = this.$(element);
1060                              objElement = document.createElement(attribute);
1061                              objElement.setAttribute('id',data);
1062                              if (type && type != '')
1063                                  objElement.setAttribute('type',type);
1064                              objParent.appendChild(objElement);
1065                              if (objParent.tagName == "FORM")
1066                              {
1067  
1068                              }
1069                          }
1070                      }    
1071                  }
1072                  document.body.style.cursor = 'default';
1073                  <?php if ($this->bStatusMessages == true){?> window.status = 'Done'; <?php } ?>
1074              }
1075          }
1076          
1077          var xajax = new Xajax();
1078          <?php
1079          $js .= ob_get_contents()."\n";
1080          ob_end_clean();
1081          foreach($this->aFunctions as $sFunction)
1082              $js .= $this->wrap($sFunction,$this->aFunctionRequestTypes[$sFunction]);
1083      
1084          if ($this->bDebug == false)
1085              $js = $this->compressJavascript($js);
1086          
1087          print $js;
1088      }
1089  }// end class xajax 
1090  ?>


Généré le : Sun Feb 25 17:20:01 2007 par Balluche grâce à PHPXref 0.7