xmlrpc.inc 138 KB

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