xmlrpc.php 112 KB

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