xmlrpc.inc 110 KB

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