xmlrpc.inc 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566
  1. <?php
  2. // by Edd Dumbill (C) 1999-2002
  3. // <edd@usefulinc.com>
  4. // $Id: xmlrpc.inc,v 1.150 2006/08/28 09:06:21 ggiunta Exp $
  5. // Copyright (c) 1999,2000,2002 Edd Dumbill.
  6. // All rights reserved.
  7. //
  8. // Redistribution and use in source and binary forms, with or without
  9. // modification, are permitted provided that the following conditions
  10. // are met:
  11. //
  12. // * Redistributions of source code must retain the above copyright
  13. // notice, this list of conditions and the following disclaimer.
  14. //
  15. // * Redistributions in binary form must reproduce the above
  16. // copyright notice, this list of conditions and the following
  17. // disclaimer in the documentation and/or other materials provided
  18. // with the distribution.
  19. //
  20. // * Neither the name of the "XML-RPC for PHP" nor the names of its
  21. // contributors may be used to endorse or promote products derived
  22. // from this software without specific prior written permission.
  23. //
  24. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  25. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  26. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  27. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  28. // REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  29. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  30. // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  31. // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  32. // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  33. // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  34. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  35. // OF THE POSSIBILITY OF SUCH DAMAGE.
  36. if(!function_exists('xml_parser_create'))
  37. {
  38. // For PHP 4 onward, XML functionality is always compiled-in on windows:
  39. // no more need to dl-open it. It might have been compiled out on *nix...
  40. if(strtoupper(substr(PHP_OS, 0, 3) != 'WIN'))
  41. {
  42. dl('xml.so');
  43. }
  44. }
  45. // Try to be backward compat with php < 4.2 (are we not being nice ?)
  46. $phpversion = phpversion();
  47. if($phpversion[0] == '4' && $phpversion[2] < 2)
  48. {
  49. // give an opportunity to user to specify where to include other files from
  50. if(!defined('PHP_XMLRPC_COMPAT_DIR'))
  51. {
  52. define('PHP_XMLRPC_COMPAT_DIR',dirname(__FILE__).'/compat/');
  53. }
  54. if($phpversion[2] == '0')
  55. {
  56. if($phpversion[4] < 6)
  57. {
  58. include(PHP_XMLRPC_COMPAT_DIR.'is_callable.php');
  59. }
  60. include(PHP_XMLRPC_COMPAT_DIR.'is_scalar.php');
  61. include(PHP_XMLRPC_COMPAT_DIR.'array_key_exists.php');
  62. include(PHP_XMLRPC_COMPAT_DIR.'version_compare.php');
  63. }
  64. include(PHP_XMLRPC_COMPAT_DIR.'var_export.php');
  65. include(PHP_XMLRPC_COMPAT_DIR.'is_a.php');
  66. }
  67. // G. Giunta 2005/01/29: declare global these variables,
  68. // so that xmlrpc.inc will work even if included from within a function
  69. // Milosch: 2005/08/07 - explicitly request these via $GLOBALS where used.
  70. $GLOBALS['xmlrpcI4']='i4';
  71. $GLOBALS['xmlrpcInt']='int';
  72. $GLOBALS['xmlrpcBoolean']='boolean';
  73. $GLOBALS['xmlrpcDouble']='double';
  74. $GLOBALS['xmlrpcString']='string';
  75. $GLOBALS['xmlrpcDateTime']='dateTime.iso8601';
  76. $GLOBALS['xmlrpcBase64']='base64';
  77. $GLOBALS['xmlrpcArray']='array';
  78. $GLOBALS['xmlrpcStruct']='struct';
  79. $GLOBALS['xmlrpcValue']='undefined';
  80. $GLOBALS['xmlrpcTypes']=array(
  81. $GLOBALS['xmlrpcI4'] => 1,
  82. $GLOBALS['xmlrpcInt'] => 1,
  83. $GLOBALS['xmlrpcBoolean'] => 1,
  84. $GLOBALS['xmlrpcString'] => 1,
  85. $GLOBALS['xmlrpcDouble'] => 1,
  86. $GLOBALS['xmlrpcDateTime'] => 1,
  87. $GLOBALS['xmlrpcBase64'] => 1,
  88. $GLOBALS['xmlrpcArray'] => 2,
  89. $GLOBALS['xmlrpcStruct'] => 3
  90. );
  91. $GLOBALS['xmlrpc_valid_parents'] = array(
  92. 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'),
  93. 'BOOLEAN' => array('VALUE'),
  94. 'I4' => array('VALUE'),
  95. 'INT' => array('VALUE'),
  96. 'STRING' => array('VALUE'),
  97. 'DOUBLE' => array('VALUE'),
  98. 'DATETIME.ISO8601' => array('VALUE'),
  99. 'BASE64' => array('VALUE'),
  100. 'MEMBER' => array('STRUCT'),
  101. 'NAME' => array('MEMBER'),
  102. 'DATA' => array('ARRAY'),
  103. 'ARRAY' => array('VALUE'),
  104. 'STRUCT' => array('VALUE'),
  105. 'PARAM' => array('PARAMS'),
  106. 'METHODNAME' => array('METHODCALL'),
  107. 'PARAMS' => array('METHODCALL', 'METHODRESPONSE'),
  108. 'FAULT' => array('METHODRESPONSE'),
  109. 'NIL' => array('VALUE') // only used when extension activated
  110. );
  111. // define extra types for supporting NULL (useful for json or <NIL/>)
  112. $GLOBALS['xmlrpcNull']='null';
  113. $GLOBALS['xmlrpcTypes']['null']=1;
  114. // Not in use anymore since 2.0. Shall we remove it?
  115. /// @deprecated
  116. $GLOBALS['xmlEntities']=array(
  117. 'amp' => '&',
  118. 'quot' => '"',
  119. 'lt' => '<',
  120. 'gt' => '>',
  121. 'apos' => "'"
  122. );
  123. // tables used for transcoding different charsets into us-ascii xml
  124. $GLOBALS['xml_iso88591_Entities']=array();
  125. $GLOBALS['xml_iso88591_Entities']['in'] = array();
  126. $GLOBALS['xml_iso88591_Entities']['out'] = array();
  127. for ($i = 0; $i < 32; $i++)
  128. {
  129. $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i);
  130. $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';';
  131. }
  132. for ($i = 160; $i < 256; $i++)
  133. {
  134. $GLOBALS['xml_iso88591_Entities']['in'][] = chr($i);
  135. $GLOBALS['xml_iso88591_Entities']['out'][] = '&#'.$i.';';
  136. }
  137. /// @todo add to iso table the characters from cp_1252 range, i.e. 128 to 159.
  138. /// These will NOT be present in true ISO-8859-1, but will save the unwary
  139. /// windows user from sending junk.
  140. /*
  141. $cp1252_to_xmlent =
  142. array(
  143. '\x80'=>'&#x20AC;', '\x81'=>'?', '\x82'=>'&#x201A;', '\x83'=>'&#x0192;',
  144. '\x84'=>'&#x201E;', '\x85'=>'&#x2026;', '\x86'=>'&#x2020;', \x87'=>'&#x2021;',
  145. '\x88'=>'&#x02C6;', '\x89'=>'&#x2030;', '\x8A'=>'&#x0160;', '\x8B'=>'&#x2039;',
  146. '\x8C'=>'&#x0152;', '\x8D'=>'?', '\x8E'=>'&#x017D;', '\x8F'=>'?',
  147. '\x90'=>'?', '\x91'=>'&#x2018;', '\x92'=>'&#x2019;', '\x93'=>'&#x201C;',
  148. '\x94'=>'&#x201D;', '\x95'=>'&#x2022;', '\x96'=>'&#x2013;', '\x97'=>'&#x2014;',
  149. '\x98'=>'&#x02DC;', '\x99'=>'&#x2122;', '\x9A'=>'&#x0161;', '\x9B'=>'&#x203A;',
  150. '\x9C'=>'&#x0153;', '\x9D'=>'?', '\x9E'=>'&#x017E;', '\x9F'=>'&#x0178;'
  151. );
  152. */
  153. $GLOBALS['xmlrpcerr']['unknown_method']=1;
  154. $GLOBALS['xmlrpcstr']['unknown_method']='Unknown method';
  155. $GLOBALS['xmlrpcerr']['invalid_return']=2;
  156. $GLOBALS['xmlrpcstr']['invalid_return']='Invalid return payload: enable debugging to examine incoming payload';
  157. $GLOBALS['xmlrpcerr']['incorrect_params']=3;
  158. $GLOBALS['xmlrpcstr']['incorrect_params']='Incorrect parameters passed to method';
  159. $GLOBALS['xmlrpcerr']['introspect_unknown']=4;
  160. $GLOBALS['xmlrpcstr']['introspect_unknown']="Can't introspect: method unknown";
  161. $GLOBALS['xmlrpcerr']['http_error']=5;
  162. $GLOBALS['xmlrpcstr']['http_error']="Didn't receive 200 OK from remote server.";
  163. $GLOBALS['xmlrpcerr']['no_data']=6;
  164. $GLOBALS['xmlrpcstr']['no_data']='No data received from server.';
  165. $GLOBALS['xmlrpcerr']['no_ssl']=7;
  166. $GLOBALS['xmlrpcstr']['no_ssl']='No SSL support compiled in.';
  167. $GLOBALS['xmlrpcerr']['curl_fail']=8;
  168. $GLOBALS['xmlrpcstr']['curl_fail']='CURL error';
  169. $GLOBALS['xmlrpcerr']['invalid_request']=15;
  170. $GLOBALS['xmlrpcstr']['invalid_request']='Invalid request payload';
  171. $GLOBALS['xmlrpcerr']['no_curl']=16;
  172. $GLOBALS['xmlrpcstr']['no_curl']='No CURL support compiled in.';
  173. $GLOBALS['xmlrpcerr']['server_error']=17;
  174. $GLOBALS['xmlrpcstr']['server_error']='Internal server error';
  175. $GLOBALS['xmlrpcerr']['multicall_error']=18;
  176. $GLOBALS['xmlrpcstr']['multicall_error']='Received from server invalid multicall response';
  177. $GLOBALS['xmlrpcerr']['multicall_notstruct'] = 9;
  178. $GLOBALS['xmlrpcstr']['multicall_notstruct'] = 'system.multicall expected struct';
  179. $GLOBALS['xmlrpcerr']['multicall_nomethod'] = 10;
  180. $GLOBALS['xmlrpcstr']['multicall_nomethod'] = 'missing methodName';
  181. $GLOBALS['xmlrpcerr']['multicall_notstring'] = 11;
  182. $GLOBALS['xmlrpcstr']['multicall_notstring'] = 'methodName is not a string';
  183. $GLOBALS['xmlrpcerr']['multicall_recursion'] = 12;
  184. $GLOBALS['xmlrpcstr']['multicall_recursion'] = 'recursive system.multicall forbidden';
  185. $GLOBALS['xmlrpcerr']['multicall_noparams'] = 13;
  186. $GLOBALS['xmlrpcstr']['multicall_noparams'] = 'missing params';
  187. $GLOBALS['xmlrpcerr']['multicall_notarray'] = 14;
  188. $GLOBALS['xmlrpcstr']['multicall_notarray'] = 'params is not an array';
  189. $GLOBALS['xmlrpcerr']['cannot_decompress']=103;
  190. $GLOBALS['xmlrpcstr']['cannot_decompress']='Received from server compressed HTTP and cannot decompress';
  191. $GLOBALS['xmlrpcerr']['decompress_fail']=104;
  192. $GLOBALS['xmlrpcstr']['decompress_fail']='Received from server invalid compressed HTTP';
  193. $GLOBALS['xmlrpcerr']['dechunk_fail']=105;
  194. $GLOBALS['xmlrpcstr']['dechunk_fail']='Received from server invalid chunked HTTP';
  195. $GLOBALS['xmlrpcerr']['server_cannot_decompress']=106;
  196. $GLOBALS['xmlrpcstr']['server_cannot_decompress']='Received from client compressed HTTP request and cannot decompress';
  197. $GLOBALS['xmlrpcerr']['server_decompress_fail']=107;
  198. $GLOBALS['xmlrpcstr']['server_decompress_fail']='Received from client invalid compressed HTTP request';
  199. // The charset encoding used by the server for received messages and
  200. // by the client for received responses when received charset cannot be determined
  201. // or is not supported
  202. $GLOBALS['xmlrpc_defencoding']='UTF-8';
  203. // The encoding used internally by PHP.
  204. // String values received as xml will be converted to this, and php strings will be converted to xml
  205. // as if having been coded with this
  206. $GLOBALS['xmlrpc_internalencoding']='ISO-8859-1';
  207. $GLOBALS['xmlrpcName']='XML-RPC for PHP';
  208. $GLOBALS['xmlrpcVersion']='2.1';
  209. // let user errors start at 800
  210. $GLOBALS['xmlrpcerruser']=800;
  211. // let XML parse errors start at 100
  212. $GLOBALS['xmlrpcerrxml']=100;
  213. // formulate backslashes for escaping regexp
  214. // Not in use anymore since 2.0. Shall we remove it?
  215. /// @deprecated
  216. $GLOBALS['xmlrpc_backslash']=chr(92).chr(92);
  217. // used to store state during parsing
  218. // quick explanation of components:
  219. // ac - used to accumulate values
  220. // isf - used to indicate a parsing fault (2) or xmlrpcresp fault (1)
  221. // isf_reason - used for storing xmlrpcresp fault string
  222. // lv - used to indicate "looking for a value": implements
  223. // the logic to allow values with no types to be strings
  224. // params - used to store parameters in method calls
  225. // method - used to store method name
  226. // stack - array with genealogy of xml elements names:
  227. // used to validate nesting of xmlrpc elements
  228. $GLOBALS['_xh']=null;
  229. /**
  230. * Convert a string to the correct XML representation in a target charset
  231. * To help correct communication of non-ascii chars inside strings, regardless
  232. * of the charset used when sending requests, parsing them, sending responses
  233. * and parsing responses, an option is to convert all non-ascii chars present in the message
  234. * into their equivalent 'charset entity'. Charset entities enumerated this way
  235. * are independent of the charset encoding used to transmit them, and all XML
  236. * parsers are bound to understand them.
  237. * Note that in the std case we are not sending a charset encoding mime type
  238. * along with http headers, so we are bound by RFC 3023 to emit strict us-ascii.
  239. *
  240. * @todo do a bit of basic benchmarking (strtr vs. str_replace)
  241. * @todo make usage of iconv() or recode_string() or mb_string() where available
  242. */
  243. function xmlrpc_encode_entitites($data, $src_encoding='', $dest_encoding='')
  244. {
  245. if ($src_encoding == '')
  246. {
  247. // lame, but we know no better...
  248. $src_encoding = $GLOBALS['xmlrpc_internalencoding'];
  249. }
  250. switch(strtoupper($src_encoding.'_'.$dest_encoding))
  251. {
  252. case 'ISO-8859-1_':
  253. case 'ISO-8859-1_US-ASCII':
  254. $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
  255. $escaped_data = str_replace($GLOBALS['xml_iso88591_Entities']['in'], $GLOBALS['xml_iso88591_Entities']['out'], $escaped_data);
  256. break;
  257. case 'ISO-8859-1_UTF-8':
  258. $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
  259. $escaped_data = utf8_encode($escaped_data);
  260. break;
  261. case 'ISO-8859-1_ISO-8859-1':
  262. case 'US-ASCII_US-ASCII':
  263. case 'US-ASCII_UTF-8':
  264. case 'US-ASCII_':
  265. case 'US-ASCII_ISO-8859-1':
  266. case 'UTF-8_UTF-8':
  267. $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
  268. break;
  269. case 'UTF-8_':
  270. case 'UTF-8_US-ASCII':
  271. case 'UTF-8_ISO-8859-1':
  272. // NB: this will choke on invalid UTF-8, going most likely beyond EOF
  273. $escaped_data = '';
  274. // be kind to users creating string xmlrpcvals out of different php types
  275. $data = (string) $data;
  276. $ns = strlen ($data);
  277. for ($nn = 0; $nn < $ns; $nn++)
  278. {
  279. $ch = $data[$nn];
  280. $ii = ord($ch);
  281. //1 7 0bbbbbbb (127)
  282. if ($ii < 128)
  283. {
  284. /// @todo shall we replace this with a (supposedly) faster str_replace?
  285. switch($ii){
  286. case 34:
  287. $escaped_data .= '&quot;';
  288. break;
  289. case 38:
  290. $escaped_data .= '&amp;';
  291. break;
  292. case 39:
  293. $escaped_data .= '&apos;';
  294. break;
  295. case 60:
  296. $escaped_data .= '&lt;';
  297. break;
  298. case 62:
  299. $escaped_data .= '&gt;';
  300. break;
  301. default:
  302. $escaped_data .= $ch;
  303. } // switch
  304. }
  305. //2 11 110bbbbb 10bbbbbb (2047)
  306. else if ($ii>>5 == 6)
  307. {
  308. $b1 = ($ii & 31);
  309. $ii = ord($data[$nn+1]);
  310. $b2 = ($ii & 63);
  311. $ii = ($b1 * 64) + $b2;
  312. $ent = sprintf ('&#%d;', $ii);
  313. $escaped_data .= $ent;
  314. }
  315. //3 16 1110bbbb 10bbbbbb 10bbbbbb
  316. else if ($ii>>4 == 14)
  317. {
  318. $b1 = ($ii & 31);
  319. $ii = ord($data[$nn+1]);
  320. $b2 = ($ii & 63);
  321. $ii = ord($data[$nn+2]);
  322. $b3 = ($ii & 63);
  323. $ii = ((($b1 * 64) + $b2) * 64) + $b3;
  324. $ent = sprintf ('&#%d;', $ii);
  325. $escaped_data .= $ent;
  326. }
  327. //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
  328. else if ($ii>>3 == 30)
  329. {
  330. $b1 = ($ii & 31);
  331. $ii = ord($data[$nn+1]);
  332. $b2 = ($ii & 63);
  333. $ii = ord($data[$nn+2]);
  334. $b3 = ($ii & 63);
  335. $ii = ord($data[$nn+3]);
  336. $b4 = ($ii & 63);
  337. $ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4;
  338. $ent = sprintf ('&#%d;', $ii);
  339. $escaped_data .= $ent;
  340. }
  341. }
  342. break;
  343. default:
  344. $escaped_data = '';
  345. error_log("Converting from $src_encoding to $dest_encoding: not supported...");
  346. }
  347. return $escaped_data;
  348. }
  349. /// xml parser handler function for opening element tags
  350. function xmlrpc_se($parser, $name, $attrs, $accept_single_vals=false)
  351. {
  352. // if invalid xmlrpc already detected, skip all processing
  353. if ($GLOBALS['_xh']['isf'] < 2)
  354. {
  355. // check for correct element nesting
  356. // top level element can only be of 2 types
  357. /// @todo optimization creep: save this check into a bool variable, instead of using count() every time:
  358. /// there is only a single top level element in xml anyway
  359. if (count($GLOBALS['_xh']['stack']) == 0)
  360. {
  361. if ($name != 'METHODRESPONSE' && $name != 'METHODCALL' && (
  362. $name != 'VALUE' && !$accept_single_vals))
  363. {
  364. $GLOBALS['_xh']['isf'] = 2;
  365. $GLOBALS['_xh']['isf_reason'] = 'missing top level xmlrpc element';
  366. return;
  367. }
  368. else
  369. {
  370. $GLOBALS['_xh']['rt'] = strtolower($name);
  371. }
  372. }
  373. else
  374. {
  375. // not top level element: see if parent is OK
  376. $parent = end($GLOBALS['_xh']['stack']);
  377. if (!array_key_exists($name, $GLOBALS['xmlrpc_valid_parents']) || !in_array($parent, $GLOBALS['xmlrpc_valid_parents'][$name]))
  378. {
  379. $GLOBALS['_xh']['isf'] = 2;
  380. $GLOBALS['_xh']['isf_reason'] = "xmlrpc element $name cannot be child of $parent";
  381. return;
  382. }
  383. }
  384. switch($name)
  385. {
  386. // optimize for speed switch cases: most common cases first
  387. case 'VALUE':
  388. /// @todo we could check for 2 VALUE elements inside a MEMBER or PARAM element
  389. $GLOBALS['_xh']['vt']='value'; // indicator: no value found yet
  390. $GLOBALS['_xh']['ac']='';
  391. $GLOBALS['_xh']['lv']=1;
  392. $GLOBALS['_xh']['php_class']=null;
  393. break;
  394. case 'I4':
  395. case 'INT':
  396. case 'STRING':
  397. case 'BOOLEAN':
  398. case 'DOUBLE':
  399. case 'DATETIME.ISO8601':
  400. case 'BASE64':
  401. if ($GLOBALS['_xh']['vt']!='value')
  402. {
  403. //two data elements inside a value: an error occurred!
  404. $GLOBALS['_xh']['isf'] = 2;
  405. $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
  406. return;
  407. }
  408. $GLOBALS['_xh']['ac']=''; // reset the accumulator
  409. break;
  410. case 'STRUCT':
  411. case 'ARRAY':
  412. if ($GLOBALS['_xh']['vt']!='value')
  413. {
  414. //two data elements inside a value: an error occurred!
  415. $GLOBALS['_xh']['isf'] = 2;
  416. $GLOBALS['_xh']['isf_reason'] = "$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
  417. return;
  418. }
  419. // create an empty array to hold child values, and push it onto appropriate stack
  420. $cur_val = array();
  421. $cur_val['values'] = array();
  422. $cur_val['type'] = $name;
  423. // check for out-of-band information to rebuild php objs
  424. // and in case it is found, save it
  425. if (@isset($attrs['PHP_CLASS']))
  426. {
  427. $cur_val['php_class'] = $attrs['PHP_CLASS'];
  428. }
  429. $GLOBALS['_xh']['valuestack'][] = $cur_val;
  430. $GLOBALS['_xh']['vt']='data'; // be prepared for a data element next
  431. break;
  432. case 'DATA':
  433. if ($GLOBALS['_xh']['vt']!='data')
  434. {
  435. //two data elements inside a value: an error occurred!
  436. $GLOBALS['_xh']['isf'] = 2;
  437. $GLOBALS['_xh']['isf_reason'] = "found two data elements inside an array element";
  438. return;
  439. }
  440. case 'METHODCALL':
  441. case 'METHODRESPONSE':
  442. case 'PARAMS':
  443. // valid elements that add little to processing
  444. break;
  445. case 'METHODNAME':
  446. case 'NAME':
  447. /// @todo we could check for 2 NAME elements inside a MEMBER element
  448. $GLOBALS['_xh']['ac']='';
  449. break;
  450. case 'FAULT':
  451. $GLOBALS['_xh']['isf']=1;
  452. break;
  453. case 'MEMBER':
  454. $GLOBALS['_xh']['valuestack'][count($GLOBALS['_xh']['valuestack'])-1]['name']=''; // set member name to null, in case we do not find in the xml later on
  455. //$GLOBALS['_xh']['ac']='';
  456. // Drop trough intentionally
  457. case 'PARAM':
  458. // clear value type, so we can check later if no value has been passed for this param/member
  459. $GLOBALS['_xh']['vt']=null;
  460. break;
  461. case 'NIL':
  462. // we do not support the <NIL/> extension yet, so
  463. // drop through intentionally
  464. default:
  465. /// INVALID ELEMENT: RAISE ISF so that it is later recognized!!!
  466. $GLOBALS['_xh']['isf'] = 2;
  467. $GLOBALS['_xh']['isf_reason'] = "found not-xmlrpc xml element $name";
  468. break;
  469. }
  470. // Save current element name to stack, to validate nesting
  471. $GLOBALS['_xh']['stack'][] = $name;
  472. /// @todo optimization creep: move this inside the big switch() above
  473. if($name!='VALUE')
  474. {
  475. $GLOBALS['_xh']['lv']=0;
  476. }
  477. }
  478. }
  479. /// Used in decoding xml chunks that might represent single xmlrpc values
  480. function xmlrpc_se_any($parser, $name, $attrs)
  481. {
  482. xmlrpc_se($parser, $name, $attrs, true);
  483. }
  484. /// xml parser handler function for close element tags
  485. function xmlrpc_ee($parser, $name, $rebuild_xmlrpcvals = true)
  486. {
  487. if ($GLOBALS['_xh']['isf'] < 2)
  488. {
  489. // push this element name from stack
  490. // NB: if XML validates, correct opening/closing is guaranteed and
  491. // we do not have to check for $name == $curr_elem.
  492. // we also checked for proper nesting at start of elements...
  493. $curr_elem = array_pop($GLOBALS['_xh']['stack']);
  494. switch($name)
  495. {
  496. case 'VALUE':
  497. // This if() detects if no scalar was inside <VALUE></VALUE>
  498. if ($GLOBALS['_xh']['vt']=='value')
  499. {
  500. $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];
  501. $GLOBALS['_xh']['vt']=$GLOBALS['xmlrpcString'];
  502. }
  503. if ($rebuild_xmlrpcvals)
  504. {
  505. // build the xmlrpc val out of the data received, and substitute it
  506. $temp =& new xmlrpcval($GLOBALS['_xh']['value'], $GLOBALS['_xh']['vt']);
  507. // in case we got info about underlying php class, save it
  508. // in the object we're rebuilding
  509. if (isset($GLOBALS['_xh']['php_class']))
  510. $temp->_php_class = $GLOBALS['_xh']['php_class'];
  511. // check if we are inside an array or struct:
  512. // if value just built is inside an array, let's move it into array on the stack
  513. $vscount = count($GLOBALS['_xh']['valuestack']);
  514. if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY')
  515. {
  516. $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][] = $temp;
  517. }
  518. else
  519. {
  520. $GLOBALS['_xh']['value'] = $temp;
  521. }
  522. }
  523. else
  524. {
  525. /// @todo this needs to treat correctly php-serialized objects,
  526. /// since std deserializing is done by php_xmlrpc_decode,
  527. /// which we will not be calling...
  528. if (isset($GLOBALS['_xh']['php_class']))
  529. {
  530. }
  531. // check if we are inside an array or struct:
  532. // if value just built is inside an array, let's move it into array on the stack
  533. $vscount = count($GLOBALS['_xh']['valuestack']);
  534. if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY')
  535. {
  536. $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][] = $GLOBALS['_xh']['value'];
  537. }
  538. }
  539. break;
  540. case 'BOOLEAN':
  541. case 'I4':
  542. case 'INT':
  543. case 'STRING':
  544. case 'DOUBLE':
  545. case 'DATETIME.ISO8601':
  546. case 'BASE64':
  547. $GLOBALS['_xh']['vt']=strtolower($name);
  548. /// @todo: optimization creep - remove the if/elseif cycle below
  549. /// since the case() in which we are already did that
  550. if ($name=='STRING')
  551. {
  552. $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];
  553. }
  554. elseif ($name=='DATETIME.ISO8601')
  555. {
  556. if (!preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $GLOBALS['_xh']['ac']))
  557. {
  558. error_log('XML-RPC: invalid value received in DATETIME: '.$GLOBALS['_xh']['ac']);
  559. }
  560. $GLOBALS['_xh']['vt']=$GLOBALS['xmlrpcDateTime'];
  561. $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];
  562. }
  563. elseif ($name=='BASE64')
  564. {
  565. /// @todo check for failure of base64 decoding / catch warnings
  566. $GLOBALS['_xh']['value']=base64_decode($GLOBALS['_xh']['ac']);
  567. }
  568. elseif ($name=='BOOLEAN')
  569. {
  570. // special case here: we translate boolean 1 or 0 into PHP
  571. // constants true or false.
  572. // Strings 'true' and 'false' are accepted, even though the
  573. // spec never mentions them (see eg. Blogger api docs)
  574. // NB: this simple checks helps a lot sanitizing input, ie no
  575. // security problems around here
  576. if ($GLOBALS['_xh']['ac']=='1' || strcasecmp($GLOBALS['_xh']['ac'], 'true') == 0)
  577. {
  578. $GLOBALS['_xh']['value']=true;
  579. }
  580. else
  581. {
  582. // log if receiveing something strange, even though we set the value to false anyway
  583. if ($GLOBALS['_xh']['ac']!='0' && strcasecmp($_xh[$parser]['ac'], 'false') != 0)
  584. error_log('XML-RPC: invalid value received in BOOLEAN: '.$GLOBALS['_xh']['ac']);
  585. $GLOBALS['_xh']['value']=false;
  586. }
  587. }
  588. elseif ($name=='DOUBLE')
  589. {
  590. // we have a DOUBLE
  591. // we must check that only 0123456789-.<space> are characters here
  592. if (!preg_match('/^[+-]?[eE0123456789 \t.]+$/', $GLOBALS['_xh']['ac']))
  593. {
  594. /// @todo: find a better way of throwing an error
  595. // than this!
  596. error_log('XML-RPC: non numeric value received in DOUBLE: '.$GLOBALS['_xh']['ac']);
  597. $GLOBALS['_xh']['value']='ERROR_NON_NUMERIC_FOUND';
  598. }
  599. else
  600. {
  601. // it's ok, add it on
  602. $GLOBALS['_xh']['value']=(double)$GLOBALS['_xh']['ac'];
  603. }
  604. }
  605. else
  606. {
  607. // we have an I4/INT
  608. // we must check that only 0123456789-<space> are characters here
  609. if (!preg_match('/^[+-]?[0123456789 \t]+$/', $GLOBALS['_xh']['ac']))
  610. {
  611. /// @todo find a better way of throwing an error
  612. // than this!
  613. error_log('XML-RPC: non numeric value received in INT: '.$GLOBALS['_xh']['ac']);
  614. $GLOBALS['_xh']['value']='ERROR_NON_NUMERIC_FOUND';
  615. }
  616. else
  617. {
  618. // it's ok, add it on
  619. $GLOBALS['_xh']['value']=(int)$GLOBALS['_xh']['ac'];
  620. }
  621. }
  622. //$GLOBALS['_xh']['ac']=''; // is this necessary?
  623. $GLOBALS['_xh']['lv']=3; // indicate we've found a value
  624. break;
  625. case 'NAME':
  626. $GLOBALS['_xh']['valuestack'][count($GLOBALS['_xh']['valuestack'])-1]['name'] = $GLOBALS['_xh']['ac'];
  627. break;
  628. case 'MEMBER':
  629. //$GLOBALS['_xh']['ac']=''; // is this necessary?
  630. // add to array in the stack the last element built,
  631. // unless no VALUE was found
  632. if ($GLOBALS['_xh']['vt'])
  633. {
  634. $vscount = count($GLOBALS['_xh']['valuestack']);
  635. $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][$GLOBALS['_xh']['valuestack'][$vscount-1]['name']] = $GLOBALS['_xh']['value'];
  636. } else
  637. error_log('XML-RPC: missing VALUE inside STRUCT in received xml');
  638. break;
  639. case 'DATA':
  640. //$GLOBALS['_xh']['ac']=''; // is this necessary?
  641. $GLOBALS['_xh']['vt']=null; // reset this to check for 2 data elements in a row - even if they're empty
  642. break;
  643. case 'STRUCT':
  644. case 'ARRAY':
  645. // fetch out of stack array of values, and promote it to current value
  646. $curr_val = array_pop($GLOBALS['_xh']['valuestack']);
  647. $GLOBALS['_xh']['value'] = $curr_val['values'];
  648. $GLOBALS['_xh']['vt']=strtolower($name);
  649. if (isset($curr_val['php_class']))
  650. {
  651. $GLOBALS['_xh']['php_class'] = $curr_val['php_class'];
  652. }
  653. break;
  654. case 'PARAM':
  655. // add to array of params the current value,
  656. // unless no VALUE was found
  657. if ($GLOBALS['_xh']['vt'])
  658. {
  659. $GLOBALS['_xh']['params'][]=$GLOBALS['_xh']['value'];
  660. $GLOBALS['_xh']['pt'][]=$GLOBALS['_xh']['vt'];
  661. }
  662. else
  663. error_log('XML-RPC: missing VALUE inside PARAM in received xml');
  664. break;
  665. case 'METHODNAME':
  666. $GLOBALS['_xh']['method']=preg_replace('/^[\n\r\t ]+/', '', $GLOBALS['_xh']['ac']);
  667. break;
  668. case 'PARAMS':
  669. case 'FAULT':
  670. case 'METHODCALL':
  671. case 'METHORESPONSE':
  672. break;
  673. default:
  674. // End of INVALID ELEMENT!
  675. // shall we add an assert here for unreachable code???
  676. break;
  677. }
  678. }
  679. }
  680. /// Used in decoding xmlrpc requests/responses without rebuilding xmlrpc values
  681. function xmlrpc_ee_fast($parser, $name)
  682. {
  683. xmlrpc_ee($parser, $name, false);
  684. }
  685. /// xml parser handler function for character data
  686. function xmlrpc_cd($parser, $data)
  687. {
  688. // skip processing if xml fault already detected
  689. if ($GLOBALS['_xh']['isf'] < 2)
  690. {
  691. // "lookforvalue==3" means that we've found an entire value
  692. // and should discard any further character data
  693. if($GLOBALS['_xh']['lv']!=3)
  694. {
  695. // G. Giunta 2006-08-23: useless change of 'lv' from 1 to 2
  696. //if($GLOBALS['_xh']['lv']==1)
  697. //{
  698. // if we've found text and we're just in a <value> then
  699. // say we've found a value
  700. //$GLOBALS['_xh']['lv']=2;
  701. //}
  702. // we always initialize the accumulator before starting parsing, anyway...
  703. //if(!@isset($GLOBALS['_xh']['ac']))
  704. //{
  705. // $GLOBALS['_xh']['ac'] = '';
  706. //}
  707. $GLOBALS['_xh']['ac'].=$data;
  708. }
  709. }
  710. }
  711. /// xml parser handler function for 'other stuff', ie. not char data or
  712. /// element start/end tag. In fact it only gets called on unknown entities...
  713. function xmlrpc_dh($parser, $data)
  714. {
  715. // skip processing if xml fault already detected
  716. if ($GLOBALS['_xh']['isf'] < 2)
  717. {
  718. if(substr($data, 0, 1) == '&' && substr($data, -1, 1) == ';')
  719. {
  720. // G. Giunta 2006-08-25: useless change of 'lv' from 1 to 2
  721. //if($GLOBALS['_xh']['lv']==1)
  722. //{
  723. // $GLOBALS['_xh']['lv']=2;
  724. //}
  725. $GLOBALS['_xh']['ac'].=$data;
  726. }
  727. }
  728. return true;
  729. }
  730. class xmlrpc_client
  731. {
  732. var $path;
  733. var $server;
  734. var $port=0;
  735. var $method='http';
  736. var $errno;
  737. var $errstr;
  738. var $debug=0;
  739. var $username='';
  740. var $password='';
  741. var $authtype=1;
  742. var $cert='';
  743. var $certpass='';
  744. var $cacert='';
  745. var $cacertdir='';
  746. var $key='';
  747. var $keypass='';
  748. var $verifypeer=true;
  749. var $verifyhost=1;
  750. var $no_multicall=false;
  751. var $proxy='';
  752. var $proxyport=0;
  753. var $proxy_user='';
  754. var $proxy_pass='';
  755. var $proxy_authtype=1;
  756. var $cookies=array();
  757. /**
  758. * List of http compression methods accepted by the client for responses.
  759. * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib
  760. *
  761. * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since
  762. * in those cases it will be up to CURL to decide the compression methods
  763. * it supports. You might check for the presence of 'zlib' in the output of
  764. * curl_version() to determine wheter compression is supported or not
  765. */
  766. var $accepted_compression = array();
  767. /**
  768. * Name of compression scheme to be used for sending requests.
  769. * Either null, gzip or deflate
  770. */
  771. var $request_compression = '';
  772. /**
  773. * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see:
  774. * http://curl.haxx.se/docs/faq.html#7.3)
  775. */
  776. var $xmlrpc_curl_handle = null;
  777. /// Wheter to use persistent connections for http 1.1 and https
  778. var $keepalive = false;
  779. /// Charset encodings that can be decoded without problems by the client
  780. var $accepted_charset_encodings = array();
  781. /// Charset encoding to be used in serializing request. NULL = use ASCII
  782. var $request_charset_encoding = '';
  783. /**
  784. * Decides the content of xmlrpcresp objects returned by calls to send()
  785. * valid strings are 'xmlrpcvals', 'phpvals' or 'xml'
  786. */
  787. var $return_type = 'xmlrpcvals';
  788. /**
  789. * @param string $path either the complete server URL or the PATH part of the xmlrc server URL, e.g. /xmlrpc/server.php
  790. * @param string $server the server name / ip address
  791. * @param integer $port the port the server is listening on, defaults to 80 or 443 depending on protocol used
  792. * @param string $method the http protocol variant: defaults to 'http', 'https' and 'http11' can be used if CURL is installed
  793. */
  794. function xmlrpc_client($path, $server='', $port='', $method='')
  795. {
  796. // allow user to specify all params in $path
  797. if($server == '' and $port == '' and $method == '')
  798. {
  799. $parts = parse_url($path);
  800. $server = $parts['host'];
  801. $path = $parts['path'];
  802. if(isset($parts['query']))
  803. {
  804. $path .= '?'.$parts['query'];
  805. }
  806. if(isset($parts['fragment']))
  807. {
  808. $path .= '#'.$parts['fragment'];
  809. }
  810. if(isset($parts['port']))
  811. {
  812. $port = $parts['port'];
  813. }
  814. if(isset($parts['scheme']))
  815. {
  816. $method = $parts['scheme'];
  817. }
  818. if(isset($parts['user']))
  819. {
  820. $this->username = $parts['user'];
  821. }
  822. if(isset($parts['pass']))
  823. {
  824. $this->password = $parts['pass'];
  825. }
  826. }
  827. if($path == '' || $path[0] != '/')
  828. {
  829. $this->path='/'.$path;
  830. }
  831. else
  832. {
  833. $this->path=$path;
  834. }
  835. $this->server=$server;
  836. if($port != '')
  837. {
  838. $this->port=$port;
  839. }
  840. if($method != '')
  841. {
  842. $this->method=$method;
  843. }
  844. // if ZLIB is enabled, let the client by default accept compressed responses
  845. if(function_exists('gzinflate') || (
  846. function_exists('curl_init') && (($info = curl_version()) &&
  847. ((is_string($info) && strpos($info, 'zlib') !== null) || isset($info['libz_version'])))
  848. ))
  849. {
  850. $this->accepted_compression = array('gzip', 'deflate');
  851. }
  852. // keepalives: enabled by default ONLY for PHP >= 4.3.8
  853. // (see http://curl.haxx.se/docs/faq.html#7.3)
  854. if(version_compare(phpversion(), '4.3.8') >= 0)
  855. {
  856. $this->keepalive = true;
  857. }
  858. // by default the xml parser can support these 3 charset encodings
  859. $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
  860. }
  861. /**
  862. * Enables/disables the echoing to screen of the xmlrpc responses received
  863. * @param integer $debug values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)
  864. * @access public
  865. */
  866. function setDebug($in)
  867. {
  868. $this->debug=$in;
  869. }
  870. /**
  871. * Add some http BASIC AUTH credentials, used by the client to authenticate
  872. * @param string $u username
  873. * @param string $p password
  874. * @param integer $t auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC (basic auth)
  875. * @access public
  876. */
  877. function setCredentials($u, $p, $t=1)
  878. {
  879. $this->username=$u;
  880. $this->password=$p;
  881. $this->authtype=$t;
  882. }
  883. /**
  884. * Add a client-side https certificate
  885. * @param string $cert
  886. * @param string $certpass
  887. * @access public
  888. */
  889. function setCertificate($cert, $certpass)
  890. {
  891. $this->cert = $cert;
  892. $this->certpass = $certpass;
  893. }
  894. /**
  895. * Add a CA certificate to verify server with (see man page about
  896. * CURLOPT_CAINFO for more details
  897. * @param string $cacert certificate file name (or dir holding certificates)
  898. * @param bool $is_dir set to true to indicate cacert is a dir. defaults to false
  899. * @access public
  900. */
  901. function setCaCertificate($cacert, $is_dir=false)
  902. {
  903. if ($is_dir)
  904. {
  905. $this->cacert = $cacert;
  906. }
  907. else
  908. {
  909. $this->cacertdir = $cacert;
  910. }
  911. }
  912. /**
  913. * Set attributes for SSL communication: private SSL key
  914. * @param string $key The name of a file containing a private SSL key
  915. * @param string $keypass The secret password needed to use the private SSL key
  916. * @access public
  917. * NB: does not work in older php/curl installs
  918. * Thanks to Daniel Convissor
  919. */
  920. function setKey($key, $keypass)
  921. {
  922. $this->key = $key;
  923. $this->keypass = $keypass;
  924. }
  925. /**
  926. * Set attributes for SSL communication: verify server certificate
  927. * @param bool $i enable/disable verification of peer certificate
  928. * @access public
  929. */
  930. function setSSLVerifyPeer($i)
  931. {
  932. $this->verifypeer = $i;
  933. }
  934. /**
  935. * Set attributes for SSL communication: verify match of server cert w. hostname
  936. * @param int $i
  937. * @access public
  938. */
  939. function setSSLVerifyHost($i)
  940. {
  941. $this->verifyhost = $i;
  942. }
  943. /**
  944. * Set proxy info
  945. * @param string $proxyhost
  946. * @param string $proxyport Defaults to 8080 for HTTP and 443 for HTTPS
  947. * @param string $proxyusername Leave blank if proxy has public access
  948. * @param string $proxypassword Leave blank if proxy has public access
  949. * @param int $proxyauthtype set to constant CURLAUTH_MTLM to use NTLM auth with proxy
  950. * @access public
  951. */
  952. function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 1)
  953. {
  954. $this->proxy = $proxyhost;
  955. $this->proxyport = $proxyport;
  956. $this->proxy_user = $proxyusername;
  957. $this->proxy_pass = $proxypassword;
  958. $this->proxy_autthtype = $proxyauthtype;
  959. }
  960. /**
  961. * Enables/disables reception of compressed xmlrpc responses.
  962. * Note that enabling reception of compressed responses merely adds some standard
  963. * http headers to xmlrpc requests. It is up to the xmlrpc server to return
  964. * compressed responses when receiving such requests.
  965. * @param string $compmethod either 'gzip', 'deflate', 'any' or ''
  966. * @access public
  967. */
  968. function setAcceptedCompression($compmethod)
  969. {
  970. if ($compmethod == 'any')
  971. $this->accepted_compression = array('gzip', 'deflate');
  972. else
  973. $this->accepted_compression = array($compmethod);
  974. }
  975. /**
  976. * Enables/disables http compression of xmlrpc request.
  977. * Take care when sending compressed requests: servers might not support them
  978. * (and automatic fallback to uncompressed requests is not yet implemented)
  979. * @param string $compmethod either 'gzip', 'deflate' or ''
  980. * @access public
  981. */
  982. function setRequestCompression($compmethod)
  983. {
  984. $this->request_compression = $compmethod;
  985. }
  986. /**
  987. * Adds a cookie to list of cookies that will be sent to server.
  988. * NB: setting any param but name and value will turn the cookie into a 'version 1' cookie:
  989. * do not do it unless you know what you are doing
  990. * @param string $name
  991. * @param string $value
  992. * @param string $path
  993. * @param string $domain
  994. * @param int $port
  995. * @access public
  996. *
  997. * @todo check correctness of urlencoding cookie value (copied from php way of doing it...)
  998. */
  999. function setCookie($name, $value='', $path='', $domain='', $port=null)
  1000. {
  1001. $this->cookies[$name]['value'] = urlencode($value);
  1002. if ($path || $domain || $port)
  1003. {
  1004. $this->cookies[$name]['path'] = $path;
  1005. $this->cookies[$name]['domain'] = $domain;
  1006. $this->cookies[$name]['port'] = $port;
  1007. $this->cookies[$name]['version'] = 1;
  1008. }
  1009. else
  1010. {
  1011. $this->cookies[$name]['version'] = 0;
  1012. }
  1013. }
  1014. /**
  1015. * Send an xmlrpc request
  1016. * @param mixed $msg The message object, or an array of messages for using multicall, or the complete xml representation of a request
  1017. * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply
  1018. * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used
  1019. * @return xmlrpcresp
  1020. * @access public
  1021. */
  1022. function& send($msg, $timeout=0, $method='')
  1023. {
  1024. // if user deos not specify http protocol, use native method of this client
  1025. // (i.e. method set during call to constructor)
  1026. if($method == '')
  1027. {
  1028. $method = $this->method;
  1029. }
  1030. if(is_array($msg))
  1031. {
  1032. // $msg is an array of xmlrpcmsg's
  1033. $r = $this->multicall($msg, $timeout, $method);
  1034. return $r;
  1035. }
  1036. elseif(is_string($msg))
  1037. {
  1038. $n =& new xmlrpcmsg('');
  1039. $n->payload = $msg;
  1040. $msg = $n;
  1041. }
  1042. // where msg is an xmlrpcmsg
  1043. $msg->debug=$this->debug;
  1044. if($method == 'https')
  1045. {
  1046. $r =& $this->sendPayloadHTTPS(
  1047. $msg,
  1048. $this->server,
  1049. $this->port,
  1050. $timeout,
  1051. $this->username,
  1052. $this->password,
  1053. $this->authtype,
  1054. $this->cert,
  1055. $this->certpass,
  1056. $this->cacert,
  1057. $this->cacertdir,
  1058. $this->proxy,
  1059. $this->proxyport,
  1060. $this->proxy_user,
  1061. $this->proxy_pass,
  1062. $this->proxy_authtype,
  1063. $this->keepalive,
  1064. $this->key,
  1065. $this->keypass
  1066. );
  1067. }
  1068. elseif($method == 'http11')
  1069. {
  1070. $r =& $this->sendPayloadCURL(
  1071. $msg,
  1072. $this->server,
  1073. $this->port,
  1074. $timeout,
  1075. $this->username,
  1076. $this->password,
  1077. $this->authtype,
  1078. null,
  1079. null,
  1080. null,
  1081. null,
  1082. $this->proxy,
  1083. $this->proxyport,
  1084. $this->proxy_user,
  1085. $this->proxy_pass,
  1086. $this->proxy_authtype,
  1087. 'http',
  1088. $this->keepalive
  1089. );
  1090. }
  1091. else
  1092. {
  1093. $r =& $this->sendPayloadHTTP10(
  1094. $msg,
  1095. $this->server,
  1096. $this->port,
  1097. $timeout,
  1098. $this->username,
  1099. $this->password,
  1100. $this->authtype,
  1101. $this->proxy,
  1102. $this->proxyport,
  1103. $this->proxy_user,
  1104. $this->proxy_pass,
  1105. $this->proxy_authtype
  1106. );
  1107. }
  1108. return $r;
  1109. }
  1110. /**
  1111. * @access private
  1112. */
  1113. function &sendPayloadHTTP10($msg, $server, $port, $timeout=0,
  1114. $username='', $password='', $authtype=1, $proxyhost='',
  1115. $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1)
  1116. {
  1117. if($port==0)
  1118. {
  1119. $port=80;
  1120. }
  1121. // Only create the payload if it was not created previously
  1122. if(empty($msg->payload))
  1123. {
  1124. $msg->createPayload($this->request_charset_encoding);
  1125. }
  1126. $payload = $msg->payload;
  1127. // Deflate request body and set appropriate request headers
  1128. if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate'))
  1129. {
  1130. if($this->request_compression == 'gzip')
  1131. {
  1132. $a = @gzencode($payload);
  1133. if($a)
  1134. {
  1135. $payload = $a;
  1136. $encoding_hdr = "Content-Encoding: gzip\r\n";
  1137. }
  1138. }
  1139. else
  1140. {
  1141. $a = @gzcompress($payload);
  1142. if($a)
  1143. {
  1144. $payload = $a;
  1145. $encoding_hdr = "Content-Encoding: deflate\r\n";
  1146. }
  1147. }
  1148. }
  1149. else
  1150. {
  1151. $encoding_hdr = '';
  1152. }
  1153. // thanks to Grant Rauscher <grant7@firstworld.net> for this
  1154. $credentials='';
  1155. if($username!='')
  1156. {
  1157. $credentials='Authorization: Basic ' . base64_encode($username . ':' . $password) . "\r\n";
  1158. if ($authtype != 1)
  1159. {
  1160. error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth is supported with HTTP 1.0');
  1161. }
  1162. }
  1163. $accepted_encoding = '';
  1164. if(is_array($this->accepted_compression) && count($this->accepted_compression))
  1165. {
  1166. $accepted_encoding = 'Accept-Encoding: ' . implode(', ', $this->accepted_compression) . "\r\n";
  1167. }
  1168. $proxy_credentials = '';
  1169. if($proxyhost)
  1170. {
  1171. if($proxyport == 0)
  1172. {
  1173. $proxyport = 8080;
  1174. }
  1175. $connectserver = $proxyhost;
  1176. $connectport = $proxyport;
  1177. $uri = 'http://'.$server.':'.$port.$this->path;
  1178. if($proxyusername != '')
  1179. {
  1180. if ($proxyauthtype != 1)
  1181. {
  1182. error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth to proxy is supported with HTTP 1.0');
  1183. }
  1184. $proxy_credentials = 'Proxy-Authorization: Basic ' . base64_encode($proxyusername.':'.$proxypassword) . "\r\n";
  1185. }
  1186. }
  1187. else
  1188. {
  1189. $connectserver = $server;
  1190. $connectport = $port;
  1191. $uri = $this->path;
  1192. }
  1193. // Cookie generation, as per rfc2965 (version 1 cookies) or
  1194. // netscape's rules (version 0 cookies)
  1195. $cookieheader='';
  1196. foreach ($this->cookies as $name => $cookie)
  1197. {
  1198. if ($cookie['version'])
  1199. {
  1200. $cookieheader .= 'Cookie: $Version="' . $cookie['version'] . '"; ';
  1201. $cookieheader .= $name . '="' . $cookie['value'] . '";';
  1202. if ($cookie['path'])
  1203. $cookieheader .= ' $Path="' . $cookie['path'] . '";';
  1204. if ($cookie['domain'])
  1205. $cookieheader .= ' $Domain="' . $cookie['domain'] . '";';
  1206. if ($cookie['port'])
  1207. $cookieheader .= ' $Port="' . $cookie['domain'] . '";';
  1208. $cookieheader = substr($cookieheader, 0, -1) . "\r\n";
  1209. }
  1210. else
  1211. {
  1212. $cookieheader .= 'Cookie: ' . $name . '=' . $cookie['value'] . "\r\n";
  1213. }
  1214. }
  1215. $op= 'POST ' . $uri. " HTTP/1.0\r\n" .
  1216. 'User-Agent: ' . $GLOBALS['xmlrpcName'] . ' ' . $GLOBALS['xmlrpcVersion'] . "\r\n" .
  1217. 'Host: '. $server . ':' . $port . "\r\n" .
  1218. $credentials .
  1219. $proxy_credentials .
  1220. $accepted_encoding .
  1221. $encoding_hdr .
  1222. 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings) . "\r\n" .
  1223. $cookieheader .
  1224. 'Content-Type: ' . $msg->content_type . "\r\nContent-Length: " .
  1225. strlen($payload) . "\r\n\r\n" .
  1226. $payload;
  1227. if($this->debug > 1)
  1228. {
  1229. print "<PRE>\n---SENDING---\n" . htmlentities($op) . "\n---END---\n</PRE>";
  1230. // let the client see this now in case http times out...
  1231. flush();
  1232. }
  1233. if($timeout>0)
  1234. {
  1235. $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr, $timeout);
  1236. }
  1237. else
  1238. {
  1239. $fp=@fsockopen($connectserver, $connectport, $this->errno, $this->errstr);
  1240. }
  1241. if($fp)
  1242. {
  1243. if($timeout>0 && function_exists('stream_set_timeout'))
  1244. {
  1245. stream_set_timeout($fp, $timeout);
  1246. }
  1247. }
  1248. else
  1249. {
  1250. $this->errstr='Connect error: '.$this->errstr;
  1251. $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $this->errstr . ' (' . $this->errno . ')');
  1252. return $r;
  1253. }
  1254. if(!fputs($fp, $op, strlen($op)))
  1255. {
  1256. $this->errstr='Write error';
  1257. $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $this->errstr);
  1258. return $r;
  1259. }
  1260. else
  1261. {
  1262. // reset errno and errstr on succesful socket connection
  1263. $this->errstr = '';
  1264. }
  1265. // G. Giunta 2005/10/24: close socket before parsing.
  1266. // should yeld slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
  1267. $ipd='';
  1268. while($data=fread($fp, 32768))
  1269. {
  1270. // shall we check for $data === FALSE?
  1271. // as per the manual, it signals an error
  1272. $ipd.=$data;
  1273. }
  1274. fclose($fp);
  1275. $r =& $msg->parseResponse($ipd, false, $this->return_type);
  1276. return $r;
  1277. }
  1278. /**
  1279. * @access private
  1280. */
  1281. function &sendPayloadHTTPS($msg, $server, $port, $timeout=0, $username='',
  1282. $password='', $authtype=1, $cert='',$certpass='', $cacert='', $cacertdir='',
  1283. $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1,
  1284. $keepalive=false, $key='', $keypass='')
  1285. {
  1286. $r =& $this->sendPayloadCURL($msg, $server, $port, $timeout, $username,
  1287. $password, $authtype, $cert, $certpass, $cacert, $cacertdir, $proxyhost, $proxyport,
  1288. $proxyusername, $proxypassword, $proxyauthtype, 'https', $keepalive, $key, $keypass);
  1289. return $r;
  1290. }
  1291. /**
  1292. * Contributed by Justin Miller <justin@voxel.net>
  1293. * Requires curl to be built into PHP
  1294. * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
  1295. * @access private
  1296. */
  1297. function &sendPayloadCURL($msg, $server, $port, $timeout=0, $username='',
  1298. $password='', $authtype=1, $cert='', $certpass='', $cacert='', $cacertdir='',
  1299. $proxyhost='', $proxyport=0, $proxyusername='', $proxypassword='', $proxyauthtype=1, $method='https',
  1300. $keepalive=false, $key='', $keypass='')
  1301. {
  1302. if(!function_exists('curl_init'))
  1303. {
  1304. $this->errstr='CURL unavailable on this install';
  1305. $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_curl'], $GLOBALS['xmlrpcstr']['no_curl']);
  1306. return $r;
  1307. }
  1308. if($method == 'https')
  1309. {
  1310. if(($info = curl_version()) &&
  1311. ((is_string($info) && strpos($info, 'OpenSSL') === null) || (is_array($info) && !isset($info['ssl_version']))))
  1312. {
  1313. $this->errstr='SSL unavailable on this install';
  1314. $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_ssl'], $GLOBALS['xmlrpcstr']['no_ssl']);
  1315. return $r;
  1316. }
  1317. }
  1318. if($port == 0)
  1319. {
  1320. if($method == 'http')
  1321. {
  1322. $port = 80;
  1323. }
  1324. else
  1325. {
  1326. $port = 443;
  1327. }
  1328. }
  1329. // Only create the payload if it was not created previously
  1330. if(empty($msg->payload))
  1331. {
  1332. $msg->createPayload($this->request_charset_encoding);
  1333. }
  1334. // Deflate request body and set appropriate request headers
  1335. $payload = $msg->payload;
  1336. if(function_exists('gzdeflate') && ($this->request_compression == 'gzip' || $this->request_compression == 'deflate'))
  1337. {
  1338. if($this->request_compression == 'gzip')
  1339. {
  1340. $a = @gzencode($payload);
  1341. if($a)
  1342. {
  1343. $payload = $a;
  1344. $encoding_hdr = 'Content-Encoding: gzip';
  1345. }
  1346. }
  1347. else
  1348. {
  1349. $a = @gzcompress($payload);
  1350. if($a)
  1351. {
  1352. $payload = $a;
  1353. $encoding_hdr = 'Content-Encoding: deflate';
  1354. }
  1355. }
  1356. }
  1357. else
  1358. {
  1359. $encoding_hdr = '';
  1360. }
  1361. if($this->debug > 1)
  1362. {
  1363. print "<PRE>\n---SENDING---\n" . htmlentities($payload) . "\n---END---\n</PRE>";
  1364. // let the client see this now in case http times out...
  1365. flush();
  1366. }
  1367. if(!$keepalive || !$this->xmlrpc_curl_handle)
  1368. {
  1369. $curl = curl_init($method . '://' . $server . ':' . $port . $this->path);
  1370. if($keepalive)
  1371. {
  1372. $this->xmlrpc_curl_handle = $curl;
  1373. }
  1374. }
  1375. else
  1376. {
  1377. $curl = $this->xmlrpc_curl_handle;
  1378. }
  1379. // results into variable
  1380. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  1381. if($this->debug)
  1382. {
  1383. curl_setopt($curl, CURLOPT_VERBOSE, 1);
  1384. }
  1385. curl_setopt($curl, CURLOPT_USERAGENT, $GLOBALS['xmlrpcName'].' '.$GLOBALS['xmlrpcVersion']);
  1386. // required for XMLRPC: post the data
  1387. curl_setopt($curl, CURLOPT_POST, 1);
  1388. // the data
  1389. curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
  1390. // return the header too
  1391. curl_setopt($curl, CURLOPT_HEADER, 1);
  1392. // will only work with PHP >= 5.0
  1393. // NB: if we set an empty string, CURL will add http header indicating
  1394. // ALL methods it is supporting. This is possibly a better option than
  1395. // letting the user tell what curl can / cannot do...
  1396. if(is_array($this->accepted_compression) && count($this->accepted_compression))
  1397. {
  1398. //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
  1399. // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
  1400. if (count($this->accepted_compression) == 1)
  1401. {
  1402. curl_setopt($curl, CURLOPT_ENCODING, $this->accepted_compression[0]);
  1403. }
  1404. else
  1405. curl_setopt($curl, CURLOPT_ENCODING, '');
  1406. }
  1407. // extra headers
  1408. $headers = array('Content-Type: ' . $msg->content_type , 'Accept-Charset: ' . implode(',', $this->accepted_charset_encodings));
  1409. // if no keepalive is wanted, let the server know it in advance
  1410. if(!$keepalive)
  1411. {
  1412. $headers[] = 'Connection: close';
  1413. }
  1414. // request compression header
  1415. if($encoding_hdr)
  1416. {
  1417. $headers[] = $encoding_hdr;
  1418. }
  1419. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  1420. // timeout is borked
  1421. if($timeout)
  1422. {
  1423. curl_setopt($curl, CURLOPT_TIMEOUT, $timeout == 1 ? 1 : $timeout - 1);
  1424. }
  1425. if($username && $password)
  1426. {
  1427. curl_setopt($curl, CURLOPT_USERPWD, $username.':'.$password);
  1428. if (defined('CURLOPT_HTTPAUTH'))
  1429. {
  1430. curl_setopt($curl, CURLOPT_HTTPAUTH, $authtype);
  1431. }
  1432. else if ($authtype != 1)
  1433. {
  1434. error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth is supported by the current PHP/curl install');
  1435. }
  1436. }
  1437. if($method == 'https')
  1438. {
  1439. // set cert file
  1440. if($cert)
  1441. {
  1442. curl_setopt($curl, CURLOPT_SSLCERT, $cert);
  1443. }
  1444. // set cert password
  1445. if($certpass)
  1446. {
  1447. curl_setopt($curl, CURLOPT_SSLCERTPASSWD, $certpass);
  1448. }
  1449. // whether to verify remote host's cert
  1450. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
  1451. // set ca certificates file/dir
  1452. if($cacert)
  1453. {
  1454. curl_setopt($curl, CURLOPT_CAINFO, $cacert);
  1455. }
  1456. if($cacertdir)
  1457. {
  1458. curl_setopt($curl, CURLOPT_CAPATH, $cacertdir);
  1459. }
  1460. // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
  1461. if($key)
  1462. {
  1463. curl_setopt($curl, CURLOPT_SSLKEY, $key);
  1464. }
  1465. // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
  1466. if($keypass)
  1467. {
  1468. curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $keypass);
  1469. }
  1470. // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that it matches the hostname used
  1471. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->verifyhost);
  1472. }
  1473. // proxy info
  1474. if($proxyhost)
  1475. {
  1476. if($proxyport == 0)
  1477. {
  1478. $proxyport = 8080; // NB: even for HTTPS, local connection is on port 8080
  1479. }
  1480. curl_setopt($curl, CURLOPT_PROXY,$proxyhost.':'.$proxyport);
  1481. //curl_setopt($curl, CURLOPT_PROXYPORT,$proxyport);
  1482. if($proxyusername)
  1483. {
  1484. curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyusername.':'.$proxypassword);
  1485. if (defined('CURLOPT_PROXYAUTH'))
  1486. {
  1487. curl_setopt($curl, CURLOPT_PROXYAUTH, $proxyauthtype);
  1488. }
  1489. else if ($proxyauthtype != 1)
  1490. {
  1491. error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth to proxy is supported by the current PHP/curl install');
  1492. }
  1493. }
  1494. }
  1495. // NB: should we build cookie http headers by hand rather than let CURL do it?
  1496. // the following code does not honour 'expires', 'path' and 'domain' cookie attributes
  1497. // set to clint obj the the user...
  1498. if (count($this->cookies))
  1499. {
  1500. $cookieheader = '';
  1501. foreach ($this->cookies as $name => $cookie)
  1502. {
  1503. $cookieheader .= $name . '=' . $cookie['value'] . ', ';
  1504. }
  1505. curl_setopt($curl, CURLOPT_COOKIE, substr($cookieheader, 0, -2));
  1506. }
  1507. $result = curl_exec($curl);
  1508. if(!$result)
  1509. {
  1510. $this->errstr='no response';
  1511. $resp=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['curl_fail'], $GLOBALS['xmlrpcstr']['curl_fail']. ': '. curl_error($curl));
  1512. if(!$keepalive)
  1513. {
  1514. curl_close($curl);
  1515. }
  1516. }
  1517. else
  1518. {
  1519. if(!$keepalive)
  1520. {
  1521. curl_close($curl);
  1522. }
  1523. $resp =& $msg->parseResponse($result, true, $this->return_type);
  1524. }
  1525. return $resp;
  1526. }
  1527. /**
  1528. * Send an array of request messages and return an array of responses.
  1529. * Unless $this->no_multicall has been set to true, it will try first
  1530. * to use one single xmlrpc call to server method system.multicall, and
  1531. * revert to sending many successive calls in case of failure.
  1532. * This failure is also stored in $this->no_multicall for subsequent calls.
  1533. * Unfortunately, there is no server error code universally used to denote
  1534. * the fact that multicall is unsupported, so there is no way to reliably
  1535. * distinguish between that and a temporary failure.
  1536. * If you are sure that server supports multicall and do not want to
  1537. * fallback to using many single calls, set the fourth parameter to FALSE.
  1538. *
  1539. * NB: trying to shoehorn extra functionality into existing syntax has resulted
  1540. * in pretty much convoluted code...
  1541. *
  1542. * @param array $msgs an array of xmlrpcmsg objects
  1543. * @param integer $timeout connection timeout (in seconds)
  1544. * @param string $method the http protocol variant to be used
  1545. * @param boolen fallback When true, upon receiveing an error during multicall, multiple single calls will be attempted
  1546. * @return array
  1547. * @access public
  1548. */
  1549. function multicall($msgs, $timeout=0, $method='http', $fallback=true)
  1550. {
  1551. if(!$this->no_multicall)
  1552. {
  1553. $results = $this->_try_multicall($msgs, $timeout, $method);
  1554. if(is_array($results))
  1555. {
  1556. // System.multicall succeeded
  1557. return $results;
  1558. }
  1559. else
  1560. {
  1561. // either system.multicall is unsupported by server,
  1562. // or call failed for some other reason.
  1563. if ($fallback)
  1564. {
  1565. // Don't try it next time...
  1566. $this->no_multicall = true;
  1567. }
  1568. else
  1569. {
  1570. if (is_a($results, 'xmlrpcresp'))
  1571. {
  1572. $result = $results;
  1573. }
  1574. else
  1575. {
  1576. $result =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['multicall_error'], $GLOBALS['xmlrpcstr']['multicall_error']);
  1577. }
  1578. }
  1579. }
  1580. }
  1581. else
  1582. {
  1583. // override fallback, in case careless user tries to do two
  1584. // opposite things at the same time
  1585. $fallback = true;
  1586. }
  1587. $results = array();
  1588. if ($fallback)
  1589. {
  1590. // system.multicall is (probably) unsupported by server:
  1591. // emulate multicall via multiple requests
  1592. foreach($msgs as $msg)
  1593. {
  1594. $results[] =& $this->send($msg, $timeout, $method);
  1595. }
  1596. }
  1597. else
  1598. {
  1599. // user does NOT want to fallback on many single calls:
  1600. // since we should always return an array of responses,
  1601. // return an array with the same error repeated n times
  1602. foreach($msgs as $msg)
  1603. {
  1604. $results[] = $result;
  1605. }
  1606. }
  1607. return $results;
  1608. }
  1609. /**
  1610. * Attempt to boxcar $msgs via system.multicall.
  1611. * Returns either an array of xmlrpcreponses, an xmlrpc error response
  1612. * or false (when recived response does not respect valid multiccall syntax)
  1613. * @access private
  1614. */
  1615. function _try_multicall($msgs, $timeout, $method)
  1616. {
  1617. // Construct multicall message
  1618. $calls = array();
  1619. foreach($msgs as $msg)
  1620. {
  1621. $call['methodName'] =& new xmlrpcval($msg->method(),'string');
  1622. $numParams = $msg->getNumParams();
  1623. $params = array();
  1624. for($i = 0; $i < $numParams; $i++)
  1625. {
  1626. $params[$i] = $msg->getParam($i);
  1627. }
  1628. $call['params'] =& new xmlrpcval($params, 'array');
  1629. $calls[] =& new xmlrpcval($call, 'struct');
  1630. }
  1631. $multicall =& new xmlrpcmsg('system.multicall');
  1632. $multicall->addParam(new xmlrpcval($calls, 'array'));
  1633. // Attempt RPC call
  1634. $result =& $this->send($multicall, $timeout, $method);
  1635. if($result->faultCode() != 0)
  1636. {
  1637. // call to system.multicall failed
  1638. return $result;
  1639. }
  1640. // Unpack responses.
  1641. $rets = $result->value();
  1642. if ($this->return_type == 'xml')
  1643. {
  1644. return $rets;
  1645. }
  1646. else if ($this->return_type == 'phpvals')
  1647. {
  1648. ///@todo test this code branch...
  1649. $rets = $result->value();
  1650. if(!is_array($rets))
  1651. {
  1652. return false; // bad return type from system.multicall
  1653. }
  1654. $numRets = count($rets);
  1655. if($numRets != count($msgs))
  1656. {
  1657. return false; // wrong number of return values.
  1658. }
  1659. $response = array();
  1660. for($i = 0; $i < $numRets; $i++)
  1661. {
  1662. $val = $rets[$i];
  1663. if (!is_array($val)) {
  1664. return false;
  1665. }
  1666. switch(count($val))
  1667. {
  1668. case 1:
  1669. if(!isset($val[0]))
  1670. {
  1671. return false; // Bad value
  1672. }
  1673. // Normal return value
  1674. $response[$i] =& new xmlrpcresp($val[0], 0, '', 'phpvals');
  1675. break;
  1676. case 2:
  1677. /// @todo remove usage of @: it is apparently quite slow
  1678. $code = @$val['faultCode'];
  1679. if(!is_int($code))
  1680. {
  1681. return false;
  1682. }
  1683. $str = @$val['faultString'];
  1684. if(!is_string($str))
  1685. {
  1686. return false;
  1687. }
  1688. $response[$i] =& new xmlrpcresp(0, $code, $str);
  1689. break;
  1690. default:
  1691. return false;
  1692. }
  1693. }
  1694. return $response;
  1695. }
  1696. else // return type == 'xmlrpcvals'
  1697. {
  1698. $rets = $result->value();
  1699. if($rets->kindOf() != 'array')
  1700. {
  1701. return false; // bad return type from system.multicall
  1702. }
  1703. $numRets = $rets->arraysize();
  1704. if($numRets != count($msgs))
  1705. {
  1706. return false; // wrong number of return values.
  1707. }
  1708. $response = array();
  1709. for($i = 0; $i < $numRets; $i++)
  1710. {
  1711. $val = $rets->arraymem($i);
  1712. switch($val->kindOf())
  1713. {
  1714. case 'array':
  1715. if($val->arraysize() != 1)
  1716. {
  1717. return false; // Bad value
  1718. }
  1719. // Normal return value
  1720. $response[$i] =& new xmlrpcresp($val->arraymem(0));
  1721. break;
  1722. case 'struct':
  1723. $code = $val->structmem('faultCode');
  1724. if($code->kindOf() != 'scalar' || $code->scalartyp() != 'int')
  1725. {
  1726. return false;
  1727. }
  1728. $str = $val->structmem('faultString');
  1729. if($str->kindOf() != 'scalar' || $str->scalartyp() != 'string')
  1730. {
  1731. return false;
  1732. }
  1733. $response[$i] =& new xmlrpcresp(0, $code->scalarval(), $str->scalarval());
  1734. break;
  1735. default:
  1736. return false;
  1737. }
  1738. }
  1739. return $response;
  1740. }
  1741. }
  1742. } // end class xmlrpc_client
  1743. class xmlrpcresp
  1744. {
  1745. var $val = 0;
  1746. var $valtyp;
  1747. var $errno = 0;
  1748. var $errstr = '';
  1749. var $payload;
  1750. var $hdrs = array();
  1751. var $_cookies = array();
  1752. var $content_type = 'text/xml';
  1753. var $raw_data = '';
  1754. /**
  1755. * @param mixed $val either an xmlrpcval obj, a php value or the xml serialization of an xmlrpcval (a string)
  1756. * @param integer $fcode set it to anything but 0 to create an error response
  1757. * @param string $fstr the error string, in case of an error response
  1758. * @param string $valtyp either 'xmlrpcvals', 'phpvals' or 'xml'
  1759. *
  1760. * @todo add check that $val / $fcode / $fstr is of correct type???
  1761. * NB: as of now we do not do it, since it might be either an xmlrpcval or a plain
  1762. * php val, or a complete xml chunk, depending on usage of xmlrpc_client::send() inside which creator is called...
  1763. */
  1764. function xmlrpcresp($val, $fcode = 0, $fstr = '', $valtyp='')
  1765. {
  1766. if($fcode != 0)
  1767. {
  1768. // error response
  1769. $this->errno = $fcode;
  1770. $this->errstr = $fstr;
  1771. //$this->errstr = htmlspecialchars($fstr); // XXX: encoding probably shouldn't be done here; fix later.
  1772. }
  1773. else
  1774. {
  1775. // successful response
  1776. $this->val = $val;
  1777. if ($valtyp == '')
  1778. {
  1779. // user did not declare type of response value: try to guess it
  1780. if (is_object($this->val) && is_a($this->val, 'xmlrpcval'))
  1781. {
  1782. $this->valtyp = 'xmlrpcvals';
  1783. }
  1784. else if (is_string($this->val))
  1785. {
  1786. $this->valtyp = 'xml';
  1787. }
  1788. else
  1789. {
  1790. $this->valtyp = 'phpvals';
  1791. }
  1792. }
  1793. else
  1794. {
  1795. // user declares type of resp value: believe him
  1796. $this->valtyp = $valtyp;
  1797. }
  1798. }
  1799. }
  1800. /**
  1801. * Returns the error code of the response.
  1802. * @return integer the error code of this response (0 for not-error responses)
  1803. * @access public
  1804. */
  1805. function faultCode()
  1806. {
  1807. return $this->errno;
  1808. }
  1809. /**
  1810. * Returns the error code of the response.
  1811. * @return string the error string of this response ('' for not-error responses)
  1812. * @access public
  1813. */
  1814. function faultString()
  1815. {
  1816. return $this->errstr;
  1817. }
  1818. /**
  1819. * Returns the value received by the server.
  1820. * @return mixed the xmlrpcval object returned by the server. Might be an xml string or php value if the response has been created by specially configured xmlrpc_client objects
  1821. * @access public
  1822. */
  1823. function value()
  1824. {
  1825. return $this->val;
  1826. }
  1827. /**
  1828. * Returns an array with the cookies received from the server.
  1829. * Array has the form: $cookiename => array ('value' => $val, $attr1 => $val1, $attr2 = $val2, ...)
  1830. * with attributes being e.g. 'expires', 'path', domain'.
  1831. * NB: cookies sent as 'expired' by the server (i.e. with an expiry date in the past)
  1832. * are still present in the array. It is up to the user-defined code to decide
  1833. * how to use the received cookies, and wheter they have to be sent back with the next
  1834. * request to the server (using xmlrpc_client::setCookie) or not
  1835. * @return array array of cookies received from the server
  1836. * @access public
  1837. */
  1838. function cookies()
  1839. {
  1840. return $this->_cookies;
  1841. }
  1842. /**
  1843. * Returns xml representation of the response. XML prologue not included
  1844. * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed
  1845. * @return string the xml representation of the response
  1846. * @access public
  1847. */
  1848. function serialize($charset_encoding='')
  1849. {
  1850. if ($charset_encoding != '')
  1851. $this->content_type = 'text/xml; charset=' . $charset_encoding;
  1852. else
  1853. $this->content_type = 'text/xml';
  1854. $result = "<methodResponse>\n";
  1855. if($this->errno)
  1856. {
  1857. // G. Giunta 2005/2/13: let non-ASCII response messages be tolerated by clients
  1858. // by xml-encoding non ascii chars
  1859. $result .= "<fault>\n" .
  1860. "<value>\n<struct><member><name>faultCode</name>\n<value><int>" . $this->errno .
  1861. "</int></value>\n</member>\n<member>\n<name>faultString</name>\n<value><string>" .
  1862. xmlrpc_encode_entitites($this->errstr, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding) . "</string></value>\n</member>\n" .
  1863. "</struct>\n</value>\n</fault>";
  1864. }
  1865. else
  1866. {
  1867. if(!is_object($this->val) || !is_a($this->val, 'xmlrpcval'))
  1868. {
  1869. if (is_string($this->val) && $this->valtyp == 'xml')
  1870. {
  1871. $result .= "<params>\n<param>\n" .
  1872. $this->val .
  1873. "</param>\n</params>";
  1874. }
  1875. else
  1876. {
  1877. /// @todo try to build something serializable?
  1878. die('cannot serialize xmlrpcresp objects whose content is native php values');
  1879. }
  1880. }
  1881. else
  1882. {
  1883. $result .= "<params>\n<param>\n" .
  1884. $this->val->serialize($charset_encoding) .
  1885. "</param>\n</params>";
  1886. }
  1887. }
  1888. $result .= "\n</methodResponse>";
  1889. $this->payload = $result;
  1890. return $result;
  1891. }
  1892. }
  1893. class xmlrpcmsg
  1894. {
  1895. var $payload;
  1896. var $methodname;
  1897. var $params=array();
  1898. var $debug=0;
  1899. var $content_type = 'text/xml';
  1900. /**
  1901. * @param string $meth the name of the method to invoke
  1902. * @param array $pars array of parameters to be paased to the method (xmlrpcval objects)
  1903. */
  1904. function xmlrpcmsg($meth, $pars=0)
  1905. {
  1906. $this->methodname=$meth;
  1907. if(is_array($pars) && count($pars)>0)
  1908. {
  1909. for($i=0; $i<count($pars); $i++)
  1910. {
  1911. $this->addParam($pars[$i]);
  1912. }
  1913. }
  1914. }
  1915. /**
  1916. * @access private
  1917. */
  1918. function xml_header($charset_encoding='')
  1919. {
  1920. if ($charset_encoding != '')
  1921. {
  1922. return "<?xml version=\"1.0\" encoding=\"$charset_encoding\" ?" . ">\n<methodCall>\n";
  1923. }
  1924. else
  1925. {
  1926. return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";
  1927. }
  1928. }
  1929. /**
  1930. * @access private
  1931. */
  1932. function xml_footer()
  1933. {
  1934. return '</methodCall>';
  1935. }
  1936. /**
  1937. * @access private
  1938. */
  1939. function kindOf()
  1940. {
  1941. return 'msg';
  1942. }
  1943. /**
  1944. * @access private
  1945. */
  1946. function createPayload($charset_encoding='')
  1947. {
  1948. if ($charset_encoding != '')
  1949. $this->content_type = 'text/xml; charset=' . $charset_encoding;
  1950. else
  1951. $this->content_type = 'text/xml';
  1952. $this->payload=$this->xml_header($charset_encoding);
  1953. $this->payload.='<methodName>' . $this->methodname . "</methodName>\n";
  1954. $this->payload.="<params>\n";
  1955. for($i=0; $i<count($this->params); $i++)
  1956. {
  1957. $p=$this->params[$i];
  1958. $this->payload.="<param>\n" . $p->serialize($charset_encoding) .
  1959. "</param>\n";
  1960. }
  1961. $this->payload.="</params>\n";
  1962. $this->payload.=$this->xml_footer();
  1963. }
  1964. /**
  1965. * Gets/sets the xmlrpc method to be invoked
  1966. * @param string $meth the method to be set (leave empty not to set it)
  1967. * @return string the method that will be invoked
  1968. * @access public
  1969. */
  1970. function method($meth='')
  1971. {
  1972. if($meth!='')
  1973. {
  1974. $this->methodname=$meth;
  1975. }
  1976. return $this->methodname;
  1977. }
  1978. /**
  1979. * Returns xml representation of the message. XML prologue included
  1980. * @return string the xml representation of the message, xml prologue included
  1981. * @access public
  1982. */
  1983. function serialize($charset_encoding='')
  1984. {
  1985. $this->createPayload($charset_encoding);
  1986. return $this->payload;
  1987. }
  1988. /**
  1989. * Add a parameter to the list of parameters to be used upon method invocation
  1990. * @param xmlrpcval $par
  1991. * @return boolean false on failure
  1992. * @access public
  1993. */
  1994. function addParam($par)
  1995. {
  1996. // add check: do not add to self params which are not xmlrpcvals
  1997. if(is_object($par) && is_a($par, 'xmlrpcval'))
  1998. {
  1999. $this->params[]=$par;
  2000. return true;
  2001. }
  2002. else
  2003. {
  2004. return false;
  2005. }
  2006. }
  2007. /**
  2008. * Returns the nth parameter in the message. The index zero-based.
  2009. * @param integer $i the index of the parameter to fetch (zero based)
  2010. * @return xmlrpcval the i-th parameter
  2011. * @access public
  2012. */
  2013. function getParam($i) { return $this->params[$i]; }
  2014. /**
  2015. * Returns the number of parameters in the messge.
  2016. * @return integer the number of parameters currently set
  2017. * @access public
  2018. */
  2019. function getNumParams() { return count($this->params); }
  2020. /**
  2021. * Given an open file handle, read all data available and parse it as axmlrpc response.
  2022. * NB: the file handle is not closed by this function.
  2023. * @access public
  2024. * @return xmlrpcresp
  2025. * @todo add 2nd & 3rd param to be passed to ParseResponse() ???
  2026. */
  2027. function &parseResponseFile($fp)
  2028. {
  2029. $ipd='';
  2030. while($data=fread($fp, 32768))
  2031. {
  2032. $ipd.=$data;
  2033. }
  2034. //fclose($fp);
  2035. $r =& $this->parseResponse($ipd);
  2036. return $r;
  2037. }
  2038. /**
  2039. * Parses HTTP headers and separates them from data.
  2040. * @access private
  2041. */
  2042. function &parseResponseHeaders(&$data, $headers_processed=false)
  2043. {
  2044. // Strip HTTP 1.1 100 Continue header if present
  2045. while(preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data))
  2046. {
  2047. $pos = strpos($data, 'HTTP', 12);
  2048. // server sent a Continue header without any (valid) content following...
  2049. // give the client a chance to know it
  2050. if(!$pos && !is_int($pos)) // works fine in php 3, 4 and 5
  2051. {
  2052. break;
  2053. }
  2054. $data = substr($data, $pos);
  2055. }
  2056. if(!preg_match('/^HTTP\/[0-9.]+ 200 /', $data))
  2057. {
  2058. $errstr= substr($data, 0, strpos($data, "\n")-1);
  2059. error_log('XML-RPC: xmlrpcmsg::parseResponse: HTTP error, got response: ' .$errstr);
  2060. $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (' . $errstr . ')');
  2061. return $r;
  2062. }
  2063. $GLOBALS['_xh']['headers'] = array();
  2064. $GLOBALS['_xh']['cookies'] = array();
  2065. // be tolerant to usage of \n instead of \r\n to separate headers and data
  2066. // (even though it is not valid http)
  2067. $pos = strpos($data,"\r\n\r\n");
  2068. if($pos || is_int($pos))
  2069. {
  2070. $bd = $pos+4;
  2071. }
  2072. else
  2073. {
  2074. $pos = strpos($data,"\n\n");
  2075. if($pos || is_int($pos))
  2076. {
  2077. $bd = $pos+2;
  2078. }
  2079. else
  2080. {
  2081. // No separation between response headers and body: fault?
  2082. $bd = 0;
  2083. }
  2084. }
  2085. // be tolerant to line endings, and extra empty lines
  2086. $ar = split("\r?\n", trim(substr($data, 0, $pos)));
  2087. while(list(,$line) = @each($ar))
  2088. {
  2089. // take care of multi-line headers and cookies
  2090. $arr = explode(':',$line,2);
  2091. if(count($arr) > 1)
  2092. {
  2093. $header_name = strtolower(trim($arr[0]));
  2094. /// @todo some other headers (the ones that allow a CSV list of values)
  2095. /// do allow many values to be passed using multiple header lines.
  2096. /// We should add content to $GLOBALS['_xh']['headers'][$header_name]
  2097. /// instead of replacing it for those...
  2098. if ($header_name == 'set-cookie' || $header_name == 'set-cookie2')
  2099. {
  2100. if ($header_name == 'set-cookie2')
  2101. {
  2102. // version 2 cookies:
  2103. // there could be many cookies on one line, comma separated
  2104. $cookies = explode(',', $arr[1]);
  2105. }
  2106. else
  2107. {
  2108. $cookies = array($arr[1]);
  2109. }
  2110. foreach ($cookies as $cookie)
  2111. {
  2112. // glue together all received cookies, using a comma to separate them
  2113. // (same as php does with getallheaders())
  2114. if (isset($GLOBALS['_xh']['headers'][$header_name]))
  2115. $GLOBALS['_xh']['headers'][$header_name] .= ', ' . trim($cookie);
  2116. else
  2117. $GLOBALS['_xh']['headers'][$header_name] = trim($cookie);
  2118. // parse cookie attributes, in case user wants to coorectly honour then
  2119. // feature creep: only allow rfc-compliant cookie attributes?
  2120. $cookie = explode(';', $cookie);
  2121. foreach ($cookie as $pos => $val)
  2122. {
  2123. $val = explode('=', $val, 2);
  2124. $tag = trim($val[0]);
  2125. $val = trim(@$val[1]);
  2126. /// @todo with version 1 cookies, we should strip leading and trailing " chars
  2127. if ($pos == 0)
  2128. {
  2129. $cookiename = $tag;
  2130. $GLOBALS['_xh']['cookies'][$tag] = array();
  2131. $GLOBALS['_xh']['cookies'][$cookiename]['value'] = urldecode($val);
  2132. }
  2133. else
  2134. {
  2135. $GLOBALS['_xh']['cookies'][$cookiename][$tag] = $val;
  2136. }
  2137. }
  2138. }
  2139. }
  2140. else
  2141. {
  2142. $GLOBALS['_xh']['headers'][$header_name] = trim($arr[1]);
  2143. }
  2144. }
  2145. elseif(isset($header_name))
  2146. {
  2147. /// @todo version1 cookies might span multiple lines, thus breaking the parsing above
  2148. $GLOBALS['_xh']['headers'][$header_name] .= ' ' . trim($line);
  2149. }
  2150. }
  2151. $data = substr($data, $bd);
  2152. if($this->debug && count($GLOBALS['_xh']['headers']))
  2153. {
  2154. print '<PRE>';
  2155. foreach($GLOBALS['_xh']['headers'] as $header => $value)
  2156. {
  2157. print "HEADER: $header: $value\n";
  2158. }
  2159. foreach($GLOBALS['_xh']['cookies'] as $header => $value)
  2160. {
  2161. print "COOKIE: $header={$value['value']}\n";
  2162. }
  2163. print "</PRE>\n";
  2164. }
  2165. // if CURL was used for the call, http headers have been processed,
  2166. // and dechunking + reinflating have been carried out
  2167. if(!$headers_processed)
  2168. {
  2169. // Decode chunked encoding sent by http 1.1 servers
  2170. if(isset($GLOBALS['_xh']['headers']['transfer-encoding']) && $GLOBALS['_xh']['headers']['transfer-encoding'] == 'chunked')
  2171. {
  2172. if(!$data = decode_chunked($data))
  2173. {
  2174. error_log('XML-RPC: xmlrpcmsg::parseResponse: errors occurred when trying to rebuild the chunked data received from server');
  2175. $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['dechunk_fail'], $GLOBALS['xmlrpcstr']['dechunk_fail']);
  2176. return $r;
  2177. }
  2178. }
  2179. // Decode gzip-compressed stuff
  2180. // code shamelessly inspired from nusoap library by Dietrich Ayala
  2181. if(isset($GLOBALS['_xh']['headers']['content-encoding']))
  2182. {
  2183. $GLOBALS['_xh']['headers']['content-encoding'] = str_replace('x-', '', $GLOBALS['_xh']['headers']['content-encoding']);
  2184. if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' || $GLOBALS['_xh']['headers']['content-encoding'] == 'gzip')
  2185. {
  2186. // if decoding works, use it. else assume data wasn't gzencoded
  2187. if(function_exists('gzinflate'))
  2188. {
  2189. if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data))
  2190. {
  2191. $data = $degzdata;
  2192. if($this->debug)
  2193. print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
  2194. }
  2195. elseif($GLOBALS['_xh']['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))
  2196. {
  2197. $data = $degzdata;
  2198. if($this->debug)
  2199. print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
  2200. }
  2201. else
  2202. {
  2203. error_log('XML-RPC: xmlrpcmsg::parseResponse: errors occurred when trying to decode the deflated data received from server');
  2204. $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['decompress_fail'], $GLOBALS['xmlrpcstr']['decompress_fail']);
  2205. return $r;
  2206. }
  2207. }
  2208. else
  2209. {
  2210. error_log('XML-RPC: xmlrpcmsg::parseResponse: the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
  2211. $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['cannot_decompress'], $GLOBALS['xmlrpcstr']['cannot_decompress']);
  2212. return $r;
  2213. }
  2214. }
  2215. }
  2216. } // end of 'if needed, de-chunk, re-inflate response'
  2217. // real stupid hack to avoid PHP 4 complaining about returning NULL by ref
  2218. $r = null;
  2219. $r =& $r;
  2220. return $r;
  2221. }
  2222. /**
  2223. * Parse the xmlrpc response containeed in the string $data and return an xmlrpcresp object.
  2224. * @param string $data the xmlrpc response, eventually including http headers
  2225. * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding
  2226. * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'
  2227. * @return xmlrpcresp
  2228. * @access public
  2229. */
  2230. function &parseResponse($data='', $headers_processed=false, $return_type='xmlrpcvals')
  2231. {
  2232. if($this->debug)
  2233. {
  2234. //by maHo, replaced htmlspecialchars with htmlentities
  2235. print "<PRE>---GOT---\n" . htmlentities($data) . "\n---END---\n</PRE>";
  2236. $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
  2237. if ($start)
  2238. {
  2239. $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
  2240. $end = strpos($data, '-->', $start);
  2241. $comments = substr($data, $start, $end-$start);
  2242. print "<PRE>---SERVER DEBUG INFO (DECODED) ---\n\t".htmlentities(str_replace("\n", "\n\t", base64_decode($comments)))."\n---END---\n</PRE>";
  2243. }
  2244. }
  2245. if($data == '')
  2246. {
  2247. error_log('XML-RPC: xmlrpcmsg::parseResponse: no response received from server.');
  2248. $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['no_data'], $GLOBALS['xmlrpcstr']['no_data']);
  2249. return $r;
  2250. }
  2251. $GLOBALS['_xh']=array();
  2252. $raw_data = $data;
  2253. // parse the HTTP headers of the response, if present, and separate them from data
  2254. if(substr($data, 0, 4) == 'HTTP')
  2255. {
  2256. $r =& $this->parseResponseHeaders($data, $headers_processed);
  2257. if ($r)
  2258. {
  2259. // failed processing of HTTP response headers
  2260. // save into response obj the full payload received, for debugging
  2261. $r->raw_data = $data;
  2262. return $r;
  2263. }
  2264. }
  2265. else
  2266. {
  2267. $GLOBALS['_xh']['headers'] = array();
  2268. $GLOBALS['_xh']['cookies'] = array();
  2269. }
  2270. // be tolerant of extra whitespace in response body
  2271. $data = trim($data);
  2272. /// @todo return an error msg if $data=='' ?
  2273. // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
  2274. // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
  2275. $bd = false;
  2276. // Poor man's version of strrpos for php 4...
  2277. $pos = strpos($data, '</methodResponse>');
  2278. while($pos || is_int($pos))
  2279. {
  2280. $bd = $pos+17;
  2281. $pos = strpos($data, '</methodResponse>', $bd);
  2282. }
  2283. if($bd)
  2284. {
  2285. $data = substr($data, 0, $bd);
  2286. }
  2287. // if user wants back raw xml, give it to him
  2288. if ($return_type == 'xml')
  2289. {
  2290. $r =& new xmlrpcresp($data, 0, '', 'xml');
  2291. $r->hdrs = $GLOBALS['_xh']['headers'];
  2292. $r->_cookies = $GLOBALS['_xh']['cookies'];
  2293. $r->raw_data = $raw_data;
  2294. return $r;
  2295. }
  2296. // try to 'guestimate' the character encoding of the received response
  2297. $resp_encoding = guess_encoding(@$GLOBALS['_xh']['headers']['content-type'], $data);
  2298. $GLOBALS['_xh']['ac']='';
  2299. //$GLOBALS['_xh']['qt']=''; //unused...
  2300. $GLOBALS['_xh']['stack'] = array();
  2301. $GLOBALS['_xh']['valuestack'] = array();
  2302. $GLOBALS['_xh']['isf']=0; // 0 = OK, 1 for xmlrpc fault responses, 2 = invalid xmlrpc
  2303. $GLOBALS['_xh']['isf_reason']='';
  2304. $GLOBALS['_xh']['rt']=''; // 'methodcall or 'methodresponse'
  2305. // if response charset encoding is not known / supported, try to use
  2306. // the default encoding and parse the xml anyway, but log a warning...
  2307. if (!in_array($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
  2308. // the following code might be better for mb_string enabled installs, but
  2309. // makes the lib about 200% slower...
  2310. //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
  2311. {
  2312. error_log('XML-RPC: xmlrpcmsg::parseResponse: invalid charset encoding of received response: '.$resp_encoding);
  2313. $resp_encoding = $GLOBALS['xmlrpc_defencoding'];
  2314. }
  2315. $parser = xml_parser_create($resp_encoding);
  2316. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
  2317. // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
  2318. // the xml parser to give us back data in the expected charset
  2319. xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']);
  2320. if ($return_type == 'phpvals')
  2321. {
  2322. xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
  2323. }
  2324. else
  2325. {
  2326. xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
  2327. }
  2328. xml_set_character_data_handler($parser, 'xmlrpc_cd');
  2329. xml_set_default_handler($parser, 'xmlrpc_dh');
  2330. // first error check: xml not well formed
  2331. if(!xml_parse($parser, $data, count($data)))
  2332. {
  2333. // thanks to Peter Kocks <peter.kocks@baygate.com>
  2334. if((xml_get_current_line_number($parser)) == 1)
  2335. {
  2336. $errstr = 'XML error at line 1, check URL';
  2337. }
  2338. else
  2339. {
  2340. $errstr = sprintf('XML error: %s at line %d, column %d',
  2341. xml_error_string(xml_get_error_code($parser)),
  2342. xml_get_current_line_number($parser), xml_get_current_column_number($parser));
  2343. }
  2344. error_log($errstr);
  2345. $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'], $GLOBALS['xmlrpcstr']['invalid_return'].' ('.$errstr.')');
  2346. xml_parser_free($parser);
  2347. if($this->debug)
  2348. {
  2349. print $errstr;
  2350. }
  2351. $r->hdrs = $GLOBALS['_xh']['headers'];
  2352. $r->_cookies = $GLOBALS['_xh']['cookies'];
  2353. $r->raw_data = $raw_data;
  2354. return $r;
  2355. }
  2356. xml_parser_free($parser);
  2357. // second error check: xml well formed but not xml-rpc compliant
  2358. if ($GLOBALS['_xh']['isf'] > 1)
  2359. {
  2360. if ($this->debug)
  2361. {
  2362. /// @todo echo something for user?
  2363. }
  2364. $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'],
  2365. $GLOBALS['xmlrpcstr']['invalid_return'] . ' ' . $GLOBALS['_xh']['isf_reason']);
  2366. }
  2367. // third error check: parsing of the response has somehow gone boink.
  2368. // NB: shall we omit this check, since we trust the parsing code?
  2369. elseif ($return_type == 'xmlrpcvals' && !is_object($GLOBALS['_xh']['value']))
  2370. {
  2371. // something odd has happened
  2372. // and it's time to generate a client side error
  2373. // indicating something odd went on
  2374. $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['invalid_return'],
  2375. $GLOBALS['xmlrpcstr']['invalid_return']);
  2376. }
  2377. else
  2378. {
  2379. if ($this->debug)
  2380. {
  2381. print "<PRE>---PARSED---\n" ;
  2382. var_export($GLOBALS['_xh']['value']);
  2383. print "\n---END---</PRE>";
  2384. }
  2385. // note that using =& will raise an error if $GLOBALS['_xh']['st'] does not generate an object.
  2386. $v =& $GLOBALS['_xh']['value'];
  2387. if($GLOBALS['_xh']['isf'])
  2388. {
  2389. /// @todo we should test here if server sent an int and a string,
  2390. /// and/or coerce them into such...
  2391. if ($return_type == 'xmlrpcvals')
  2392. {
  2393. $errno_v = $v->structmem('faultCode');
  2394. $errstr_v = $v->structmem('faultString');
  2395. $errno = $errno_v->scalarval();
  2396. $errstr = $errstr_v->scalarval();
  2397. }
  2398. else
  2399. {
  2400. $errno = $v['faultCode'];
  2401. $errstr = $v['faultString'];
  2402. }
  2403. if($errno == 0)
  2404. {
  2405. // FAULT returned, errno needs to reflect that
  2406. $errno = -1;
  2407. }
  2408. $r =& new xmlrpcresp(0, $errno, $errstr);
  2409. }
  2410. else
  2411. {
  2412. $r=&new xmlrpcresp($v, 0, '', $return_type);
  2413. }
  2414. }
  2415. $r->hdrs = $GLOBALS['_xh']['headers'];
  2416. $r->_cookies = $GLOBALS['_xh']['cookies'];
  2417. $r->raw_data = $raw_data;
  2418. return $r;
  2419. }
  2420. }
  2421. class xmlrpcval
  2422. {
  2423. var $me=array();
  2424. var $mytype=0;
  2425. var $_php_class=null;
  2426. /**
  2427. * @param mixed $val
  2428. * @param string $type any valid xmlrpc type name (lowercase). If null, 'string' is assumed
  2429. */
  2430. function xmlrpcval($val=-1, $type='')
  2431. {
  2432. /// @todo: optimization creep - do not call addXX, do it all inline.
  2433. /// downside: booleans will not be coerced anymore
  2434. if($val!==-1 || $type!='')
  2435. {
  2436. // optimization creep: inlined all work done by constructor
  2437. switch($type)
  2438. {
  2439. case '':
  2440. $this->mytype=1;
  2441. $this->me['string']=$val;
  2442. break;
  2443. case 'i4':
  2444. case 'int':
  2445. case 'double':
  2446. case 'string':
  2447. case 'boolean':
  2448. case 'dateTime.iso8601':
  2449. case 'base64':
  2450. case 'null':
  2451. $this->mytype=1;
  2452. $this->me[$type]=$val;
  2453. break;
  2454. case 'array':
  2455. $this->mytype=2;
  2456. $this->me['array']=$val;
  2457. break;
  2458. case 'struct':
  2459. $this->mytype=3;
  2460. $this->me['struct']=$val;
  2461. break;
  2462. default:
  2463. error_log("XML-RPC: xmlrpcval::xmlrpcval: not a known type ($type)");
  2464. }
  2465. /*if($type=='')
  2466. {
  2467. $type='string';
  2468. }
  2469. if($GLOBALS['xmlrpcTypes'][$type]==1)
  2470. {
  2471. $this->addScalar($val,$type);
  2472. }
  2473. elseif($GLOBALS['xmlrpcTypes'][$type]==2)
  2474. {
  2475. $this->addArray($val);
  2476. }
  2477. elseif($GLOBALS['xmlrpcTypes'][$type]==3)
  2478. {
  2479. $this->addStruct($val);
  2480. }*/
  2481. }
  2482. }
  2483. /**
  2484. * Add a single php value to an (unitialized) xmlrpcval
  2485. * @param mixed $val
  2486. * @param string $type
  2487. * @return int 1 or 0 on failure
  2488. */
  2489. function addScalar($val, $type='string')
  2490. {
  2491. $typeof=@$GLOBALS['xmlrpcTypes'][$type];
  2492. if($typeof!=1)
  2493. {
  2494. error_log("XML-RPC: xmlrpcval::addScalar: not a scalar type ($type)");
  2495. return 0;
  2496. }
  2497. // coerce booleans into correct values
  2498. // NB: we should iether do it for datetimes, integers and doubles, too,
  2499. // or just plain remove this check, implemnted on booleans only...
  2500. if($type==$GLOBALS['xmlrpcBoolean'])
  2501. {
  2502. if(strcasecmp($val,'true')==0 || $val==1 || ($val==true && strcasecmp($val,'false')))
  2503. {
  2504. $val=true;
  2505. }
  2506. else
  2507. {
  2508. $val=false;
  2509. }
  2510. }
  2511. switch($this->mytype)
  2512. {
  2513. case 1:
  2514. error_log('XML-RPC: xmlrpcval::addScalar: scalar xmlrpcval can have only one value');
  2515. return 0;
  2516. case 3:
  2517. error_log('XML-RPC: xmlrpcval::addScalar: cannot add anonymous scalar to struct xmlrpcval');
  2518. return 0;
  2519. case 2:
  2520. // we're adding a scalar value to an array here
  2521. //$ar=$this->me['array'];
  2522. //$ar[]=&new xmlrpcval($val, $type);
  2523. //$this->me['array']=$ar;
  2524. // Faster (?) avoid all the costly array-copy-by-val done here...
  2525. $this->me['array'][]=&new xmlrpcval($val, $type);
  2526. return 1;
  2527. default:
  2528. // a scalar, so set the value and remember we're scalar
  2529. $this->me[$type]=$val;
  2530. $this->mytype=$typeof;
  2531. return 1;
  2532. }
  2533. }
  2534. /**
  2535. * Add an array of xmlrpcval objects to an xmlrpcval
  2536. * @param array $vals
  2537. * @return int 1 or 0 on failure
  2538. * @access public
  2539. *
  2540. * @todo add some checking for $vals to be an array of xmlrpcvals?
  2541. */
  2542. function addArray($vals)
  2543. {
  2544. if($this->mytype==0)
  2545. {
  2546. $this->mytype=$GLOBALS['xmlrpcTypes']['array'];
  2547. $this->me['array']=$vals;
  2548. return 1;
  2549. }
  2550. elseif($this->mytype==2)
  2551. {
  2552. // we're adding to an array here
  2553. $this->me['array'] = array_merge($this->me['array'], $vals);
  2554. return 1;
  2555. }
  2556. else
  2557. {
  2558. error_log('XML-RPC: xmlrpcval::addArray: already initialized as a [' . $this->kindOf() . ']');
  2559. return 0;
  2560. }
  2561. }
  2562. /**
  2563. * Add an array of named xmlrpcval objects to an xmlrpcval
  2564. * @param array $vals
  2565. * @return int 1 or 0 on failure
  2566. * @access public
  2567. *
  2568. * @todo add some checking for $vals to be an array?
  2569. */
  2570. function addStruct($vals)
  2571. {
  2572. if($this->mytype==0)
  2573. {
  2574. $this->mytype=$GLOBALS['xmlrpcTypes']['struct'];
  2575. $this->me['struct']=$vals;
  2576. return 1;
  2577. }
  2578. elseif($this->mytype==3)
  2579. {
  2580. // we're adding to a struct here
  2581. $this->me['struct'] = array_merge($this->me['struct'], $vals);
  2582. return 1;
  2583. }
  2584. else
  2585. {
  2586. error_log('XML-RPC: xmlrpcval::addStruct: already initialized as a [' . $this->kindOf() . ']');
  2587. return 0;
  2588. }
  2589. }
  2590. // poor man's version of print_r ???
  2591. // DEPRECATED!
  2592. function dump($ar)
  2593. {
  2594. foreach($ar as $key => $val)
  2595. {
  2596. echo "$key => $val<br />";
  2597. if($key == 'array')
  2598. {
  2599. while(list($key2, $val2) = each($val))
  2600. {
  2601. echo "-- $key2 => $val2<br />";
  2602. }
  2603. }
  2604. }
  2605. }
  2606. /**
  2607. * Returns a string containing "struct", "array" or "scalar" describing the base type of the value
  2608. * @return string
  2609. * @access public
  2610. */
  2611. function kindOf()
  2612. {
  2613. switch($this->mytype)
  2614. {
  2615. case 3:
  2616. return 'struct';
  2617. break;
  2618. case 2:
  2619. return 'array';
  2620. break;
  2621. case 1:
  2622. return 'scalar';
  2623. break;
  2624. default:
  2625. return 'undef';
  2626. }
  2627. }
  2628. /**
  2629. * @access private
  2630. */
  2631. function serializedata($typ, $val, $charset_encoding='')
  2632. {
  2633. $rs='';
  2634. switch(@$GLOBALS['xmlrpcTypes'][$typ])
  2635. {
  2636. case 1:
  2637. switch($typ)
  2638. {
  2639. case $GLOBALS['xmlrpcBase64']:
  2640. $rs.="<${typ}>" . base64_encode($val) . "</${typ}>";
  2641. break;
  2642. case $GLOBALS['xmlrpcBoolean']:
  2643. $rs.="<${typ}>" . ($val ? '1' : '0') . "</${typ}>";
  2644. break;
  2645. case $GLOBALS['xmlrpcString']:
  2646. // G. Giunta 2005/2/13: do NOT use htmlentities, since
  2647. // it will produce named html entities, which are invalid xml
  2648. $rs.="<${typ}>" . xmlrpc_encode_entitites($val, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding). "</${typ}>";
  2649. break;
  2650. case $GLOBALS['xmlrpcInt']:
  2651. case $GLOBALS['xmlrpcI4']:
  2652. $rs.="<${typ}>".(int)$val."</${typ}>";
  2653. break;
  2654. case $GLOBALS['xmlrpcDouble']:
  2655. $rs.="<${typ}>".(double)$val."</${typ}>";
  2656. break;
  2657. case $GLOBALS['xmlrpcNull']:
  2658. $rs.="<nil/>";
  2659. break;
  2660. default:
  2661. // no standard type value should arrive here, but provide a possibility
  2662. // for xmlrpcvals of unknown type...
  2663. $rs.="<${typ}>${val}</${typ}>";
  2664. }
  2665. break;
  2666. case 3:
  2667. // struct
  2668. if ($this->_php_class)
  2669. {
  2670. $rs.='<struct php_class="' . $this->_php_class . "\">\n";
  2671. }
  2672. else
  2673. {
  2674. $rs.="<struct>\n";
  2675. }
  2676. foreach($val as $key2 => $val2)
  2677. {
  2678. $rs.='<member><name>'.xmlrpc_encode_entitites($key2, $GLOBALS['xmlrpc_internalencoding'], $charset_encoding)."</name>\n";
  2679. //$rs.=$this->serializeval($val2);
  2680. $rs.=$val2->serialize($charset_encoding);
  2681. $rs.="</member>\n";
  2682. }
  2683. $rs.='</struct>';
  2684. break;
  2685. case 2:
  2686. // array
  2687. $rs.="<array>\n<data>\n";
  2688. for($i=0; $i<count($val); $i++)
  2689. {
  2690. //$rs.=$this->serializeval($val[$i]);
  2691. $rs.=$val[$i]->serialize($charset_encoding);
  2692. }
  2693. $rs.="</data>\n</array>";
  2694. break;
  2695. default:
  2696. break;
  2697. }
  2698. return $rs;
  2699. }
  2700. /**
  2701. * Returns xml representation of the value. XML prologue not included
  2702. * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed
  2703. * @return string
  2704. * @access public
  2705. */
  2706. function serialize($charset_encoding='')
  2707. {
  2708. // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals...
  2709. //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))
  2710. //{
  2711. reset($this->me);
  2712. list($typ, $val) = each($this->me);
  2713. return '<value>' . $this->serializedata($typ, $val, $charset_encoding) . "</value>\n";
  2714. //}
  2715. }
  2716. // DEPRECATED
  2717. function serializeval($o)
  2718. {
  2719. // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals...
  2720. //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))
  2721. //{
  2722. $ar=$o->me;
  2723. reset($ar);
  2724. list($typ, $val) = each($ar);
  2725. return '<value>' . $this->serializedata($typ, $val) . "</value>\n";
  2726. //}
  2727. }
  2728. /**
  2729. * Checks wheter a struct member with a given name is present.
  2730. * Works only on xmlrpcvals of type struct.
  2731. * @param string $m the name of the struct member to be looked up
  2732. * @return boolean
  2733. * @access public
  2734. */
  2735. function structmemexists($m)
  2736. {
  2737. return array_key_exists($m, $this->me['struct']);
  2738. }
  2739. /**
  2740. * Returns the value of a given struct member (an xmlrpcval object in itself).
  2741. * Will raise a php warning if struct member of given name does not exist
  2742. * @param string $m the name of the struct member to be looked up
  2743. * @return xmlrpcval
  2744. * @access public
  2745. */
  2746. function structmem($m)
  2747. {
  2748. return $this->me['struct'][$m];
  2749. }
  2750. /**
  2751. * Reset internal pointer for xmlrpcvals of type struct.
  2752. * @access public
  2753. */
  2754. function structreset()
  2755. {
  2756. reset($this->me['struct']);
  2757. }
  2758. /**
  2759. * Return next member element for xmlrpcvals of type struct.
  2760. * @return xmlrpcval
  2761. * @access public
  2762. */
  2763. function structeach()
  2764. {
  2765. return each($this->me['struct']);
  2766. }
  2767. // DEPRECATED! this code looks like it is very fragile and has not been fixed
  2768. // for a long long time. Shall we remove it for 2.0?
  2769. function getval()
  2770. {
  2771. // UNSTABLE
  2772. reset($this->me);
  2773. list($a,$b)=each($this->me);
  2774. // contributed by I Sofer, 2001-03-24
  2775. // add support for nested arrays to scalarval
  2776. // i've created a new method here, so as to
  2777. // preserve back compatibility
  2778. if(is_array($b))
  2779. {
  2780. @reset($b);
  2781. while(list($id,$cont) = @each($b))
  2782. {
  2783. $b[$id] = $cont->scalarval();
  2784. }
  2785. }
  2786. // add support for structures directly encoding php objects
  2787. if(is_object($b))
  2788. {
  2789. $t = get_object_vars($b);
  2790. @reset($t);
  2791. while(list($id,$cont) = @each($t))
  2792. {
  2793. $t[$id] = $cont->scalarval();
  2794. }
  2795. @reset($t);
  2796. while(list($id,$cont) = @each($t))
  2797. {
  2798. @$b->$id = $cont;
  2799. }
  2800. }
  2801. // end contrib
  2802. return $b;
  2803. }
  2804. /**
  2805. * Returns the value of a scalar xmlrpcval
  2806. * @return mixed
  2807. * @access public
  2808. */
  2809. function scalarval()
  2810. {
  2811. reset($this->me);
  2812. list(,$b)=each($this->me);
  2813. return $b;
  2814. }
  2815. /**
  2816. * Returns the type of the xmlrpcval.
  2817. * For integers, 'int' is always returned in place of 'i4'
  2818. * @return string
  2819. * @access public
  2820. */
  2821. function scalartyp()
  2822. {
  2823. reset($this->me);
  2824. list($a,)=each($this->me);
  2825. if($a==$GLOBALS['xmlrpcI4'])
  2826. {
  2827. $a=$GLOBALS['xmlrpcInt'];
  2828. }
  2829. return $a;
  2830. }
  2831. /**
  2832. * Returns the m-th member of an xmlrpcval of struct type
  2833. * @param integer $m the index of the value to be retrieved (zero based)
  2834. * @return xmlrpcval
  2835. * @access public
  2836. */
  2837. function arraymem($m)
  2838. {
  2839. return $this->me['array'][$m];
  2840. }
  2841. /**
  2842. * Returns the number of members in an xmlrpcval of array type
  2843. * @return integer
  2844. * @access public
  2845. */
  2846. function arraysize()
  2847. {
  2848. return count($this->me['array']);
  2849. }
  2850. /**
  2851. * Returns the number of members in an xmlrpcval of struct type
  2852. * @return integer
  2853. * @access public
  2854. */
  2855. function structsize()
  2856. {
  2857. return count($this->me['struct']);
  2858. }
  2859. }
  2860. // date helpers
  2861. /**
  2862. * Given a timestamp, return the corresponding ISO8601 encoded string.
  2863. *
  2864. * Really, timezones ought to be supported
  2865. * but the XML-RPC spec says:
  2866. *
  2867. * "Don't assume a timezone. It should be specified by the server in its
  2868. * documentation what assumptions it makes about timezones."
  2869. *
  2870. * These routines always assume localtime unless
  2871. * $utc is set to 1, in which case UTC is assumed
  2872. * and an adjustment for locale is made when encoding
  2873. *
  2874. * @param int $timet (timestamp)
  2875. * @param int $utc (0 or 1)
  2876. * @return string
  2877. */
  2878. function iso8601_encode($timet, $utc=0)
  2879. {
  2880. if(!$utc)
  2881. {
  2882. $t=strftime("%Y%m%dT%H:%M:%S", $timet);
  2883. }
  2884. else
  2885. {
  2886. if(function_exists('gmstrftime'))
  2887. {
  2888. // gmstrftime doesn't exist in some versions
  2889. // of PHP
  2890. $t=gmstrftime("%Y%m%dT%H:%M:%S", $timet);
  2891. }
  2892. else
  2893. {
  2894. $t=strftime("%Y%m%dT%H:%M:%S", $timet-date('Z'));
  2895. }
  2896. }
  2897. return $t;
  2898. }
  2899. /**
  2900. * Given an ISO8601 date string, return a timet in the localtime, or UTC
  2901. * @param string $idate
  2902. * @param int $utc either 0 or 1
  2903. * @return int (datetime)
  2904. */
  2905. function iso8601_decode($idate, $utc=0)
  2906. {
  2907. $t=0;
  2908. if(preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})/', $idate, $regs))
  2909. {
  2910. if($utc)
  2911. {
  2912. $t=gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
  2913. }
  2914. else
  2915. {
  2916. $t=mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
  2917. }
  2918. }
  2919. return $t;
  2920. }
  2921. /**
  2922. * Takes an xmlrpc value in PHP xmlrpcval object format and translates it into native PHP types.
  2923. *
  2924. * Works with xmlrpc message objects as input, too.
  2925. *
  2926. * Given proper options parameter, can rebuild generic php object instances
  2927. * (provided those have been encoded to xmlrpc format using a corresponding
  2928. * option in php_xmlrpc_encode())
  2929. * PLEASE NOTE that rebuilding php objects involves calling their constructor function.
  2930. * This means that the remote communication end can decide which php code will
  2931. * get executed on your server, leaving the door possibly open to 'php-injection'
  2932. * style of attacks (provided you have some classes defined on your server that
  2933. * might wreak havoc if instances are built outside an appropriate context).
  2934. * Make sure you trust the remote server/client before eanbling this!
  2935. *
  2936. * @author Dan Libby (dan@libby.com)
  2937. *
  2938. * @param xmlrpcval $xmlrpc_val
  2939. * @param array $options if 'decode_php_objs' is set in the options array, xmlrpc structs can be decoded into php objects
  2940. * @return mixed
  2941. */
  2942. function php_xmlrpc_decode($xmlrpc_val, $options=array())
  2943. {
  2944. switch($xmlrpc_val->kindOf())
  2945. {
  2946. case 'scalar':
  2947. if (in_array('extension_api', $options))
  2948. {
  2949. reset($xmlrpc_val->me);
  2950. list($typ,$val) = each($xmlrpc_val->me);
  2951. switch ($typ)
  2952. {
  2953. case 'dateTime.iso8601':
  2954. $xmlrpc_val->scalar = $val;
  2955. $xmlrpc_val->xmlrpc_type = 'datetime';
  2956. $xmlrpc_val->timestamp = iso8601_decode($val);
  2957. return $xmlrpc_val;
  2958. case 'base64':
  2959. $xmlrpc_val->scalar = $val;
  2960. $xmlrpc_val->type = $typ;
  2961. return $xmlrpc_val;
  2962. default:
  2963. return $xmlrpc_val->scalarval();
  2964. }
  2965. }
  2966. return $xmlrpc_val->scalarval();
  2967. case 'array':
  2968. $size = $xmlrpc_val->arraysize();
  2969. $arr = array();
  2970. for($i = 0; $i < $size; $i++)
  2971. {
  2972. $arr[] = php_xmlrpc_decode($xmlrpc_val->arraymem($i), $options);
  2973. }
  2974. return $arr;
  2975. case 'struct':
  2976. $xmlrpc_val->structreset();
  2977. // If user said so, try to rebuild php objects for specific struct vals.
  2978. /// @todo should we raise a warning for class not found?
  2979. // shall we check for proper subclass of xmlrpcval instead of
  2980. // presence of _php_class to detect what we can do?
  2981. if (in_array('decode_php_objs', $options) && $xmlrpc_val->_php_class != ''
  2982. && class_exists($xmlrpc_val->_php_class))
  2983. {
  2984. $obj = @new $xmlrpc_val->_php_class;
  2985. while(list($key,$value)=$xmlrpc_val->structeach())
  2986. {
  2987. $obj->$key = php_xmlrpc_decode($value, $options);
  2988. }
  2989. return $obj;
  2990. }
  2991. else
  2992. {
  2993. $arr = array();
  2994. while(list($key,$value)=$xmlrpc_val->structeach())
  2995. {
  2996. $arr[$key] = php_xmlrpc_decode($value, $options);
  2997. }
  2998. return $arr;
  2999. }
  3000. case 'msg':
  3001. $paramcount = $xmlrpc_val->getNumParams();
  3002. $arr = array();
  3003. for($i = 0; $i < $paramcount; $i++)
  3004. {
  3005. $arr[] = php_xmlrpc_decode($xmlrpc_val->getParam($i));
  3006. }
  3007. return $arr;
  3008. }
  3009. }
  3010. // This constant left here only for historical reasons...
  3011. // it was used to decide if we have to define xmlrpc_encode on our own, but
  3012. // we do not do it anymore
  3013. if(function_exists('xmlrpc_decode'))
  3014. {
  3015. define('XMLRPC_EPI_ENABLED','1');
  3016. }
  3017. else
  3018. {
  3019. define('XMLRPC_EPI_ENABLED','0');
  3020. }
  3021. /**
  3022. * Takes native php types and encodes them into xmlrpc PHP object format.
  3023. * It will not re-encode xmlrpcval objects.
  3024. *
  3025. * Feature creep -- could support more types via optional type argument
  3026. * (string => datetime support has been added, ??? => base64 not yet)
  3027. *
  3028. * If given a proper options parameter, php object instances will be encoded
  3029. * into 'special' xmlrpc values, that can later be decoded into php objects
  3030. * by calling php_xmlrpc_decode() with a corresponding option
  3031. *
  3032. * @author Dan Libby (dan@libby.com)
  3033. *
  3034. * @param mixed $php_val the value to be converted into an xmlrpcval object
  3035. * @param array $options can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api'
  3036. * @return xmlrpcval
  3037. */
  3038. function &php_xmlrpc_encode($php_val, $options=array())
  3039. {
  3040. $type = gettype($php_val);
  3041. switch($type)
  3042. {
  3043. case 'string':
  3044. if (in_array('auto_dates', $options) && preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/', $php_val))
  3045. $xmlrpc_val =& new xmlrpcval($php_val, $GLOBALS['xmlrpcDateTime']);
  3046. else
  3047. $xmlrpc_val =& new xmlrpcval($php_val, $GLOBALS['xmlrpcString']);
  3048. break;
  3049. case 'integer':
  3050. $xmlrpc_val =& new xmlrpcval($php_val, $GLOBALS['xmlrpcInt']);
  3051. break;
  3052. case 'double':
  3053. $xmlrpc_val =& new xmlrpcval($php_val, $GLOBALS['xmlrpcDouble']);
  3054. break;
  3055. // <G_Giunta_2001-02-29>
  3056. // Add support for encoding/decoding of booleans, since they are supported in PHP
  3057. case 'boolean':
  3058. $xmlrpc_val =& new xmlrpcval($php_val, $GLOBALS['xmlrpcBoolean']);
  3059. break;
  3060. // </G_Giunta_2001-02-29>
  3061. case 'array':
  3062. // PHP arrays can be encoded to either xmlrpc structs or arrays,
  3063. // depending on wheter they are hashes or plain 0..n integer indexed
  3064. // A shorter one-liner would be
  3065. // $tmp = array_diff(array_keys($php_val), range(0, count($php_val)-1));
  3066. // but execution time skyrockets!
  3067. $j = 0;
  3068. $arr = array();
  3069. $ko = false;
  3070. foreach($php_val as $key => $val)
  3071. {
  3072. $arr[$key] =& php_xmlrpc_encode($val, $options);
  3073. if(!$ko && $key !== $j)
  3074. {
  3075. $ko = true;
  3076. }
  3077. $j++;
  3078. }
  3079. if($ko)
  3080. {
  3081. $xmlrpc_val =& new xmlrpcval($arr, $GLOBALS['xmlrpcStruct']);
  3082. }
  3083. else
  3084. {
  3085. $xmlrpc_val =& new xmlrpcval($arr, $GLOBALS['xmlrpcArray']);
  3086. }
  3087. break;
  3088. case 'object':
  3089. if(is_a($php_val, 'xmlrpcval'))
  3090. {
  3091. $xmlrpc_val = $php_val;
  3092. }
  3093. else
  3094. {
  3095. $arr = array();
  3096. while(list($k,$v) = each($php_val))
  3097. {
  3098. $arr[$k] = php_xmlrpc_encode($v, $options);
  3099. }
  3100. $xmlrpc_val =& new xmlrpcval($arr, $GLOBALS['xmlrpcStruct']);
  3101. if (in_array('encode_php_objs', $options))
  3102. {
  3103. // let's save original class name into xmlrpcval:
  3104. // might be useful later on...
  3105. $xmlrpc_val->_php_class = get_class($php_val);
  3106. }
  3107. }
  3108. break;
  3109. case 'NULL':
  3110. if (in_array('extension_api', $options))
  3111. {
  3112. $xmlrpc_val =& new xmlrpcval('', $GLOBALS['xmlrpcString']);
  3113. }
  3114. if (in_array('null_extension', $options))
  3115. {
  3116. $xmlrpc_val =& new xmlrpcval('', $GLOBALS['xmlrpcNull']);
  3117. }
  3118. else
  3119. {
  3120. $xmlrpc_val =& new xmlrpcval();
  3121. }
  3122. break;
  3123. case 'resource':
  3124. if (in_array('extension_api', $options))
  3125. {
  3126. $xmlrpc_val =& new xmlrpcval((int)$php_val, $GLOBALS['xmlrpcInt']);
  3127. }
  3128. else
  3129. {
  3130. $xmlrpc_val =& new xmlrpcval();
  3131. }
  3132. // catch "user function", "unknown type"
  3133. default:
  3134. // giancarlo pinerolo <ping@alt.it>
  3135. // it has to return
  3136. // an empty object in case, not a boolean.
  3137. $xmlrpc_val =& new xmlrpcval();
  3138. break;
  3139. }
  3140. return $xmlrpc_val;
  3141. }
  3142. /**
  3143. * Convert the xml representation of a method call, method request or single
  3144. * xmlrpc value into the appropriate object (a.k.a. deserialize)
  3145. * @param string $xml_val
  3146. * @param array $options
  3147. * @return mixed false on error, or an instance of either xmlrpcval, xmlrpcmsg or xmlrpcresp
  3148. */
  3149. function php_xmlrpc_decode_xml($xml_val, $options=array())
  3150. {
  3151. $GLOBALS['_xh'] = array();
  3152. $GLOBALS['_xh']['ac'] = '';
  3153. $GLOBALS['_xh']['stack'] = array();
  3154. $GLOBALS['_xh']['valuestack'] = array();
  3155. $GLOBALS['_xh']['params'] = array();
  3156. $GLOBALS['_xh']['pt'] = array();
  3157. $GLOBALS['_xh']['isf'] = 0;
  3158. $GLOBALS['_xh']['isf_reason'] = '';
  3159. $GLOBALS['_xh']['method'] = false;
  3160. $GLOBALS['_xh']['rt'] = '';
  3161. /// @todo 'guestimate' encoding
  3162. $parser = xml_parser_create();
  3163. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
  3164. xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']);
  3165. xml_set_element_handler($parser, 'xmlrpc_se_any', 'xmlrpc_ee');
  3166. xml_set_character_data_handler($parser, 'xmlrpc_cd');
  3167. xml_set_default_handler($parser, 'xmlrpc_dh');
  3168. if(!xml_parse($parser, $xml_val, 1))
  3169. {
  3170. $errstr = sprintf('XML error: %s at line %d, column %d',
  3171. xml_error_string(xml_get_error_code($parser)),
  3172. xml_get_current_line_number($parser), xml_get_current_column_number($parser));
  3173. error_log($errstr);
  3174. xml_parser_free($parser);
  3175. return false;
  3176. }
  3177. xml_parser_free($parser);
  3178. if ($GLOBALS['_xh']['isf'] > 1) // test that $GLOBALS['_xh']['value'] is an obj, too???
  3179. {
  3180. error_log($GLOBALS['_xh']['isf_reason']);
  3181. return false;
  3182. }
  3183. switch ($GLOBALS['_xh']['rt'])
  3184. {
  3185. case 'methodresponse':
  3186. $v =& $GLOBALS['_xh']['value'];
  3187. if ($GLOBALS['_xh']['isf'] == 1)
  3188. {
  3189. $vc = $v->structmem('faultCode');
  3190. $vs = $v->structmem('faultString');
  3191. $r =& new xmlrpcresp(0, $vc->scalarval(), $vs->scalarval());
  3192. }
  3193. else
  3194. {
  3195. $r =& new xmlrpcresp($v);
  3196. }
  3197. return $r;
  3198. case 'methodcall':
  3199. $m =& new xmlrpcmsg($GLOBALS['_xh']['method']);
  3200. for($i=0; $i < count($GLOBALS['_xh']['params']); $i++)
  3201. {
  3202. $m->addParam($GLOBALS['_xh']['params'][$i]);
  3203. }
  3204. return $m;
  3205. case 'value':
  3206. return $GLOBALS['_xh']['value'];
  3207. default:
  3208. return false;
  3209. }
  3210. }
  3211. /**
  3212. * decode a string that is encoded w/ "chunked" transfer encoding
  3213. * as defined in rfc2068 par. 19.4.6
  3214. * code shamelessly stolen from nusoap library by Dietrich Ayala
  3215. *
  3216. * @param string $buffer the string to be decoded
  3217. * @return string
  3218. */
  3219. function decode_chunked($buffer)
  3220. {
  3221. // length := 0
  3222. $length = 0;
  3223. $new = '';
  3224. // read chunk-size, chunk-extension (if any) and crlf
  3225. // get the position of the linebreak
  3226. $chunkend = strpos($buffer,"\r\n") + 2;
  3227. $temp = substr($buffer,0,$chunkend);
  3228. $chunk_size = hexdec( trim($temp) );
  3229. $chunkstart = $chunkend;
  3230. while($chunk_size > 0)
  3231. {
  3232. $chunkend = strpos($buffer, "\r\n", $chunkstart + $chunk_size);
  3233. // just in case we got a broken connection
  3234. if($chunkend == false)
  3235. {
  3236. $chunk = substr($buffer,$chunkstart);
  3237. // append chunk-data to entity-body
  3238. $new .= $chunk;
  3239. $length += strlen($chunk);
  3240. break;
  3241. }
  3242. // read chunk-data and crlf
  3243. $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart);
  3244. // append chunk-data to entity-body
  3245. $new .= $chunk;
  3246. // length := length + chunk-size
  3247. $length += strlen($chunk);
  3248. // read chunk-size and crlf
  3249. $chunkstart = $chunkend + 2;
  3250. $chunkend = strpos($buffer,"\r\n",$chunkstart)+2;
  3251. if($chunkend == false)
  3252. {
  3253. break; //just in case we got a broken connection
  3254. }
  3255. $temp = substr($buffer,$chunkstart,$chunkend-$chunkstart);
  3256. $chunk_size = hexdec( trim($temp) );
  3257. $chunkstart = $chunkend;
  3258. }
  3259. return $new;
  3260. }
  3261. /**
  3262. * xml charset encoding guessing helper function.
  3263. * Tries to determine the charset encoding of an XML chunk
  3264. * received over HTTP.
  3265. * NB: according to the spec (RFC 3023, if text/xml content-type is received over HTTP without a content-type,
  3266. * we SHOULD assume it is strictly US-ASCII. But we try to be more tolerant of unconforming (legacy?) clients/servers,
  3267. * which will be most probably using UTF-8 anyway...
  3268. *
  3269. * @param string $httpheaders the http Content-type header
  3270. * @param string $xmlchunk xml content buffer
  3271. * @param string $encoding_prefs comma separated list of character encodings to be used as default (when mb extension is enabled)
  3272. *
  3273. * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!!
  3274. */
  3275. function guess_encoding($httpheader='', $xmlchunk='', $encoding_prefs=null)
  3276. {
  3277. // discussion: see http://www.yale.edu/pclt/encoding/
  3278. // 1 - test if encoding is specified in HTTP HEADERS
  3279. //Details:
  3280. // LWS: (\13\10)?( |\t)+
  3281. // token: (any char but excluded stuff)+
  3282. // header: Content-type = ...; charset=value(; ...)*
  3283. // where value is of type token, no LWS allowed between 'charset' and value
  3284. // Note: we do not check for invalid chars in VALUE:
  3285. // this had better be done using pure ereg as below
  3286. /// @todo this test will pass if ANY header has charset specification, not only Content-Type. Fix it?
  3287. $matches = array();
  3288. if(preg_match('/;\s*charset=([^;]+)/i', $httpheader, $matches))
  3289. {
  3290. return strtoupper(trim($matches[1]));
  3291. }
  3292. // 2 - scan the first bytes of the data for a UTF-16 (or other) BOM pattern
  3293. // (source: http://www.w3.org/TR/2000/REC-xml-20001006)
  3294. // NOTE: actually, according to the spec, even if we find the BOM and determine
  3295. // an encoding, we should check if there is an encoding specified
  3296. // in the xml declaration, and verify if they match.
  3297. /// @todo implement check as described above?
  3298. /// @todo implement check for first bytes of string even without a BOM? (It sure looks harder than for cases WITH a BOM)
  3299. if(preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/', $xmlchunk))
  3300. {
  3301. return 'UCS-4';
  3302. }
  3303. elseif(preg_match('/^(\xFE\xFF|\xFF\xFE)/', $xmlchunk))
  3304. {
  3305. return 'UTF-16';
  3306. }
  3307. elseif(preg_match('/^(\xEF\xBB\xBF)/', $xmlchunk))
  3308. {
  3309. return 'UTF-8';
  3310. }
  3311. // 3 - test if encoding is specified in the xml declaration
  3312. // Details:
  3313. // SPACE: (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+
  3314. // EQ: SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]*
  3315. if (preg_match('/^<\?xml\s+version\s*=\s*'. "((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))".
  3316. '\s+encoding\s*=\s*' . "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/",
  3317. $xmlchunk, $matches))
  3318. {
  3319. return strtoupper(substr($matches[2], 1, -1));
  3320. }
  3321. // 4 - if mbstring is available, let it do the guesswork
  3322. // NB: we favour finding an encoding that is compatible with what we can process
  3323. if(extension_loaded('mbstring'))
  3324. {
  3325. if($encoding_prefs)
  3326. {
  3327. $enc = mb_detect_encoding($xmlchunk, $encoding_prefs);
  3328. }
  3329. else
  3330. {
  3331. $enc = mb_detect_encoding($xmlchunk);
  3332. }
  3333. // NB: mb_detect likes to call it ascii, xml parser likes to call it US_ASCII...
  3334. // IANA also likes better US-ASCII, so go with it
  3335. if($enc == 'ASCII')
  3336. {
  3337. $enc = 'US-'.$enc;
  3338. }
  3339. return $enc;
  3340. }
  3341. else
  3342. {
  3343. // no encoding specified: as per HTTP1.1 assume it is iso-8859-1?
  3344. // Both RFC 2616 (HTTP 1.1) and 1945(http 1.0) clearly state that for text/xxx content types
  3345. // this should be the standard. And we should be getting text/xml as request and response.
  3346. // BUT we have to be backward compatible with the lib, which always used UTF-8 as default...
  3347. return $GLOBALS['xmlrpc_defencoding'];
  3348. }
  3349. }
  3350. /**
  3351. * Checks if a given charset encoding is present in a list of encodings or
  3352. * if it is a valid subset of any encoding in the list
  3353. * @param string $encoding charset to be tested
  3354. * @param mixed $validlist comma separated list of valid charsets (or array of charsets)
  3355. */
  3356. function is_valid_charset($encoding, $validlist)
  3357. {
  3358. $charset_supersets = array(
  3359. 'US-ASCII' => array ('ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
  3360. 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8',
  3361. 'ISO-8859-9', 'ISO-8859-10', 'ISO-8859-11', 'ISO-8859-12',
  3362. 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'UTF-8',
  3363. 'EUC-JP', 'EUC-', 'EUC-KR', 'EUC-CN')
  3364. );
  3365. if (is_string($validlist))
  3366. $validlist = explode(',', $validlist);
  3367. if (@in_array(strtoupper($encoding), $validlist))
  3368. return true;
  3369. else
  3370. {
  3371. if (array_key_exists($encoding, $charset_supersets))
  3372. foreach ($validlist as $allowed)
  3373. if (in_array($allowed, $charset_supersets[$encoding]))
  3374. return true;
  3375. return false;
  3376. }
  3377. }
  3378. ?>