Client.php 150 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348
  1. <?php
  2. /**
  3. * Licensed to Jasig under one or more contributor license
  4. * agreements. See the NOTICE file distributed with this work for
  5. * additional information regarding copyright ownership.
  6. *
  7. * Jasig licenses this file to you under the Apache License,
  8. * Version 2.0 (the "License"); you may not use this file except in
  9. * compliance with the License. You may obtain a copy of the License at:
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * PHP Version 5
  20. *
  21. * @file CAS/Client.php
  22. * @category Authentication
  23. * @package PhpCAS
  24. * @author Pascal Aubry <pascal.aubry@univ-rennes1.fr>
  25. * @author Olivier Berger <olivier.berger@it-sudparis.eu>
  26. * @author Brett Bieber <brett.bieber@gmail.com>
  27. * @author Joachim Fritschi <jfritschi@freenet.de>
  28. * @author Adam Franco <afranco@middlebury.edu>
  29. * @author Tobias Schiebeck <tobias.schiebeck@manchester.ac.uk>
  30. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
  31. * @link https://wiki.jasig.org/display/CASC/phpCAS
  32. */
  33. /**
  34. * The CAS_Client class is a client interface that provides CAS authentication
  35. * to PHP applications.
  36. *
  37. * @class CAS_Client
  38. * @category Authentication
  39. * @package PhpCAS
  40. * @author Pascal Aubry <pascal.aubry@univ-rennes1.fr>
  41. * @author Olivier Berger <olivier.berger@it-sudparis.eu>
  42. * @author Brett Bieber <brett.bieber@gmail.com>
  43. * @author Joachim Fritschi <jfritschi@freenet.de>
  44. * @author Adam Franco <afranco@middlebury.edu>
  45. * @author Tobias Schiebeck <tobias.schiebeck@manchester.ac.uk>
  46. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
  47. * @link https://wiki.jasig.org/display/CASC/phpCAS
  48. *
  49. */
  50. class CAS_Client
  51. {
  52. // ########################################################################
  53. // HTML OUTPUT
  54. // ########################################################################
  55. /**
  56. * @addtogroup internalOutput
  57. * @{
  58. */
  59. /**
  60. * This method filters a string by replacing special tokens by appropriate values
  61. * and prints it. The corresponding tokens are taken into account:
  62. * - __CAS_VERSION__
  63. * - __PHPCAS_VERSION__
  64. * - __SERVER_BASE_URL__
  65. *
  66. * Used by CAS_Client::PrintHTMLHeader() and CAS_Client::printHTMLFooter().
  67. *
  68. * @param string $str the string to filter and output
  69. *
  70. * @return void
  71. */
  72. private function _htmlFilterOutput($str)
  73. {
  74. $str = str_replace('__CAS_VERSION__', $this->getServerVersion(), $str);
  75. $str = str_replace('__PHPCAS_VERSION__', phpCAS::getVersion(), $str);
  76. $str = str_replace('__SERVER_BASE_URL__', $this->_getServerBaseURL(), $str);
  77. echo $str;
  78. }
  79. /**
  80. * A string used to print the header of HTML pages. Written by
  81. * CAS_Client::setHTMLHeader(), read by CAS_Client::printHTMLHeader().
  82. *
  83. * @hideinitializer
  84. * @see CAS_Client::setHTMLHeader, CAS_Client::printHTMLHeader()
  85. */
  86. private $_output_header = '';
  87. /**
  88. * This method prints the header of the HTML output (after filtering). If
  89. * CAS_Client::setHTMLHeader() was not used, a default header is output.
  90. *
  91. * @param string $title the title of the page
  92. *
  93. * @return void
  94. * @see _htmlFilterOutput()
  95. */
  96. public function printHTMLHeader($title)
  97. {
  98. $this->_htmlFilterOutput(
  99. str_replace(
  100. '__TITLE__', $title,
  101. (empty($this->_output_header)
  102. ? '<html><head><title>__TITLE__</title></head><body><h1>__TITLE__</h1>'
  103. : $this->_output_header)
  104. )
  105. );
  106. }
  107. /**
  108. * A string used to print the footer of HTML pages. Written by
  109. * CAS_Client::setHTMLFooter(), read by printHTMLFooter().
  110. *
  111. * @hideinitializer
  112. * @see CAS_Client::setHTMLFooter, CAS_Client::printHTMLFooter()
  113. */
  114. private $_output_footer = '';
  115. /**
  116. * This method prints the footer of the HTML output (after filtering). If
  117. * CAS_Client::setHTMLFooter() was not used, a default footer is output.
  118. *
  119. * @return void
  120. * @see _htmlFilterOutput()
  121. */
  122. public function printHTMLFooter()
  123. {
  124. $lang = $this->getLangObj();
  125. $this->_htmlFilterOutput(
  126. empty($this->_output_footer)?
  127. (phpCAS::getVerbose())?
  128. '<hr><address>phpCAS __PHPCAS_VERSION__ '
  129. .$lang->getUsingServer()
  130. .' <a href="__SERVER_BASE_URL__">__SERVER_BASE_URL__</a> (CAS __CAS_VERSION__)</a></address></body></html>'
  131. :'</body></html>'
  132. :$this->_output_footer
  133. );
  134. }
  135. /**
  136. * This method set the HTML header used for all outputs.
  137. *
  138. * @param string $header the HTML header.
  139. *
  140. * @return void
  141. */
  142. public function setHTMLHeader($header)
  143. {
  144. // Argument Validation
  145. if (gettype($header) != 'string')
  146. throw new CAS_TypeMismatchException($header, '$header', 'string');
  147. $this->_output_header = $header;
  148. }
  149. /**
  150. * This method set the HTML footer used for all outputs.
  151. *
  152. * @param string $footer the HTML footer.
  153. *
  154. * @return void
  155. */
  156. public function setHTMLFooter($footer)
  157. {
  158. // Argument Validation
  159. if (gettype($footer) != 'string')
  160. throw new CAS_TypeMismatchException($footer, '$footer', 'string');
  161. $this->_output_footer = $footer;
  162. }
  163. /** @} */
  164. // ########################################################################
  165. // INTERNATIONALIZATION
  166. // ########################################################################
  167. /**
  168. * @addtogroup internalLang
  169. * @{
  170. */
  171. /**
  172. * A string corresponding to the language used by phpCAS. Written by
  173. * CAS_Client::setLang(), read by CAS_Client::getLang().
  174. * @note debugging information is always in english (debug purposes only).
  175. */
  176. private $_lang = PHPCAS_LANG_DEFAULT;
  177. /**
  178. * This method is used to set the language used by phpCAS.
  179. *
  180. * @param string $lang representing the language.
  181. *
  182. * @return void
  183. */
  184. public function setLang($lang)
  185. {
  186. // Argument Validation
  187. if (gettype($lang) != 'string')
  188. throw new CAS_TypeMismatchException($lang, '$lang', 'string');
  189. phpCAS::traceBegin();
  190. $obj = new $lang();
  191. if (!($obj instanceof CAS_Languages_LanguageInterface)) {
  192. throw new CAS_InvalidArgumentException(
  193. '$className must implement the CAS_Languages_LanguageInterface'
  194. );
  195. }
  196. $this->_lang = $lang;
  197. phpCAS::traceEnd();
  198. }
  199. /**
  200. * Create the language
  201. *
  202. * @return CAS_Languages_LanguageInterface object implementing the class
  203. */
  204. public function getLangObj()
  205. {
  206. $classname = $this->_lang;
  207. return new $classname();
  208. }
  209. /** @} */
  210. // ########################################################################
  211. // CAS SERVER CONFIG
  212. // ########################################################################
  213. /**
  214. * @addtogroup internalConfig
  215. * @{
  216. */
  217. /**
  218. * a record to store information about the CAS server.
  219. * - $_server['version']: the version of the CAS server
  220. * - $_server['hostname']: the hostname of the CAS server
  221. * - $_server['port']: the port the CAS server is running on
  222. * - $_server['uri']: the base URI the CAS server is responding on
  223. * - $_server['base_url']: the base URL of the CAS server
  224. * - $_server['login_url']: the login URL of the CAS server
  225. * - $_server['service_validate_url']: the service validating URL of the
  226. * CAS server
  227. * - $_server['proxy_url']: the proxy URL of the CAS server
  228. * - $_server['proxy_validate_url']: the proxy validating URL of the CAS server
  229. * - $_server['logout_url']: the logout URL of the CAS server
  230. *
  231. * $_server['version'], $_server['hostname'], $_server['port'] and
  232. * $_server['uri'] are written by CAS_Client::CAS_Client(), read by
  233. * CAS_Client::getServerVersion(), CAS_Client::_getServerHostname(),
  234. * CAS_Client::_getServerPort() and CAS_Client::_getServerURI().
  235. *
  236. * The other fields are written and read by CAS_Client::_getServerBaseURL(),
  237. * CAS_Client::getServerLoginURL(), CAS_Client::getServerServiceValidateURL(),
  238. * CAS_Client::getServerProxyValidateURL() and CAS_Client::getServerLogoutURL().
  239. *
  240. * @hideinitializer
  241. */
  242. private $_server = array(
  243. 'version' => '',
  244. 'hostname' => 'none',
  245. 'port' => -1,
  246. 'uri' => 'none');
  247. /**
  248. * This method is used to retrieve the version of the CAS server.
  249. *
  250. * @return string the version of the CAS server.
  251. */
  252. public function getServerVersion()
  253. {
  254. return $this->_server['version'];
  255. }
  256. /**
  257. * This method is used to retrieve the hostname of the CAS server.
  258. *
  259. * @return string the hostname of the CAS server.
  260. */
  261. private function _getServerHostname()
  262. {
  263. return $this->_server['hostname'];
  264. }
  265. /**
  266. * This method is used to retrieve the port of the CAS server.
  267. *
  268. * @return int the port of the CAS server.
  269. */
  270. private function _getServerPort()
  271. {
  272. return $this->_server['port'];
  273. }
  274. /**
  275. * This method is used to retrieve the URI of the CAS server.
  276. *
  277. * @return string a URI.
  278. */
  279. private function _getServerURI()
  280. {
  281. return $this->_server['uri'];
  282. }
  283. /**
  284. * This method is used to retrieve the base URL of the CAS server.
  285. *
  286. * @return string a URL.
  287. */
  288. private function _getServerBaseURL()
  289. {
  290. // the URL is build only when needed
  291. if ( empty($this->_server['base_url']) ) {
  292. $this->_server['base_url'] = 'https://' . $this->_getServerHostname();
  293. if ($this->_getServerPort()!=443) {
  294. $this->_server['base_url'] .= ':'
  295. .$this->_getServerPort();
  296. }
  297. $this->_server['base_url'] .= $this->_getServerURI();
  298. }
  299. return $this->_server['base_url'];
  300. }
  301. /**
  302. * This method is used to retrieve the login URL of the CAS server.
  303. *
  304. * @param bool $gateway true to check authentication, false to force it
  305. * @param bool $renew true to force the authentication with the CAS server
  306. *
  307. * @return string a URL.
  308. * @note It is recommended that CAS implementations ignore the "gateway"
  309. * parameter if "renew" is set
  310. */
  311. public function getServerLoginURL($gateway=false,$renew=false)
  312. {
  313. phpCAS::traceBegin();
  314. // the URL is build only when needed
  315. if ( empty($this->_server['login_url']) ) {
  316. $this->_server['login_url'] = $this->_buildQueryUrl($this->_getServerBaseURL().'login','service='.urlencode($this->getURL()));
  317. }
  318. $url = $this->_server['login_url'];
  319. if ($renew) {
  320. // It is recommended that when the "renew" parameter is set, its
  321. // value be "true"
  322. $url = $this->_buildQueryUrl($url, 'renew=true');
  323. } elseif ($gateway) {
  324. // It is recommended that when the "gateway" parameter is set, its
  325. // value be "true"
  326. $url = $this->_buildQueryUrl($url, 'gateway=true');
  327. }
  328. phpCAS::traceEnd($url);
  329. return $url;
  330. }
  331. /**
  332. * This method sets the login URL of the CAS server.
  333. *
  334. * @param string $url the login URL
  335. *
  336. * @return string login url
  337. */
  338. public function setServerLoginURL($url)
  339. {
  340. // Argument Validation
  341. if (gettype($url) != 'string')
  342. throw new CAS_TypeMismatchException($url, '$url', 'string');
  343. return $this->_server['login_url'] = $url;
  344. }
  345. /**
  346. * This method sets the serviceValidate URL of the CAS server.
  347. *
  348. * @param string $url the serviceValidate URL
  349. *
  350. * @return string serviceValidate URL
  351. */
  352. public function setServerServiceValidateURL($url)
  353. {
  354. // Argument Validation
  355. if (gettype($url) != 'string')
  356. throw new CAS_TypeMismatchException($url, '$url', 'string');
  357. return $this->_server['service_validate_url'] = $url;
  358. }
  359. /**
  360. * This method sets the proxyValidate URL of the CAS server.
  361. *
  362. * @param string $url the proxyValidate URL
  363. *
  364. * @return string proxyValidate URL
  365. */
  366. public function setServerProxyValidateURL($url)
  367. {
  368. // Argument Validation
  369. if (gettype($url) != 'string')
  370. throw new CAS_TypeMismatchException($url, '$url', 'string');
  371. return $this->_server['proxy_validate_url'] = $url;
  372. }
  373. /**
  374. * This method sets the samlValidate URL of the CAS server.
  375. *
  376. * @param string $url the samlValidate URL
  377. *
  378. * @return string samlValidate URL
  379. */
  380. public function setServerSamlValidateURL($url)
  381. {
  382. // Argument Validation
  383. if (gettype($url) != 'string')
  384. throw new CAS_TypeMismatchException($url, '$url', 'string');
  385. return $this->_server['saml_validate_url'] = $url;
  386. }
  387. /**
  388. * This method is used to retrieve the service validating URL of the CAS server.
  389. *
  390. * @return string serviceValidate URL.
  391. */
  392. public function getServerServiceValidateURL()
  393. {
  394. phpCAS::traceBegin();
  395. // the URL is build only when needed
  396. if ( empty($this->_server['service_validate_url']) ) {
  397. switch ($this->getServerVersion()) {
  398. case CAS_VERSION_1_0:
  399. $this->_server['service_validate_url'] = $this->_getServerBaseURL()
  400. .'validate';
  401. break;
  402. case CAS_VERSION_2_0:
  403. $this->_server['service_validate_url'] = $this->_getServerBaseURL()
  404. .'serviceValidate';
  405. break;
  406. case CAS_VERSION_3_0:
  407. $this->_server['service_validate_url'] = $this->_getServerBaseURL()
  408. .'p3/serviceValidate';
  409. break;
  410. }
  411. }
  412. $url = $this->_buildQueryUrl(
  413. $this->_server['service_validate_url'],
  414. 'service='.urlencode($this->getURL())
  415. );
  416. phpCAS::traceEnd($url);
  417. return $url;
  418. }
  419. /**
  420. * This method is used to retrieve the SAML validating URL of the CAS server.
  421. *
  422. * @return string samlValidate URL.
  423. */
  424. public function getServerSamlValidateURL()
  425. {
  426. phpCAS::traceBegin();
  427. // the URL is build only when needed
  428. if ( empty($this->_server['saml_validate_url']) ) {
  429. switch ($this->getServerVersion()) {
  430. case SAML_VERSION_1_1:
  431. $this->_server['saml_validate_url'] = $this->_getServerBaseURL().'samlValidate';
  432. break;
  433. }
  434. }
  435. $url = $this->_buildQueryUrl(
  436. $this->_server['saml_validate_url'],
  437. 'TARGET='.urlencode($this->getURL())
  438. );
  439. phpCAS::traceEnd($url);
  440. return $url;
  441. }
  442. /**
  443. * This method is used to retrieve the proxy validating URL of the CAS server.
  444. *
  445. * @return string proxyValidate URL.
  446. */
  447. public function getServerProxyValidateURL()
  448. {
  449. phpCAS::traceBegin();
  450. // the URL is build only when needed
  451. if ( empty($this->_server['proxy_validate_url']) ) {
  452. switch ($this->getServerVersion()) {
  453. case CAS_VERSION_1_0:
  454. $this->_server['proxy_validate_url'] = '';
  455. break;
  456. case CAS_VERSION_2_0:
  457. $this->_server['proxy_validate_url'] = $this->_getServerBaseURL().'proxyValidate';
  458. break;
  459. case CAS_VERSION_3_0:
  460. $this->_server['proxy_validate_url'] = $this->_getServerBaseURL().'p3/proxyValidate';
  461. break;
  462. }
  463. }
  464. $url = $this->_buildQueryUrl(
  465. $this->_server['proxy_validate_url'],
  466. 'service='.urlencode($this->getURL())
  467. );
  468. phpCAS::traceEnd($url);
  469. return $url;
  470. }
  471. /**
  472. * This method is used to retrieve the proxy URL of the CAS server.
  473. *
  474. * @return string proxy URL.
  475. */
  476. public function getServerProxyURL()
  477. {
  478. // the URL is build only when needed
  479. if ( empty($this->_server['proxy_url']) ) {
  480. switch ($this->getServerVersion()) {
  481. case CAS_VERSION_1_0:
  482. $this->_server['proxy_url'] = '';
  483. break;
  484. case CAS_VERSION_2_0:
  485. case CAS_VERSION_3_0:
  486. $this->_server['proxy_url'] = $this->_getServerBaseURL().'proxy';
  487. break;
  488. }
  489. }
  490. return $this->_server['proxy_url'];
  491. }
  492. /**
  493. * This method is used to retrieve the logout URL of the CAS server.
  494. *
  495. * @return string logout URL.
  496. */
  497. public function getServerLogoutURL()
  498. {
  499. // the URL is build only when needed
  500. if ( empty($this->_server['logout_url']) ) {
  501. $this->_server['logout_url'] = $this->_getServerBaseURL().'logout';
  502. }
  503. return $this->_server['logout_url'];
  504. }
  505. /**
  506. * This method sets the logout URL of the CAS server.
  507. *
  508. * @param string $url the logout URL
  509. *
  510. * @return string logout url
  511. */
  512. public function setServerLogoutURL($url)
  513. {
  514. // Argument Validation
  515. if (gettype($url) != 'string')
  516. throw new CAS_TypeMismatchException($url, '$url', 'string');
  517. return $this->_server['logout_url'] = $url;
  518. }
  519. /**
  520. * An array to store extra curl options.
  521. */
  522. private $_curl_options = array();
  523. /**
  524. * This method is used to set additional user curl options.
  525. *
  526. * @param string $key name of the curl option
  527. * @param string $value value of the curl option
  528. *
  529. * @return void
  530. */
  531. public function setExtraCurlOption($key, $value)
  532. {
  533. $this->_curl_options[$key] = $value;
  534. }
  535. /** @} */
  536. // ########################################################################
  537. // Change the internal behaviour of phpcas
  538. // ########################################################################
  539. /**
  540. * @addtogroup internalBehave
  541. * @{
  542. */
  543. /**
  544. * The class to instantiate for making web requests in readUrl().
  545. * The class specified must implement the CAS_Request_RequestInterface.
  546. * By default CAS_Request_CurlRequest is used, but this may be overridden to
  547. * supply alternate request mechanisms for testing.
  548. */
  549. private $_requestImplementation = 'CAS_Request_CurlRequest';
  550. /**
  551. * Override the default implementation used to make web requests in readUrl().
  552. * This class must implement the CAS_Request_RequestInterface.
  553. *
  554. * @param string $className name of the RequestImplementation class
  555. *
  556. * @return void
  557. */
  558. public function setRequestImplementation ($className)
  559. {
  560. $obj = new $className;
  561. if (!($obj instanceof CAS_Request_RequestInterface)) {
  562. throw new CAS_InvalidArgumentException(
  563. '$className must implement the CAS_Request_RequestInterface'
  564. );
  565. }
  566. $this->_requestImplementation = $className;
  567. }
  568. /**
  569. * @var boolean $_clearTicketsFromUrl; If true, phpCAS will clear session
  570. * tickets from the URL after a successful authentication.
  571. */
  572. private $_clearTicketsFromUrl = true;
  573. /**
  574. * Configure the client to not send redirect headers and call exit() on
  575. * authentication success. The normal redirect is used to remove the service
  576. * ticket from the client's URL, but for running unit tests we need to
  577. * continue without exiting.
  578. *
  579. * Needed for testing authentication
  580. *
  581. * @return void
  582. */
  583. public function setNoClearTicketsFromUrl ()
  584. {
  585. $this->_clearTicketsFromUrl = false;
  586. }
  587. /**
  588. * @var callback $_attributeParserCallbackFunction;
  589. */
  590. private $_casAttributeParserCallbackFunction = null;
  591. /**
  592. * @var array $_attributeParserCallbackArgs;
  593. */
  594. private $_casAttributeParserCallbackArgs = array();
  595. /**
  596. * Set a callback function to be run when parsing CAS attributes
  597. *
  598. * The callback function will be passed a XMLNode as its first parameter,
  599. * followed by any $additionalArgs you pass.
  600. *
  601. * @param string $function callback function to call
  602. * @param array $additionalArgs optional array of arguments
  603. *
  604. * @return void
  605. */
  606. public function setCasAttributeParserCallback($function, array $additionalArgs = array())
  607. {
  608. $this->_casAttributeParserCallbackFunction = $function;
  609. $this->_casAttributeParserCallbackArgs = $additionalArgs;
  610. }
  611. /** @var callable $_postAuthenticateCallbackFunction;
  612. */
  613. private $_postAuthenticateCallbackFunction = null;
  614. /**
  615. * @var array $_postAuthenticateCallbackArgs;
  616. */
  617. private $_postAuthenticateCallbackArgs = array();
  618. /**
  619. * Set a callback function to be run when a user authenticates.
  620. *
  621. * The callback function will be passed a $logoutTicket as its first parameter,
  622. * followed by any $additionalArgs you pass. The $logoutTicket parameter is an
  623. * opaque string that can be used to map a session-id to the logout request
  624. * in order to support single-signout in applications that manage their own
  625. * sessions (rather than letting phpCAS start the session).
  626. *
  627. * phpCAS::forceAuthentication() will always exit and forward client unless
  628. * they are already authenticated. To perform an action at the moment the user
  629. * logs in (such as registering an account, performing logging, etc), register
  630. * a callback function here.
  631. *
  632. * @param callable $function callback function to call
  633. * @param array $additionalArgs optional array of arguments
  634. *
  635. * @return void
  636. */
  637. public function setPostAuthenticateCallback ($function, array $additionalArgs = array())
  638. {
  639. $this->_postAuthenticateCallbackFunction = $function;
  640. $this->_postAuthenticateCallbackArgs = $additionalArgs;
  641. }
  642. /**
  643. * @var callable $_signoutCallbackFunction;
  644. */
  645. private $_signoutCallbackFunction = null;
  646. /**
  647. * @var array $_signoutCallbackArgs;
  648. */
  649. private $_signoutCallbackArgs = array();
  650. /**
  651. * Set a callback function to be run when a single-signout request is received.
  652. *
  653. * The callback function will be passed a $logoutTicket as its first parameter,
  654. * followed by any $additionalArgs you pass. The $logoutTicket parameter is an
  655. * opaque string that can be used to map a session-id to the logout request in
  656. * order to support single-signout in applications that manage their own sessions
  657. * (rather than letting phpCAS start and destroy the session).
  658. *
  659. * @param callable $function callback function to call
  660. * @param array $additionalArgs optional array of arguments
  661. *
  662. * @return void
  663. */
  664. public function setSingleSignoutCallback ($function, array $additionalArgs = array())
  665. {
  666. $this->_signoutCallbackFunction = $function;
  667. $this->_signoutCallbackArgs = $additionalArgs;
  668. }
  669. // ########################################################################
  670. // Methods for supplying code-flow feedback to integrators.
  671. // ########################################################################
  672. /**
  673. * Ensure that this is actually a proxy object or fail with an exception
  674. *
  675. * @throws CAS_OutOfSequenceBeforeProxyException
  676. *
  677. * @return void
  678. */
  679. public function ensureIsProxy()
  680. {
  681. if (!$this->isProxy()) {
  682. throw new CAS_OutOfSequenceBeforeProxyException();
  683. }
  684. }
  685. /**
  686. * Mark the caller of authentication. This will help client integraters determine
  687. * problems with their code flow if they call a function such as getUser() before
  688. * authentication has occurred.
  689. *
  690. * @param bool $auth True if authentication was successful, false otherwise.
  691. *
  692. * @return null
  693. */
  694. public function markAuthenticationCall ($auth)
  695. {
  696. // store where the authentication has been checked and the result
  697. $dbg = debug_backtrace();
  698. $this->_authentication_caller = array (
  699. 'file' => $dbg[1]['file'],
  700. 'line' => $dbg[1]['line'],
  701. 'method' => $dbg[1]['class'] . '::' . $dbg[1]['function'],
  702. 'result' => (boolean)$auth
  703. );
  704. }
  705. private $_authentication_caller;
  706. /**
  707. * Answer true if authentication has been checked.
  708. *
  709. * @return bool
  710. */
  711. public function wasAuthenticationCalled ()
  712. {
  713. return !empty($this->_authentication_caller);
  714. }
  715. /**
  716. * Ensure that authentication was checked. Terminate with exception if no
  717. * authentication was performed
  718. *
  719. * @throws CAS_OutOfSequenceBeforeAuthenticationCallException
  720. *
  721. * @return void
  722. */
  723. private function _ensureAuthenticationCalled()
  724. {
  725. if (!$this->wasAuthenticationCalled()) {
  726. throw new CAS_OutOfSequenceBeforeAuthenticationCallException();
  727. }
  728. }
  729. /**
  730. * Answer the result of the authentication call.
  731. *
  732. * Throws a CAS_OutOfSequenceException if wasAuthenticationCalled() is false
  733. * and markAuthenticationCall() didn't happen.
  734. *
  735. * @return bool
  736. */
  737. public function wasAuthenticationCallSuccessful ()
  738. {
  739. $this->_ensureAuthenticationCalled();
  740. return $this->_authentication_caller['result'];
  741. }
  742. /**
  743. * Ensure that authentication was checked. Terminate with exception if no
  744. * authentication was performed
  745. *
  746. * @throws CAS_OutOfSequenceException
  747. *
  748. * @return void
  749. */
  750. public function ensureAuthenticationCallSuccessful()
  751. {
  752. $this->_ensureAuthenticationCalled();
  753. if (!$this->_authentication_caller['result']) {
  754. throw new CAS_OutOfSequenceException(
  755. 'authentication was checked (by '
  756. . $this->getAuthenticationCallerMethod()
  757. . '() at ' . $this->getAuthenticationCallerFile()
  758. . ':' . $this->getAuthenticationCallerLine()
  759. . ') but the method returned false'
  760. );
  761. }
  762. }
  763. /**
  764. * Answer information about the authentication caller.
  765. *
  766. * Throws a CAS_OutOfSequenceException if wasAuthenticationCalled() is false
  767. * and markAuthenticationCall() didn't happen.
  768. *
  769. * @return string the file that called authentication
  770. */
  771. public function getAuthenticationCallerFile ()
  772. {
  773. $this->_ensureAuthenticationCalled();
  774. return $this->_authentication_caller['file'];
  775. }
  776. /**
  777. * Answer information about the authentication caller.
  778. *
  779. * Throws a CAS_OutOfSequenceException if wasAuthenticationCalled() is false
  780. * and markAuthenticationCall() didn't happen.
  781. *
  782. * @return int the line that called authentication
  783. */
  784. public function getAuthenticationCallerLine ()
  785. {
  786. $this->_ensureAuthenticationCalled();
  787. return $this->_authentication_caller['line'];
  788. }
  789. /**
  790. * Answer information about the authentication caller.
  791. *
  792. * Throws a CAS_OutOfSequenceException if wasAuthenticationCalled() is false
  793. * and markAuthenticationCall() didn't happen.
  794. *
  795. * @return string the method that called authentication
  796. */
  797. public function getAuthenticationCallerMethod ()
  798. {
  799. $this->_ensureAuthenticationCalled();
  800. return $this->_authentication_caller['method'];
  801. }
  802. /** @} */
  803. // ########################################################################
  804. // CONSTRUCTOR
  805. // ########################################################################
  806. /**
  807. * @addtogroup internalConfig
  808. * @{
  809. */
  810. /**
  811. * CAS_Client constructor.
  812. *
  813. * @param string $server_version the version of the CAS server
  814. * @param bool $proxy true if the CAS client is a CAS proxy
  815. * @param string $server_hostname the hostname of the CAS server
  816. * @param int $server_port the port the CAS server is running on
  817. * @param string $server_uri the URI the CAS server is responding on
  818. * @param bool $changeSessionID Allow phpCAS to change the session_id
  819. * (Single Sign Out/handleLogoutRequests
  820. * is based on that change)
  821. * @param \SessionHandlerInterface $sessionHandler the session handler
  822. *
  823. * @return self a newly created CAS_Client object
  824. */
  825. public function __construct(
  826. $server_version,
  827. $proxy,
  828. $server_hostname,
  829. $server_port,
  830. $server_uri,
  831. $changeSessionID = true,
  832. \SessionHandlerInterface $sessionHandler = null
  833. ) {
  834. // Argument validation
  835. if (gettype($server_version) != 'string')
  836. throw new CAS_TypeMismatchException($server_version, '$server_version', 'string');
  837. if (gettype($proxy) != 'boolean')
  838. throw new CAS_TypeMismatchException($proxy, '$proxy', 'boolean');
  839. if (gettype($server_hostname) != 'string')
  840. throw new CAS_TypeMismatchException($server_hostname, '$server_hostname', 'string');
  841. if (gettype($server_port) != 'integer')
  842. throw new CAS_TypeMismatchException($server_port, '$server_port', 'integer');
  843. if (gettype($server_uri) != 'string')
  844. throw new CAS_TypeMismatchException($server_uri, '$server_uri', 'string');
  845. if (gettype($changeSessionID) != 'boolean')
  846. throw new CAS_TypeMismatchException($changeSessionID, '$changeSessionID', 'boolean');
  847. if (empty($sessionHandler)) {
  848. $sessionHandler = new CAS_Session_PhpSession;
  849. }
  850. phpCAS::traceBegin();
  851. // true : allow to change the session_id(), false session_id won't be
  852. // changed and logout won't be handled because of that
  853. $this->_setChangeSessionID($changeSessionID);
  854. $this->setSessionHandler($sessionHandler);
  855. if (!$this->_isLogoutRequest()) {
  856. if (session_id() === "") {
  857. // skip Session Handling for logout requests and if don't want it
  858. session_start();
  859. phpCAS :: trace("Starting a new session " . session_id());
  860. }
  861. // init phpCAS session array
  862. if (!isset($_SESSION[static::PHPCAS_SESSION_PREFIX])
  863. || !is_array($_SESSION[static::PHPCAS_SESSION_PREFIX])) {
  864. $_SESSION[static::PHPCAS_SESSION_PREFIX] = array();
  865. }
  866. }
  867. // Only for debug purposes
  868. if ($this->isSessionAuthenticated()){
  869. phpCAS :: trace("Session is authenticated as: " . $this->getSessionValue('user'));
  870. } else {
  871. phpCAS :: trace("Session is not authenticated");
  872. }
  873. // are we in proxy mode ?
  874. $this->_proxy = $proxy;
  875. // Make cookie handling available.
  876. if ($this->isProxy()) {
  877. if (!$this->hasSessionValue('service_cookies')) {
  878. $this->setSessionValue('service_cookies', array());
  879. }
  880. // TODO remove explicit call to $_SESSION
  881. $this->_serviceCookieJar = new CAS_CookieJar(
  882. $_SESSION[static::PHPCAS_SESSION_PREFIX]['service_cookies']
  883. );
  884. }
  885. // check version
  886. $supportedProtocols = phpCAS::getSupportedProtocols();
  887. if (isset($supportedProtocols[$server_version]) === false) {
  888. phpCAS::error(
  889. 'this version of CAS (`'.$server_version
  890. .'\') is not supported by phpCAS '.phpCAS::getVersion()
  891. );
  892. }
  893. if ($server_version === CAS_VERSION_1_0 && $this->isProxy()) {
  894. phpCAS::error(
  895. 'CAS proxies are not supported in CAS '.$server_version
  896. );
  897. }
  898. $this->_server['version'] = $server_version;
  899. // check hostname
  900. if ( empty($server_hostname)
  901. || !preg_match('/[\.\d\-a-z]*/', $server_hostname)
  902. ) {
  903. phpCAS::error('bad CAS server hostname (`'.$server_hostname.'\')');
  904. }
  905. $this->_server['hostname'] = $server_hostname;
  906. // check port
  907. if ( $server_port == 0
  908. || !is_int($server_port)
  909. ) {
  910. phpCAS::error('bad CAS server port (`'.$server_hostname.'\')');
  911. }
  912. $this->_server['port'] = $server_port;
  913. // check URI
  914. if ( !preg_match('/[\.\d\-_a-z\/]*/', $server_uri) ) {
  915. phpCAS::error('bad CAS server URI (`'.$server_uri.'\')');
  916. }
  917. // add leading and trailing `/' and remove doubles
  918. if(strstr($server_uri, '?') === false) $server_uri .= '/';
  919. $server_uri = preg_replace('/\/\//', '/', '/'.$server_uri);
  920. $this->_server['uri'] = $server_uri;
  921. // set to callback mode if PgtIou and PgtId CGI GET parameters are provided
  922. if ( $this->isProxy() ) {
  923. if(!empty($_GET['pgtIou'])&&!empty($_GET['pgtId'])) {
  924. $this->_setCallbackMode(true);
  925. $this->_setCallbackModeUsingPost(false);
  926. } elseif (!empty($_POST['pgtIou'])&&!empty($_POST['pgtId'])) {
  927. $this->_setCallbackMode(true);
  928. $this->_setCallbackModeUsingPost(true);
  929. } else {
  930. $this->_setCallbackMode(false);
  931. $this->_setCallbackModeUsingPost(false);
  932. }
  933. }
  934. if ( $this->_isCallbackMode() ) {
  935. //callback mode: check that phpCAS is secured
  936. if ( !$this->_isHttps() ) {
  937. phpCAS::error(
  938. 'CAS proxies must be secured to use phpCAS; PGT\'s will not be received from the CAS server'
  939. );
  940. }
  941. } else {
  942. //normal mode: get ticket and remove it from CGI parameters for
  943. // developers
  944. $ticket = (isset($_GET['ticket']) ? $_GET['ticket'] : null);
  945. if (preg_match('/^[SP]T-/', $ticket) ) {
  946. phpCAS::trace('Ticket \''.$ticket.'\' found');
  947. $this->setTicket($ticket);
  948. unset($_GET['ticket']);
  949. } else if ( !empty($ticket) ) {
  950. //ill-formed ticket, halt
  951. phpCAS::error(
  952. 'ill-formed ticket found in the URL (ticket=`'
  953. .htmlentities($ticket).'\')'
  954. );
  955. }
  956. }
  957. phpCAS::traceEnd();
  958. }
  959. /** @} */
  960. // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  961. // XX XX
  962. // XX Session Handling XX
  963. // XX XX
  964. // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  965. /**
  966. * @addtogroup internalConfig
  967. * @{
  968. */
  969. /** The session prefix for phpCAS values */
  970. const PHPCAS_SESSION_PREFIX = 'phpCAS';
  971. /**
  972. * @var bool A variable to whether phpcas will use its own session handling. Default = true
  973. * @hideinitializer
  974. */
  975. private $_change_session_id = true;
  976. /**
  977. * @var SessionHandlerInterface
  978. */
  979. private $_sessionHandler;
  980. /**
  981. * Set a parameter whether to allow phpCAS to change session_id
  982. *
  983. * @param bool $allowed allow phpCAS to change session_id
  984. *
  985. * @return void
  986. */
  987. private function _setChangeSessionID($allowed)
  988. {
  989. $this->_change_session_id = $allowed;
  990. }
  991. /**
  992. * Get whether phpCAS is allowed to change session_id
  993. *
  994. * @return bool
  995. */
  996. public function getChangeSessionID()
  997. {
  998. return $this->_change_session_id;
  999. }
  1000. /**
  1001. * Set the session handler.
  1002. *
  1003. * @param \SessionHandlerInterface $sessionHandler
  1004. *
  1005. * @return bool
  1006. */
  1007. public function setSessionHandler(\SessionHandlerInterface $sessionHandler)
  1008. {
  1009. $this->_sessionHandler = $sessionHandler;
  1010. if (session_status() !== PHP_SESSION_ACTIVE) {
  1011. return session_set_save_handler($this->_sessionHandler, true);
  1012. }
  1013. return true;
  1014. }
  1015. /**
  1016. * Get a session value using the given key.
  1017. *
  1018. * @param string $key
  1019. * @param mixed $default default value if the key is not set
  1020. *
  1021. * @return mixed
  1022. */
  1023. protected function getSessionValue($key, $default = null)
  1024. {
  1025. $this->validateSession($key);
  1026. if (isset($_SESSION[static::PHPCAS_SESSION_PREFIX][$key])) {
  1027. return $_SESSION[static::PHPCAS_SESSION_PREFIX][$key];
  1028. }
  1029. return $default;
  1030. }
  1031. /**
  1032. * Determine whether a session value is set or not.
  1033. *
  1034. * To check if a session value is empty or not please use
  1035. * !!(getSessionValue($key)).
  1036. *
  1037. * @param string $key
  1038. *
  1039. * @return bool
  1040. */
  1041. protected function hasSessionValue($key)
  1042. {
  1043. $this->validateSession($key);
  1044. return isset($_SESSION[static::PHPCAS_SESSION_PREFIX][$key]);
  1045. }
  1046. /**
  1047. * Set a session value using the given key and value.
  1048. *
  1049. * @param string $key
  1050. * @param mixed $value
  1051. *
  1052. * @return string
  1053. */
  1054. protected function setSessionValue($key, $value)
  1055. {
  1056. $this->validateSession($key);
  1057. $_SESSION[static::PHPCAS_SESSION_PREFIX][$key] = $value;
  1058. }
  1059. /**
  1060. * Remove a session value with the given key.
  1061. *
  1062. * @param string $key
  1063. */
  1064. protected function removeSessionValue($key)
  1065. {
  1066. $this->validateSession($key);
  1067. if (isset($_SESSION[static::PHPCAS_SESSION_PREFIX][$key])) {
  1068. unset($_SESSION[static::PHPCAS_SESSION_PREFIX][$key]);
  1069. return true;
  1070. }
  1071. return false;
  1072. }
  1073. /**
  1074. * Remove all phpCAS session values.
  1075. */
  1076. protected function clearSessionValues()
  1077. {
  1078. unset($_SESSION[static::PHPCAS_SESSION_PREFIX]);
  1079. }
  1080. /**
  1081. * Ensure $key is a string for session utils input
  1082. *
  1083. * @param string $key
  1084. *
  1085. * @return bool
  1086. */
  1087. protected function validateSession($key)
  1088. {
  1089. if (!is_string($key)) {
  1090. throw new InvalidArgumentException('Session key must be a string.');
  1091. }
  1092. return true;
  1093. }
  1094. /**
  1095. * Renaming the session
  1096. *
  1097. * @param string $ticket name of the ticket
  1098. *
  1099. * @return void
  1100. */
  1101. protected function _renameSession($ticket)
  1102. {
  1103. phpCAS::traceBegin();
  1104. if ($this->getChangeSessionID()) {
  1105. if (!empty($this->_user)) {
  1106. $old_session = $_SESSION;
  1107. phpCAS :: trace("Killing session: ". session_id());
  1108. session_destroy();
  1109. // set up a new session, of name based on the ticket
  1110. $session_id = $this->_sessionIdForTicket($ticket);
  1111. phpCAS :: trace("Starting session: ". $session_id);
  1112. session_id($session_id);
  1113. session_start();
  1114. phpCAS :: trace("Restoring old session vars");
  1115. $_SESSION = $old_session;
  1116. } else {
  1117. phpCAS :: trace (
  1118. 'Session should only be renamed after successfull authentication'
  1119. );
  1120. }
  1121. } else {
  1122. phpCAS :: trace(
  1123. "Skipping session rename since phpCAS is not handling the session."
  1124. );
  1125. }
  1126. phpCAS::traceEnd();
  1127. }
  1128. /** @} */
  1129. // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  1130. // XX XX
  1131. // XX AUTHENTICATION XX
  1132. // XX XX
  1133. // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  1134. /**
  1135. * @addtogroup internalAuthentication
  1136. * @{
  1137. */
  1138. /**
  1139. * The Authenticated user. Written by CAS_Client::_setUser(), read by
  1140. * CAS_Client::getUser().
  1141. *
  1142. * @hideinitializer
  1143. */
  1144. private $_user = '';
  1145. /**
  1146. * This method sets the CAS user's login name.
  1147. *
  1148. * @param string $user the login name of the authenticated user.
  1149. *
  1150. * @return void
  1151. */
  1152. private function _setUser($user)
  1153. {
  1154. $this->_user = $user;
  1155. }
  1156. /**
  1157. * This method returns the CAS user's login name.
  1158. *
  1159. * @return string the login name of the authenticated user
  1160. *
  1161. * @warning should be called only after CAS_Client::forceAuthentication() or
  1162. * CAS_Client::isAuthenticated(), otherwise halt with an error.
  1163. */
  1164. public function getUser()
  1165. {
  1166. // Sequence validation
  1167. $this->ensureAuthenticationCallSuccessful();
  1168. return $this->_getUser();
  1169. }
  1170. /**
  1171. * This method returns the CAS user's login name.
  1172. *
  1173. * @return string the login name of the authenticated user
  1174. *
  1175. * @warning should be called only after CAS_Client::forceAuthentication() or
  1176. * CAS_Client::isAuthenticated(), otherwise halt with an error.
  1177. */
  1178. private function _getUser()
  1179. {
  1180. // This is likely a duplicate check that could be removed....
  1181. if ( empty($this->_user) ) {
  1182. phpCAS::error(
  1183. 'this method should be used only after '.__CLASS__
  1184. .'::forceAuthentication() or '.__CLASS__.'::isAuthenticated()'
  1185. );
  1186. }
  1187. return $this->_user;
  1188. }
  1189. /**
  1190. * The Authenticated users attributes. Written by
  1191. * CAS_Client::setAttributes(), read by CAS_Client::getAttributes().
  1192. * @attention client applications should use phpCAS::getAttributes().
  1193. *
  1194. * @hideinitializer
  1195. */
  1196. private $_attributes = array();
  1197. /**
  1198. * Set an array of attributes
  1199. *
  1200. * @param array $attributes a key value array of attributes
  1201. *
  1202. * @return void
  1203. */
  1204. public function setAttributes($attributes)
  1205. {
  1206. $this->_attributes = $attributes;
  1207. }
  1208. /**
  1209. * Get an key values arry of attributes
  1210. *
  1211. * @return array of attributes
  1212. */
  1213. public function getAttributes()
  1214. {
  1215. // Sequence validation
  1216. $this->ensureAuthenticationCallSuccessful();
  1217. // This is likely a duplicate check that could be removed....
  1218. if ( empty($this->_user) ) {
  1219. // if no user is set, there shouldn't be any attributes also...
  1220. phpCAS::error(
  1221. 'this method should be used only after '.__CLASS__
  1222. .'::forceAuthentication() or '.__CLASS__.'::isAuthenticated()'
  1223. );
  1224. }
  1225. return $this->_attributes;
  1226. }
  1227. /**
  1228. * Check whether attributes are available
  1229. *
  1230. * @return bool attributes available
  1231. */
  1232. public function hasAttributes()
  1233. {
  1234. // Sequence validation
  1235. $this->ensureAuthenticationCallSuccessful();
  1236. return !empty($this->_attributes);
  1237. }
  1238. /**
  1239. * Check whether a specific attribute with a name is available
  1240. *
  1241. * @param string $key name of attribute
  1242. *
  1243. * @return bool is attribute available
  1244. */
  1245. public function hasAttribute($key)
  1246. {
  1247. // Sequence validation
  1248. $this->ensureAuthenticationCallSuccessful();
  1249. return $this->_hasAttribute($key);
  1250. }
  1251. /**
  1252. * Check whether a specific attribute with a name is available
  1253. *
  1254. * @param string $key name of attribute
  1255. *
  1256. * @return bool is attribute available
  1257. */
  1258. private function _hasAttribute($key)
  1259. {
  1260. return (is_array($this->_attributes)
  1261. && array_key_exists($key, $this->_attributes));
  1262. }
  1263. /**
  1264. * Get a specific attribute by name
  1265. *
  1266. * @param string $key name of attribute
  1267. *
  1268. * @return string attribute values
  1269. */
  1270. public function getAttribute($key)
  1271. {
  1272. // Sequence validation
  1273. $this->ensureAuthenticationCallSuccessful();
  1274. if ($this->_hasAttribute($key)) {
  1275. return $this->_attributes[$key];
  1276. }
  1277. }
  1278. /**
  1279. * This method is called to renew the authentication of the user
  1280. * If the user is authenticated, renew the connection
  1281. * If not, redirect to CAS
  1282. *
  1283. * @return bool true when the user is authenticated; otherwise halt.
  1284. */
  1285. public function renewAuthentication()
  1286. {
  1287. phpCAS::traceBegin();
  1288. // Either way, the user is authenticated by CAS
  1289. $this->removeSessionValue('auth_checked');
  1290. if ( $this->isAuthenticated(true) ) {
  1291. phpCAS::trace('user already authenticated');
  1292. $res = true;
  1293. } else {
  1294. $this->redirectToCas(false, true);
  1295. // never reached
  1296. $res = false;
  1297. }
  1298. phpCAS::traceEnd();
  1299. return $res;
  1300. }
  1301. /**
  1302. * This method is called to be sure that the user is authenticated. When not
  1303. * authenticated, halt by redirecting to the CAS server; otherwise return true.
  1304. *
  1305. * @return bool true when the user is authenticated; otherwise halt.
  1306. */
  1307. public function forceAuthentication()
  1308. {
  1309. phpCAS::traceBegin();
  1310. if ( $this->isAuthenticated() ) {
  1311. // the user is authenticated, nothing to be done.
  1312. phpCAS::trace('no need to authenticate');
  1313. $res = true;
  1314. } else {
  1315. // the user is not authenticated, redirect to the CAS server
  1316. $this->removeSessionValue('auth_checked');
  1317. $this->redirectToCas(false/* no gateway */);
  1318. // never reached
  1319. $res = false;
  1320. }
  1321. phpCAS::traceEnd($res);
  1322. return $res;
  1323. }
  1324. /**
  1325. * An integer that gives the number of times authentication will be cached
  1326. * before rechecked.
  1327. *
  1328. * @hideinitializer
  1329. */
  1330. private $_cache_times_for_auth_recheck = 0;
  1331. /**
  1332. * Set the number of times authentication will be cached before rechecked.
  1333. *
  1334. * @param int $n number of times to wait for a recheck
  1335. *
  1336. * @return void
  1337. */
  1338. public function setCacheTimesForAuthRecheck($n)
  1339. {
  1340. if (gettype($n) != 'integer')
  1341. throw new CAS_TypeMismatchException($n, '$n', 'string');
  1342. $this->_cache_times_for_auth_recheck = $n;
  1343. }
  1344. /**
  1345. * This method is called to check whether the user is authenticated or not.
  1346. *
  1347. * @return bool true when the user is authenticated, false when a previous
  1348. * gateway login failed or the function will not return if the user is
  1349. * redirected to the cas server for a gateway login attempt
  1350. */
  1351. public function checkAuthentication()
  1352. {
  1353. phpCAS::traceBegin();
  1354. $res = false; // default
  1355. if ( $this->isAuthenticated() ) {
  1356. phpCAS::trace('user is authenticated');
  1357. /* The 'auth_checked' variable is removed just in case it's set. */
  1358. $this->removeSessionValue('auth_checked');
  1359. $res = true;
  1360. } else if ($this->getSessionValue('auth_checked')) {
  1361. // the previous request has redirected the client to the CAS server
  1362. // with gateway=true
  1363. $this->removeSessionValue('auth_checked');
  1364. } else {
  1365. // avoid a check against CAS on every request
  1366. // we need to write this back to session later
  1367. $unauth_count = $this->getSessionValue('unauth_count', -2);
  1368. if (($unauth_count != -2
  1369. && $this->_cache_times_for_auth_recheck == -1)
  1370. || ($unauth_count >= 0
  1371. && $unauth_count < $this->_cache_times_for_auth_recheck)
  1372. ) {
  1373. if ($this->_cache_times_for_auth_recheck != -1) {
  1374. $unauth_count++;
  1375. phpCAS::trace(
  1376. 'user is not authenticated (cached for '
  1377. .$unauth_count.' times of '
  1378. .$this->_cache_times_for_auth_recheck.')'
  1379. );
  1380. } else {
  1381. phpCAS::trace(
  1382. 'user is not authenticated (cached for until login pressed)'
  1383. );
  1384. }
  1385. $this->setSessionValue('unauth_count', $unauth_count);
  1386. } else {
  1387. $this->setSessionValue('unauth_count', 0);
  1388. $this->setSessionValue('auth_checked', true);
  1389. phpCAS::trace('user is not authenticated (cache reset)');
  1390. $this->redirectToCas(true/* gateway */);
  1391. // never reached
  1392. }
  1393. }
  1394. phpCAS::traceEnd($res);
  1395. return $res;
  1396. }
  1397. /**
  1398. * This method is called to check if the user is authenticated (previously or by
  1399. * tickets given in the URL).
  1400. *
  1401. * @param bool $renew true to force the authentication with the CAS server
  1402. *
  1403. * @return bool true when the user is authenticated. Also may redirect to the
  1404. * same URL without the ticket.
  1405. */
  1406. public function isAuthenticated($renew=false)
  1407. {
  1408. phpCAS::traceBegin();
  1409. $res = false;
  1410. $validate_url = '';
  1411. if ( $this->_wasPreviouslyAuthenticated() ) {
  1412. if ($this->hasTicket()) {
  1413. // User has a additional ticket but was already authenticated
  1414. phpCAS::trace(
  1415. 'ticket was present and will be discarded, use renewAuthenticate()'
  1416. );
  1417. if ($this->_clearTicketsFromUrl) {
  1418. phpCAS::trace("Prepare redirect to : ".$this->getURL());
  1419. session_write_close();
  1420. header('Location: '.$this->getURL());
  1421. flush();
  1422. phpCAS::traceExit();
  1423. throw new CAS_GracefullTerminationException();
  1424. } else {
  1425. phpCAS::trace(
  1426. 'Already authenticated, but skipping ticket clearing since setNoClearTicketsFromUrl() was used.'
  1427. );
  1428. $res = true;
  1429. }
  1430. } else {
  1431. // the user has already (previously during the session) been
  1432. // authenticated, nothing to be done.
  1433. phpCAS::trace(
  1434. 'user was already authenticated, no need to look for tickets'
  1435. );
  1436. $res = true;
  1437. }
  1438. // Mark the auth-check as complete to allow post-authentication
  1439. // callbacks to make use of phpCAS::getUser() and similar methods
  1440. $this->markAuthenticationCall($res);
  1441. } else {
  1442. if ($this->hasTicket()) {
  1443. switch ($this->getServerVersion()) {
  1444. case CAS_VERSION_1_0:
  1445. // if a Service Ticket was given, validate it
  1446. phpCAS::trace(
  1447. 'CAS 1.0 ticket `'.$this->getTicket().'\' is present'
  1448. );
  1449. $this->validateCAS10(
  1450. $validate_url, $text_response, $tree_response, $renew
  1451. ); // if it fails, it halts
  1452. phpCAS::trace(
  1453. 'CAS 1.0 ticket `'.$this->getTicket().'\' was validated'
  1454. );
  1455. $this->setSessionValue('user', $this->_getUser());
  1456. $res = true;
  1457. $logoutTicket = $this->getTicket();
  1458. break;
  1459. case CAS_VERSION_2_0:
  1460. case CAS_VERSION_3_0:
  1461. // if a Proxy Ticket was given, validate it
  1462. phpCAS::trace(
  1463. 'CAS '.$this->getServerVersion().' ticket `'.$this->getTicket().'\' is present'
  1464. );
  1465. $this->validateCAS20(
  1466. $validate_url, $text_response, $tree_response, $renew
  1467. ); // note: if it fails, it halts
  1468. phpCAS::trace(
  1469. 'CAS '.$this->getServerVersion().' ticket `'.$this->getTicket().'\' was validated'
  1470. );
  1471. if ( $this->isProxy() ) {
  1472. $this->_validatePGT(
  1473. $validate_url, $text_response, $tree_response
  1474. ); // idem
  1475. phpCAS::trace('PGT `'.$this->_getPGT().'\' was validated');
  1476. $this->setSessionValue('pgt', $this->_getPGT());
  1477. }
  1478. $this->setSessionValue('user', $this->_getUser());
  1479. if (!empty($this->_attributes)) {
  1480. $this->setSessionValue('attributes', $this->_attributes);
  1481. }
  1482. $proxies = $this->getProxies();
  1483. if (!empty($proxies)) {
  1484. $this->setSessionValue('proxies', $this->getProxies());
  1485. }
  1486. $res = true;
  1487. $logoutTicket = $this->getTicket();
  1488. break;
  1489. case SAML_VERSION_1_1:
  1490. // if we have a SAML ticket, validate it.
  1491. phpCAS::trace(
  1492. 'SAML 1.1 ticket `'.$this->getTicket().'\' is present'
  1493. );
  1494. $this->validateSA(
  1495. $validate_url, $text_response, $tree_response, $renew
  1496. ); // if it fails, it halts
  1497. phpCAS::trace(
  1498. 'SAML 1.1 ticket `'.$this->getTicket().'\' was validated'
  1499. );
  1500. $this->setSessionValue('user', $this->_getUser());
  1501. $this->setSessionValue('attributes', $this->_attributes);
  1502. $res = true;
  1503. $logoutTicket = $this->getTicket();
  1504. break;
  1505. default:
  1506. phpCAS::trace('Protocoll error');
  1507. break;
  1508. }
  1509. } else {
  1510. // no ticket given, not authenticated
  1511. phpCAS::trace('no ticket found');
  1512. }
  1513. // Mark the auth-check as complete to allow post-authentication
  1514. // callbacks to make use of phpCAS::getUser() and similar methods
  1515. $this->markAuthenticationCall($res);
  1516. if ($res) {
  1517. // call the post-authenticate callback if registered.
  1518. if ($this->_postAuthenticateCallbackFunction) {
  1519. $args = $this->_postAuthenticateCallbackArgs;
  1520. array_unshift($args, $logoutTicket);
  1521. call_user_func_array(
  1522. $this->_postAuthenticateCallbackFunction, $args
  1523. );
  1524. }
  1525. // if called with a ticket parameter, we need to redirect to the
  1526. // app without the ticket so that CAS-ification is transparent
  1527. // to the browser (for later POSTS) most of the checks and
  1528. // errors should have been made now, so we're safe for redirect
  1529. // without masking error messages. remove the ticket as a
  1530. // security precaution to prevent a ticket in the HTTP_REFERRER
  1531. if ($this->_clearTicketsFromUrl) {
  1532. phpCAS::trace("Prepare redirect to : ".$this->getURL());
  1533. session_write_close();
  1534. header('Location: '.$this->getURL());
  1535. flush();
  1536. phpCAS::traceExit();
  1537. throw new CAS_GracefullTerminationException();
  1538. }
  1539. }
  1540. }
  1541. phpCAS::traceEnd($res);
  1542. return $res;
  1543. }
  1544. /**
  1545. * This method tells if the current session is authenticated.
  1546. *
  1547. * @return bool true if authenticated based soley on $_SESSION variable
  1548. */
  1549. public function isSessionAuthenticated ()
  1550. {
  1551. return !!$this->getSessionValue('user');
  1552. }
  1553. /**
  1554. * This method tells if the user has already been (previously) authenticated
  1555. * by looking into the session variables.
  1556. *
  1557. * @note This function switches to callback mode when needed.
  1558. *
  1559. * @return bool true when the user has already been authenticated; false otherwise.
  1560. */
  1561. private function _wasPreviouslyAuthenticated()
  1562. {
  1563. phpCAS::traceBegin();
  1564. if ( $this->_isCallbackMode() ) {
  1565. // Rebroadcast the pgtIou and pgtId to all nodes
  1566. if ($this->_rebroadcast&&!isset($_POST['rebroadcast'])) {
  1567. $this->_rebroadcast(self::PGTIOU);
  1568. }
  1569. $this->_callback();
  1570. }
  1571. $auth = false;
  1572. if ( $this->isProxy() ) {
  1573. // CAS proxy: username and PGT must be present
  1574. if ( $this->isSessionAuthenticated()
  1575. && $this->getSessionValue('pgt')
  1576. ) {
  1577. // authentication already done
  1578. $this->_setUser($this->getSessionValue('user'));
  1579. if ($this->hasSessionValue('attributes')) {
  1580. $this->setAttributes($this->getSessionValue('attributes'));
  1581. }
  1582. $this->_setPGT($this->getSessionValue('pgt'));
  1583. phpCAS::trace(
  1584. 'user = `'.$this->getSessionValue('user').'\', PGT = `'
  1585. .$this->getSessionValue('pgt').'\''
  1586. );
  1587. // Include the list of proxies
  1588. if ($this->hasSessionValue('proxies')) {
  1589. $this->_setProxies($this->getSessionValue('proxies'));
  1590. phpCAS::trace(
  1591. 'proxies = "'
  1592. .implode('", "', $this->getSessionValue('proxies')).'"'
  1593. );
  1594. }
  1595. $auth = true;
  1596. } elseif ( $this->isSessionAuthenticated()
  1597. && !$this->getSessionValue('pgt')
  1598. ) {
  1599. // these two variables should be empty or not empty at the same time
  1600. phpCAS::trace(
  1601. 'username found (`'.$this->getSessionValue('user')
  1602. .'\') but PGT is empty'
  1603. );
  1604. // unset all tickets to enforce authentication
  1605. $this->clearSessionValues();
  1606. $this->setTicket('');
  1607. } elseif ( !$this->isSessionAuthenticated()
  1608. && $this->getSessionValue('pgt')
  1609. ) {
  1610. // these two variables should be empty or not empty at the same time
  1611. phpCAS::trace(
  1612. 'PGT found (`'.$this->getSessionValue('pgt')
  1613. .'\') but username is empty'
  1614. );
  1615. // unset all tickets to enforce authentication
  1616. $this->clearSessionValues();
  1617. $this->setTicket('');
  1618. } else {
  1619. phpCAS::trace('neither user nor PGT found');
  1620. }
  1621. } else {
  1622. // `simple' CAS client (not a proxy): username must be present
  1623. if ( $this->isSessionAuthenticated() ) {
  1624. // authentication already done
  1625. $this->_setUser($this->getSessionValue('user'));
  1626. if ($this->hasSessionValue('attributes')) {
  1627. $this->setAttributes($this->getSessionValue('attributes'));
  1628. }
  1629. phpCAS::trace('user = `'.$this->getSessionValue('user').'\'');
  1630. // Include the list of proxies
  1631. if ($this->hasSessionValue('proxies')) {
  1632. $this->_setProxies($this->getSessionValue('proxies'));
  1633. phpCAS::trace(
  1634. 'proxies = "'
  1635. .implode('", "', $this->getSessionValue('proxies')).'"'
  1636. );
  1637. }
  1638. $auth = true;
  1639. } else {
  1640. phpCAS::trace('no user found');
  1641. }
  1642. }
  1643. phpCAS::traceEnd($auth);
  1644. return $auth;
  1645. }
  1646. /**
  1647. * This method is used to redirect the client to the CAS server.
  1648. * It is used by CAS_Client::forceAuthentication() and
  1649. * CAS_Client::checkAuthentication().
  1650. *
  1651. * @param bool $gateway true to check authentication, false to force it
  1652. * @param bool $renew true to force the authentication with the CAS server
  1653. *
  1654. * @return void
  1655. */
  1656. public function redirectToCas($gateway=false,$renew=false)
  1657. {
  1658. phpCAS::traceBegin();
  1659. $cas_url = $this->getServerLoginURL($gateway, $renew);
  1660. session_write_close();
  1661. if (php_sapi_name() === 'cli') {
  1662. @header('Location: '.$cas_url);
  1663. } else {
  1664. header('Location: '.$cas_url);
  1665. }
  1666. phpCAS::trace("Redirect to : ".$cas_url);
  1667. $lang = $this->getLangObj();
  1668. $this->printHTMLHeader($lang->getAuthenticationWanted());
  1669. printf('<p>'. $lang->getShouldHaveBeenRedirected(). '</p>', $cas_url);
  1670. $this->printHTMLFooter();
  1671. phpCAS::traceExit();
  1672. throw new CAS_GracefullTerminationException();
  1673. }
  1674. /**
  1675. * This method is used to logout from CAS.
  1676. *
  1677. * @param array $params an array that contains the optional url and service
  1678. * parameters that will be passed to the CAS server
  1679. *
  1680. * @return void
  1681. */
  1682. public function logout($params)
  1683. {
  1684. phpCAS::traceBegin();
  1685. $cas_url = $this->getServerLogoutURL();
  1686. $paramSeparator = '?';
  1687. if (isset($params['url'])) {
  1688. $cas_url = $cas_url . $paramSeparator . "url="
  1689. . urlencode($params['url']);
  1690. $paramSeparator = '&';
  1691. }
  1692. if (isset($params['service'])) {
  1693. $cas_url = $cas_url . $paramSeparator . "service="
  1694. . urlencode($params['service']);
  1695. }
  1696. header('Location: '.$cas_url);
  1697. phpCAS::trace("Prepare redirect to : ".$cas_url);
  1698. phpCAS::trace("Destroying session : ".session_id());
  1699. session_unset();
  1700. session_destroy();
  1701. if (session_status() === PHP_SESSION_NONE) {
  1702. phpCAS::trace("Session terminated");
  1703. } else {
  1704. phpCAS::error("Session was not terminated");
  1705. phpCAS::trace("Session was not terminated");
  1706. }
  1707. $lang = $this->getLangObj();
  1708. $this->printHTMLHeader($lang->getLogout());
  1709. printf('<p>'.$lang->getShouldHaveBeenRedirected(). '</p>', $cas_url);
  1710. $this->printHTMLFooter();
  1711. phpCAS::traceExit();
  1712. throw new CAS_GracefullTerminationException();
  1713. }
  1714. /**
  1715. * Check of the current request is a logout request
  1716. *
  1717. * @return bool is logout request.
  1718. */
  1719. private function _isLogoutRequest()
  1720. {
  1721. return !empty($_POST['logoutRequest']);
  1722. }
  1723. /**
  1724. * This method handles logout requests.
  1725. *
  1726. * @param bool $check_client true to check the client bofore handling
  1727. * the request, false not to perform any access control. True by default.
  1728. * @param array $allowed_clients an array of host names allowed to send
  1729. * logout requests.
  1730. *
  1731. * @return void
  1732. */
  1733. public function handleLogoutRequests($check_client=true, $allowed_clients=array())
  1734. {
  1735. phpCAS::traceBegin();
  1736. if (!$this->_isLogoutRequest()) {
  1737. phpCAS::trace("Not a logout request");
  1738. phpCAS::traceEnd();
  1739. return;
  1740. }
  1741. if (!$this->getChangeSessionID()
  1742. && is_null($this->_signoutCallbackFunction)
  1743. ) {
  1744. phpCAS::trace(
  1745. "phpCAS can't handle logout requests if it is not allowed to change session_id."
  1746. );
  1747. }
  1748. phpCAS::trace("Logout requested");
  1749. $decoded_logout_rq = urldecode($_POST['logoutRequest']);
  1750. phpCAS::trace("SAML REQUEST: ".$decoded_logout_rq);
  1751. $allowed = false;
  1752. if ($check_client) {
  1753. if ($allowed_clients === array()) {
  1754. $allowed_clients = array( $this->_getServerHostname() );
  1755. }
  1756. $client_ip = $_SERVER['REMOTE_ADDR'];
  1757. $client = gethostbyaddr($client_ip);
  1758. phpCAS::trace("Client: ".$client."/".$client_ip);
  1759. foreach ($allowed_clients as $allowed_client) {
  1760. if (($client == $allowed_client)
  1761. || ($client_ip == $allowed_client)
  1762. ) {
  1763. phpCAS::trace(
  1764. "Allowed client '".$allowed_client
  1765. ."' matches, logout request is allowed"
  1766. );
  1767. $allowed = true;
  1768. break;
  1769. } else {
  1770. phpCAS::trace(
  1771. "Allowed client '".$allowed_client."' does not match"
  1772. );
  1773. }
  1774. }
  1775. } else {
  1776. phpCAS::trace("No access control set");
  1777. $allowed = true;
  1778. }
  1779. // If Logout command is permitted proceed with the logout
  1780. if ($allowed) {
  1781. phpCAS::trace("Logout command allowed");
  1782. // Rebroadcast the logout request
  1783. if ($this->_rebroadcast && !isset($_POST['rebroadcast'])) {
  1784. $this->_rebroadcast(self::LOGOUT);
  1785. }
  1786. // Extract the ticket from the SAML Request
  1787. preg_match(
  1788. "|<samlp:SessionIndex>(.*)</samlp:SessionIndex>|",
  1789. $decoded_logout_rq, $tick, PREG_OFFSET_CAPTURE, 3
  1790. );
  1791. $wrappedSamlSessionIndex = preg_replace(
  1792. '|<samlp:SessionIndex>|', '', $tick[0][0]
  1793. );
  1794. $ticket2logout = preg_replace(
  1795. '|</samlp:SessionIndex>|', '', $wrappedSamlSessionIndex
  1796. );
  1797. phpCAS::trace("Ticket to logout: ".$ticket2logout);
  1798. // call the post-authenticate callback if registered.
  1799. if ($this->_signoutCallbackFunction) {
  1800. $args = $this->_signoutCallbackArgs;
  1801. array_unshift($args, $ticket2logout);
  1802. call_user_func_array($this->_signoutCallbackFunction, $args);
  1803. }
  1804. // If phpCAS is managing the session_id, destroy session thanks to
  1805. // session_id.
  1806. if ($this->getChangeSessionID()) {
  1807. $session_id = $this->_sessionIdForTicket($ticket2logout);
  1808. phpCAS::trace("Session id: ".$session_id);
  1809. // destroy a possible application session created before phpcas
  1810. if (session_id() !== "") {
  1811. session_unset();
  1812. session_destroy();
  1813. }
  1814. // fix session ID
  1815. session_id($session_id);
  1816. $_COOKIE[session_name()]=$session_id;
  1817. $_GET[session_name()]=$session_id;
  1818. // Overwrite session
  1819. session_start();
  1820. session_unset();
  1821. session_destroy();
  1822. phpCAS::trace("Session ". $session_id . " destroyed");
  1823. }
  1824. } else {
  1825. phpCAS::error("Unauthorized logout request from client '".$client."'");
  1826. phpCAS::trace("Unauthorized logout request from client '".$client."'");
  1827. }
  1828. flush();
  1829. phpCAS::traceExit();
  1830. throw new CAS_GracefullTerminationException();
  1831. }
  1832. /** @} */
  1833. // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  1834. // XX XX
  1835. // XX BASIC CLIENT FEATURES (CAS 1.0) XX
  1836. // XX XX
  1837. // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  1838. // ########################################################################
  1839. // ST
  1840. // ########################################################################
  1841. /**
  1842. * @addtogroup internalBasic
  1843. * @{
  1844. */
  1845. /**
  1846. * The Ticket provided in the URL of the request if present
  1847. * (empty otherwise). Written by CAS_Client::CAS_Client(), read by
  1848. * CAS_Client::getTicket() and CAS_Client::_hasPGT().
  1849. *
  1850. * @hideinitializer
  1851. */
  1852. private $_ticket = '';
  1853. /**
  1854. * This method returns the Service Ticket provided in the URL of the request.
  1855. *
  1856. * @return string service ticket.
  1857. */
  1858. public function getTicket()
  1859. {
  1860. return $this->_ticket;
  1861. }
  1862. /**
  1863. * This method stores the Service Ticket.
  1864. *
  1865. * @param string $st The Service Ticket.
  1866. *
  1867. * @return void
  1868. */
  1869. public function setTicket($st)
  1870. {
  1871. $this->_ticket = $st;
  1872. }
  1873. /**
  1874. * This method tells if a Service Ticket was stored.
  1875. *
  1876. * @return bool if a Service Ticket has been stored.
  1877. */
  1878. public function hasTicket()
  1879. {
  1880. return !empty($this->_ticket);
  1881. }
  1882. /** @} */
  1883. // ########################################################################
  1884. // ST VALIDATION
  1885. // ########################################################################
  1886. /**
  1887. * @addtogroup internalBasic
  1888. * @{
  1889. */
  1890. /**
  1891. * @var string the certificate of the CAS server CA.
  1892. *
  1893. * @hideinitializer
  1894. */
  1895. private $_cas_server_ca_cert = null;
  1896. /**
  1897. * validate CN of the CAS server certificate
  1898. *
  1899. * @hideinitializer
  1900. */
  1901. private $_cas_server_cn_validate = true;
  1902. /**
  1903. * Set to true not to validate the CAS server.
  1904. *
  1905. * @hideinitializer
  1906. */
  1907. private $_no_cas_server_validation = false;
  1908. /**
  1909. * Set the CA certificate of the CAS server.
  1910. *
  1911. * @param string $cert the PEM certificate file name of the CA that emited
  1912. * the cert of the server
  1913. * @param bool $validate_cn valiate CN of the CAS server certificate
  1914. *
  1915. * @return void
  1916. */
  1917. public function setCasServerCACert($cert, $validate_cn)
  1918. {
  1919. // Argument validation
  1920. if (gettype($cert) != 'string') {
  1921. throw new CAS_TypeMismatchException($cert, '$cert', 'string');
  1922. }
  1923. if (gettype($validate_cn) != 'boolean') {
  1924. throw new CAS_TypeMismatchException($validate_cn, '$validate_cn', 'boolean');
  1925. }
  1926. if (!file_exists($cert)) {
  1927. throw new CAS_InvalidArgumentException("Certificate file does not exist " . $this->_requestImplementation);
  1928. }
  1929. $this->_cas_server_ca_cert = $cert;
  1930. $this->_cas_server_cn_validate = $validate_cn;
  1931. }
  1932. /**
  1933. * Set no SSL validation for the CAS server.
  1934. *
  1935. * @return void
  1936. */
  1937. public function setNoCasServerValidation()
  1938. {
  1939. $this->_no_cas_server_validation = true;
  1940. }
  1941. /**
  1942. * This method is used to validate a CAS 1,0 ticket; halt on failure, and
  1943. * sets $validate_url, $text_reponse and $tree_response on success.
  1944. *
  1945. * @param string &$validate_url reference to the the URL of the request to
  1946. * the CAS server.
  1947. * @param string &$text_response reference to the response of the CAS
  1948. * server, as is (XML text).
  1949. * @param string &$tree_response reference to the response of the CAS
  1950. * server, as a DOM XML tree.
  1951. * @param bool $renew true to force the authentication with the CAS server
  1952. *
  1953. * @return bool true when successfull and issue a CAS_AuthenticationException
  1954. * and false on an error
  1955. * @throws CAS_AuthenticationException
  1956. */
  1957. public function validateCAS10(&$validate_url,&$text_response,&$tree_response,$renew=false)
  1958. {
  1959. phpCAS::traceBegin();
  1960. // build the URL to validate the ticket
  1961. $validate_url = $this->getServerServiceValidateURL()
  1962. .'&ticket='.urlencode($this->getTicket());
  1963. if ( $renew ) {
  1964. // pass the renew
  1965. $validate_url .= '&renew=true';
  1966. }
  1967. // open and read the URL
  1968. if ( !$this->_readURL($validate_url, $headers, $text_response, $err_msg) ) {
  1969. phpCAS::trace(
  1970. 'could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')'
  1971. );
  1972. throw new CAS_AuthenticationException(
  1973. $this, 'CAS 1.0 ticket not validated', $validate_url,
  1974. true/*$no_response*/
  1975. );
  1976. }
  1977. if (preg_match('/^no\n/', $text_response)) {
  1978. phpCAS::trace('Ticket has not been validated');
  1979. throw new CAS_AuthenticationException(
  1980. $this, 'ST not validated', $validate_url, false/*$no_response*/,
  1981. false/*$bad_response*/, $text_response
  1982. );
  1983. } else if (!preg_match('/^yes\n/', $text_response)) {
  1984. phpCAS::trace('ill-formed response');
  1985. throw new CAS_AuthenticationException(
  1986. $this, 'Ticket not validated', $validate_url,
  1987. false/*$no_response*/, true/*$bad_response*/, $text_response
  1988. );
  1989. }
  1990. // ticket has been validated, extract the user name
  1991. $arr = preg_split('/\n/', $text_response);
  1992. $this->_setUser(trim($arr[1]));
  1993. $this->_renameSession($this->getTicket());
  1994. // at this step, ticket has been validated and $this->_user has been set,
  1995. phpCAS::traceEnd(true);
  1996. return true;
  1997. }
  1998. /** @} */
  1999. // ########################################################################
  2000. // SAML VALIDATION
  2001. // ########################################################################
  2002. /**
  2003. * @addtogroup internalSAML
  2004. * @{
  2005. */
  2006. /**
  2007. * This method is used to validate a SAML TICKET; halt on failure, and sets
  2008. * $validate_url, $text_reponse and $tree_response on success. These
  2009. * parameters are used later by CAS_Client::_validatePGT() for CAS proxies.
  2010. *
  2011. * @param string &$validate_url reference to the the URL of the request to
  2012. * the CAS server.
  2013. * @param string &$text_response reference to the response of the CAS
  2014. * server, as is (XML text).
  2015. * @param string &$tree_response reference to the response of the CAS
  2016. * server, as a DOM XML tree.
  2017. * @param bool $renew true to force the authentication with the CAS server
  2018. *
  2019. * @return bool true when successfull and issue a CAS_AuthenticationException
  2020. * and false on an error
  2021. *
  2022. * @throws CAS_AuthenticationException
  2023. */
  2024. public function validateSA(&$validate_url,&$text_response,&$tree_response,$renew=false)
  2025. {
  2026. phpCAS::traceBegin();
  2027. $result = false;
  2028. // build the URL to validate the ticket
  2029. $validate_url = $this->getServerSamlValidateURL();
  2030. if ( $renew ) {
  2031. // pass the renew
  2032. $validate_url .= '&renew=true';
  2033. }
  2034. // open and read the URL
  2035. if ( !$this->_readURL($validate_url, $headers, $text_response, $err_msg) ) {
  2036. phpCAS::trace(
  2037. 'could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')'
  2038. );
  2039. throw new CAS_AuthenticationException(
  2040. $this, 'SA not validated', $validate_url, true/*$no_response*/
  2041. );
  2042. }
  2043. phpCAS::trace('server version: '.$this->getServerVersion());
  2044. // analyze the result depending on the version
  2045. switch ($this->getServerVersion()) {
  2046. case SAML_VERSION_1_1:
  2047. // create new DOMDocument Object
  2048. $dom = new DOMDocument();
  2049. // Fix possible whitspace problems
  2050. $dom->preserveWhiteSpace = false;
  2051. // read the response of the CAS server into a DOM object
  2052. if (!($dom->loadXML($text_response))) {
  2053. phpCAS::trace('dom->loadXML() failed');
  2054. throw new CAS_AuthenticationException(
  2055. $this, 'SA not validated', $validate_url,
  2056. false/*$no_response*/, true/*$bad_response*/,
  2057. $text_response
  2058. );
  2059. }
  2060. // read the root node of the XML tree
  2061. if (!($tree_response = $dom->documentElement)) {
  2062. phpCAS::trace('documentElement() failed');
  2063. throw new CAS_AuthenticationException(
  2064. $this, 'SA not validated', $validate_url,
  2065. false/*$no_response*/, true/*$bad_response*/,
  2066. $text_response
  2067. );
  2068. } else if ( $tree_response->localName != 'Envelope' ) {
  2069. // insure that tag name is 'Envelope'
  2070. phpCAS::trace(
  2071. 'bad XML root node (should be `Envelope\' instead of `'
  2072. .$tree_response->localName.'\''
  2073. );
  2074. throw new CAS_AuthenticationException(
  2075. $this, 'SA not validated', $validate_url,
  2076. false/*$no_response*/, true/*$bad_response*/,
  2077. $text_response
  2078. );
  2079. } else if ($tree_response->getElementsByTagName("NameIdentifier")->length != 0) {
  2080. // check for the NameIdentifier tag in the SAML response
  2081. $success_elements = $tree_response->getElementsByTagName("NameIdentifier");
  2082. phpCAS::trace('NameIdentifier found');
  2083. $user = trim($success_elements->item(0)->nodeValue);
  2084. phpCAS::trace('user = `'.$user.'`');
  2085. $this->_setUser($user);
  2086. $this->_setSessionAttributes($text_response);
  2087. $result = true;
  2088. } else {
  2089. phpCAS::trace('no <NameIdentifier> tag found in SAML payload');
  2090. throw new CAS_AuthenticationException(
  2091. $this, 'SA not validated', $validate_url,
  2092. false/*$no_response*/, true/*$bad_response*/,
  2093. $text_response
  2094. );
  2095. }
  2096. }
  2097. if ($result) {
  2098. $this->_renameSession($this->getTicket());
  2099. }
  2100. // at this step, ST has been validated and $this->_user has been set,
  2101. phpCAS::traceEnd($result);
  2102. return $result;
  2103. }
  2104. /**
  2105. * This method will parse the DOM and pull out the attributes from the SAML
  2106. * payload and put them into an array, then put the array into the session.
  2107. *
  2108. * @param string $text_response the SAML payload.
  2109. *
  2110. * @return bool true when successfull and false if no attributes a found
  2111. */
  2112. private function _setSessionAttributes($text_response)
  2113. {
  2114. phpCAS::traceBegin();
  2115. $result = false;
  2116. $attr_array = array();
  2117. // create new DOMDocument Object
  2118. $dom = new DOMDocument();
  2119. // Fix possible whitspace problems
  2120. $dom->preserveWhiteSpace = false;
  2121. if (($dom->loadXML($text_response))) {
  2122. $xPath = new DOMXPath($dom);
  2123. $xPath->registerNamespace('samlp', 'urn:oasis:names:tc:SAML:1.0:protocol');
  2124. $xPath->registerNamespace('saml', 'urn:oasis:names:tc:SAML:1.0:assertion');
  2125. $nodelist = $xPath->query("//saml:Attribute");
  2126. if ($nodelist) {
  2127. foreach ($nodelist as $node) {
  2128. $xres = $xPath->query("saml:AttributeValue", $node);
  2129. $name = $node->getAttribute("AttributeName");
  2130. $value_array = array();
  2131. foreach ($xres as $node2) {
  2132. $value_array[] = $node2->nodeValue;
  2133. }
  2134. $attr_array[$name] = $value_array;
  2135. }
  2136. // UGent addition...
  2137. foreach ($attr_array as $attr_key => $attr_value) {
  2138. if (count($attr_value) > 1) {
  2139. $this->_attributes[$attr_key] = $attr_value;
  2140. phpCAS::trace("* " . $attr_key . "=" . print_r($attr_value, true));
  2141. } else {
  2142. $this->_attributes[$attr_key] = $attr_value[0];
  2143. phpCAS::trace("* " . $attr_key . "=" . $attr_value[0]);
  2144. }
  2145. }
  2146. $result = true;
  2147. } else {
  2148. phpCAS::trace("SAML Attributes are empty");
  2149. $result = false;
  2150. }
  2151. }
  2152. phpCAS::traceEnd($result);
  2153. return $result;
  2154. }
  2155. /** @} */
  2156. // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  2157. // XX XX
  2158. // XX PROXY FEATURES (CAS 2.0) XX
  2159. // XX XX
  2160. // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  2161. // ########################################################################
  2162. // PROXYING
  2163. // ########################################################################
  2164. /**
  2165. * @addtogroup internalProxy
  2166. * @{
  2167. */
  2168. /**
  2169. * @var bool is the client a proxy
  2170. * A boolean telling if the client is a CAS proxy or not. Written by
  2171. * CAS_Client::CAS_Client(), read by CAS_Client::isProxy().
  2172. */
  2173. private $_proxy;
  2174. /**
  2175. * @var CAS_CookieJar Handler for managing service cookies.
  2176. */
  2177. private $_serviceCookieJar;
  2178. /**
  2179. * Tells if a CAS client is a CAS proxy or not
  2180. *
  2181. * @return bool true when the CAS client is a CAS proxy, false otherwise
  2182. */
  2183. public function isProxy()
  2184. {
  2185. return $this->_proxy;
  2186. }
  2187. /** @} */
  2188. // ########################################################################
  2189. // PGT
  2190. // ########################################################################
  2191. /**
  2192. * @addtogroup internalProxy
  2193. * @{
  2194. */
  2195. /**
  2196. * the Proxy Grnting Ticket given by the CAS server (empty otherwise).
  2197. * Written by CAS_Client::_setPGT(), read by CAS_Client::_getPGT() and
  2198. * CAS_Client::_hasPGT().
  2199. *
  2200. * @hideinitializer
  2201. */
  2202. private $_pgt = '';
  2203. /**
  2204. * This method returns the Proxy Granting Ticket given by the CAS server.
  2205. *
  2206. * @return string the Proxy Granting Ticket.
  2207. */
  2208. private function _getPGT()
  2209. {
  2210. return $this->_pgt;
  2211. }
  2212. /**
  2213. * This method stores the Proxy Granting Ticket.
  2214. *
  2215. * @param string $pgt The Proxy Granting Ticket.
  2216. *
  2217. * @return void
  2218. */
  2219. private function _setPGT($pgt)
  2220. {
  2221. $this->_pgt = $pgt;
  2222. }
  2223. /**
  2224. * This method tells if a Proxy Granting Ticket was stored.
  2225. *
  2226. * @return bool true if a Proxy Granting Ticket has been stored.
  2227. */
  2228. private function _hasPGT()
  2229. {
  2230. return !empty($this->_pgt);
  2231. }
  2232. /** @} */
  2233. // ########################################################################
  2234. // CALLBACK MODE
  2235. // ########################################################################
  2236. /**
  2237. * @addtogroup internalCallback
  2238. * @{
  2239. */
  2240. /**
  2241. * each PHP script using phpCAS in proxy mode is its own callback to get the
  2242. * PGT back from the CAS server. callback_mode is detected by the constructor
  2243. * thanks to the GET parameters.
  2244. */
  2245. /**
  2246. * @var bool a boolean to know if the CAS client is running in callback mode. Written by
  2247. * CAS_Client::setCallBackMode(), read by CAS_Client::_isCallbackMode().
  2248. *
  2249. * @hideinitializer
  2250. */
  2251. private $_callback_mode = false;
  2252. /**
  2253. * This method sets/unsets callback mode.
  2254. *
  2255. * @param bool $callback_mode true to set callback mode, false otherwise.
  2256. *
  2257. * @return void
  2258. */
  2259. private function _setCallbackMode($callback_mode)
  2260. {
  2261. $this->_callback_mode = $callback_mode;
  2262. }
  2263. /**
  2264. * This method returns true when the CAS client is running in callback mode,
  2265. * false otherwise.
  2266. *
  2267. * @return bool A boolean.
  2268. */
  2269. private function _isCallbackMode()
  2270. {
  2271. return $this->_callback_mode;
  2272. }
  2273. /**
  2274. * @var bool a boolean to know if the CAS client is using POST parameters when in callback mode.
  2275. * Written by CAS_Client::_setCallbackModeUsingPost(), read by CAS_Client::_isCallbackModeUsingPost().
  2276. *
  2277. * @hideinitializer
  2278. */
  2279. private $_callback_mode_using_post = false;
  2280. /**
  2281. * This method sets/unsets usage of POST parameters in callback mode (default/false is GET parameters)
  2282. *
  2283. * @param bool $callback_mode_using_post true to use POST, false to use GET (default).
  2284. *
  2285. * @return void
  2286. */
  2287. private function _setCallbackModeUsingPost($callback_mode_using_post)
  2288. {
  2289. $this->_callback_mode_using_post = $callback_mode_using_post;
  2290. }
  2291. /**
  2292. * This method returns true when the callback mode is using POST, false otherwise.
  2293. *
  2294. * @return bool A boolean.
  2295. */
  2296. private function _isCallbackModeUsingPost()
  2297. {
  2298. return $this->_callback_mode_using_post;
  2299. }
  2300. /**
  2301. * the URL that should be used for the PGT callback (in fact the URL of the
  2302. * current request without any CGI parameter). Written and read by
  2303. * CAS_Client::_getCallbackURL().
  2304. *
  2305. * @hideinitializer
  2306. */
  2307. private $_callback_url = '';
  2308. /**
  2309. * This method returns the URL that should be used for the PGT callback (in
  2310. * fact the URL of the current request without any CGI parameter, except if
  2311. * phpCAS::setFixedCallbackURL() was used).
  2312. *
  2313. * @return string The callback URL
  2314. */
  2315. private function _getCallbackURL()
  2316. {
  2317. // the URL is built when needed only
  2318. if ( empty($this->_callback_url) ) {
  2319. // remove the ticket if present in the URL
  2320. $final_uri = 'https://';
  2321. $final_uri .= $this->_getClientUrl();
  2322. $request_uri = $_SERVER['REQUEST_URI'];
  2323. $request_uri = preg_replace('/\?.*$/', '', $request_uri);
  2324. $final_uri .= $request_uri;
  2325. $this->_callback_url = $final_uri;
  2326. }
  2327. return $this->_callback_url;
  2328. }
  2329. /**
  2330. * This method sets the callback url.
  2331. *
  2332. * @param string $url url to set callback
  2333. *
  2334. * @return string the callback url
  2335. */
  2336. public function setCallbackURL($url)
  2337. {
  2338. // Sequence validation
  2339. $this->ensureIsProxy();
  2340. // Argument Validation
  2341. if (gettype($url) != 'string')
  2342. throw new CAS_TypeMismatchException($url, '$url', 'string');
  2343. return $this->_callback_url = $url;
  2344. }
  2345. /**
  2346. * This method is called by CAS_Client::CAS_Client() when running in callback
  2347. * mode. It stores the PGT and its PGT Iou, prints its output and halts.
  2348. *
  2349. * @return void
  2350. */
  2351. private function _callback()
  2352. {
  2353. phpCAS::traceBegin();
  2354. if ($this->_isCallbackModeUsingPost()) {
  2355. $pgtId = $_POST['pgtId'];
  2356. $pgtIou = $_POST['pgtIou'];
  2357. } else {
  2358. $pgtId = $_GET['pgtId'];
  2359. $pgtIou = $_GET['pgtIou'];
  2360. }
  2361. if (preg_match('/^PGTIOU-[\.\-\w]+$/', $pgtIou)) {
  2362. if (preg_match('/^[PT]GT-[\.\-\w]+$/', $pgtId)) {
  2363. phpCAS::trace('Storing PGT `'.$pgtId.'\' (id=`'.$pgtIou.'\')');
  2364. $this->_storePGT($pgtId, $pgtIou);
  2365. if ($this->isXmlResponse()) {
  2366. echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n";
  2367. echo '<proxySuccess xmlns="http://www.yale.edu/tp/cas" />';
  2368. phpCAS::traceExit("XML response sent");
  2369. } else {
  2370. $this->printHTMLHeader('phpCAS callback');
  2371. echo '<p>Storing PGT `'.$pgtId.'\' (id=`'.$pgtIou.'\').</p>';
  2372. $this->printHTMLFooter();
  2373. phpCAS::traceExit("HTML response sent");
  2374. }
  2375. phpCAS::traceExit("Successfull Callback");
  2376. } else {
  2377. phpCAS::error('PGT format invalid' . $pgtId);
  2378. phpCAS::traceExit('PGT format invalid' . $pgtId);
  2379. }
  2380. } else {
  2381. phpCAS::error('PGTiou format invalid' . $pgtIou);
  2382. phpCAS::traceExit('PGTiou format invalid' . $pgtIou);
  2383. }
  2384. // Flush the buffer to prevent from sending anything other then a 200
  2385. // Success Status back to the CAS Server. The Exception would normally
  2386. // report as a 500 error.
  2387. flush();
  2388. throw new CAS_GracefullTerminationException();
  2389. }
  2390. /**
  2391. * Check if application/xml or text/xml is pressent in HTTP_ACCEPT header values
  2392. * when return value is complex and contains attached q parameters.
  2393. * Example: HTTP_ACCEPT = text/html,application/xhtml+xml,application/xml;q=0.9
  2394. * @return bool
  2395. */
  2396. private function isXmlResponse()
  2397. {
  2398. if (!array_key_exists('HTTP_ACCEPT', $_SERVER)) {
  2399. return false;
  2400. }
  2401. if (strpos($_SERVER['HTTP_ACCEPT'], 'application/xml') === false && strpos($_SERVER['HTTP_ACCEPT'], 'text/xml') === false) {
  2402. return false;
  2403. }
  2404. return true;
  2405. }
  2406. /** @} */
  2407. // ########################################################################
  2408. // PGT STORAGE
  2409. // ########################################################################
  2410. /**
  2411. * @addtogroup internalPGTStorage
  2412. * @{
  2413. */
  2414. /**
  2415. * @var CAS_PGTStorage_AbstractStorage
  2416. * an instance of a class inheriting of PGTStorage, used to deal with PGT
  2417. * storage. Created by CAS_Client::setPGTStorageFile(), used
  2418. * by CAS_Client::setPGTStorageFile() and CAS_Client::_initPGTStorage().
  2419. *
  2420. * @hideinitializer
  2421. */
  2422. private $_pgt_storage = null;
  2423. /**
  2424. * This method is used to initialize the storage of PGT's.
  2425. * Halts on error.
  2426. *
  2427. * @return void
  2428. */
  2429. private function _initPGTStorage()
  2430. {
  2431. // if no SetPGTStorageXxx() has been used, default to file
  2432. if ( !is_object($this->_pgt_storage) ) {
  2433. $this->setPGTStorageFile();
  2434. }
  2435. // initializes the storage
  2436. $this->_pgt_storage->init();
  2437. }
  2438. /**
  2439. * This method stores a PGT. Halts on error.
  2440. *
  2441. * @param string $pgt the PGT to store
  2442. * @param string $pgt_iou its corresponding Iou
  2443. *
  2444. * @return void
  2445. */
  2446. private function _storePGT($pgt,$pgt_iou)
  2447. {
  2448. // ensure that storage is initialized
  2449. $this->_initPGTStorage();
  2450. // writes the PGT
  2451. $this->_pgt_storage->write($pgt, $pgt_iou);
  2452. }
  2453. /**
  2454. * This method reads a PGT from its Iou and deletes the corresponding
  2455. * storage entry.
  2456. *
  2457. * @param string $pgt_iou the PGT Iou
  2458. *
  2459. * @return string mul The PGT corresponding to the Iou, false when not found.
  2460. */
  2461. private function _loadPGT($pgt_iou)
  2462. {
  2463. // ensure that storage is initialized
  2464. $this->_initPGTStorage();
  2465. // read the PGT
  2466. return $this->_pgt_storage->read($pgt_iou);
  2467. }
  2468. /**
  2469. * This method can be used to set a custom PGT storage object.
  2470. *
  2471. * @param CAS_PGTStorage_AbstractStorage $storage a PGT storage object that
  2472. * inherits from the CAS_PGTStorage_AbstractStorage class
  2473. *
  2474. * @return void
  2475. */
  2476. public function setPGTStorage($storage)
  2477. {
  2478. // Sequence validation
  2479. $this->ensureIsProxy();
  2480. // check that the storage has not already been set
  2481. if ( is_object($this->_pgt_storage) ) {
  2482. phpCAS::error('PGT storage already defined');
  2483. }
  2484. // check to make sure a valid storage object was specified
  2485. if ( !($storage instanceof CAS_PGTStorage_AbstractStorage) )
  2486. throw new CAS_TypeMismatchException($storage, '$storage', 'CAS_PGTStorage_AbstractStorage object');
  2487. // store the PGTStorage object
  2488. $this->_pgt_storage = $storage;
  2489. }
  2490. /**
  2491. * This method is used to tell phpCAS to store the response of the
  2492. * CAS server to PGT requests in a database.
  2493. *
  2494. * @param string|PDO $dsn_or_pdo a dsn string to use for creating a PDO
  2495. * object or a PDO object
  2496. * @param string $username the username to use when connecting to the
  2497. * database
  2498. * @param string $password the password to use when connecting to the
  2499. * database
  2500. * @param string $table the table to use for storing and retrieving
  2501. * PGTs
  2502. * @param string $driver_options any driver options to use when connecting
  2503. * to the database
  2504. *
  2505. * @return void
  2506. */
  2507. public function setPGTStorageDb(
  2508. $dsn_or_pdo, $username='', $password='', $table='', $driver_options=null
  2509. ) {
  2510. // Sequence validation
  2511. $this->ensureIsProxy();
  2512. // Argument validation
  2513. if (!(is_object($dsn_or_pdo) && $dsn_or_pdo instanceof PDO) && !is_string($dsn_or_pdo))
  2514. throw new CAS_TypeMismatchException($dsn_or_pdo, '$dsn_or_pdo', 'string or PDO object');
  2515. if (gettype($username) != 'string')
  2516. throw new CAS_TypeMismatchException($username, '$username', 'string');
  2517. if (gettype($password) != 'string')
  2518. throw new CAS_TypeMismatchException($password, '$password', 'string');
  2519. if (gettype($table) != 'string')
  2520. throw new CAS_TypeMismatchException($table, '$password', 'string');
  2521. // create the storage object
  2522. $this->setPGTStorage(
  2523. new CAS_PGTStorage_Db(
  2524. $this, $dsn_or_pdo, $username, $password, $table, $driver_options
  2525. )
  2526. );
  2527. }
  2528. /**
  2529. * This method is used to tell phpCAS to store the response of the
  2530. * CAS server to PGT requests onto the filesystem.
  2531. *
  2532. * @param string $path the path where the PGT's should be stored
  2533. *
  2534. * @return void
  2535. */
  2536. public function setPGTStorageFile($path='')
  2537. {
  2538. // Sequence validation
  2539. $this->ensureIsProxy();
  2540. // Argument validation
  2541. if (gettype($path) != 'string')
  2542. throw new CAS_TypeMismatchException($path, '$path', 'string');
  2543. // create the storage object
  2544. $this->setPGTStorage(new CAS_PGTStorage_File($this, $path));
  2545. }
  2546. // ########################################################################
  2547. // PGT VALIDATION
  2548. // ########################################################################
  2549. /**
  2550. * This method is used to validate a PGT; halt on failure.
  2551. *
  2552. * @param string &$validate_url the URL of the request to the CAS server.
  2553. * @param string $text_response the response of the CAS server, as is
  2554. * (XML text); result of
  2555. * CAS_Client::validateCAS10() or
  2556. * CAS_Client::validateCAS20().
  2557. * @param DOMElement $tree_response the response of the CAS server, as a DOM XML
  2558. * tree; result of CAS_Client::validateCAS10() or CAS_Client::validateCAS20().
  2559. *
  2560. * @return bool true when successfull and issue a CAS_AuthenticationException
  2561. * and false on an error
  2562. *
  2563. * @throws CAS_AuthenticationException
  2564. */
  2565. private function _validatePGT(&$validate_url,$text_response,$tree_response)
  2566. {
  2567. phpCAS::traceBegin();
  2568. if ( $tree_response->getElementsByTagName("proxyGrantingTicket")->length == 0) {
  2569. phpCAS::trace('<proxyGrantingTicket> not found');
  2570. // authentication succeded, but no PGT Iou was transmitted
  2571. throw new CAS_AuthenticationException(
  2572. $this, 'Ticket validated but no PGT Iou transmitted',
  2573. $validate_url, false/*$no_response*/, false/*$bad_response*/,
  2574. $text_response
  2575. );
  2576. } else {
  2577. // PGT Iou transmitted, extract it
  2578. $pgt_iou = trim(
  2579. $tree_response->getElementsByTagName("proxyGrantingTicket")->item(0)->nodeValue
  2580. );
  2581. if (preg_match('/^PGTIOU-[\.\-\w]+$/', $pgt_iou)) {
  2582. $pgt = $this->_loadPGT($pgt_iou);
  2583. if ( $pgt == false ) {
  2584. phpCAS::trace('could not load PGT');
  2585. throw new CAS_AuthenticationException(
  2586. $this,
  2587. 'PGT Iou was transmitted but PGT could not be retrieved',
  2588. $validate_url, false/*$no_response*/,
  2589. false/*$bad_response*/, $text_response
  2590. );
  2591. }
  2592. $this->_setPGT($pgt);
  2593. } else {
  2594. phpCAS::trace('PGTiou format error');
  2595. throw new CAS_AuthenticationException(
  2596. $this, 'PGT Iou was transmitted but has wrong format',
  2597. $validate_url, false/*$no_response*/, false/*$bad_response*/,
  2598. $text_response
  2599. );
  2600. }
  2601. }
  2602. phpCAS::traceEnd(true);
  2603. return true;
  2604. }
  2605. // ########################################################################
  2606. // PGT VALIDATION
  2607. // ########################################################################
  2608. /**
  2609. * This method is used to retrieve PT's from the CAS server thanks to a PGT.
  2610. *
  2611. * @param string $target_service the service to ask for with the PT.
  2612. * @param int &$err_code an error code (PHPCAS_SERVICE_OK on success).
  2613. * @param string &$err_msg an error message (empty on success).
  2614. *
  2615. * @return string|false a Proxy Ticket, or false on error.
  2616. */
  2617. public function retrievePT($target_service,&$err_code,&$err_msg)
  2618. {
  2619. // Argument validation
  2620. if (gettype($target_service) != 'string')
  2621. throw new CAS_TypeMismatchException($target_service, '$target_service', 'string');
  2622. phpCAS::traceBegin();
  2623. // by default, $err_msg is set empty and $pt to true. On error, $pt is
  2624. // set to false and $err_msg to an error message. At the end, if $pt is false
  2625. // and $error_msg is still empty, it is set to 'invalid response' (the most
  2626. // commonly encountered error).
  2627. $err_msg = '';
  2628. // build the URL to retrieve the PT
  2629. $cas_url = $this->getServerProxyURL().'?targetService='
  2630. .urlencode($target_service).'&pgt='.$this->_getPGT();
  2631. // open and read the URL
  2632. if ( !$this->_readURL($cas_url, $headers, $cas_response, $err_msg) ) {
  2633. phpCAS::trace(
  2634. 'could not open URL \''.$cas_url.'\' to validate ('.$err_msg.')'
  2635. );
  2636. $err_code = PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE;
  2637. $err_msg = 'could not retrieve PT (no response from the CAS server)';
  2638. phpCAS::traceEnd(false);
  2639. return false;
  2640. }
  2641. $bad_response = false;
  2642. // create new DOMDocument object
  2643. $dom = new DOMDocument();
  2644. // Fix possible whitspace problems
  2645. $dom->preserveWhiteSpace = false;
  2646. // read the response of the CAS server into a DOM object
  2647. if ( !($dom->loadXML($cas_response))) {
  2648. phpCAS::trace('dom->loadXML() failed');
  2649. // read failed
  2650. $bad_response = true;
  2651. }
  2652. if ( !$bad_response ) {
  2653. // read the root node of the XML tree
  2654. if ( !($root = $dom->documentElement) ) {
  2655. phpCAS::trace('documentElement failed');
  2656. // read failed
  2657. $bad_response = true;
  2658. }
  2659. }
  2660. if ( !$bad_response ) {
  2661. // insure that tag name is 'serviceResponse'
  2662. if ( $root->localName != 'serviceResponse' ) {
  2663. phpCAS::trace('localName failed');
  2664. // bad root node
  2665. $bad_response = true;
  2666. }
  2667. }
  2668. if ( !$bad_response ) {
  2669. // look for a proxySuccess tag
  2670. if ( $root->getElementsByTagName("proxySuccess")->length != 0) {
  2671. $proxy_success_list = $root->getElementsByTagName("proxySuccess");
  2672. // authentication succeded, look for a proxyTicket tag
  2673. if ( $proxy_success_list->item(0)->getElementsByTagName("proxyTicket")->length != 0) {
  2674. $err_code = PHPCAS_SERVICE_OK;
  2675. $err_msg = '';
  2676. $pt = trim(
  2677. $proxy_success_list->item(0)->getElementsByTagName("proxyTicket")->item(0)->nodeValue
  2678. );
  2679. phpCAS::trace('original PT: '.trim($pt));
  2680. phpCAS::traceEnd($pt);
  2681. return $pt;
  2682. } else {
  2683. phpCAS::trace('<proxySuccess> was found, but not <proxyTicket>');
  2684. }
  2685. } else if ($root->getElementsByTagName("proxyFailure")->length != 0) {
  2686. // look for a proxyFailure tag
  2687. $proxy_failure_list = $root->getElementsByTagName("proxyFailure");
  2688. // authentication failed, extract the error
  2689. $err_code = PHPCAS_SERVICE_PT_FAILURE;
  2690. $err_msg = 'PT retrieving failed (code=`'
  2691. .$proxy_failure_list->item(0)->getAttribute('code')
  2692. .'\', message=`'
  2693. .trim($proxy_failure_list->item(0)->nodeValue)
  2694. .'\')';
  2695. phpCAS::traceEnd(false);
  2696. return false;
  2697. } else {
  2698. phpCAS::trace('neither <proxySuccess> nor <proxyFailure> found');
  2699. }
  2700. }
  2701. // at this step, we are sure that the response of the CAS server was
  2702. // illformed
  2703. $err_code = PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE;
  2704. $err_msg = 'Invalid response from the CAS server (response=`'
  2705. .$cas_response.'\')';
  2706. phpCAS::traceEnd(false);
  2707. return false;
  2708. }
  2709. /** @} */
  2710. // ########################################################################
  2711. // READ CAS SERVER ANSWERS
  2712. // ########################################################################
  2713. /**
  2714. * @addtogroup internalMisc
  2715. * @{
  2716. */
  2717. /**
  2718. * This method is used to acces a remote URL.
  2719. *
  2720. * @param string $url the URL to access.
  2721. * @param string &$headers an array containing the HTTP header lines of the
  2722. * response (an empty array on failure).
  2723. * @param string &$body the body of the response, as a string (empty on
  2724. * failure).
  2725. * @param string &$err_msg an error message, filled on failure.
  2726. *
  2727. * @return bool true on success, false otherwise (in this later case, $err_msg
  2728. * contains an error message).
  2729. */
  2730. private function _readURL($url, &$headers, &$body, &$err_msg)
  2731. {
  2732. phpCAS::traceBegin();
  2733. $className = $this->_requestImplementation;
  2734. $request = new $className();
  2735. if (count($this->_curl_options)) {
  2736. $request->setCurlOptions($this->_curl_options);
  2737. }
  2738. $request->setUrl($url);
  2739. if (empty($this->_cas_server_ca_cert) && !$this->_no_cas_server_validation) {
  2740. phpCAS::error(
  2741. 'one of the methods phpCAS::setCasServerCACert() or phpCAS::setNoCasServerValidation() must be called.'
  2742. );
  2743. }
  2744. if ($this->_cas_server_ca_cert != '') {
  2745. $request->setSslCaCert(
  2746. $this->_cas_server_ca_cert, $this->_cas_server_cn_validate
  2747. );
  2748. }
  2749. // add extra stuff if SAML
  2750. if ($this->getServerVersion() == SAML_VERSION_1_1) {
  2751. $request->addHeader("soapaction: http://www.oasis-open.org/committees/security");
  2752. $request->addHeader("cache-control: no-cache");
  2753. $request->addHeader("pragma: no-cache");
  2754. $request->addHeader("accept: text/xml");
  2755. $request->addHeader("connection: keep-alive");
  2756. $request->addHeader("content-type: text/xml");
  2757. $request->makePost();
  2758. $request->setPostBody($this->_buildSAMLPayload());
  2759. }
  2760. if ($request->send()) {
  2761. $headers = $request->getResponseHeaders();
  2762. $body = $request->getResponseBody();
  2763. $err_msg = '';
  2764. phpCAS::traceEnd(true);
  2765. return true;
  2766. } else {
  2767. $headers = '';
  2768. $body = '';
  2769. $err_msg = $request->getErrorMessage();
  2770. phpCAS::traceEnd(false);
  2771. return false;
  2772. }
  2773. }
  2774. /**
  2775. * This method is used to build the SAML POST body sent to /samlValidate URL.
  2776. *
  2777. * @return string the SOAP-encased SAMLP artifact (the ticket).
  2778. */
  2779. private function _buildSAMLPayload()
  2780. {
  2781. phpCAS::traceBegin();
  2782. //get the ticket
  2783. $sa = urlencode($this->getTicket());
  2784. $body = SAML_SOAP_ENV.SAML_SOAP_BODY.SAMLP_REQUEST
  2785. .SAML_ASSERTION_ARTIFACT.$sa.SAML_ASSERTION_ARTIFACT_CLOSE
  2786. .SAMLP_REQUEST_CLOSE.SAML_SOAP_BODY_CLOSE.SAML_SOAP_ENV_CLOSE;
  2787. phpCAS::traceEnd($body);
  2788. return ($body);
  2789. }
  2790. /** @} **/
  2791. // ########################################################################
  2792. // ACCESS TO EXTERNAL SERVICES
  2793. // ########################################################################
  2794. /**
  2795. * @addtogroup internalProxyServices
  2796. * @{
  2797. */
  2798. /**
  2799. * Answer a proxy-authenticated service handler.
  2800. *
  2801. * @param string $type The service type. One of:
  2802. * PHPCAS_PROXIED_SERVICE_HTTP_GET, PHPCAS_PROXIED_SERVICE_HTTP_POST,
  2803. * PHPCAS_PROXIED_SERVICE_IMAP
  2804. *
  2805. * @return CAS_ProxiedService
  2806. * @throws InvalidArgumentException If the service type is unknown.
  2807. */
  2808. public function getProxiedService ($type)
  2809. {
  2810. // Sequence validation
  2811. $this->ensureIsProxy();
  2812. $this->ensureAuthenticationCallSuccessful();
  2813. // Argument validation
  2814. if (gettype($type) != 'string')
  2815. throw new CAS_TypeMismatchException($type, '$type', 'string');
  2816. switch ($type) {
  2817. case PHPCAS_PROXIED_SERVICE_HTTP_GET:
  2818. case PHPCAS_PROXIED_SERVICE_HTTP_POST:
  2819. $requestClass = $this->_requestImplementation;
  2820. $request = new $requestClass();
  2821. if (count($this->_curl_options)) {
  2822. $request->setCurlOptions($this->_curl_options);
  2823. }
  2824. $proxiedService = new $type($request, $this->_serviceCookieJar);
  2825. if ($proxiedService instanceof CAS_ProxiedService_Testable) {
  2826. $proxiedService->setCasClient($this);
  2827. }
  2828. return $proxiedService;
  2829. case PHPCAS_PROXIED_SERVICE_IMAP;
  2830. $proxiedService = new CAS_ProxiedService_Imap($this->_getUser());
  2831. if ($proxiedService instanceof CAS_ProxiedService_Testable) {
  2832. $proxiedService->setCasClient($this);
  2833. }
  2834. return $proxiedService;
  2835. default:
  2836. throw new CAS_InvalidArgumentException(
  2837. "Unknown proxied-service type, $type."
  2838. );
  2839. }
  2840. }
  2841. /**
  2842. * Initialize a proxied-service handler with the proxy-ticket it should use.
  2843. *
  2844. * @param CAS_ProxiedService $proxiedService service handler
  2845. *
  2846. * @return void
  2847. *
  2848. * @throws CAS_ProxyTicketException If there is a proxy-ticket failure.
  2849. * The code of the Exception will be one of:
  2850. * PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE
  2851. * PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE
  2852. * PHPCAS_SERVICE_PT_FAILURE
  2853. * @throws CAS_ProxiedService_Exception If there is a failure getting the
  2854. * url from the proxied service.
  2855. */
  2856. public function initializeProxiedService (CAS_ProxiedService $proxiedService)
  2857. {
  2858. // Sequence validation
  2859. $this->ensureIsProxy();
  2860. $this->ensureAuthenticationCallSuccessful();
  2861. $url = $proxiedService->getServiceUrl();
  2862. if (!is_string($url)) {
  2863. throw new CAS_ProxiedService_Exception(
  2864. "Proxied Service ".get_class($proxiedService)
  2865. ."->getServiceUrl() should have returned a string, returned a "
  2866. .gettype($url)." instead."
  2867. );
  2868. }
  2869. $pt = $this->retrievePT($url, $err_code, $err_msg);
  2870. if (!$pt) {
  2871. throw new CAS_ProxyTicketException($err_msg, $err_code);
  2872. }
  2873. $proxiedService->setProxyTicket($pt);
  2874. }
  2875. /**
  2876. * This method is used to access an HTTP[S] service.
  2877. *
  2878. * @param string $url the service to access.
  2879. * @param int &$err_code an error code Possible values are
  2880. * PHPCAS_SERVICE_OK (on success), PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE,
  2881. * PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE, PHPCAS_SERVICE_PT_FAILURE,
  2882. * PHPCAS_SERVICE_NOT_AVAILABLE.
  2883. * @param string &$output the output of the service (also used to give an error
  2884. * message on failure).
  2885. *
  2886. * @return bool true on success, false otherwise (in this later case, $err_code
  2887. * gives the reason why it failed and $output contains an error message).
  2888. */
  2889. public function serviceWeb($url,&$err_code,&$output)
  2890. {
  2891. // Sequence validation
  2892. $this->ensureIsProxy();
  2893. $this->ensureAuthenticationCallSuccessful();
  2894. // Argument validation
  2895. if (gettype($url) != 'string')
  2896. throw new CAS_TypeMismatchException($url, '$url', 'string');
  2897. try {
  2898. $service = $this->getProxiedService(PHPCAS_PROXIED_SERVICE_HTTP_GET);
  2899. $service->setUrl($url);
  2900. $service->send();
  2901. $output = $service->getResponseBody();
  2902. $err_code = PHPCAS_SERVICE_OK;
  2903. return true;
  2904. } catch (CAS_ProxyTicketException $e) {
  2905. $err_code = $e->getCode();
  2906. $output = $e->getMessage();
  2907. return false;
  2908. } catch (CAS_ProxiedService_Exception $e) {
  2909. $lang = $this->getLangObj();
  2910. $output = sprintf(
  2911. $lang->getServiceUnavailable(), $url, $e->getMessage()
  2912. );
  2913. $err_code = PHPCAS_SERVICE_NOT_AVAILABLE;
  2914. return false;
  2915. }
  2916. }
  2917. /**
  2918. * This method is used to access an IMAP/POP3/NNTP service.
  2919. *
  2920. * @param string $url a string giving the URL of the service, including
  2921. * the mailing box for IMAP URLs, as accepted by imap_open().
  2922. * @param string $serviceUrl a string giving for CAS retrieve Proxy ticket
  2923. * @param string $flags options given to imap_open().
  2924. * @param int &$err_code an error code Possible values are
  2925. * PHPCAS_SERVICE_OK (on success), PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE,
  2926. * PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE, PHPCAS_SERVICE_PT_FAILURE,
  2927. * PHPCAS_SERVICE_NOT_AVAILABLE.
  2928. * @param string &$err_msg an error message on failure
  2929. * @param string &$pt the Proxy Ticket (PT) retrieved from the CAS
  2930. * server to access the URL on success, false on error).
  2931. *
  2932. * @return object|false an IMAP stream on success, false otherwise (in this later
  2933. * case, $err_code gives the reason why it failed and $err_msg contains an
  2934. * error message).
  2935. */
  2936. public function serviceMail($url,$serviceUrl,$flags,&$err_code,&$err_msg,&$pt)
  2937. {
  2938. // Sequence validation
  2939. $this->ensureIsProxy();
  2940. $this->ensureAuthenticationCallSuccessful();
  2941. // Argument validation
  2942. if (gettype($url) != 'string')
  2943. throw new CAS_TypeMismatchException($url, '$url', 'string');
  2944. if (gettype($serviceUrl) != 'string')
  2945. throw new CAS_TypeMismatchException($serviceUrl, '$serviceUrl', 'string');
  2946. if (gettype($flags) != 'integer')
  2947. throw new CAS_TypeMismatchException($flags, '$flags', 'string');
  2948. try {
  2949. $service = $this->getProxiedService(PHPCAS_PROXIED_SERVICE_IMAP);
  2950. $service->setServiceUrl($serviceUrl);
  2951. $service->setMailbox($url);
  2952. $service->setOptions($flags);
  2953. $stream = $service->open();
  2954. $err_code = PHPCAS_SERVICE_OK;
  2955. $pt = $service->getImapProxyTicket();
  2956. return $stream;
  2957. } catch (CAS_ProxyTicketException $e) {
  2958. $err_msg = $e->getMessage();
  2959. $err_code = $e->getCode();
  2960. $pt = false;
  2961. return false;
  2962. } catch (CAS_ProxiedService_Exception $e) {
  2963. $lang = $this->getLangObj();
  2964. $err_msg = sprintf(
  2965. $lang->getServiceUnavailable(),
  2966. $url,
  2967. $e->getMessage()
  2968. );
  2969. $err_code = PHPCAS_SERVICE_NOT_AVAILABLE;
  2970. $pt = false;
  2971. return false;
  2972. }
  2973. }
  2974. /** @} **/
  2975. // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  2976. // XX XX
  2977. // XX PROXIED CLIENT FEATURES (CAS 2.0) XX
  2978. // XX XX
  2979. // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  2980. // ########################################################################
  2981. // PT
  2982. // ########################################################################
  2983. /**
  2984. * @addtogroup internalService
  2985. * @{
  2986. */
  2987. /**
  2988. * This array will store a list of proxies in front of this application. This
  2989. * property will only be populated if this script is being proxied rather than
  2990. * accessed directly.
  2991. *
  2992. * It is set in CAS_Client::validateCAS20() and can be read by
  2993. * CAS_Client::getProxies()
  2994. *
  2995. * @access private
  2996. */
  2997. private $_proxies = array();
  2998. /**
  2999. * Answer an array of proxies that are sitting in front of this application.
  3000. *
  3001. * This method will only return a non-empty array if we have received and
  3002. * validated a Proxy Ticket.
  3003. *
  3004. * @return array
  3005. * @access public
  3006. */
  3007. public function getProxies()
  3008. {
  3009. return $this->_proxies;
  3010. }
  3011. /**
  3012. * Set the Proxy array, probably from persistant storage.
  3013. *
  3014. * @param array $proxies An array of proxies
  3015. *
  3016. * @return void
  3017. * @access private
  3018. */
  3019. private function _setProxies($proxies)
  3020. {
  3021. $this->_proxies = $proxies;
  3022. if (!empty($proxies)) {
  3023. // For proxy-authenticated requests people are not viewing the URL
  3024. // directly since the client is another application making a
  3025. // web-service call.
  3026. // Because of this, stripping the ticket from the URL is unnecessary
  3027. // and causes another web-service request to be performed. Additionally,
  3028. // if session handling on either the client or the server malfunctions
  3029. // then the subsequent request will not complete successfully.
  3030. $this->setNoClearTicketsFromUrl();
  3031. }
  3032. }
  3033. /**
  3034. * A container of patterns to be allowed as proxies in front of the cas client.
  3035. *
  3036. * @var CAS_ProxyChain_AllowedList
  3037. */
  3038. private $_allowed_proxy_chains;
  3039. /**
  3040. * Answer the CAS_ProxyChain_AllowedList object for this client.
  3041. *
  3042. * @return CAS_ProxyChain_AllowedList
  3043. */
  3044. public function getAllowedProxyChains ()
  3045. {
  3046. if (empty($this->_allowed_proxy_chains)) {
  3047. $this->_allowed_proxy_chains = new CAS_ProxyChain_AllowedList();
  3048. }
  3049. return $this->_allowed_proxy_chains;
  3050. }
  3051. /** @} */
  3052. // ########################################################################
  3053. // PT VALIDATION
  3054. // ########################################################################
  3055. /**
  3056. * @addtogroup internalProxied
  3057. * @{
  3058. */
  3059. /**
  3060. * This method is used to validate a cas 2.0 ST or PT; halt on failure
  3061. * Used for all CAS 2.0 validations
  3062. *
  3063. * @param string &$validate_url the url of the reponse
  3064. * @param string &$text_response the text of the repsones
  3065. * @param DOMElement &$tree_response the domxml tree of the respones
  3066. * @param bool $renew true to force the authentication with the CAS server
  3067. *
  3068. * @return bool true when successfull and issue a CAS_AuthenticationException
  3069. * and false on an error
  3070. *
  3071. * @throws CAS_AuthenticationException
  3072. */
  3073. public function validateCAS20(&$validate_url,&$text_response,&$tree_response, $renew=false)
  3074. {
  3075. phpCAS::traceBegin();
  3076. phpCAS::trace($text_response);
  3077. // build the URL to validate the ticket
  3078. if ($this->getAllowedProxyChains()->isProxyingAllowed()) {
  3079. $validate_url = $this->getServerProxyValidateURL().'&ticket='
  3080. .urlencode($this->getTicket());
  3081. } else {
  3082. $validate_url = $this->getServerServiceValidateURL().'&ticket='
  3083. .urlencode($this->getTicket());
  3084. }
  3085. if ( $this->isProxy() ) {
  3086. // pass the callback url for CAS proxies
  3087. $validate_url .= '&pgtUrl='.urlencode($this->_getCallbackURL());
  3088. }
  3089. if ( $renew ) {
  3090. // pass the renew
  3091. $validate_url .= '&renew=true';
  3092. }
  3093. // open and read the URL
  3094. if ( !$this->_readURL($validate_url, $headers, $text_response, $err_msg) ) {
  3095. phpCAS::trace(
  3096. 'could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')'
  3097. );
  3098. throw new CAS_AuthenticationException(
  3099. $this, 'Ticket not validated', $validate_url,
  3100. true/*$no_response*/
  3101. );
  3102. }
  3103. // create new DOMDocument object
  3104. $dom = new DOMDocument();
  3105. // Fix possible whitspace problems
  3106. $dom->preserveWhiteSpace = false;
  3107. // CAS servers should only return data in utf-8
  3108. $dom->encoding = "utf-8";
  3109. // read the response of the CAS server into a DOMDocument object
  3110. if ( !($dom->loadXML($text_response))) {
  3111. // read failed
  3112. throw new CAS_AuthenticationException(
  3113. $this, 'Ticket not validated', $validate_url,
  3114. false/*$no_response*/, true/*$bad_response*/, $text_response
  3115. );
  3116. } else if ( !($tree_response = $dom->documentElement) ) {
  3117. // read the root node of the XML tree
  3118. // read failed
  3119. throw new CAS_AuthenticationException(
  3120. $this, 'Ticket not validated', $validate_url,
  3121. false/*$no_response*/, true/*$bad_response*/, $text_response
  3122. );
  3123. } else if ($tree_response->localName != 'serviceResponse') {
  3124. // insure that tag name is 'serviceResponse'
  3125. // bad root node
  3126. throw new CAS_AuthenticationException(
  3127. $this, 'Ticket not validated', $validate_url,
  3128. false/*$no_response*/, true/*$bad_response*/, $text_response
  3129. );
  3130. } else if ( $tree_response->getElementsByTagName("authenticationFailure")->length != 0) {
  3131. // authentication failed, extract the error code and message and throw exception
  3132. $auth_fail_list = $tree_response
  3133. ->getElementsByTagName("authenticationFailure");
  3134. throw new CAS_AuthenticationException(
  3135. $this, 'Ticket not validated', $validate_url,
  3136. false/*$no_response*/, false/*$bad_response*/,
  3137. $text_response,
  3138. $auth_fail_list->item(0)->getAttribute('code')/*$err_code*/,
  3139. trim($auth_fail_list->item(0)->nodeValue)/*$err_msg*/
  3140. );
  3141. } else if ($tree_response->getElementsByTagName("authenticationSuccess")->length != 0) {
  3142. // authentication succeded, extract the user name
  3143. $success_elements = $tree_response
  3144. ->getElementsByTagName("authenticationSuccess");
  3145. if ( $success_elements->item(0)->getElementsByTagName("user")->length == 0) {
  3146. // no user specified => error
  3147. throw new CAS_AuthenticationException(
  3148. $this, 'Ticket not validated', $validate_url,
  3149. false/*$no_response*/, true/*$bad_response*/, $text_response
  3150. );
  3151. } else {
  3152. $this->_setUser(
  3153. trim(
  3154. $success_elements->item(0)->getElementsByTagName("user")->item(0)->nodeValue
  3155. )
  3156. );
  3157. $this->_readExtraAttributesCas20($success_elements);
  3158. // Store the proxies we are sitting behind for authorization checking
  3159. $proxyList = array();
  3160. if ( sizeof($arr = $success_elements->item(0)->getElementsByTagName("proxy")) > 0) {
  3161. foreach ($arr as $proxyElem) {
  3162. phpCAS::trace("Found Proxy: ".$proxyElem->nodeValue);
  3163. $proxyList[] = trim($proxyElem->nodeValue);
  3164. }
  3165. $this->_setProxies($proxyList);
  3166. phpCAS::trace("Storing Proxy List");
  3167. }
  3168. // Check if the proxies in front of us are allowed
  3169. if (!$this->getAllowedProxyChains()->isProxyListAllowed($proxyList)) {
  3170. throw new CAS_AuthenticationException(
  3171. $this, 'Proxy not allowed', $validate_url,
  3172. false/*$no_response*/, true/*$bad_response*/,
  3173. $text_response
  3174. );
  3175. } else {
  3176. $result = true;
  3177. }
  3178. }
  3179. } else {
  3180. throw new CAS_AuthenticationException(
  3181. $this, 'Ticket not validated', $validate_url,
  3182. false/*$no_response*/, true/*$bad_response*/,
  3183. $text_response
  3184. );
  3185. }
  3186. $this->_renameSession($this->getTicket());
  3187. // at this step, Ticket has been validated and $this->_user has been set,
  3188. phpCAS::traceEnd($result);
  3189. return $result;
  3190. }
  3191. /**
  3192. * This method recursively parses the attribute XML.
  3193. * It also collapses name-value pairs into a single
  3194. * array entry. It parses all common formats of
  3195. * attributes and well formed XML files.
  3196. *
  3197. * @param string $root the DOM root element to be parsed
  3198. * @param string $namespace namespace of the elements
  3199. *
  3200. * @return an array of the parsed XML elements
  3201. *
  3202. * Formats tested:
  3203. *
  3204. * "Jasig Style" Attributes:
  3205. *
  3206. * <cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
  3207. * <cas:authenticationSuccess>
  3208. * <cas:user>jsmith</cas:user>
  3209. * <cas:attributes>
  3210. * <cas:attraStyle>RubyCAS</cas:attraStyle>
  3211. * <cas:surname>Smith</cas:surname>
  3212. * <cas:givenName>John</cas:givenName>
  3213. * <cas:memberOf>CN=Staff,OU=Groups,DC=example,DC=edu</cas:memberOf>
  3214. * <cas:memberOf>CN=Spanish Department,OU=Departments,OU=Groups,DC=example,DC=edu</cas:memberOf>
  3215. * </cas:attributes>
  3216. * <cas:proxyGrantingTicket>PGTIOU-84678-8a9d2sfa23casd</cas:proxyGrantingTicket>
  3217. * </cas:authenticationSuccess>
  3218. * </cas:serviceResponse>
  3219. *
  3220. * "Jasig Style" Attributes (longer version):
  3221. *
  3222. * <cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
  3223. * <cas:authenticationSuccess>
  3224. * <cas:user>jsmith</cas:user>
  3225. * <cas:attributes>
  3226. * <cas:attribute>
  3227. * <cas:name>surname</cas:name>
  3228. * <cas:value>Smith</cas:value>
  3229. * </cas:attribute>
  3230. * <cas:attribute>
  3231. * <cas:name>givenName</cas:name>
  3232. * <cas:value>John</cas:value>
  3233. * </cas:attribute>
  3234. * <cas:attribute>
  3235. * <cas:name>memberOf</cas:name>
  3236. * <cas:value>['CN=Staff,OU=Groups,DC=example,DC=edu', 'CN=Spanish Department,OU=Departments,OU=Groups,DC=example,DC=edu']</cas:value>
  3237. * </cas:attribute>
  3238. * </cas:attributes>
  3239. * <cas:proxyGrantingTicket>PGTIOU-84678-8a9d2sfa23casd</cas:proxyGrantingTicket>
  3240. * </cas:authenticationSuccess>
  3241. * </cas:serviceResponse>
  3242. *
  3243. * "RubyCAS Style" attributes
  3244. *
  3245. * <cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
  3246. * <cas:authenticationSuccess>
  3247. * <cas:user>jsmith</cas:user>
  3248. *
  3249. * <cas:attraStyle>RubyCAS</cas:attraStyle>
  3250. * <cas:surname>Smith</cas:surname>
  3251. * <cas:givenName>John</cas:givenName>
  3252. * <cas:memberOf>CN=Staff,OU=Groups,DC=example,DC=edu</cas:memberOf>
  3253. * <cas:memberOf>CN=Spanish Department,OU=Departments,OU=Groups,DC=example,DC=edu</cas:memberOf>
  3254. *
  3255. * <cas:proxyGrantingTicket>PGTIOU-84678-8a9d2sfa23casd</cas:proxyGrantingTicket>
  3256. * </cas:authenticationSuccess>
  3257. * </cas:serviceResponse>
  3258. *
  3259. * "Name-Value" attributes.
  3260. *
  3261. * Attribute format from these mailing list thread:
  3262. * http://jasig.275507.n4.nabble.com/CAS-attributes-and-how-they-appear-in-the-CAS-response-td264272.html
  3263. * Note: This is a less widely used format, but in use by at least two institutions.
  3264. *
  3265. * <cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
  3266. * <cas:authenticationSuccess>
  3267. * <cas:user>jsmith</cas:user>
  3268. *
  3269. * <cas:attribute name='attraStyle' value='Name-Value' />
  3270. * <cas:attribute name='surname' value='Smith' />
  3271. * <cas:attribute name='givenName' value='John' />
  3272. * <cas:attribute name='memberOf' value='CN=Staff,OU=Groups,DC=example,DC=edu' />
  3273. * <cas:attribute name='memberOf' value='CN=Spanish Department,OU=Departments,OU=Groups,DC=example,DC=edu' />
  3274. *
  3275. * <cas:proxyGrantingTicket>PGTIOU-84678-8a9d2sfa23casd</cas:proxyGrantingTicket>
  3276. * </cas:authenticationSuccess>
  3277. * </cas:serviceResponse>
  3278. *
  3279. * result:
  3280. *
  3281. * Array (
  3282. * [surname] => Smith
  3283. * [givenName] => John
  3284. * [memberOf] => Array (
  3285. * [0] => CN=Staff, OU=Groups, DC=example, DC=edu
  3286. * [1] => CN=Spanish Department, OU=Departments, OU=Groups, DC=example, DC=edu
  3287. * )
  3288. * )
  3289. */
  3290. private function _xml_to_array($root, $namespace = "cas")
  3291. {
  3292. $result = array();
  3293. if ($root->hasAttributes()) {
  3294. $attrs = $root->attributes;
  3295. $pair = array();
  3296. foreach ($attrs as $attr) {
  3297. if ($attr->name === "name") {
  3298. $pair['name'] = $attr->value;
  3299. } elseif ($attr->name === "value") {
  3300. $pair['value'] = $attr->value;
  3301. } else {
  3302. $result[$attr->name] = $attr->value;
  3303. }
  3304. if (array_key_exists('name', $pair) && array_key_exists('value', $pair)) {
  3305. $result[$pair['name']] = $pair['value'];
  3306. }
  3307. }
  3308. }
  3309. if ($root->hasChildNodes()) {
  3310. $children = $root->childNodes;
  3311. if ($children->length == 1) {
  3312. $child = $children->item(0);
  3313. if ($child->nodeType == XML_TEXT_NODE) {
  3314. $result['_value'] = $child->nodeValue;
  3315. return (count($result) == 1) ? $result['_value'] : $result;
  3316. }
  3317. }
  3318. $groups = array();
  3319. foreach ($children as $child) {
  3320. $child_nodeName = str_ireplace($namespace . ":", "", $child->nodeName);
  3321. if (in_array($child_nodeName, array("user", "proxies", "proxyGrantingTicket"))) {
  3322. continue;
  3323. }
  3324. if (!isset($result[$child_nodeName])) {
  3325. $res = $this->_xml_to_array($child, $namespace);
  3326. if (!empty($res)) {
  3327. $result[$child_nodeName] = $this->_xml_to_array($child, $namespace);
  3328. }
  3329. } else {
  3330. if (!isset($groups[$child_nodeName])) {
  3331. $result[$child_nodeName] = array($result[$child_nodeName]);
  3332. $groups[$child_nodeName] = 1;
  3333. }
  3334. $result[$child_nodeName][] = $this->_xml_to_array($child, $namespace);
  3335. }
  3336. }
  3337. }
  3338. return $result;
  3339. }
  3340. /**
  3341. * This method parses a "JSON-like array" of strings
  3342. * into an array of strings
  3343. *
  3344. * @param string $json_value the json-like string:
  3345. * e.g.:
  3346. * ['CN=Staff,OU=Groups,DC=example,DC=edu', 'CN=Spanish Department,OU=Departments,OU=Groups,DC=example,DC=edu']
  3347. *
  3348. * @return array of strings Description
  3349. * e.g.:
  3350. * Array (
  3351. * [0] => CN=Staff,OU=Groups,DC=example,DC=edu
  3352. * [1] => CN=Spanish Department,OU=Departments,OU=Groups,DC=example,DC=edu
  3353. * )
  3354. */
  3355. private function _parse_json_like_array_value($json_value)
  3356. {
  3357. $parts = explode(",", trim($json_value, "[]"));
  3358. $out = array();
  3359. $quote = '';
  3360. foreach ($parts as $part) {
  3361. $part = trim($part);
  3362. if ($quote === '') {
  3363. $value = "";
  3364. if ($this->_startsWith($part, '\'')) {
  3365. $quote = '\'';
  3366. } elseif ($this->_startsWith($part, '"')) {
  3367. $quote = '"';
  3368. } else {
  3369. $out[] = $part;
  3370. }
  3371. $part = ltrim($part, $quote);
  3372. }
  3373. if ($quote !== '') {
  3374. $value .= $part;
  3375. if ($this->_endsWith($part, $quote)) {
  3376. $out[] = rtrim($value, $quote);
  3377. $quote = '';
  3378. } else {
  3379. $value .= ", ";
  3380. };
  3381. }
  3382. }
  3383. return $out;
  3384. }
  3385. /**
  3386. * This method recursively removes unneccessary hirarchy levels in array-trees.
  3387. * into an array of strings
  3388. *
  3389. * @param array $arr the array to flatten
  3390. * e.g.:
  3391. * Array (
  3392. * [attributes] => Array (
  3393. * [attribute] => Array (
  3394. * [0] => Array (
  3395. * [name] => surname
  3396. * [value] => Smith
  3397. * )
  3398. * [1] => Array (
  3399. * [name] => givenName
  3400. * [value] => John
  3401. * )
  3402. * [2] => Array (
  3403. * [name] => memberOf
  3404. * [value] => ['CN=Staff,OU=Groups,DC=example,DC=edu', 'CN=Spanish Department,OU=Departments,OU=Groups,DC=example,DC=edu']
  3405. * )
  3406. * )
  3407. * )
  3408. * )
  3409. *
  3410. * @return array the flattened array
  3411. * e.g.:
  3412. * Array (
  3413. * [attribute] => Array (
  3414. * [surname] => Smith
  3415. * [givenName] => John
  3416. * [memberOf] => Array (
  3417. * [0] => CN=Staff, OU=Groups, DC=example, DC=edu
  3418. * [1] => CN=Spanish Department, OU=Departments, OU=Groups, DC=example, DC=edu
  3419. * )
  3420. * )
  3421. * )
  3422. */
  3423. private function _flatten_array($arr)
  3424. {
  3425. if (!is_array($arr)) {
  3426. if ($this->_startsWith($arr, '[') && $this->_endsWith($arr, ']')) {
  3427. return $this->_parse_json_like_array_value($arr);
  3428. } else {
  3429. return $arr;
  3430. }
  3431. }
  3432. $out = array();
  3433. foreach ($arr as $key => $val) {
  3434. if (!is_array($val)) {
  3435. $out[$key] = $val;
  3436. } else {
  3437. switch (count($val)) {
  3438. case 1 : {
  3439. $key = key($val);
  3440. if (array_key_exists($key, $out)) {
  3441. $value = $out[$key];
  3442. if (!is_array($value)) {
  3443. $out[$key] = array();
  3444. $out[$key][] = $value;
  3445. }
  3446. $out[$key][] = $this->_flatten_array($val[$key]);
  3447. } else {
  3448. $out[$key] = $this->_flatten_array($val[$key]);
  3449. };
  3450. break;
  3451. };
  3452. case 2 : {
  3453. if (array_key_exists("name", $val) && array_key_exists("value", $val)) {
  3454. $key = $val['name'];
  3455. if (array_key_exists($key, $out)) {
  3456. $value = $out[$key];
  3457. if (!is_array($value)) {
  3458. $out[$key] = array();
  3459. $out[$key][] = $value;
  3460. }
  3461. $out[$key][] = $this->_flatten_array($val['value']);
  3462. } else {
  3463. $out[$key] = $this->_flatten_array($val['value']);
  3464. };
  3465. } else {
  3466. $out[$key] = $this->_flatten_array($val);
  3467. }
  3468. break;
  3469. };
  3470. default: {
  3471. $out[$key] = $this->_flatten_array($val);
  3472. }
  3473. }
  3474. }
  3475. }
  3476. return $out;
  3477. }
  3478. /**
  3479. * This method will parse the DOM and pull out the attributes from the XML
  3480. * payload and put them into an array, then put the array into the session.
  3481. *
  3482. * @param DOMNodeList $success_elements payload of the response
  3483. *
  3484. * @return bool true when successfull, halt otherwise by calling
  3485. * CAS_Client::_authError().
  3486. */
  3487. private function _readExtraAttributesCas20($success_elements)
  3488. {
  3489. phpCAS::traceBegin();
  3490. $extra_attributes = array();
  3491. if ($this->_casAttributeParserCallbackFunction !== null
  3492. && is_callable($this->_casAttributeParserCallbackFunction)
  3493. ) {
  3494. array_unshift($this->_casAttributeParserCallbackArgs, $success_elements->item(0));
  3495. phpCAS :: trace("Calling attritubeParser callback");
  3496. $extra_attributes = call_user_func_array(
  3497. $this->_casAttributeParserCallbackFunction,
  3498. $this->_casAttributeParserCallbackArgs
  3499. );
  3500. } else {
  3501. phpCAS :: trace("Parse extra attributes: ");
  3502. $attributes = $this->_xml_to_array($success_elements->item(0));
  3503. phpCAS :: trace(print_r($attributes,true). "\nFLATTEN Array: ");
  3504. $extra_attributes = $this->_flatten_array($attributes);
  3505. phpCAS :: trace(print_r($extra_attributes, true)."\nFILTER : ");
  3506. if (array_key_exists("attribute", $extra_attributes)) {
  3507. $extra_attributes = $extra_attributes["attribute"];
  3508. } elseif (array_key_exists("attributes", $extra_attributes)) {
  3509. $extra_attributes = $extra_attributes["attributes"];
  3510. };
  3511. phpCAS :: trace(print_r($extra_attributes, true)."return");
  3512. }
  3513. $this->setAttributes($extra_attributes);
  3514. phpCAS::traceEnd();
  3515. return true;
  3516. }
  3517. /**
  3518. * Add an attribute value to an array of attributes.
  3519. *
  3520. * @param array &$attributeArray reference to array
  3521. * @param string $name name of attribute
  3522. * @param string $value value of attribute
  3523. *
  3524. * @return void
  3525. */
  3526. private function _addAttributeToArray(array &$attributeArray, $name, $value)
  3527. {
  3528. // If multiple attributes exist, add as an array value
  3529. if (isset($attributeArray[$name])) {
  3530. // Initialize the array with the existing value
  3531. if (!is_array($attributeArray[$name])) {
  3532. $existingValue = $attributeArray[$name];
  3533. $attributeArray[$name] = array($existingValue);
  3534. }
  3535. $attributeArray[$name][] = trim($value);
  3536. } else {
  3537. $attributeArray[$name] = trim($value);
  3538. }
  3539. }
  3540. /** @} */
  3541. // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  3542. // XX XX
  3543. // XX MISC XX
  3544. // XX XX
  3545. // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  3546. /**
  3547. * @addtogroup internalMisc
  3548. * @{
  3549. */
  3550. // ########################################################################
  3551. // URL
  3552. // ########################################################################
  3553. /**
  3554. * the URL of the current request (without any ticket CGI parameter). Written
  3555. * and read by CAS_Client::getURL().
  3556. *
  3557. * @hideinitializer
  3558. */
  3559. private $_url = '';
  3560. /**
  3561. * This method sets the URL of the current request
  3562. *
  3563. * @param string $url url to set for service
  3564. *
  3565. * @return void
  3566. */
  3567. public function setURL($url)
  3568. {
  3569. // Argument Validation
  3570. if (gettype($url) != 'string')
  3571. throw new CAS_TypeMismatchException($url, '$url', 'string');
  3572. $this->_url = $url;
  3573. }
  3574. /**
  3575. * This method returns the URL of the current request (without any ticket
  3576. * CGI parameter).
  3577. *
  3578. * @return string The URL
  3579. */
  3580. public function getURL()
  3581. {
  3582. phpCAS::traceBegin();
  3583. // the URL is built when needed only
  3584. if ( empty($this->_url) ) {
  3585. // remove the ticket if present in the URL
  3586. $final_uri = ($this->_isHttps()) ? 'https' : 'http';
  3587. $final_uri .= '://';
  3588. $final_uri .= $this->_getClientUrl();
  3589. $request_uri = explode('?', $_SERVER['REQUEST_URI'], 2);
  3590. $final_uri .= $request_uri[0];
  3591. if (isset($request_uri[1]) && $request_uri[1]) {
  3592. $query_string= $this->_removeParameterFromQueryString('ticket', $request_uri[1]);
  3593. // If the query string still has anything left,
  3594. // append it to the final URI
  3595. if ($query_string !== '') {
  3596. $final_uri .= "?$query_string";
  3597. }
  3598. }
  3599. phpCAS::trace("Final URI: $final_uri");
  3600. $this->setURL($final_uri);
  3601. }
  3602. phpCAS::traceEnd($this->_url);
  3603. return $this->_url;
  3604. }
  3605. /**
  3606. * This method sets the base URL of the CAS server.
  3607. *
  3608. * @param string $url the base URL
  3609. *
  3610. * @return string base url
  3611. */
  3612. public function setBaseURL($url)
  3613. {
  3614. // Argument Validation
  3615. if (gettype($url) != 'string')
  3616. throw new CAS_TypeMismatchException($url, '$url', 'string');
  3617. return $this->_server['base_url'] = $url;
  3618. }
  3619. /**
  3620. * Try to figure out the phpCAS client URL with possible Proxys / Ports etc.
  3621. *
  3622. * @return string Server URL with domain:port
  3623. */
  3624. private function _getClientUrl()
  3625. {
  3626. if (!empty($_SERVER['HTTP_X_FORWARDED_HOST'])) {
  3627. // explode the host list separated by comma and use the first host
  3628. $hosts = explode(',', $_SERVER['HTTP_X_FORWARDED_HOST']);
  3629. // see rfc7239#5.3 and rfc7230#2.7.1: port is in HTTP_X_FORWARDED_HOST if non default
  3630. return $hosts[0];
  3631. } else if (!empty($_SERVER['HTTP_X_FORWARDED_SERVER'])) {
  3632. $server_url = $_SERVER['HTTP_X_FORWARDED_SERVER'];
  3633. } else {
  3634. if (empty($_SERVER['SERVER_NAME'])) {
  3635. $server_url = $_SERVER['HTTP_HOST'];
  3636. } else {
  3637. $server_url = $_SERVER['SERVER_NAME'];
  3638. }
  3639. }
  3640. if (!strpos($server_url, ':')) {
  3641. if (empty($_SERVER['HTTP_X_FORWARDED_PORT'])) {
  3642. $server_port = $_SERVER['SERVER_PORT'];
  3643. } else {
  3644. $ports = explode(',', $_SERVER['HTTP_X_FORWARDED_PORT']);
  3645. $server_port = $ports[0];
  3646. }
  3647. if ( ($this->_isHttps() && $server_port!=443)
  3648. || (!$this->_isHttps() && $server_port!=80)
  3649. ) {
  3650. $server_url .= ':';
  3651. $server_url .= $server_port;
  3652. }
  3653. }
  3654. return $server_url;
  3655. }
  3656. /**
  3657. * This method checks to see if the request is secured via HTTPS
  3658. *
  3659. * @return bool true if https, false otherwise
  3660. */
  3661. private function _isHttps()
  3662. {
  3663. if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
  3664. return ($_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https');
  3665. } elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTOCOL'])) {
  3666. return ($_SERVER['HTTP_X_FORWARDED_PROTOCOL'] === 'https');
  3667. } elseif ( isset($_SERVER['HTTPS'])
  3668. && !empty($_SERVER['HTTPS'])
  3669. && strcasecmp($_SERVER['HTTPS'], 'off') !== 0
  3670. ) {
  3671. return true;
  3672. }
  3673. return false;
  3674. }
  3675. /**
  3676. * Removes a parameter from a query string
  3677. *
  3678. * @param string $parameterName name of parameter
  3679. * @param string $queryString query string
  3680. *
  3681. * @return string new query string
  3682. *
  3683. * @link http://stackoverflow.com/questions/1842681/regular-expression-to-remove-one-parameter-from-query-string
  3684. */
  3685. private function _removeParameterFromQueryString($parameterName, $queryString)
  3686. {
  3687. $parameterName = preg_quote($parameterName);
  3688. return preg_replace(
  3689. "/&$parameterName(=[^&]*)?|^$parameterName(=[^&]*)?&?/",
  3690. '', $queryString
  3691. );
  3692. }
  3693. /**
  3694. * This method is used to append query parameters to an url. Since the url
  3695. * might already contain parameter it has to be detected and to build a proper
  3696. * URL
  3697. *
  3698. * @param string $url base url to add the query params to
  3699. * @param string $query params in query form with & separated
  3700. *
  3701. * @return string url with query params
  3702. */
  3703. private function _buildQueryUrl($url, $query)
  3704. {
  3705. $url .= (strstr($url, '?') === false) ? '?' : '&';
  3706. $url .= $query;
  3707. return $url;
  3708. }
  3709. /**
  3710. * This method tests if a string starts with a given character.
  3711. *
  3712. * @param string $text text to test
  3713. * @param string $char character to test for
  3714. *
  3715. * @return bool true if the $text starts with $char
  3716. */
  3717. private function _startsWith($text, $char)
  3718. {
  3719. return (strpos($text, $char) === 0);
  3720. }
  3721. /**
  3722. * This method tests if a string ends with a given character
  3723. *
  3724. * @param string $text text to test
  3725. * @param string $char character to test for
  3726. *
  3727. * @return bool true if the $text ends with $char
  3728. */
  3729. private function _endsWith($text, $char)
  3730. {
  3731. return (strpos(strrev($text), $char) === 0);
  3732. }
  3733. /**
  3734. * Answer a valid session-id given a CAS ticket.
  3735. *
  3736. * The output must be deterministic to allow single-log-out when presented with
  3737. * the ticket to log-out.
  3738. *
  3739. *
  3740. * @param string $ticket name of the ticket
  3741. *
  3742. * @return string
  3743. */
  3744. private function _sessionIdForTicket($ticket)
  3745. {
  3746. // Hash the ticket to ensure that the value meets the PHP 7.1 requirement
  3747. // that session-ids have a length between 22 and 256 characters.
  3748. return hash('sha256', $this->_sessionIdSalt . $ticket);
  3749. }
  3750. /**
  3751. * Set a salt/seed for the session-id hash to make it harder to guess.
  3752. *
  3753. * @var string $_sessionIdSalt
  3754. */
  3755. private $_sessionIdSalt = '';
  3756. /**
  3757. * Set a salt/seed for the session-id hash to make it harder to guess.
  3758. *
  3759. * @param string $salt
  3760. *
  3761. * @return void
  3762. */
  3763. public function setSessionIdSalt($salt) {
  3764. $this->_sessionIdSalt = (string)$salt;
  3765. }
  3766. // ########################################################################
  3767. // AUTHENTICATION ERROR HANDLING
  3768. // ########################################################################
  3769. /**
  3770. * This method is used to print the HTML output when the user was not
  3771. * authenticated.
  3772. *
  3773. * @param string $failure the failure that occured
  3774. * @param string $cas_url the URL the CAS server was asked for
  3775. * @param bool $no_response the response from the CAS server (other
  3776. * parameters are ignored if true)
  3777. * @param bool $bad_response bad response from the CAS server ($err_code
  3778. * and $err_msg ignored if true)
  3779. * @param string $cas_response the response of the CAS server
  3780. * @param int $err_code the error code given by the CAS server
  3781. * @param string $err_msg the error message given by the CAS server
  3782. *
  3783. * @return void
  3784. */
  3785. private function _authError(
  3786. $failure,
  3787. $cas_url,
  3788. $no_response=false,
  3789. $bad_response=false,
  3790. $cas_response='',
  3791. $err_code=-1,
  3792. $err_msg=''
  3793. ) {
  3794. phpCAS::traceBegin();
  3795. $lang = $this->getLangObj();
  3796. $this->printHTMLHeader($lang->getAuthenticationFailed());
  3797. printf(
  3798. $lang->getYouWereNotAuthenticated(), htmlentities($this->getURL()),
  3799. isset($_SERVER['SERVER_ADMIN']) ? $_SERVER['SERVER_ADMIN']:''
  3800. );
  3801. phpCAS::trace('CAS URL: '.$cas_url);
  3802. phpCAS::trace('Authentication failure: '.$failure);
  3803. if ( $no_response ) {
  3804. phpCAS::trace('Reason: no response from the CAS server');
  3805. } else {
  3806. if ( $bad_response ) {
  3807. phpCAS::trace('Reason: bad response from the CAS server');
  3808. } else {
  3809. switch ($this->getServerVersion()) {
  3810. case CAS_VERSION_1_0:
  3811. phpCAS::trace('Reason: CAS error');
  3812. break;
  3813. case CAS_VERSION_2_0:
  3814. case CAS_VERSION_3_0:
  3815. if ( $err_code === -1 ) {
  3816. phpCAS::trace('Reason: no CAS error');
  3817. } else {
  3818. phpCAS::trace(
  3819. 'Reason: ['.$err_code.'] CAS error: '.$err_msg
  3820. );
  3821. }
  3822. break;
  3823. }
  3824. }
  3825. phpCAS::trace('CAS response: '.$cas_response);
  3826. }
  3827. $this->printHTMLFooter();
  3828. phpCAS::traceExit();
  3829. throw new CAS_GracefullTerminationException();
  3830. }
  3831. // ########################################################################
  3832. // PGTIOU/PGTID and logoutRequest rebroadcasting
  3833. // ########################################################################
  3834. /**
  3835. * Boolean of whether to rebroadcast pgtIou/pgtId and logoutRequest, and
  3836. * array of the nodes.
  3837. */
  3838. private $_rebroadcast = false;
  3839. private $_rebroadcast_nodes = array();
  3840. /**
  3841. * Constants used for determining rebroadcast node type.
  3842. */
  3843. const HOSTNAME = 0;
  3844. const IP = 1;
  3845. /**
  3846. * Determine the node type from the URL.
  3847. *
  3848. * @param String $nodeURL The node URL.
  3849. *
  3850. * @return int hostname
  3851. *
  3852. */
  3853. private function _getNodeType($nodeURL)
  3854. {
  3855. phpCAS::traceBegin();
  3856. if (preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $nodeURL)) {
  3857. phpCAS::traceEnd(self::IP);
  3858. return self::IP;
  3859. } else {
  3860. phpCAS::traceEnd(self::HOSTNAME);
  3861. return self::HOSTNAME;
  3862. }
  3863. }
  3864. /**
  3865. * Store the rebroadcast node for pgtIou/pgtId and logout requests.
  3866. *
  3867. * @param string $rebroadcastNodeUrl The rebroadcast node URL.
  3868. *
  3869. * @return void
  3870. */
  3871. public function addRebroadcastNode($rebroadcastNodeUrl)
  3872. {
  3873. // Argument validation
  3874. if ( !(bool)preg_match("/^(http|https):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i", $rebroadcastNodeUrl))
  3875. throw new CAS_TypeMismatchException($rebroadcastNodeUrl, '$rebroadcastNodeUrl', 'url');
  3876. // Store the rebroadcast node and set flag
  3877. $this->_rebroadcast = true;
  3878. $this->_rebroadcast_nodes[] = $rebroadcastNodeUrl;
  3879. }
  3880. /**
  3881. * An array to store extra rebroadcast curl options.
  3882. */
  3883. private $_rebroadcast_headers = array();
  3884. /**
  3885. * This method is used to add header parameters when rebroadcasting
  3886. * pgtIou/pgtId or logoutRequest.
  3887. *
  3888. * @param string $header Header to send when rebroadcasting.
  3889. *
  3890. * @return void
  3891. */
  3892. public function addRebroadcastHeader($header)
  3893. {
  3894. if (gettype($header) != 'string')
  3895. throw new CAS_TypeMismatchException($header, '$header', 'string');
  3896. $this->_rebroadcast_headers[] = $header;
  3897. }
  3898. /**
  3899. * Constants used for determining rebroadcast type (logout or pgtIou/pgtId).
  3900. */
  3901. const LOGOUT = 0;
  3902. const PGTIOU = 1;
  3903. /**
  3904. * This method rebroadcasts logout/pgtIou requests. Can be LOGOUT,PGTIOU
  3905. *
  3906. * @param int $type type of rebroadcasting.
  3907. *
  3908. * @return void
  3909. */
  3910. private function _rebroadcast($type)
  3911. {
  3912. phpCAS::traceBegin();
  3913. $rebroadcast_curl_options = array(
  3914. CURLOPT_FAILONERROR => 1,
  3915. CURLOPT_FOLLOWLOCATION => 1,
  3916. CURLOPT_RETURNTRANSFER => 1,
  3917. CURLOPT_CONNECTTIMEOUT => 1,
  3918. CURLOPT_TIMEOUT => 4);
  3919. // Try to determine the IP address of the server
  3920. if (!empty($_SERVER['SERVER_ADDR'])) {
  3921. $ip = $_SERVER['SERVER_ADDR'];
  3922. } else if (!empty($_SERVER['LOCAL_ADDR'])) {
  3923. // IIS 7
  3924. $ip = $_SERVER['LOCAL_ADDR'];
  3925. }
  3926. // Try to determine the DNS name of the server
  3927. if (!empty($ip)) {
  3928. $dns = gethostbyaddr($ip);
  3929. }
  3930. $multiClassName = 'CAS_Request_CurlMultiRequest';
  3931. $multiRequest = new $multiClassName();
  3932. for ($i = 0; $i < sizeof($this->_rebroadcast_nodes); $i++) {
  3933. if ((($this->_getNodeType($this->_rebroadcast_nodes[$i]) == self::HOSTNAME) && !empty($dns) && (stripos($this->_rebroadcast_nodes[$i], $dns) === false))
  3934. || (($this->_getNodeType($this->_rebroadcast_nodes[$i]) == self::IP) && !empty($ip) && (stripos($this->_rebroadcast_nodes[$i], $ip) === false))
  3935. ) {
  3936. phpCAS::trace(
  3937. 'Rebroadcast target URL: '.$this->_rebroadcast_nodes[$i]
  3938. .$_SERVER['REQUEST_URI']
  3939. );
  3940. $className = $this->_requestImplementation;
  3941. $request = new $className();
  3942. $url = $this->_rebroadcast_nodes[$i].$_SERVER['REQUEST_URI'];
  3943. $request->setUrl($url);
  3944. if (count($this->_rebroadcast_headers)) {
  3945. $request->addHeaders($this->_rebroadcast_headers);
  3946. }
  3947. $request->makePost();
  3948. if ($type == self::LOGOUT) {
  3949. // Logout request
  3950. $request->setPostBody(
  3951. 'rebroadcast=false&logoutRequest='.$_POST['logoutRequest']
  3952. );
  3953. } else if ($type == self::PGTIOU) {
  3954. // pgtIou/pgtId rebroadcast
  3955. $request->setPostBody('rebroadcast=false');
  3956. }
  3957. $request->setCurlOptions($rebroadcast_curl_options);
  3958. $multiRequest->addRequest($request);
  3959. } else {
  3960. phpCAS::trace(
  3961. 'Rebroadcast not sent to self: '
  3962. .$this->_rebroadcast_nodes[$i].' == '.(!empty($ip)?$ip:'')
  3963. .'/'.(!empty($dns)?$dns:'')
  3964. );
  3965. }
  3966. }
  3967. // We need at least 1 request
  3968. if ($multiRequest->getNumRequests() > 0) {
  3969. $multiRequest->send();
  3970. }
  3971. phpCAS::traceEnd();
  3972. }
  3973. /** @} */
  3974. }