geshi.php 199 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755
  1. <?php
  2. /**
  3. * GeSHi - Generic Syntax Highlighter
  4. *
  5. * The GeSHi class for Generic Syntax Highlighting. Please refer to the
  6. * documentation at http://qbnz.com/highlighter/documentation.php for more
  7. * information about how to use this class.
  8. *
  9. * For changes, release notes, TODOs etc, see the relevant files in the docs/
  10. * directory.
  11. *
  12. * This file is part of GeSHi.
  13. *
  14. * GeSHi is free software; you can redistribute it and/or modify
  15. * it under the terms of the GNU General Public License as published by
  16. * the Free Software Foundation; either version 2 of the License, or
  17. * (at your option) any later version.
  18. *
  19. * GeSHi is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU General Public License
  25. * along with GeSHi; if not, write to the Free Software
  26. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  27. *
  28. * @package geshi
  29. * @subpackage core
  30. * @author Nigel McNie <nigel@geshi.org>, Benny Baumann <BenBE@omorphia.de>
  31. * @copyright (C) 2004 - 2007 Nigel McNie, (C) 2007 - 2008 Benny Baumann
  32. * @license http://gnu.org/copyleft/gpl.html GNU GPL
  33. *
  34. */
  35. //
  36. // GeSHi Constants
  37. // You should use these constant names in your programs instead of
  38. // their values - you never know when a value may change in a future
  39. // version
  40. //
  41. /** The version of this GeSHi file */
  42. define('GESHI_VERSION', '1.0.8.10');
  43. // Define the root directory for the GeSHi code tree
  44. if (!defined('GESHI_ROOT')) {
  45. /** The root directory for GeSHi */
  46. define('GESHI_ROOT', dirname(__FILE__) . DIRECTORY_SEPARATOR);
  47. }
  48. /** The language file directory for GeSHi
  49. @access private */
  50. define('GESHI_LANG_ROOT', GESHI_ROOT . 'geshi' . DIRECTORY_SEPARATOR);
  51. // Define if GeSHi should be paranoid about security
  52. if (!defined('GESHI_SECURITY_PARANOID')) {
  53. /** Tells GeSHi to be paranoid about security settings */
  54. define('GESHI_SECURITY_PARANOID', false);
  55. }
  56. // Line numbers - use with enable_line_numbers()
  57. /** Use no line numbers when building the result */
  58. define('GESHI_NO_LINE_NUMBERS', 0);
  59. /** Use normal line numbers when building the result */
  60. define('GESHI_NORMAL_LINE_NUMBERS', 1);
  61. /** Use fancy line numbers when building the result */
  62. define('GESHI_FANCY_LINE_NUMBERS', 2);
  63. // Container HTML type
  64. /** Use nothing to surround the source */
  65. define('GESHI_HEADER_NONE', 0);
  66. /** Use a "div" to surround the source */
  67. define('GESHI_HEADER_DIV', 1);
  68. /** Use a "pre" to surround the source */
  69. define('GESHI_HEADER_PRE', 2);
  70. /** Use a pre to wrap lines when line numbers are enabled or to wrap the whole code. */
  71. define('GESHI_HEADER_PRE_VALID', 3);
  72. /**
  73. * Use a "table" to surround the source:
  74. *
  75. * <table>
  76. * <thead><tr><td colspan="2">$header</td></tr></thead>
  77. * <tbody><tr><td><pre>$linenumbers</pre></td><td><pre>$code></pre></td></tr></tbody>
  78. * <tfooter><tr><td colspan="2">$footer</td></tr></tfoot>
  79. * </table>
  80. *
  81. * this is essentially only a workaround for Firefox, see sf#1651996 or take a look at
  82. * https://bugzilla.mozilla.org/show_bug.cgi?id=365805
  83. * @note when linenumbers are disabled this is essentially the same as GESHI_HEADER_PRE
  84. */
  85. define('GESHI_HEADER_PRE_TABLE', 4);
  86. // Capatalisation constants
  87. /** Lowercase keywords found */
  88. define('GESHI_CAPS_NO_CHANGE', 0);
  89. /** Uppercase keywords found */
  90. define('GESHI_CAPS_UPPER', 1);
  91. /** Leave keywords found as the case that they are */
  92. define('GESHI_CAPS_LOWER', 2);
  93. // Link style constants
  94. /** Links in the source in the :link state */
  95. define('GESHI_LINK', 0);
  96. /** Links in the source in the :hover state */
  97. define('GESHI_HOVER', 1);
  98. /** Links in the source in the :active state */
  99. define('GESHI_ACTIVE', 2);
  100. /** Links in the source in the :visited state */
  101. define('GESHI_VISITED', 3);
  102. // Important string starter/finisher
  103. // Note that if you change these, they should be as-is: i.e., don't
  104. // write them as if they had been run through htmlentities()
  105. /** The starter for important parts of the source */
  106. define('GESHI_START_IMPORTANT', '<BEGIN GeSHi>');
  107. /** The ender for important parts of the source */
  108. define('GESHI_END_IMPORTANT', '<END GeSHi>');
  109. /**#@+
  110. * @access private
  111. */
  112. // When strict mode applies for a language
  113. /** Strict mode never applies (this is the most common) */
  114. define('GESHI_NEVER', 0);
  115. /** Strict mode *might* apply, and can be enabled or
  116. disabled by {@link GeSHi->enable_strict_mode()} */
  117. define('GESHI_MAYBE', 1);
  118. /** Strict mode always applies */
  119. define('GESHI_ALWAYS', 2);
  120. // Advanced regexp handling constants, used in language files
  121. /** The key of the regex array defining what to search for */
  122. define('GESHI_SEARCH', 0);
  123. /** The key of the regex array defining what bracket group in a
  124. matched search to use as a replacement */
  125. define('GESHI_REPLACE', 1);
  126. /** The key of the regex array defining any modifiers to the regular expression */
  127. define('GESHI_MODIFIERS', 2);
  128. /** The key of the regex array defining what bracket group in a
  129. matched search to put before the replacement */
  130. define('GESHI_BEFORE', 3);
  131. /** The key of the regex array defining what bracket group in a
  132. matched search to put after the replacement */
  133. define('GESHI_AFTER', 4);
  134. /** The key of the regex array defining a custom keyword to use
  135. for this regexp's html tag class */
  136. define('GESHI_CLASS', 5);
  137. /** Used in language files to mark comments */
  138. define('GESHI_COMMENTS', 0);
  139. /** Used to work around missing PHP features **/
  140. define('GESHI_PHP_PRE_433', !(version_compare(PHP_VERSION, '4.3.3') === 1));
  141. /** make sure we can call stripos **/
  142. if (!function_exists('stripos')) {
  143. // the offset param of preg_match is not supported below PHP 4.3.3
  144. if (GESHI_PHP_PRE_433) {
  145. /**
  146. * @ignore
  147. */
  148. function stripos($haystack, $needle, $offset = null) {
  149. if (!is_null($offset)) {
  150. $haystack = substr($haystack, $offset);
  151. }
  152. if (preg_match('/'. preg_quote($needle, '/') . '/', $haystack, $match, PREG_OFFSET_CAPTURE)) {
  153. return $match[0][1];
  154. }
  155. return false;
  156. }
  157. }
  158. else {
  159. /**
  160. * @ignore
  161. */
  162. function stripos($haystack, $needle, $offset = null) {
  163. if (preg_match('/'. preg_quote($needle, '/') . '/', $haystack, $match, PREG_OFFSET_CAPTURE, $offset)) {
  164. return $match[0][1];
  165. }
  166. return false;
  167. }
  168. }
  169. }
  170. /** some old PHP / PCRE subpatterns only support up to xxx subpatterns in
  171. regular expressions. Set this to false if your PCRE lib is up to date
  172. @see GeSHi->optimize_regexp_list()
  173. **/
  174. define('GESHI_MAX_PCRE_SUBPATTERNS', 500);
  175. /** it's also important not to generate too long regular expressions
  176. be generous here... but keep in mind, that when reaching this limit we
  177. still have to close open patterns. 12k should do just fine on a 16k limit.
  178. @see GeSHi->optimize_regexp_list()
  179. **/
  180. define('GESHI_MAX_PCRE_LENGTH', 12288);
  181. //Number format specification
  182. /** Basic number format for integers */
  183. define('GESHI_NUMBER_INT_BASIC', 1); //Default integers \d+
  184. /** Enhanced number format for integers like seen in C */
  185. define('GESHI_NUMBER_INT_CSTYLE', 2); //Default C-Style \d+[lL]?
  186. /** Number format to highlight binary numbers with a suffix "b" */
  187. define('GESHI_NUMBER_BIN_SUFFIX', 16); //[01]+[bB]
  188. /** Number format to highlight binary numbers with a prefix % */
  189. define('GESHI_NUMBER_BIN_PREFIX_PERCENT', 32); //%[01]+
  190. /** Number format to highlight binary numbers with a prefix 0b (C) */
  191. define('GESHI_NUMBER_BIN_PREFIX_0B', 64); //0b[01]+
  192. /** Number format to highlight octal numbers with a leading zero */
  193. define('GESHI_NUMBER_OCT_PREFIX', 256); //0[0-7]+
  194. /** Number format to highlight octal numbers with a prefix 0o (logtalk) */
  195. define('GESHI_NUMBER_OCT_PREFIX_0O', 512); //0[0-7]+
  196. /** Number format to highlight octal numbers with a leading @ (Used in HiSofts Devpac series). */
  197. define('GESHI_NUMBER_OCT_PREFIX_AT', 1024); //@[0-7]+
  198. /** Number format to highlight octal numbers with a suffix of o */
  199. define('GESHI_NUMBER_OCT_SUFFIX', 2048); //[0-7]+[oO]
  200. /** Number format to highlight hex numbers with a prefix 0x */
  201. define('GESHI_NUMBER_HEX_PREFIX', 4096); //0x[0-9a-fA-F]+
  202. /** Number format to highlight hex numbers with a prefix $ */
  203. define('GESHI_NUMBER_HEX_PREFIX_DOLLAR', 8192); //$[0-9a-fA-F]+
  204. /** Number format to highlight hex numbers with a suffix of h */
  205. define('GESHI_NUMBER_HEX_SUFFIX', 16384); //[0-9][0-9a-fA-F]*h
  206. /** Number format to highlight floating-point numbers without support for scientific notation */
  207. define('GESHI_NUMBER_FLT_NONSCI', 65536); //\d+\.\d+
  208. /** Number format to highlight floating-point numbers without support for scientific notation */
  209. define('GESHI_NUMBER_FLT_NONSCI_F', 131072); //\d+(\.\d+)?f
  210. /** Number format to highlight floating-point numbers with support for scientific notation (E) and optional leading zero */
  211. define('GESHI_NUMBER_FLT_SCI_SHORT', 262144); //\.\d+e\d+
  212. /** Number format to highlight floating-point numbers with support for scientific notation (E) and required leading digit */
  213. define('GESHI_NUMBER_FLT_SCI_ZERO', 524288); //\d+(\.\d+)?e\d+
  214. //Custom formats are passed by RX array
  215. // Error detection - use these to analyse faults
  216. /** No sourcecode to highlight was specified
  217. * @deprecated
  218. */
  219. define('GESHI_ERROR_NO_INPUT', 1);
  220. /** The language specified does not exist */
  221. define('GESHI_ERROR_NO_SUCH_LANG', 2);
  222. /** GeSHi could not open a file for reading (generally a language file) */
  223. define('GESHI_ERROR_FILE_NOT_READABLE', 3);
  224. /** The header type passed to {@link GeSHi->set_header_type()} was invalid */
  225. define('GESHI_ERROR_INVALID_HEADER_TYPE', 4);
  226. /** The line number type passed to {@link GeSHi->enable_line_numbers()} was invalid */
  227. define('GESHI_ERROR_INVALID_LINE_NUMBER_TYPE', 5);
  228. /**#@-*/
  229. /**
  230. * The GeSHi Class.
  231. *
  232. * Please refer to the documentation for GeSHi 1.0.X that is available
  233. * at http://qbnz.com/highlighter/documentation.php for more information
  234. * about how to use this class.
  235. *
  236. * @package geshi
  237. * @author Nigel McNie <nigel@geshi.org>, Benny Baumann <BenBE@omorphia.de>
  238. * @copyright (C) 2004 - 2007 Nigel McNie, (C) 2007 - 2008 Benny Baumann
  239. */
  240. class GeSHi {
  241. /**#@+
  242. * @access private
  243. */
  244. /**
  245. * The source code to highlight
  246. * @var string
  247. */
  248. var $source = '';
  249. /**
  250. * The language to use when highlighting
  251. * @var string
  252. */
  253. var $language = '';
  254. /**
  255. * The data for the language used
  256. * @var array
  257. */
  258. var $language_data = array();
  259. /**
  260. * The path to the language files
  261. * @var string
  262. */
  263. var $language_path = GESHI_LANG_ROOT;
  264. /**
  265. * The error message associated with an error
  266. * @var string
  267. * @todo check err reporting works
  268. */
  269. var $error = false;
  270. /**
  271. * Possible error messages
  272. * @var array
  273. */
  274. var $error_messages = array(
  275. GESHI_ERROR_NO_SUCH_LANG => 'GeSHi could not find the language {LANGUAGE} (using path {PATH})',
  276. GESHI_ERROR_FILE_NOT_READABLE => 'The file specified for load_from_file was not readable',
  277. GESHI_ERROR_INVALID_HEADER_TYPE => 'The header type specified is invalid',
  278. GESHI_ERROR_INVALID_LINE_NUMBER_TYPE => 'The line number type specified is invalid'
  279. );
  280. /**
  281. * Whether highlighting is strict or not
  282. * @var boolean
  283. */
  284. var $strict_mode = false;
  285. /**
  286. * Whether to use CSS classes in output
  287. * @var boolean
  288. */
  289. var $use_classes = false;
  290. /**
  291. * The type of header to use. Can be one of the following
  292. * values:
  293. *
  294. * - GESHI_HEADER_PRE: Source is outputted in a "pre" HTML element.
  295. * - GESHI_HEADER_DIV: Source is outputted in a "div" HTML element.
  296. * - GESHI_HEADER_NONE: No header is outputted.
  297. *
  298. * @var int
  299. */
  300. var $header_type = GESHI_HEADER_PRE;
  301. /**
  302. * Array of permissions for which lexics should be highlighted
  303. * @var array
  304. */
  305. var $lexic_permissions = array(
  306. 'KEYWORDS' => array(),
  307. 'COMMENTS' => array('MULTI' => true),
  308. 'REGEXPS' => array(),
  309. 'ESCAPE_CHAR' => true,
  310. 'BRACKETS' => true,
  311. 'SYMBOLS' => false,
  312. 'STRINGS' => true,
  313. 'NUMBERS' => true,
  314. 'METHODS' => true,
  315. 'SCRIPT' => true
  316. );
  317. /**
  318. * The time it took to parse the code
  319. * @var double
  320. */
  321. var $time = 0;
  322. /**
  323. * The content of the header block
  324. * @var string
  325. */
  326. var $header_content = '';
  327. /**
  328. * The content of the footer block
  329. * @var string
  330. */
  331. var $footer_content = '';
  332. /**
  333. * The style of the header block
  334. * @var string
  335. */
  336. var $header_content_style = '';
  337. /**
  338. * The style of the footer block
  339. * @var string
  340. */
  341. var $footer_content_style = '';
  342. /**
  343. * Tells if a block around the highlighted source should be forced
  344. * if not using line numbering
  345. * @var boolean
  346. */
  347. var $force_code_block = false;
  348. /**
  349. * The styles for hyperlinks in the code
  350. * @var array
  351. */
  352. var $link_styles = array();
  353. /**
  354. * Whether important blocks should be recognised or not
  355. * @var boolean
  356. * @deprecated
  357. * @todo REMOVE THIS FUNCTIONALITY!
  358. */
  359. var $enable_important_blocks = false;
  360. /**
  361. * Styles for important parts of the code
  362. * @var string
  363. * @deprecated
  364. * @todo As above - rethink the whole idea of important blocks as it is buggy and
  365. * will be hard to implement in 1.2
  366. */
  367. var $important_styles = 'font-weight: bold; color: red;'; // Styles for important parts of the code
  368. /**
  369. * Whether CSS IDs should be added to the code
  370. * @var boolean
  371. */
  372. var $add_ids = false;
  373. /**
  374. * Lines that should be highlighted extra
  375. * @var array
  376. */
  377. var $highlight_extra_lines = array();
  378. /**
  379. * Styles of lines that should be highlighted extra
  380. * @var array
  381. */
  382. var $highlight_extra_lines_styles = array();
  383. /**
  384. * Styles of extra-highlighted lines
  385. * @var string
  386. */
  387. var $highlight_extra_lines_style = 'background-color: #ffc;';
  388. /**
  389. * The line ending
  390. * If null, nl2br() will be used on the result string.
  391. * Otherwise, all instances of \n will be replaced with $line_ending
  392. * @var string
  393. */
  394. var $line_ending = null;
  395. /**
  396. * Number at which line numbers should start at
  397. * @var int
  398. */
  399. var $line_numbers_start = 1;
  400. /**
  401. * The overall style for this code block
  402. * @var string
  403. */
  404. var $overall_style = 'font-family:monospace;';
  405. /**
  406. * The style for the actual code
  407. * @var string
  408. */
  409. var $code_style = 'font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;';
  410. /**
  411. * The overall class for this code block
  412. * @var string
  413. */
  414. var $overall_class = '';
  415. /**
  416. * The overall ID for this code block
  417. * @var string
  418. */
  419. var $overall_id = '';
  420. /**
  421. * Line number styles
  422. * @var string
  423. */
  424. var $line_style1 = 'font-weight: normal; vertical-align:top;';
  425. /**
  426. * Line number styles for fancy lines
  427. * @var string
  428. */
  429. var $line_style2 = 'font-weight: bold; vertical-align:top;';
  430. /**
  431. * Style for line numbers when GESHI_HEADER_PRE_TABLE is chosen
  432. * @var string
  433. */
  434. var $table_linenumber_style = 'width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;';
  435. /**
  436. * Flag for how line numbers are displayed
  437. * @var boolean
  438. */
  439. var $line_numbers = GESHI_NO_LINE_NUMBERS;
  440. /**
  441. * Flag to decide if multi line spans are allowed. Set it to false to make sure
  442. * each tag is closed before and reopened after each linefeed.
  443. * @var boolean
  444. */
  445. var $allow_multiline_span = true;
  446. /**
  447. * The "nth" value for fancy line highlighting
  448. * @var int
  449. */
  450. var $line_nth_row = 0;
  451. /**
  452. * The size of tab stops
  453. * @var int
  454. */
  455. var $tab_width = 8;
  456. /**
  457. * Should we use language-defined tab stop widths?
  458. * @var int
  459. */
  460. var $use_language_tab_width = false;
  461. /**
  462. * Default target for keyword links
  463. * @var string
  464. */
  465. var $link_target = '';
  466. /**
  467. * The encoding to use for entity encoding
  468. * NOTE: Used with Escape Char Sequences to fix UTF-8 handling (cf. SF#2037598)
  469. * @var string
  470. */
  471. var $encoding = 'utf-8';
  472. /**
  473. * Should keywords be linked?
  474. * @var boolean
  475. */
  476. var $keyword_links = true;
  477. /**
  478. * Currently loaded language file
  479. * @var string
  480. * @since 1.0.7.22
  481. */
  482. var $loaded_language = '';
  483. /**
  484. * Wether the caches needed for parsing are built or not
  485. *
  486. * @var bool
  487. * @since 1.0.8
  488. */
  489. var $parse_cache_built = false;
  490. /**
  491. * Work around for Suhosin Patch with disabled /e modifier
  492. *
  493. * Note from suhosins author in config file:
  494. * <blockquote>
  495. * The /e modifier inside <code>preg_replace()</code> allows code execution.
  496. * Often it is the cause for remote code execution exploits. It is wise to
  497. * deactivate this feature and test where in the application it is used.
  498. * The developer using the /e modifier should be made aware that he should
  499. * use <code>preg_replace_callback()</code> instead
  500. * </blockquote>
  501. *
  502. * @var array
  503. * @since 1.0.8
  504. */
  505. var $_kw_replace_group = 0;
  506. var $_rx_key = 0;
  507. /**
  508. * some "callback parameters" for handle_multiline_regexps
  509. *
  510. * @since 1.0.8
  511. * @access private
  512. * @var string
  513. */
  514. var $_hmr_before = '';
  515. var $_hmr_replace = '';
  516. var $_hmr_after = '';
  517. var $_hmr_key = 0;
  518. /**#@-*/
  519. /**
  520. * Creates a new GeSHi object, with source and language
  521. *
  522. * @param string The source code to highlight
  523. * @param string The language to highlight the source with
  524. * @param string The path to the language file directory. <b>This
  525. * is deprecated!</b> I've backported the auto path
  526. * detection from the 1.1.X dev branch, so now it
  527. * should be automatically set correctly. If you have
  528. * renamed the language directory however, you will
  529. * still need to set the path using this parameter or
  530. * {@link GeSHi->set_language_path()}
  531. * @since 1.0.0
  532. */
  533. function GeSHi($source = '', $language = '', $path = '') {
  534. if (!empty($source)) {
  535. $this->set_source($source);
  536. }
  537. if (!empty($language)) {
  538. $this->set_language($language);
  539. }
  540. $this->set_language_path($path);
  541. }
  542. /**
  543. * Returns an error message associated with the last GeSHi operation,
  544. * or false if no error has occured
  545. *
  546. * @return string|false An error message if there has been an error, else false
  547. * @since 1.0.0
  548. */
  549. function error() {
  550. if ($this->error) {
  551. //Put some template variables for debugging here ...
  552. $debug_tpl_vars = array(
  553. '{LANGUAGE}' => $this->language,
  554. '{PATH}' => $this->language_path
  555. );
  556. $msg = str_replace(
  557. array_keys($debug_tpl_vars),
  558. array_values($debug_tpl_vars),
  559. $this->error_messages[$this->error]);
  560. return "<br /><strong>GeSHi Error:</strong> $msg (code {$this->error})<br />";
  561. }
  562. return false;
  563. }
  564. /**
  565. * Gets a human-readable language name (thanks to Simon Patterson
  566. * for the idea :))
  567. *
  568. * @return string The name for the current language
  569. * @since 1.0.2
  570. */
  571. function get_language_name() {
  572. if (GESHI_ERROR_NO_SUCH_LANG == $this->error) {
  573. return $this->language_data['LANG_NAME'] . ' (Unknown Language)';
  574. }
  575. return $this->language_data['LANG_NAME'];
  576. }
  577. /**
  578. * Sets the source code for this object
  579. *
  580. * @param string The source code to highlight
  581. * @since 1.0.0
  582. */
  583. function set_source($source) {
  584. $this->source = $source;
  585. $this->highlight_extra_lines = array();
  586. }
  587. /**
  588. * Sets the language for this object
  589. *
  590. * @note since 1.0.8 this function won't reset language-settings by default anymore!
  591. * if you need this set $force_reset = true
  592. *
  593. * @param string The name of the language to use
  594. * @since 1.0.0
  595. */
  596. function set_language($language, $force_reset = false) {
  597. if ($force_reset) {
  598. $this->loaded_language = false;
  599. }
  600. //Clean up the language name to prevent malicious code injection
  601. $language = preg_replace('#[^a-zA-Z0-9\-_]#', '', $language);
  602. $language = strtolower($language);
  603. //Retreive the full filename
  604. $file_name = $this->language_path . $language . '.php';
  605. if ($file_name == $this->loaded_language) {
  606. // this language is already loaded!
  607. return;
  608. }
  609. $this->language = $language;
  610. $this->error = false;
  611. $this->strict_mode = GESHI_NEVER;
  612. //Check if we can read the desired file
  613. if (!is_readable($file_name)) {
  614. $this->error = GESHI_ERROR_NO_SUCH_LANG;
  615. return;
  616. }
  617. // Load the language for parsing
  618. $this->load_language($file_name);
  619. }
  620. /**
  621. * Sets the path to the directory containing the language files. Note
  622. * that this path is relative to the directory of the script that included
  623. * geshi.php, NOT geshi.php itself.
  624. *
  625. * @param string The path to the language directory
  626. * @since 1.0.0
  627. * @deprecated The path to the language files should now be automatically
  628. * detected, so this method should no longer be needed. The
  629. * 1.1.X branch handles manual setting of the path differently
  630. * so this method will disappear in 1.2.0.
  631. */
  632. function set_language_path($path) {
  633. if(strpos($path,':')) {
  634. //Security Fix to prevent external directories using fopen wrappers.
  635. if(DIRECTORY_SEPARATOR == "\\") {
  636. if(!preg_match('#^[a-zA-Z]:#', $path) || false !== strpos($path, ':', 2)) {
  637. return;
  638. }
  639. } else {
  640. return;
  641. }
  642. }
  643. if(preg_match('#[^/a-zA-Z0-9_\.\-\\\s:]#', $path)) {
  644. //Security Fix to prevent external directories using fopen wrappers.
  645. return;
  646. }
  647. if(GESHI_SECURITY_PARANOID && false !== strpos($path, '/.')) {
  648. //Security Fix to prevent external directories using fopen wrappers.
  649. return;
  650. }
  651. if(GESHI_SECURITY_PARANOID && false !== strpos($path, '..')) {
  652. //Security Fix to prevent external directories using fopen wrappers.
  653. return;
  654. }
  655. if ($path) {
  656. $this->language_path = ('/' == $path[strlen($path) - 1]) ? $path : $path . '/';
  657. $this->set_language($this->language); // otherwise set_language_path has no effect
  658. }
  659. }
  660. /**
  661. * Get supported langs or an associative array lang=>full_name.
  662. * @param boolean $longnames
  663. * @return array
  664. */
  665. function get_supported_languages($full_names=false)
  666. {
  667. // return array
  668. $back = array();
  669. // we walk the lang root
  670. $dir = dir($this->language_path);
  671. // foreach entry
  672. while (false !== ($entry = $dir->read()))
  673. {
  674. $full_path = $this->language_path.$entry;
  675. // Skip all dirs
  676. if (is_dir($full_path)) {
  677. continue;
  678. }
  679. // we only want lang.php files
  680. if (!preg_match('/^([^.]+)\.php$/', $entry, $matches)) {
  681. continue;
  682. }
  683. // Raw lang name is here
  684. $langname = $matches[1];
  685. // We want the fullname too?
  686. if ($full_names === true)
  687. {
  688. if (false !== ($fullname = $this->get_language_fullname($langname)))
  689. {
  690. $back[$langname] = $fullname; // we go associative
  691. }
  692. }
  693. else
  694. {
  695. // just store raw langname
  696. $back[] = $langname;
  697. }
  698. }
  699. $dir->close();
  700. return $back;
  701. }
  702. /**
  703. * Get full_name for a lang or false.
  704. * @param string $language short langname (html4strict for example)
  705. * @return mixed
  706. */
  707. function get_language_fullname($language)
  708. {
  709. //Clean up the language name to prevent malicious code injection
  710. $language = preg_replace('#[^a-zA-Z0-9\-_]#', '', $language);
  711. $language = strtolower($language);
  712. // get fullpath-filename for a langname
  713. $fullpath = $this->language_path.$language.'.php';
  714. // we need to get contents :S
  715. if (false === ($data = file_get_contents($fullpath))) {
  716. $this->error = sprintf('Geshi::get_lang_fullname() Unknown Language: %s', $language);
  717. return false;
  718. }
  719. // match the langname
  720. if (!preg_match("/'LANG_NAME'\s*=>\s*'(.+|(?:\\')+)'/", $data, $matches)) {
  721. $this->error = sprintf('Geshi::get_lang_fullname(%s): Regex can not detect language', $language);
  722. return false;
  723. }
  724. // return fullname for langname
  725. return stripcslashes($matches[1]);
  726. }
  727. /**
  728. * Sets the type of header to be used.
  729. *
  730. * If GESHI_HEADER_DIV is used, the code is surrounded in a "div".This
  731. * means more source code but more control over tab width and line-wrapping.
  732. * GESHI_HEADER_PRE means that a "pre" is used - less source, but less
  733. * control. Default is GESHI_HEADER_PRE.
  734. *
  735. * From 1.0.7.2, you can use GESHI_HEADER_NONE to specify that no header code
  736. * should be outputted.
  737. *
  738. * @param int The type of header to be used
  739. * @since 1.0.0
  740. */
  741. function set_header_type($type) {
  742. //Check if we got a valid header type
  743. if (!in_array($type, array(GESHI_HEADER_NONE, GESHI_HEADER_DIV,
  744. GESHI_HEADER_PRE, GESHI_HEADER_PRE_VALID, GESHI_HEADER_PRE_TABLE))) {
  745. $this->error = GESHI_ERROR_INVALID_HEADER_TYPE;
  746. return;
  747. }
  748. //Set that new header type
  749. $this->header_type = $type;
  750. }
  751. /**
  752. * Sets the styles for the code that will be outputted
  753. * when this object is parsed. The style should be a
  754. * string of valid stylesheet declarations
  755. *
  756. * @param string The overall style for the outputted code block
  757. * @param boolean Whether to merge the styles with the current styles or not
  758. * @since 1.0.0
  759. */
  760. function set_overall_style($style, $preserve_defaults = false) {
  761. if (!$preserve_defaults) {
  762. $this->overall_style = $style;
  763. } else {
  764. $this->overall_style .= $style;
  765. }
  766. }
  767. /**
  768. * Sets the overall classname for this block of code. This
  769. * class can then be used in a stylesheet to style this object's
  770. * output
  771. *
  772. * @param string The class name to use for this block of code
  773. * @since 1.0.0
  774. */
  775. function set_overall_class($class) {
  776. $this->overall_class = $class;
  777. }
  778. /**
  779. * Sets the overall id for this block of code. This id can then
  780. * be used in a stylesheet to style this object's output
  781. *
  782. * @param string The ID to use for this block of code
  783. * @since 1.0.0
  784. */
  785. function set_overall_id($id) {
  786. $this->overall_id = $id;
  787. }
  788. /**
  789. * Sets whether CSS classes should be used to highlight the source. Default
  790. * is off, calling this method with no arguments will turn it on
  791. *
  792. * @param boolean Whether to turn classes on or not
  793. * @since 1.0.0
  794. */
  795. function enable_classes($flag = true) {
  796. $this->use_classes = ($flag) ? true : false;
  797. }
  798. /**
  799. * Sets the style for the actual code. This should be a string
  800. * containing valid stylesheet declarations. If $preserve_defaults is
  801. * true, then styles are merged with the default styles, with the
  802. * user defined styles having priority
  803. *
  804. * Note: Use this method to override any style changes you made to
  805. * the line numbers if you are using line numbers, else the line of
  806. * code will have the same style as the line number! Consult the
  807. * GeSHi documentation for more information about this.
  808. *
  809. * @param string The style to use for actual code
  810. * @param boolean Whether to merge the current styles with the new styles
  811. * @since 1.0.2
  812. */
  813. function set_code_style($style, $preserve_defaults = false) {
  814. if (!$preserve_defaults) {
  815. $this->code_style = $style;
  816. } else {
  817. $this->code_style .= $style;
  818. }
  819. }
  820. /**
  821. * Sets the styles for the line numbers.
  822. *
  823. * @param string The style for the line numbers that are "normal"
  824. * @param string|boolean If a string, this is the style of the line
  825. * numbers that are "fancy", otherwise if boolean then this
  826. * defines whether the normal styles should be merged with the
  827. * new normal styles or not
  828. * @param boolean If set, is the flag for whether to merge the "fancy"
  829. * styles with the current styles or not
  830. * @since 1.0.2
  831. */
  832. function set_line_style($style1, $style2 = '', $preserve_defaults = false) {
  833. //Check if we got 2 or three parameters
  834. if (is_bool($style2)) {
  835. $preserve_defaults = $style2;
  836. $style2 = '';
  837. }
  838. //Actually set the new styles
  839. if (!$preserve_defaults) {
  840. $this->line_style1 = $style1;
  841. $this->line_style2 = $style2;
  842. } else {
  843. $this->line_style1 .= $style1;
  844. $this->line_style2 .= $style2;
  845. }
  846. }
  847. /**
  848. * Sets whether line numbers should be displayed.
  849. *
  850. * Valid values for the first parameter are:
  851. *
  852. * - GESHI_NO_LINE_NUMBERS: Line numbers will not be displayed
  853. * - GESHI_NORMAL_LINE_NUMBERS: Line numbers will be displayed
  854. * - GESHI_FANCY_LINE_NUMBERS: Fancy line numbers will be displayed
  855. *
  856. * For fancy line numbers, the second parameter is used to signal which lines
  857. * are to be fancy. For example, if the value of this parameter is 5 then every
  858. * 5th line will be fancy.
  859. *
  860. * @param int How line numbers should be displayed
  861. * @param int Defines which lines are fancy
  862. * @since 1.0.0
  863. */
  864. function enable_line_numbers($flag, $nth_row = 5) {
  865. if (GESHI_NO_LINE_NUMBERS != $flag && GESHI_NORMAL_LINE_NUMBERS != $flag
  866. && GESHI_FANCY_LINE_NUMBERS != $flag) {
  867. $this->error = GESHI_ERROR_INVALID_LINE_NUMBER_TYPE;
  868. }
  869. $this->line_numbers = $flag;
  870. $this->line_nth_row = $nth_row;
  871. }
  872. /**
  873. * Sets wether spans and other HTML markup generated by GeSHi can
  874. * span over multiple lines or not. Defaults to true to reduce overhead.
  875. * Set it to false if you want to manipulate the output or manually display
  876. * the code in an ordered list.
  877. *
  878. * @param boolean Wether multiline spans are allowed or not
  879. * @since 1.0.7.22
  880. */
  881. function enable_multiline_span($flag) {
  882. $this->allow_multiline_span = (bool) $flag;
  883. }
  884. /**
  885. * Get current setting for multiline spans, see GeSHi->enable_multiline_span().
  886. *
  887. * @see enable_multiline_span
  888. * @return bool
  889. */
  890. function get_multiline_span() {
  891. return $this->allow_multiline_span;
  892. }
  893. /**
  894. * Sets the style for a keyword group. If $preserve_defaults is
  895. * true, then styles are merged with the default styles, with the
  896. * user defined styles having priority
  897. *
  898. * @param int The key of the keyword group to change the styles of
  899. * @param string The style to make the keywords
  900. * @param boolean Whether to merge the new styles with the old or just
  901. * to overwrite them
  902. * @since 1.0.0
  903. */
  904. function set_keyword_group_style($key, $style, $preserve_defaults = false) {
  905. //Set the style for this keyword group
  906. if (!$preserve_defaults) {
  907. $this->language_data['STYLES']['KEYWORDS'][$key] = $style;
  908. } else {
  909. $this->language_data['STYLES']['KEYWORDS'][$key] .= $style;
  910. }
  911. //Update the lexic permissions
  912. if (!isset($this->lexic_permissions['KEYWORDS'][$key])) {
  913. $this->lexic_permissions['KEYWORDS'][$key] = true;
  914. }
  915. }
  916. /**
  917. * Turns highlighting on/off for a keyword group
  918. *
  919. * @param int The key of the keyword group to turn on or off
  920. * @param boolean Whether to turn highlighting for that group on or off
  921. * @since 1.0.0
  922. */
  923. function set_keyword_group_highlighting($key, $flag = true) {
  924. $this->lexic_permissions['KEYWORDS'][$key] = ($flag) ? true : false;
  925. }
  926. /**
  927. * Sets the styles for comment groups. If $preserve_defaults is
  928. * true, then styles are merged with the default styles, with the
  929. * user defined styles having priority
  930. *
  931. * @param int The key of the comment group to change the styles of
  932. * @param string The style to make the comments
  933. * @param boolean Whether to merge the new styles with the old or just
  934. * to overwrite them
  935. * @since 1.0.0
  936. */
  937. function set_comments_style($key, $style, $preserve_defaults = false) {
  938. if (!$preserve_defaults) {
  939. $this->language_data['STYLES']['COMMENTS'][$key] = $style;
  940. } else {
  941. $this->language_data['STYLES']['COMMENTS'][$key] .= $style;
  942. }
  943. }
  944. /**
  945. * Turns highlighting on/off for comment groups
  946. *
  947. * @param int The key of the comment group to turn on or off
  948. * @param boolean Whether to turn highlighting for that group on or off
  949. * @since 1.0.0
  950. */
  951. function set_comments_highlighting($key, $flag = true) {
  952. $this->lexic_permissions['COMMENTS'][$key] = ($flag) ? true : false;
  953. }
  954. /**
  955. * Sets the styles for escaped characters. If $preserve_defaults is
  956. * true, then styles are merged with the default styles, with the
  957. * user defined styles having priority
  958. *
  959. * @param string The style to make the escape characters
  960. * @param boolean Whether to merge the new styles with the old or just
  961. * to overwrite them
  962. * @since 1.0.0
  963. */
  964. function set_escape_characters_style($style, $preserve_defaults = false, $group = 0) {
  965. if (!$preserve_defaults) {
  966. $this->language_data['STYLES']['ESCAPE_CHAR'][$group] = $style;
  967. } else {
  968. $this->language_data['STYLES']['ESCAPE_CHAR'][$group] .= $style;
  969. }
  970. }
  971. /**
  972. * Turns highlighting on/off for escaped characters
  973. *
  974. * @param boolean Whether to turn highlighting for escape characters on or off
  975. * @since 1.0.0
  976. */
  977. function set_escape_characters_highlighting($flag = true) {
  978. $this->lexic_permissions['ESCAPE_CHAR'] = ($flag) ? true : false;
  979. }
  980. /**
  981. * Sets the styles for brackets. If $preserve_defaults is
  982. * true, then styles are merged with the default styles, with the
  983. * user defined styles having priority
  984. *
  985. * This method is DEPRECATED: use set_symbols_style instead.
  986. * This method will be removed in 1.2.X
  987. *
  988. * @param string The style to make the brackets
  989. * @param boolean Whether to merge the new styles with the old or just
  990. * to overwrite them
  991. * @since 1.0.0
  992. * @deprecated In favour of set_symbols_style
  993. */
  994. function set_brackets_style($style, $preserve_defaults = false) {
  995. if (!$preserve_defaults) {
  996. $this->language_data['STYLES']['BRACKETS'][0] = $style;
  997. } else {
  998. $this->language_data['STYLES']['BRACKETS'][0] .= $style;
  999. }
  1000. }
  1001. /**
  1002. * Turns highlighting on/off for brackets
  1003. *
  1004. * This method is DEPRECATED: use set_symbols_highlighting instead.
  1005. * This method will be remove in 1.2.X
  1006. *
  1007. * @param boolean Whether to turn highlighting for brackets on or off
  1008. * @since 1.0.0
  1009. * @deprecated In favour of set_symbols_highlighting
  1010. */
  1011. function set_brackets_highlighting($flag) {
  1012. $this->lexic_permissions['BRACKETS'] = ($flag) ? true : false;
  1013. }
  1014. /**
  1015. * Sets the styles for symbols. If $preserve_defaults is
  1016. * true, then styles are merged with the default styles, with the
  1017. * user defined styles having priority
  1018. *
  1019. * @param string The style to make the symbols
  1020. * @param boolean Whether to merge the new styles with the old or just
  1021. * to overwrite them
  1022. * @param int Tells the group of symbols for which style should be set.
  1023. * @since 1.0.1
  1024. */
  1025. function set_symbols_style($style, $preserve_defaults = false, $group = 0) {
  1026. // Update the style of symbols
  1027. if (!$preserve_defaults) {
  1028. $this->language_data['STYLES']['SYMBOLS'][$group] = $style;
  1029. } else {
  1030. $this->language_data['STYLES']['SYMBOLS'][$group] .= $style;
  1031. }
  1032. // For backward compatibility
  1033. if (0 == $group) {
  1034. $this->set_brackets_style ($style, $preserve_defaults);
  1035. }
  1036. }
  1037. /**
  1038. * Turns highlighting on/off for symbols
  1039. *
  1040. * @param boolean Whether to turn highlighting for symbols on or off
  1041. * @since 1.0.0
  1042. */
  1043. function set_symbols_highlighting($flag) {
  1044. // Update lexic permissions for this symbol group
  1045. $this->lexic_permissions['SYMBOLS'] = ($flag) ? true : false;
  1046. // For backward compatibility
  1047. $this->set_brackets_highlighting ($flag);
  1048. }
  1049. /**
  1050. * Sets the styles for strings. If $preserve_defaults is
  1051. * true, then styles are merged with the default styles, with the
  1052. * user defined styles having priority
  1053. *
  1054. * @param string The style to make the escape characters
  1055. * @param boolean Whether to merge the new styles with the old or just
  1056. * to overwrite them
  1057. * @param int Tells the group of strings for which style should be set.
  1058. * @since 1.0.0
  1059. */
  1060. function set_strings_style($style, $preserve_defaults = false, $group = 0) {
  1061. if (!$preserve_defaults) {
  1062. $this->language_data['STYLES']['STRINGS'][$group] = $style;
  1063. } else {
  1064. $this->language_data['STYLES']['STRINGS'][$group] .= $style;
  1065. }
  1066. }
  1067. /**
  1068. * Turns highlighting on/off for strings
  1069. *
  1070. * @param boolean Whether to turn highlighting for strings on or off
  1071. * @since 1.0.0
  1072. */
  1073. function set_strings_highlighting($flag) {
  1074. $this->lexic_permissions['STRINGS'] = ($flag) ? true : false;
  1075. }
  1076. /**
  1077. * Sets the styles for strict code blocks. If $preserve_defaults is
  1078. * true, then styles are merged with the default styles, with the
  1079. * user defined styles having priority
  1080. *
  1081. * @param string The style to make the script blocks
  1082. * @param boolean Whether to merge the new styles with the old or just
  1083. * to overwrite them
  1084. * @param int Tells the group of script blocks for which style should be set.
  1085. * @since 1.0.8.4
  1086. */
  1087. function set_script_style($style, $preserve_defaults = false, $group = 0) {
  1088. // Update the style of symbols
  1089. if (!$preserve_defaults) {
  1090. $this->language_data['STYLES']['SCRIPT'][$group] = $style;
  1091. } else {
  1092. $this->language_data['STYLES']['SCRIPT'][$group] .= $style;
  1093. }
  1094. }
  1095. /**
  1096. * Sets the styles for numbers. If $preserve_defaults is
  1097. * true, then styles are merged with the default styles, with the
  1098. * user defined styles having priority
  1099. *
  1100. * @param string The style to make the numbers
  1101. * @param boolean Whether to merge the new styles with the old or just
  1102. * to overwrite them
  1103. * @param int Tells the group of numbers for which style should be set.
  1104. * @since 1.0.0
  1105. */
  1106. function set_numbers_style($style, $preserve_defaults = false, $group = 0) {
  1107. if (!$preserve_defaults) {
  1108. $this->language_data['STYLES']['NUMBERS'][$group] = $style;
  1109. } else {
  1110. $this->language_data['STYLES']['NUMBERS'][$group] .= $style;
  1111. }
  1112. }
  1113. /**
  1114. * Turns highlighting on/off for numbers
  1115. *
  1116. * @param boolean Whether to turn highlighting for numbers on or off
  1117. * @since 1.0.0
  1118. */
  1119. function set_numbers_highlighting($flag) {
  1120. $this->lexic_permissions['NUMBERS'] = ($flag) ? true : false;
  1121. }
  1122. /**
  1123. * Sets the styles for methods. $key is a number that references the
  1124. * appropriate "object splitter" - see the language file for the language
  1125. * you are highlighting to get this number. If $preserve_defaults is
  1126. * true, then styles are merged with the default styles, with the
  1127. * user defined styles having priority
  1128. *
  1129. * @param int The key of the object splitter to change the styles of
  1130. * @param string The style to make the methods
  1131. * @param boolean Whether to merge the new styles with the old or just
  1132. * to overwrite them
  1133. * @since 1.0.0
  1134. */
  1135. function set_methods_style($key, $style, $preserve_defaults = false) {
  1136. if (!$preserve_defaults) {
  1137. $this->language_data['STYLES']['METHODS'][$key] = $style;
  1138. } else {
  1139. $this->language_data['STYLES']['METHODS'][$key] .= $style;
  1140. }
  1141. }
  1142. /**
  1143. * Turns highlighting on/off for methods
  1144. *
  1145. * @param boolean Whether to turn highlighting for methods on or off
  1146. * @since 1.0.0
  1147. */
  1148. function set_methods_highlighting($flag) {
  1149. $this->lexic_permissions['METHODS'] = ($flag) ? true : false;
  1150. }
  1151. /**
  1152. * Sets the styles for regexps. If $preserve_defaults is
  1153. * true, then styles are merged with the default styles, with the
  1154. * user defined styles having priority
  1155. *
  1156. * @param string The style to make the regular expression matches
  1157. * @param boolean Whether to merge the new styles with the old or just
  1158. * to overwrite them
  1159. * @since 1.0.0
  1160. */
  1161. function set_regexps_style($key, $style, $preserve_defaults = false) {
  1162. if (!$preserve_defaults) {
  1163. $this->language_data['STYLES']['REGEXPS'][$key] = $style;
  1164. } else {
  1165. $this->language_data['STYLES']['REGEXPS'][$key] .= $style;
  1166. }
  1167. }
  1168. /**
  1169. * Turns highlighting on/off for regexps
  1170. *
  1171. * @param int The key of the regular expression group to turn on or off
  1172. * @param boolean Whether to turn highlighting for the regular expression group on or off
  1173. * @since 1.0.0
  1174. */
  1175. function set_regexps_highlighting($key, $flag) {
  1176. $this->lexic_permissions['REGEXPS'][$key] = ($flag) ? true : false;
  1177. }
  1178. /**
  1179. * Sets whether a set of keywords are checked for in a case sensitive manner
  1180. *
  1181. * @param int The key of the keyword group to change the case sensitivity of
  1182. * @param boolean Whether to check in a case sensitive manner or not
  1183. * @since 1.0.0
  1184. */
  1185. function set_case_sensitivity($key, $case) {
  1186. $this->language_data['CASE_SENSITIVE'][$key] = ($case) ? true : false;
  1187. }
  1188. /**
  1189. * Sets the case that keywords should use when found. Use the constants:
  1190. *
  1191. * - GESHI_CAPS_NO_CHANGE: leave keywords as-is
  1192. * - GESHI_CAPS_UPPER: convert all keywords to uppercase where found
  1193. * - GESHI_CAPS_LOWER: convert all keywords to lowercase where found
  1194. *
  1195. * @param int A constant specifying what to do with matched keywords
  1196. * @since 1.0.1
  1197. */
  1198. function set_case_keywords($case) {
  1199. if (in_array($case, array(
  1200. GESHI_CAPS_NO_CHANGE, GESHI_CAPS_UPPER, GESHI_CAPS_LOWER))) {
  1201. $this->language_data['CASE_KEYWORDS'] = $case;
  1202. }
  1203. }
  1204. /**
  1205. * Sets how many spaces a tab is substituted for
  1206. *
  1207. * Widths below zero are ignored
  1208. *
  1209. * @param int The tab width
  1210. * @since 1.0.0
  1211. */
  1212. function set_tab_width($width) {
  1213. $this->tab_width = intval($width);
  1214. //Check if it fit's the constraints:
  1215. if ($this->tab_width < 1) {
  1216. //Return it to the default
  1217. $this->tab_width = 8;
  1218. }
  1219. }
  1220. /**
  1221. * Sets whether or not to use tab-stop width specifed by language
  1222. *
  1223. * @param boolean Whether to use language-specific tab-stop widths
  1224. * @since 1.0.7.20
  1225. */
  1226. function set_use_language_tab_width($use) {
  1227. $this->use_language_tab_width = (bool) $use;
  1228. }
  1229. /**
  1230. * Returns the tab width to use, based on the current language and user
  1231. * preference
  1232. *
  1233. * @return int Tab width
  1234. * @since 1.0.7.20
  1235. */
  1236. function get_real_tab_width() {
  1237. if (!$this->use_language_tab_width ||
  1238. !isset($this->language_data['TAB_WIDTH'])) {
  1239. return $this->tab_width;
  1240. } else {
  1241. return $this->language_data['TAB_WIDTH'];
  1242. }
  1243. }
  1244. /**
  1245. * Enables/disables strict highlighting. Default is off, calling this
  1246. * method without parameters will turn it on. See documentation
  1247. * for more details on strict mode and where to use it.
  1248. *
  1249. * @param boolean Whether to enable strict mode or not
  1250. * @since 1.0.0
  1251. */
  1252. function enable_strict_mode($mode = true) {
  1253. if (GESHI_MAYBE == $this->language_data['STRICT_MODE_APPLIES']) {
  1254. $this->strict_mode = ($mode) ? GESHI_ALWAYS : GESHI_NEVER;
  1255. }
  1256. }
  1257. /**
  1258. * Disables all highlighting
  1259. *
  1260. * @since 1.0.0
  1261. * @todo Rewrite with array traversal
  1262. * @deprecated In favour of enable_highlighting
  1263. */
  1264. function disable_highlighting() {
  1265. $this->enable_highlighting(false);
  1266. }
  1267. /**
  1268. * Enables all highlighting
  1269. *
  1270. * The optional flag parameter was added in version 1.0.7.21 and can be used
  1271. * to enable (true) or disable (false) all highlighting.
  1272. *
  1273. * @since 1.0.0
  1274. * @param boolean A flag specifying whether to enable or disable all highlighting
  1275. * @todo Rewrite with array traversal
  1276. */
  1277. function enable_highlighting($flag = true) {
  1278. $flag = $flag ? true : false;
  1279. foreach ($this->lexic_permissions as $key => $value) {
  1280. if (is_array($value)) {
  1281. foreach ($value as $k => $v) {
  1282. $this->lexic_permissions[$key][$k] = $flag;
  1283. }
  1284. } else {
  1285. $this->lexic_permissions[$key] = $flag;
  1286. }
  1287. }
  1288. // Context blocks
  1289. $this->enable_important_blocks = $flag;
  1290. }
  1291. /**
  1292. * Given a file extension, this method returns either a valid geshi language
  1293. * name, or the empty string if it couldn't be found
  1294. *
  1295. * @param string The extension to get a language name for
  1296. * @param array A lookup array to use instead of the default one
  1297. * @since 1.0.5
  1298. * @todo Re-think about how this method works (maybe make it private and/or make it
  1299. * a extension->lang lookup?)
  1300. * @todo static?
  1301. */
  1302. function get_language_name_from_extension( $extension, $lookup = array() ) {
  1303. if ( !is_array($lookup) || empty($lookup)) {
  1304. $lookup = array(
  1305. '6502acme' => array( 'a', 's', 'asm', 'inc' ),
  1306. '6502tasm' => array( 'a', 's', 'asm', 'inc' ),
  1307. '6502kickass' => array( 'a', 's', 'asm', 'inc' ),
  1308. '68000devpac' => array( 'a', 's', 'asm', 'inc' ),
  1309. 'abap' => array('abap'),
  1310. 'actionscript' => array('as'),
  1311. 'ada' => array('a', 'ada', 'adb', 'ads'),
  1312. 'apache' => array('conf'),
  1313. 'asm' => array('ash', 'asm', 'inc'),
  1314. 'asp' => array('asp'),
  1315. 'bash' => array('sh'),
  1316. 'bf' => array('bf'),
  1317. 'c' => array('c', 'h'),
  1318. 'c_mac' => array('c', 'h'),
  1319. 'caddcl' => array(),
  1320. 'cadlisp' => array(),
  1321. 'cdfg' => array('cdfg'),
  1322. 'cobol' => array('cbl'),
  1323. 'cpp' => array('cpp', 'hpp', 'C', 'H', 'CPP', 'HPP'),
  1324. 'csharp' => array('cs'),
  1325. 'css' => array('css'),
  1326. 'd' => array('d'),
  1327. 'delphi' => array('dpk', 'dpr', 'pp', 'pas'),
  1328. 'diff' => array('diff', 'patch'),
  1329. 'dos' => array('bat', 'cmd'),
  1330. 'gdb' => array('kcrash', 'crash', 'bt'),
  1331. 'gettext' => array('po', 'pot'),
  1332. 'gml' => array('gml'),
  1333. 'gnuplot' => array('plt'),
  1334. 'groovy' => array('groovy'),
  1335. 'haskell' => array('hs'),
  1336. 'html4strict' => array('html', 'htm'),
  1337. 'ini' => array('ini', 'desktop'),
  1338. 'java' => array('java'),
  1339. 'javascript' => array('js'),
  1340. 'klonec' => array('kl1'),
  1341. 'klonecpp' => array('klx'),
  1342. 'latex' => array('tex'),
  1343. 'lisp' => array('lisp'),
  1344. 'lua' => array('lua'),
  1345. 'matlab' => array('m'),
  1346. 'mpasm' => array(),
  1347. 'mysql' => array('sql'),
  1348. 'nsis' => array(),
  1349. 'objc' => array(),
  1350. 'oobas' => array(),
  1351. 'oracle8' => array(),
  1352. 'oracle10' => array(),
  1353. 'pascal' => array('pas'),
  1354. 'perl' => array('pl', 'pm'),
  1355. 'php' => array('php', 'php5', 'phtml', 'phps'),
  1356. 'povray' => array('pov'),
  1357. 'providex' => array('pvc', 'pvx'),
  1358. 'prolog' => array('pl'),
  1359. 'python' => array('py'),
  1360. 'qbasic' => array('bi'),
  1361. 'reg' => array('reg'),
  1362. 'ruby' => array('rb'),
  1363. 'sas' => array('sas'),
  1364. 'scala' => array('scala'),
  1365. 'scheme' => array('scm'),
  1366. 'scilab' => array('sci'),
  1367. 'smalltalk' => array('st'),
  1368. 'smarty' => array(),
  1369. 'tcl' => array('tcl'),
  1370. 'vb' => array('bas'),
  1371. 'vbnet' => array(),
  1372. 'visualfoxpro' => array(),
  1373. 'whitespace' => array('ws'),
  1374. 'xml' => array('xml', 'svg', 'xrc'),
  1375. 'z80' => array('z80', 'asm', 'inc')
  1376. );
  1377. }
  1378. foreach ($lookup as $lang => $extensions) {
  1379. if (in_array($extension, $extensions)) {
  1380. return $lang;
  1381. }
  1382. }
  1383. return '';
  1384. }
  1385. /**
  1386. * Given a file name, this method loads its contents in, and attempts
  1387. * to set the language automatically. An optional lookup table can be
  1388. * passed for looking up the language name. If not specified a default
  1389. * table is used
  1390. *
  1391. * The language table is in the form
  1392. * <pre>array(
  1393. * 'lang_name' => array('extension', 'extension', ...),
  1394. * 'lang_name' ...
  1395. * );</pre>
  1396. *
  1397. * @param string The filename to load the source from
  1398. * @param array A lookup array to use instead of the default one
  1399. * @todo Complete rethink of this and above method
  1400. * @since 1.0.5
  1401. */
  1402. function load_from_file($file_name, $lookup = array()) {
  1403. if (is_readable($file_name)) {
  1404. $this->set_source(file_get_contents($file_name));
  1405. $this->set_language($this->get_language_name_from_extension(substr(strrchr($file_name, '.'), 1), $lookup));
  1406. } else {
  1407. $this->error = GESHI_ERROR_FILE_NOT_READABLE;
  1408. }
  1409. }
  1410. /**
  1411. * Adds a keyword to a keyword group for highlighting
  1412. *
  1413. * @param int The key of the keyword group to add the keyword to
  1414. * @param string The word to add to the keyword group
  1415. * @since 1.0.0
  1416. */
  1417. function add_keyword($key, $word) {
  1418. if (!in_array($word, $this->language_data['KEYWORDS'][$key])) {
  1419. $this->language_data['KEYWORDS'][$key][] = $word;
  1420. //NEW in 1.0.8 don't recompile the whole optimized regexp, simply append it
  1421. if ($this->parse_cache_built) {
  1422. $subkey = count($this->language_data['CACHED_KEYWORD_LISTS'][$key]) - 1;
  1423. $this->language_data['CACHED_KEYWORD_LISTS'][$key][$subkey] .= '|' . preg_quote($word, '/');
  1424. }
  1425. }
  1426. }
  1427. /**
  1428. * Removes a keyword from a keyword group
  1429. *
  1430. * @param int The key of the keyword group to remove the keyword from
  1431. * @param string The word to remove from the keyword group
  1432. * @param bool Wether to automatically recompile the optimized regexp list or not.
  1433. * Note: if you set this to false and @see GeSHi->parse_code() was already called once,
  1434. * for the current language, you have to manually call @see GeSHi->optimize_keyword_group()
  1435. * or the removed keyword will stay in cache and still be highlighted! On the other hand
  1436. * it might be too expensive to recompile the regexp list for every removal if you want to
  1437. * remove a lot of keywords.
  1438. * @since 1.0.0
  1439. */
  1440. function remove_keyword($key, $word, $recompile = true) {
  1441. $key_to_remove = array_search($word, $this->language_data['KEYWORDS'][$key]);
  1442. if ($key_to_remove !== false) {
  1443. unset($this->language_data['KEYWORDS'][$key][$key_to_remove]);
  1444. //NEW in 1.0.8, optionally recompile keyword group
  1445. if ($recompile && $this->parse_cache_built) {
  1446. $this->optimize_keyword_group($key);
  1447. }
  1448. }
  1449. }
  1450. /**
  1451. * Creates a new keyword group
  1452. *
  1453. * @param int The key of the keyword group to create
  1454. * @param string The styles for the keyword group
  1455. * @param boolean Whether the keyword group is case sensitive ornot
  1456. * @param array The words to use for the keyword group
  1457. * @since 1.0.0
  1458. */
  1459. function add_keyword_group($key, $styles, $case_sensitive = true, $words = array()) {
  1460. $words = (array) $words;
  1461. if (empty($words)) {
  1462. // empty word lists mess up highlighting
  1463. return false;
  1464. }
  1465. //Add the new keyword group internally
  1466. $this->language_data['KEYWORDS'][$key] = $words;
  1467. $this->lexic_permissions['KEYWORDS'][$key] = true;
  1468. $this->language_data['CASE_SENSITIVE'][$key] = $case_sensitive;
  1469. $this->language_data['STYLES']['KEYWORDS'][$key] = $styles;
  1470. //NEW in 1.0.8, cache keyword regexp
  1471. if ($this->parse_cache_built) {
  1472. $this->optimize_keyword_group($key);
  1473. }
  1474. }
  1475. /**
  1476. * Removes a keyword group
  1477. *
  1478. * @param int The key of the keyword group to remove
  1479. * @since 1.0.0
  1480. */
  1481. function remove_keyword_group ($key) {
  1482. //Remove the keyword group internally
  1483. unset($this->language_data['KEYWORDS'][$key]);
  1484. unset($this->lexic_permissions['KEYWORDS'][$key]);
  1485. unset($this->language_data['CASE_SENSITIVE'][$key]);
  1486. unset($this->language_data['STYLES']['KEYWORDS'][$key]);
  1487. //NEW in 1.0.8
  1488. unset($this->language_data['CACHED_KEYWORD_LISTS'][$key]);
  1489. }
  1490. /**
  1491. * compile optimized regexp list for keyword group
  1492. *
  1493. * @param int The key of the keyword group to compile & optimize
  1494. * @since 1.0.8
  1495. */
  1496. function optimize_keyword_group($key) {
  1497. $this->language_data['CACHED_KEYWORD_LISTS'][$key] =
  1498. $this->optimize_regexp_list($this->language_data['KEYWORDS'][$key]);
  1499. $space_as_whitespace = false;
  1500. if(isset($this->language_data['PARSER_CONTROL'])) {
  1501. if(isset($this->language_data['PARSER_CONTROL']['KEYWORDS'])) {
  1502. if(isset($this->language_data['PARSER_CONTROL']['KEYWORDS']['SPACE_AS_WHITESPACE'])) {
  1503. $space_as_whitespace = $this->language_data['PARSER_CONTROL']['KEYWORDS']['SPACE_AS_WHITESPACE'];
  1504. }
  1505. if(isset($this->language_data['PARSER_CONTROL']['KEYWORDS'][$key]['SPACE_AS_WHITESPACE'])) {
  1506. if(isset($this->language_data['PARSER_CONTROL']['KEYWORDS'][$key]['SPACE_AS_WHITESPACE'])) {
  1507. $space_as_whitespace = $this->language_data['PARSER_CONTROL']['KEYWORDS'][$key]['SPACE_AS_WHITESPACE'];
  1508. }
  1509. }
  1510. }
  1511. }
  1512. if($space_as_whitespace) {
  1513. foreach($this->language_data['CACHED_KEYWORD_LISTS'][$key] as $rxk => $rxv) {
  1514. $this->language_data['CACHED_KEYWORD_LISTS'][$key][$rxk] =
  1515. str_replace(" ", "\\s+", $rxv);
  1516. }
  1517. }
  1518. }
  1519. /**
  1520. * Sets the content of the header block
  1521. *
  1522. * @param string The content of the header block
  1523. * @since 1.0.2
  1524. */
  1525. function set_header_content($content) {
  1526. $this->header_content = $content;
  1527. }
  1528. /**
  1529. * Sets the content of the footer block
  1530. *
  1531. * @param string The content of the footer block
  1532. * @since 1.0.2
  1533. */
  1534. function set_footer_content($content) {
  1535. $this->footer_content = $content;
  1536. }
  1537. /**
  1538. * Sets the style for the header content
  1539. *
  1540. * @param string The style for the header content
  1541. * @since 1.0.2
  1542. */
  1543. function set_header_content_style($style) {
  1544. $this->header_content_style = $style;
  1545. }
  1546. /**
  1547. * Sets the style for the footer content
  1548. *
  1549. * @param string The style for the footer content
  1550. * @since 1.0.2
  1551. */
  1552. function set_footer_content_style($style) {
  1553. $this->footer_content_style = $style;
  1554. }
  1555. /**
  1556. * Sets whether to force a surrounding block around
  1557. * the highlighted code or not
  1558. *
  1559. * @param boolean Tells whether to enable or disable this feature
  1560. * @since 1.0.7.20
  1561. */
  1562. function enable_inner_code_block($flag) {
  1563. $this->force_code_block = (bool)$flag;
  1564. }
  1565. /**
  1566. * Sets the base URL to be used for keywords
  1567. *
  1568. * @param int The key of the keyword group to set the URL for
  1569. * @param string The URL to set for the group. If {FNAME} is in
  1570. * the url somewhere, it is replaced by the keyword
  1571. * that the URL is being made for
  1572. * @since 1.0.2
  1573. */
  1574. function set_url_for_keyword_group($group, $url) {
  1575. $this->language_data['URLS'][$group] = $url;
  1576. }
  1577. /**
  1578. * Sets styles for links in code
  1579. *
  1580. * @param int A constant that specifies what state the style is being
  1581. * set for - e.g. :hover or :visited
  1582. * @param string The styles to use for that state
  1583. * @since 1.0.2
  1584. */
  1585. function set_link_styles($type, $styles) {
  1586. $this->link_styles[$type] = $styles;
  1587. }
  1588. /**
  1589. * Sets the target for links in code
  1590. *
  1591. * @param string The target for links in the code, e.g. _blank
  1592. * @since 1.0.3
  1593. */
  1594. function set_link_target($target) {
  1595. if (!$target) {
  1596. $this->link_target = '';
  1597. } else {
  1598. $this->link_target = ' target="' . $target . '"';
  1599. }
  1600. }
  1601. /**
  1602. * Sets styles for important parts of the code
  1603. *
  1604. * @param string The styles to use on important parts of the code
  1605. * @since 1.0.2
  1606. */
  1607. function set_important_styles($styles) {
  1608. $this->important_styles = $styles;
  1609. }
  1610. /**
  1611. * Sets whether context-important blocks are highlighted
  1612. *
  1613. * @param boolean Tells whether to enable or disable highlighting of important blocks
  1614. * @todo REMOVE THIS SHIZ FROM GESHI!
  1615. * @deprecated
  1616. * @since 1.0.2
  1617. */
  1618. function enable_important_blocks($flag) {
  1619. $this->enable_important_blocks = ( $flag ) ? true : false;
  1620. }
  1621. /**
  1622. * Whether CSS IDs should be added to each line
  1623. *
  1624. * @param boolean If true, IDs will be added to each line.
  1625. * @since 1.0.2
  1626. */
  1627. function enable_ids($flag = true) {
  1628. $this->add_ids = ($flag) ? true : false;
  1629. }
  1630. /**
  1631. * Specifies which lines to highlight extra
  1632. *
  1633. * The extra style parameter was added in 1.0.7.21.
  1634. *
  1635. * @param mixed An array of line numbers to highlight, or just a line
  1636. * number on its own.
  1637. * @param string A string specifying the style to use for this line.
  1638. * If null is specified, the default style is used.
  1639. * If false is specified, the line will be removed from
  1640. * special highlighting
  1641. * @since 1.0.2
  1642. * @todo Some data replication here that could be cut down on
  1643. */
  1644. function highlight_lines_extra($lines, $style = null) {
  1645. if (is_array($lines)) {
  1646. //Split up the job using single lines at a time
  1647. foreach ($lines as $line) {
  1648. $this->highlight_lines_extra($line, $style);
  1649. }
  1650. } else {
  1651. //Mark the line as being highlighted specially
  1652. $lines = intval($lines);
  1653. $this->highlight_extra_lines[$lines] = $lines;
  1654. //Decide on which style to use
  1655. if ($style === null) { //Check if we should use default style
  1656. unset($this->highlight_extra_lines_styles[$lines]);
  1657. } else if ($style === false) { //Check if to remove this line
  1658. unset($this->highlight_extra_lines[$lines]);
  1659. unset($this->highlight_extra_lines_styles[$lines]);
  1660. } else {
  1661. $this->highlight_extra_lines_styles[$lines] = $style;
  1662. }
  1663. }
  1664. }
  1665. /**
  1666. * Sets the style for extra-highlighted lines
  1667. *
  1668. * @param string The style for extra-highlighted lines
  1669. * @since 1.0.2
  1670. */
  1671. function set_highlight_lines_extra_style($styles) {
  1672. $this->highlight_extra_lines_style = $styles;
  1673. }
  1674. /**
  1675. * Sets the line-ending
  1676. *
  1677. * @param string The new line-ending
  1678. * @since 1.0.2
  1679. */
  1680. function set_line_ending($line_ending) {
  1681. $this->line_ending = (string)$line_ending;
  1682. }
  1683. /**
  1684. * Sets what number line numbers should start at. Should
  1685. * be a positive integer, and will be converted to one.
  1686. *
  1687. * <b>Warning:</b> Using this method will add the "start"
  1688. * attribute to the &lt;ol&gt; that is used for line numbering.
  1689. * This is <b>not</b> valid XHTML strict, so if that's what you
  1690. * care about then don't use this method. Firefox is getting
  1691. * support for the CSS method of doing this in 1.1 and Opera
  1692. * has support for the CSS method, but (of course) IE doesn't
  1693. * so it's not worth doing it the CSS way yet.
  1694. *
  1695. * @param int The number to start line numbers at
  1696. * @since 1.0.2
  1697. */
  1698. function start_line_numbers_at($number) {
  1699. $this->line_numbers_start = abs(intval($number));
  1700. }
  1701. /**
  1702. * Sets the encoding used for htmlspecialchars(), for international
  1703. * support.
  1704. *
  1705. * NOTE: This is not needed for now because htmlspecialchars() is not
  1706. * being used (it has a security hole in PHP4 that has not been patched).
  1707. * Maybe in a future version it may make a return for speed reasons, but
  1708. * I doubt it.
  1709. *
  1710. * @param string The encoding to use for the source
  1711. * @since 1.0.3
  1712. */
  1713. function set_encoding($encoding) {
  1714. if ($encoding) {
  1715. $this->encoding = strtolower($encoding);
  1716. }
  1717. }
  1718. /**
  1719. * Turns linking of keywords on or off.
  1720. *
  1721. * @param boolean If true, links will be added to keywords
  1722. * @since 1.0.2
  1723. */
  1724. function enable_keyword_links($enable = true) {
  1725. $this->keyword_links = (bool) $enable;
  1726. }
  1727. /**
  1728. * Setup caches needed for styling. This is automatically called in
  1729. * parse_code() and get_stylesheet() when appropriate. This function helps
  1730. * stylesheet generators as they rely on some style information being
  1731. * preprocessed
  1732. *
  1733. * @since 1.0.8
  1734. * @access private
  1735. */
  1736. function build_style_cache() {
  1737. //Build the style cache needed to highlight numbers appropriate
  1738. if($this->lexic_permissions['NUMBERS']) {
  1739. //First check what way highlighting information for numbers are given
  1740. if(!isset($this->language_data['NUMBERS'])) {
  1741. $this->language_data['NUMBERS'] = 0;
  1742. }
  1743. if(is_array($this->language_data['NUMBERS'])) {
  1744. $this->language_data['NUMBERS_CACHE'] = $this->language_data['NUMBERS'];
  1745. } else {
  1746. $this->language_data['NUMBERS_CACHE'] = array();
  1747. if(!$this->language_data['NUMBERS']) {
  1748. $this->language_data['NUMBERS'] =
  1749. GESHI_NUMBER_INT_BASIC |
  1750. GESHI_NUMBER_FLT_NONSCI;
  1751. }
  1752. for($i = 0, $j = $this->language_data['NUMBERS']; $j > 0; ++$i, $j>>=1) {
  1753. //Rearrange style indices if required ...
  1754. if(isset($this->language_data['STYLES']['NUMBERS'][1<<$i])) {
  1755. $this->language_data['STYLES']['NUMBERS'][$i] =
  1756. $this->language_data['STYLES']['NUMBERS'][1<<$i];
  1757. unset($this->language_data['STYLES']['NUMBERS'][1<<$i]);
  1758. }
  1759. //Check if this bit is set for highlighting
  1760. if($j&1) {
  1761. //So this bit is set ...
  1762. //Check if it belongs to group 0 or the actual stylegroup
  1763. if(isset($this->language_data['STYLES']['NUMBERS'][$i])) {
  1764. $this->language_data['NUMBERS_CACHE'][$i] = 1 << $i;
  1765. } else {
  1766. if(!isset($this->language_data['NUMBERS_CACHE'][0])) {
  1767. $this->language_data['NUMBERS_CACHE'][0] = 0;
  1768. }
  1769. $this->language_data['NUMBERS_CACHE'][0] |= 1 << $i;
  1770. }
  1771. }
  1772. }
  1773. }
  1774. }
  1775. }
  1776. /**
  1777. * Setup caches needed for parsing. This is automatically called in parse_code() when appropriate.
  1778. * This function makes stylesheet generators much faster as they do not need these caches.
  1779. *
  1780. * @since 1.0.8
  1781. * @access private
  1782. */
  1783. function build_parse_cache() {
  1784. // cache symbol regexp
  1785. //As this is a costy operation, we avoid doing it for multiple groups ...
  1786. //Instead we perform it for all symbols at once.
  1787. //
  1788. //For this to work, we need to reorganize the data arrays.
  1789. if ($this->lexic_permissions['SYMBOLS'] && !empty($this->language_data['SYMBOLS'])) {
  1790. $this->language_data['MULTIPLE_SYMBOL_GROUPS'] = count($this->language_data['STYLES']['SYMBOLS']) > 1;
  1791. $this->language_data['SYMBOL_DATA'] = array();
  1792. $symbol_preg_multi = array(); // multi char symbols
  1793. $symbol_preg_single = array(); // single char symbols
  1794. foreach ($this->language_data['SYMBOLS'] as $key => $symbols) {
  1795. if (is_array($symbols)) {
  1796. foreach ($symbols as $sym) {
  1797. $sym = $this->hsc($sym);
  1798. if (!isset($this->language_data['SYMBOL_DATA'][$sym])) {
  1799. $this->language_data['SYMBOL_DATA'][$sym] = $key;
  1800. if (isset($sym[1])) { // multiple chars
  1801. $symbol_preg_multi[] = preg_quote($sym, '/');
  1802. } else { // single char
  1803. if ($sym == '-') {
  1804. // don't trigger range out of order error
  1805. $symbol_preg_single[] = '\-';
  1806. } else {
  1807. $symbol_preg_single[] = preg_quote($sym, '/');
  1808. }
  1809. }
  1810. }
  1811. }
  1812. } else {
  1813. $symbols = $this->hsc($symbols);
  1814. if (!isset($this->language_data['SYMBOL_DATA'][$symbols])) {
  1815. $this->language_data['SYMBOL_DATA'][$symbols] = 0;
  1816. if (isset($symbols[1])) { // multiple chars
  1817. $symbol_preg_multi[] = preg_quote($symbols, '/');
  1818. } else if ($symbols == '-') {
  1819. // don't trigger range out of order error
  1820. $symbol_preg_single[] = '\-';
  1821. } else { // single char
  1822. $symbol_preg_single[] = preg_quote($symbols, '/');
  1823. }
  1824. }
  1825. }
  1826. }
  1827. //Now we have an array with each possible symbol as the key and the style as the actual data.
  1828. //This way we can set the correct style just the moment we highlight ...
  1829. //
  1830. //Now we need to rewrite our array to get a search string that
  1831. $symbol_preg = array();
  1832. if (!empty($symbol_preg_multi)) {
  1833. rsort($symbol_preg_multi);
  1834. $symbol_preg[] = implode('|', $symbol_preg_multi);
  1835. }
  1836. if (!empty($symbol_preg_single)) {
  1837. rsort($symbol_preg_single);
  1838. $symbol_preg[] = '[' . implode('', $symbol_preg_single) . ']';
  1839. }
  1840. $this->language_data['SYMBOL_SEARCH'] = implode("|", $symbol_preg);
  1841. }
  1842. // cache optimized regexp for keyword matching
  1843. // remove old cache
  1844. $this->language_data['CACHED_KEYWORD_LISTS'] = array();
  1845. foreach (array_keys($this->language_data['KEYWORDS']) as $key) {
  1846. if (!isset($this->lexic_permissions['KEYWORDS'][$key]) ||
  1847. $this->lexic_permissions['KEYWORDS'][$key]) {
  1848. $this->optimize_keyword_group($key);
  1849. }
  1850. }
  1851. // brackets
  1852. if ($this->lexic_permissions['BRACKETS']) {
  1853. $this->language_data['CACHE_BRACKET_MATCH'] = array('[', ']', '(', ')', '{', '}');
  1854. if (!$this->use_classes && isset($this->language_data['STYLES']['BRACKETS'][0])) {
  1855. $this->language_data['CACHE_BRACKET_REPLACE'] = array(
  1856. '<| style="' . $this->language_data['STYLES']['BRACKETS'][0] . '">&#91;|>',
  1857. '<| style="' . $this->language_data['STYLES']['BRACKETS'][0] . '">&#93;|>',
  1858. '<| style="' . $this->language_data['STYLES']['BRACKETS'][0] . '">&#40;|>',
  1859. '<| style="' . $this->language_data['STYLES']['BRACKETS'][0] . '">&#41;|>',
  1860. '<| style="' . $this->language_data['STYLES']['BRACKETS'][0] . '">&#123;|>',
  1861. '<| style="' . $this->language_data['STYLES']['BRACKETS'][0] . '">&#125;|>',
  1862. );
  1863. }
  1864. else {
  1865. $this->language_data['CACHE_BRACKET_REPLACE'] = array(
  1866. '<| class="br0">&#91;|>',
  1867. '<| class="br0">&#93;|>',
  1868. '<| class="br0">&#40;|>',
  1869. '<| class="br0">&#41;|>',
  1870. '<| class="br0">&#123;|>',
  1871. '<| class="br0">&#125;|>',
  1872. );
  1873. }
  1874. }
  1875. //Build the parse cache needed to highlight numbers appropriate
  1876. if($this->lexic_permissions['NUMBERS']) {
  1877. //Check if the style rearrangements have been processed ...
  1878. //This also does some preprocessing to check which style groups are useable ...
  1879. if(!isset($this->language_data['NUMBERS_CACHE'])) {
  1880. $this->build_style_cache();
  1881. }
  1882. //Number format specification
  1883. //All this formats are matched case-insensitively!
  1884. static $numbers_format = array(
  1885. GESHI_NUMBER_INT_BASIC =>
  1886. '(?:(?<![0-9a-z_\.%$@])|(?<=\.\.))(?<![\d\.]e[+\-])([1-9]\d*?|0)(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1887. GESHI_NUMBER_INT_CSTYLE =>
  1888. '(?<![0-9a-z_\.%])(?<![\d\.]e[+\-])([1-9]\d*?|0)l(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1889. GESHI_NUMBER_BIN_SUFFIX =>
  1890. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])[01]+?[bB](?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1891. GESHI_NUMBER_BIN_PREFIX_PERCENT =>
  1892. '(?<![0-9a-z_\.%])(?<![\d\.]e[+\-])%[01]+?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1893. GESHI_NUMBER_BIN_PREFIX_0B =>
  1894. '(?<![0-9a-z_\.%])(?<![\d\.]e[+\-])0b[01]+?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1895. GESHI_NUMBER_OCT_PREFIX =>
  1896. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])0[0-7]+?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1897. GESHI_NUMBER_OCT_PREFIX_0O =>
  1898. '(?<![0-9a-z_\.%])(?<![\d\.]e[+\-])0o[0-7]+?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1899. GESHI_NUMBER_OCT_PREFIX_AT =>
  1900. '(?<![0-9a-z_\.%])(?<![\d\.]e[+\-])\@[0-7]+?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1901. GESHI_NUMBER_OCT_SUFFIX =>
  1902. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])[0-7]+?o(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1903. GESHI_NUMBER_HEX_PREFIX =>
  1904. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])0x[0-9a-fA-F]+?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1905. GESHI_NUMBER_HEX_PREFIX_DOLLAR =>
  1906. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])\$[0-9a-fA-F]+?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1907. GESHI_NUMBER_HEX_SUFFIX =>
  1908. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])\d[0-9a-fA-F]*?[hH](?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1909. GESHI_NUMBER_FLT_NONSCI =>
  1910. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])\d+?\.\d+?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1911. GESHI_NUMBER_FLT_NONSCI_F =>
  1912. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])(?:\d+?(?:\.\d*?)?|\.\d+?)f(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1913. GESHI_NUMBER_FLT_SCI_SHORT =>
  1914. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])\.\d+?(?:e[+\-]?\d+?)?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)',
  1915. GESHI_NUMBER_FLT_SCI_ZERO =>
  1916. '(?<![0-9a-z_\.])(?<![\d\.]e[+\-])(?:\d+?(?:\.\d*?)?|\.\d+?)(?:e[+\-]?\d+?)?(?![0-9a-z]|\.(?:[eE][+\-]?)?\d)'
  1917. );
  1918. //At this step we have an associative array with flag groups for a
  1919. //specific style or an string denoting a regexp given its index.
  1920. $this->language_data['NUMBERS_RXCACHE'] = array();
  1921. foreach($this->language_data['NUMBERS_CACHE'] as $key => $rxdata) {
  1922. if(is_string($rxdata)) {
  1923. $regexp = $rxdata;
  1924. } else {
  1925. //This is a bitfield of number flags to highlight:
  1926. //Build an array, implode them together and make this the actual RX
  1927. $rxuse = array();
  1928. for($i = 1; $i <= $rxdata; $i<<=1) {
  1929. if($rxdata & $i) {
  1930. $rxuse[] = $numbers_format[$i];
  1931. }
  1932. }
  1933. $regexp = implode("|", $rxuse);
  1934. }
  1935. $this->language_data['NUMBERS_RXCACHE'][$key] =
  1936. "/(?<!<\|\/)(?<!<\|!REG3XP)(?<!<\|\/NUM!)(?<!\d\/>)($regexp)(?!(?:<DOT>|(?>[^\<]))+>)(?![^<]*>)(?!\|>)(?!\/>)/i"; //
  1937. }
  1938. if(!isset($this->language_data['PARSER_CONTROL']['NUMBERS']['PRECHECK_RX'])) {
  1939. $this->language_data['PARSER_CONTROL']['NUMBERS']['PRECHECK_RX'] = '#\d#';
  1940. }
  1941. }
  1942. $this->parse_cache_built = true;
  1943. }
  1944. /**
  1945. * Returns the code in $this->source, highlighted and surrounded by the
  1946. * nessecary HTML.
  1947. *
  1948. * This should only be called ONCE, cos it's SLOW! If you want to highlight
  1949. * the same source multiple times, you're better off doing a whole lot of
  1950. * str_replaces to replace the &lt;span&gt;s
  1951. *
  1952. * @since 1.0.0
  1953. */
  1954. function parse_code () {
  1955. // Start the timer
  1956. $start_time = microtime();
  1957. // Replace all newlines to a common form.
  1958. $code = str_replace("\r\n", "\n", $this->source);
  1959. $code = str_replace("\r", "\n", $code);
  1960. // Firstly, if there is an error, we won't highlight
  1961. if ($this->error) {
  1962. //Escape the source for output
  1963. $result = $this->hsc($this->source);
  1964. //This fix is related to SF#1923020, but has to be applied regardless of
  1965. //actually highlighting symbols.
  1966. $result = str_replace(array('<SEMI>', '<PIPE>'), array(';', '|'), $result);
  1967. // Timing is irrelevant
  1968. $this->set_time($start_time, $start_time);
  1969. $this->finalise($result);
  1970. return $result;
  1971. }
  1972. // make sure the parse cache is up2date
  1973. if (!$this->parse_cache_built) {
  1974. $this->build_parse_cache();
  1975. }
  1976. // Initialise various stuff
  1977. $length = strlen($code);
  1978. $COMMENT_MATCHED = false;
  1979. $stuff_to_parse = '';
  1980. $endresult = '';
  1981. // "Important" selections are handled like multiline comments
  1982. // @todo GET RID OF THIS SHIZ
  1983. if ($this->enable_important_blocks) {
  1984. $this->language_data['COMMENT_MULTI'][GESHI_START_IMPORTANT] = GESHI_END_IMPORTANT;
  1985. }
  1986. if ($this->strict_mode) {
  1987. // Break the source into bits. Each bit will be a portion of the code
  1988. // within script delimiters - for example, HTML between < and >
  1989. $k = 0;
  1990. $parts = array();
  1991. $matches = array();
  1992. $next_match_pointer = null;
  1993. // we use a copy to unset delimiters on demand (when they are not found)
  1994. $delim_copy = $this->language_data['SCRIPT_DELIMITERS'];
  1995. $i = 0;
  1996. while ($i < $length) {
  1997. $next_match_pos = $length + 1; // never true
  1998. foreach ($delim_copy as $dk => $delimiters) {
  1999. if(is_array($delimiters)) {
  2000. foreach ($delimiters as $open => $close) {
  2001. // make sure the cache is setup properly
  2002. if (!isset($matches[$dk][$open])) {
  2003. $matches[$dk][$open] = array(
  2004. 'next_match' => -1,
  2005. 'dk' => $dk,
  2006. 'open' => $open, // needed for grouping of adjacent code blocks (see below)
  2007. 'open_strlen' => strlen($open),
  2008. 'close' => $close,
  2009. 'close_strlen' => strlen($close),
  2010. );
  2011. }
  2012. // Get the next little bit for this opening string
  2013. if ($matches[$dk][$open]['next_match'] < $i) {
  2014. // only find the next pos if it was not already cached
  2015. $open_pos = strpos($code, $open, $i);
  2016. if ($open_pos === false) {
  2017. // no match for this delimiter ever
  2018. unset($delim_copy[$dk][$open]);
  2019. continue;
  2020. }
  2021. $matches[$dk][$open]['next_match'] = $open_pos;
  2022. }
  2023. if ($matches[$dk][$open]['next_match'] < $next_match_pos) {
  2024. //So we got a new match, update the close_pos
  2025. $matches[$dk][$open]['close_pos'] =
  2026. strpos($code, $close, $matches[$dk][$open]['next_match']+1);
  2027. $next_match_pointer =& $matches[$dk][$open];
  2028. $next_match_pos = $matches[$dk][$open]['next_match'];
  2029. }
  2030. }
  2031. } else {
  2032. //So we should match an RegExp as Strict Block ...
  2033. /**
  2034. * The value in $delimiters is expected to be an RegExp
  2035. * containing exactly 2 matching groups:
  2036. * - Group 1 is the opener
  2037. * - Group 2 is the closer
  2038. */
  2039. if(!GESHI_PHP_PRE_433 && //Needs proper rewrite to work with PHP >=4.3.0; 4.3.3 is guaranteed to work.
  2040. preg_match($delimiters, $code, $matches_rx, PREG_OFFSET_CAPTURE, $i)) {
  2041. //We got a match ...
  2042. if(isset($matches_rx['start']) && isset($matches_rx['end']))
  2043. {
  2044. $matches[$dk] = array(
  2045. 'next_match' => $matches_rx['start'][1],
  2046. 'dk' => $dk,
  2047. 'close_strlen' => strlen($matches_rx['end'][0]),
  2048. 'close_pos' => $matches_rx['end'][1],
  2049. );
  2050. } else {
  2051. $matches[$dk] = array(
  2052. 'next_match' => $matches_rx[1][1],
  2053. 'dk' => $dk,
  2054. 'close_strlen' => strlen($matches_rx[2][0]),
  2055. 'close_pos' => $matches_rx[2][1],
  2056. );
  2057. }
  2058. } else {
  2059. // no match for this delimiter ever
  2060. unset($delim_copy[$dk]);
  2061. continue;
  2062. }
  2063. if ($matches[$dk]['next_match'] <= $next_match_pos) {
  2064. $next_match_pointer =& $matches[$dk];
  2065. $next_match_pos = $matches[$dk]['next_match'];
  2066. }
  2067. }
  2068. }
  2069. // non-highlightable text
  2070. $parts[$k] = array(
  2071. 1 => substr($code, $i, $next_match_pos - $i)
  2072. );
  2073. ++$k;
  2074. if ($next_match_pos > $length) {
  2075. // out of bounds means no next match was found
  2076. break;
  2077. }
  2078. // highlightable code
  2079. $parts[$k][0] = $next_match_pointer['dk'];
  2080. //Only combine for non-rx script blocks
  2081. if(is_array($delim_copy[$next_match_pointer['dk']])) {
  2082. // group adjacent script blocks, e.g. <foobar><asdf> should be one block, not three!
  2083. $i = $next_match_pos + $next_match_pointer['open_strlen'];
  2084. while (true) {
  2085. $close_pos = strpos($code, $next_match_pointer['close'], $i);
  2086. if ($close_pos == false) {
  2087. break;
  2088. }
  2089. $i = $close_pos + $next_match_pointer['close_strlen'];
  2090. if ($i == $length) {
  2091. break;
  2092. }
  2093. if ($code[$i] == $next_match_pointer['open'][0] && ($next_match_pointer['open_strlen'] == 1 ||
  2094. substr($code, $i, $next_match_pointer['open_strlen']) == $next_match_pointer['open'])) {
  2095. // merge adjacent but make sure we don't merge things like <tag><!-- comment -->
  2096. foreach ($matches as $submatches) {
  2097. foreach ($submatches as $match) {
  2098. if ($match['next_match'] == $i) {
  2099. // a different block already matches here!
  2100. break 3;
  2101. }
  2102. }
  2103. }
  2104. } else {
  2105. break;
  2106. }
  2107. }
  2108. } else {
  2109. $close_pos = $next_match_pointer['close_pos'] + $next_match_pointer['close_strlen'];
  2110. $i = $close_pos;
  2111. }
  2112. if ($close_pos === false) {
  2113. // no closing delimiter found!
  2114. $parts[$k][1] = substr($code, $next_match_pos);
  2115. ++$k;
  2116. break;
  2117. } else {
  2118. $parts[$k][1] = substr($code, $next_match_pos, $i - $next_match_pos);
  2119. ++$k;
  2120. }
  2121. }
  2122. unset($delim_copy, $next_match_pointer, $next_match_pos, $matches);
  2123. $num_parts = $k;
  2124. if ($num_parts == 1 && $this->strict_mode == GESHI_MAYBE) {
  2125. // when we have only one part, we don't have anything to highlight at all.
  2126. // if we have a "maybe" strict language, this should be handled as highlightable code
  2127. $parts = array(
  2128. 0 => array(
  2129. 0 => '',
  2130. 1 => ''
  2131. ),
  2132. 1 => array(
  2133. 0 => null,
  2134. 1 => $parts[0][1]
  2135. )
  2136. );
  2137. $num_parts = 2;
  2138. }
  2139. } else {
  2140. // Not strict mode - simply dump the source into
  2141. // the array at index 1 (the first highlightable block)
  2142. $parts = array(
  2143. 0 => array(
  2144. 0 => '',
  2145. 1 => ''
  2146. ),
  2147. 1 => array(
  2148. 0 => null,
  2149. 1 => $code
  2150. )
  2151. );
  2152. $num_parts = 2;
  2153. }
  2154. //Unset variables we won't need any longer
  2155. unset($code);
  2156. //Preload some repeatedly used values regarding hardquotes ...
  2157. $hq = isset($this->language_data['HARDQUOTE']) ? $this->language_data['HARDQUOTE'][0] : false;
  2158. $hq_strlen = strlen($hq);
  2159. //Preload if line numbers are to be generated afterwards
  2160. //Added a check if line breaks should be forced even without line numbers, fixes SF#1727398
  2161. $check_linenumbers = $this->line_numbers != GESHI_NO_LINE_NUMBERS ||
  2162. !empty($this->highlight_extra_lines) || !$this->allow_multiline_span;
  2163. //preload the escape char for faster checking ...
  2164. $escaped_escape_char = $this->hsc($this->language_data['ESCAPE_CHAR']);
  2165. // this is used for single-line comments
  2166. $sc_disallowed_before = "";
  2167. $sc_disallowed_after = "";
  2168. if (isset($this->language_data['PARSER_CONTROL'])) {
  2169. if (isset($this->language_data['PARSER_CONTROL']['COMMENTS'])) {
  2170. if (isset($this->language_data['PARSER_CONTROL']['COMMENTS']['DISALLOWED_BEFORE'])) {
  2171. $sc_disallowed_before = $this->language_data['PARSER_CONTROL']['COMMENTS']['DISALLOWED_BEFORE'];
  2172. }
  2173. if (isset($this->language_data['PARSER_CONTROL']['COMMENTS']['DISALLOWED_AFTER'])) {
  2174. $sc_disallowed_after = $this->language_data['PARSER_CONTROL']['COMMENTS']['DISALLOWED_AFTER'];
  2175. }
  2176. }
  2177. }
  2178. //Fix for SF#1932083: Multichar Quotemarks unsupported
  2179. $is_string_starter = array();
  2180. if ($this->lexic_permissions['STRINGS']) {
  2181. foreach ($this->language_data['QUOTEMARKS'] as $quotemark) {
  2182. if (!isset($is_string_starter[$quotemark[0]])) {
  2183. $is_string_starter[$quotemark[0]] = (string)$quotemark;
  2184. } else if (is_string($is_string_starter[$quotemark[0]])) {
  2185. $is_string_starter[$quotemark[0]] = array(
  2186. $is_string_starter[$quotemark[0]],
  2187. $quotemark);
  2188. } else {
  2189. $is_string_starter[$quotemark[0]][] = $quotemark;
  2190. }
  2191. }
  2192. }
  2193. // Now we go through each part. We know that even-indexed parts are
  2194. // code that shouldn't be highlighted, and odd-indexed parts should
  2195. // be highlighted
  2196. for ($key = 0; $key < $num_parts; ++$key) {
  2197. $STRICTATTRS = '';
  2198. // If this block should be highlighted...
  2199. if (!($key & 1)) {
  2200. // Else not a block to highlight
  2201. $endresult .= $this->hsc($parts[$key][1]);
  2202. unset($parts[$key]);
  2203. continue;
  2204. }
  2205. $result = '';
  2206. $part = $parts[$key][1];
  2207. $highlight_part = true;
  2208. if ($this->strict_mode && !is_null($parts[$key][0])) {
  2209. // get the class key for this block of code
  2210. $script_key = $parts[$key][0];
  2211. $highlight_part = $this->language_data['HIGHLIGHT_STRICT_BLOCK'][$script_key];
  2212. if ($this->language_data['STYLES']['SCRIPT'][$script_key] != '' &&
  2213. $this->lexic_permissions['SCRIPT']) {
  2214. // Add a span element around the source to
  2215. // highlight the overall source block
  2216. if (!$this->use_classes &&
  2217. $this->language_data['STYLES']['SCRIPT'][$script_key] != '') {
  2218. $attributes = ' style="' . $this->language_data['STYLES']['SCRIPT'][$script_key] . '"';
  2219. } else {
  2220. $attributes = ' class="sc' . $script_key . '"';
  2221. }
  2222. $result .= "<span$attributes>";
  2223. $STRICTATTRS = $attributes;
  2224. }
  2225. }
  2226. if ($highlight_part) {
  2227. // Now, highlight the code in this block. This code
  2228. // is really the engine of GeSHi (along with the method
  2229. // parse_non_string_part).
  2230. // cache comment regexps incrementally
  2231. $next_comment_regexp_key = '';
  2232. $next_comment_regexp_pos = -1;
  2233. $next_comment_multi_pos = -1;
  2234. $next_comment_single_pos = -1;
  2235. $comment_regexp_cache_per_key = array();
  2236. $comment_multi_cache_per_key = array();
  2237. $comment_single_cache_per_key = array();
  2238. $next_open_comment_multi = '';
  2239. $next_comment_single_key = '';
  2240. $escape_regexp_cache_per_key = array();
  2241. $next_escape_regexp_key = '';
  2242. $next_escape_regexp_pos = -1;
  2243. $length = strlen($part);
  2244. for ($i = 0; $i < $length; ++$i) {
  2245. // Get the next char
  2246. $char = $part[$i];
  2247. $char_len = 1;
  2248. // update regexp comment cache if needed
  2249. if (isset($this->language_data['COMMENT_REGEXP']) && $next_comment_regexp_pos < $i) {
  2250. $next_comment_regexp_pos = $length;
  2251. foreach ($this->language_data['COMMENT_REGEXP'] as $comment_key => $regexp) {
  2252. $match_i = false;
  2253. if (isset($comment_regexp_cache_per_key[$comment_key]) &&
  2254. ($comment_regexp_cache_per_key[$comment_key]['pos'] >= $i ||
  2255. $comment_regexp_cache_per_key[$comment_key]['pos'] === false)) {
  2256. // we have already matched something
  2257. if ($comment_regexp_cache_per_key[$comment_key]['pos'] === false) {
  2258. // this comment is never matched
  2259. continue;
  2260. }
  2261. $match_i = $comment_regexp_cache_per_key[$comment_key]['pos'];
  2262. } else if (
  2263. //This is to allow use of the offset parameter in preg_match and stay as compatible with older PHP versions as possible
  2264. (GESHI_PHP_PRE_433 && preg_match($regexp, substr($part, $i), $match, PREG_OFFSET_CAPTURE)) ||
  2265. (!GESHI_PHP_PRE_433 && preg_match($regexp, $part, $match, PREG_OFFSET_CAPTURE, $i))
  2266. ) {
  2267. $match_i = $match[0][1];
  2268. if (GESHI_PHP_PRE_433) {
  2269. $match_i += $i;
  2270. }
  2271. $comment_regexp_cache_per_key[$comment_key] = array(
  2272. 'key' => $comment_key,
  2273. 'length' => strlen($match[0][0]),
  2274. 'pos' => $match_i
  2275. );
  2276. } else {
  2277. $comment_regexp_cache_per_key[$comment_key]['pos'] = false;
  2278. continue;
  2279. }
  2280. if ($match_i !== false && $match_i < $next_comment_regexp_pos) {
  2281. $next_comment_regexp_pos = $match_i;
  2282. $next_comment_regexp_key = $comment_key;
  2283. if ($match_i === $i) {
  2284. break;
  2285. }
  2286. }
  2287. }
  2288. }
  2289. $string_started = false;
  2290. if (isset($is_string_starter[$char])) {
  2291. // Possibly the start of a new string ...
  2292. //Check which starter it was ...
  2293. //Fix for SF#1932083: Multichar Quotemarks unsupported
  2294. if (is_array($is_string_starter[$char])) {
  2295. $char_new = '';
  2296. foreach ($is_string_starter[$char] as $testchar) {
  2297. if ($testchar === substr($part, $i, strlen($testchar)) &&
  2298. strlen($testchar) > strlen($char_new)) {
  2299. $char_new = $testchar;
  2300. $string_started = true;
  2301. }
  2302. }
  2303. if ($string_started) {
  2304. $char = $char_new;
  2305. }
  2306. } else {
  2307. $testchar = $is_string_starter[$char];
  2308. if ($testchar === substr($part, $i, strlen($testchar))) {
  2309. $char = $testchar;
  2310. $string_started = true;
  2311. }
  2312. }
  2313. $char_len = strlen($char);
  2314. }
  2315. if ($string_started && ($i != $next_comment_regexp_pos)) {
  2316. // Hand out the correct style information for this string
  2317. $string_key = array_search($char, $this->language_data['QUOTEMARKS']);
  2318. if (!isset($this->language_data['STYLES']['STRINGS'][$string_key]) ||
  2319. !isset($this->language_data['STYLES']['ESCAPE_CHAR'][$string_key])) {
  2320. $string_key = 0;
  2321. }
  2322. // parse the stuff before this
  2323. $result .= $this->parse_non_string_part($stuff_to_parse);
  2324. $stuff_to_parse = '';
  2325. if (!$this->use_classes) {
  2326. $string_attributes = ' style="' . $this->language_data['STYLES']['STRINGS'][$string_key] . '"';
  2327. } else {
  2328. $string_attributes = ' class="st'.$string_key.'"';
  2329. }
  2330. // now handle the string
  2331. $string = "<span$string_attributes>" . GeSHi::hsc($char);
  2332. $start = $i + $char_len;
  2333. $string_open = true;
  2334. if(empty($this->language_data['ESCAPE_REGEXP'])) {
  2335. $next_escape_regexp_pos = $length;
  2336. }
  2337. do {
  2338. //Get the regular ending pos ...
  2339. $close_pos = strpos($part, $char, $start);
  2340. if(false === $close_pos) {
  2341. $close_pos = $length;
  2342. }
  2343. if($this->lexic_permissions['ESCAPE_CHAR']) {
  2344. // update escape regexp cache if needed
  2345. if (isset($this->language_data['ESCAPE_REGEXP']) && $next_escape_regexp_pos < $start) {
  2346. $next_escape_regexp_pos = $length;
  2347. foreach ($this->language_data['ESCAPE_REGEXP'] as $escape_key => $regexp) {
  2348. $match_i = false;
  2349. if (isset($escape_regexp_cache_per_key[$escape_key]) &&
  2350. ($escape_regexp_cache_per_key[$escape_key]['pos'] >= $start ||
  2351. $escape_regexp_cache_per_key[$escape_key]['pos'] === false)) {
  2352. // we have already matched something
  2353. if ($escape_regexp_cache_per_key[$escape_key]['pos'] === false) {
  2354. // this comment is never matched
  2355. continue;
  2356. }
  2357. $match_i = $escape_regexp_cache_per_key[$escape_key]['pos'];
  2358. } else if (
  2359. //This is to allow use of the offset parameter in preg_match and stay as compatible with older PHP versions as possible
  2360. (GESHI_PHP_PRE_433 && preg_match($regexp, substr($part, $start), $match, PREG_OFFSET_CAPTURE)) ||
  2361. (!GESHI_PHP_PRE_433 && preg_match($regexp, $part, $match, PREG_OFFSET_CAPTURE, $start))
  2362. ) {
  2363. $match_i = $match[0][1];
  2364. if (GESHI_PHP_PRE_433) {
  2365. $match_i += $start;
  2366. }
  2367. $escape_regexp_cache_per_key[$escape_key] = array(
  2368. 'key' => $escape_key,
  2369. 'length' => strlen($match[0][0]),
  2370. 'pos' => $match_i
  2371. );
  2372. } else {
  2373. $escape_regexp_cache_per_key[$escape_key]['pos'] = false;
  2374. continue;
  2375. }
  2376. if ($match_i !== false && $match_i < $next_escape_regexp_pos) {
  2377. $next_escape_regexp_pos = $match_i;
  2378. $next_escape_regexp_key = $escape_key;
  2379. if ($match_i === $start) {
  2380. break;
  2381. }
  2382. }
  2383. }
  2384. }
  2385. //Find the next simple escape position
  2386. if('' != $this->language_data['ESCAPE_CHAR']) {
  2387. $simple_escape = strpos($part, $this->language_data['ESCAPE_CHAR'], $start);
  2388. if(false === $simple_escape) {
  2389. $simple_escape = $length;
  2390. }
  2391. } else {
  2392. $simple_escape = $length;
  2393. }
  2394. } else {
  2395. $next_escape_regexp_pos = $length;
  2396. $simple_escape = $length;
  2397. }
  2398. if($simple_escape < $next_escape_regexp_pos &&
  2399. $simple_escape < $length &&
  2400. $simple_escape < $close_pos) {
  2401. //The nexxt escape sequence is a simple one ...
  2402. $es_pos = $simple_escape;
  2403. //Add the stuff not in the string yet ...
  2404. $string .= $this->hsc(substr($part, $start, $es_pos - $start));
  2405. //Get the style for this escaped char ...
  2406. if (!$this->use_classes) {
  2407. $escape_char_attributes = ' style="' . $this->language_data['STYLES']['ESCAPE_CHAR'][0] . '"';
  2408. } else {
  2409. $escape_char_attributes = ' class="es0"';
  2410. }
  2411. //Add the style for the escape char ...
  2412. $string .= "<span$escape_char_attributes>" .
  2413. GeSHi::hsc($this->language_data['ESCAPE_CHAR']);
  2414. //Get the byte AFTER the ESCAPE_CHAR we just found
  2415. $es_char = $part[$es_pos + 1];
  2416. if ($es_char == "\n") {
  2417. // don't put a newline around newlines
  2418. $string .= "</span>\n";
  2419. $start = $es_pos + 2;
  2420. } else if (ord($es_char) >= 128) {
  2421. //This is an non-ASCII char (UTF8 or single byte)
  2422. //This code tries to work around SF#2037598 ...
  2423. if(function_exists('mb_substr')) {
  2424. $es_char_m = mb_substr(substr($part, $es_pos+1, 16), 0, 1, $this->encoding);
  2425. $string .= $es_char_m . '</span>';
  2426. } else if (!GESHI_PHP_PRE_433 && 'utf-8' == $this->encoding) {
  2427. if(preg_match("/[\xC2-\xDF][\x80-\xBF]".
  2428. "|\xE0[\xA0-\xBF][\x80-\xBF]".
  2429. "|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}".
  2430. "|\xED[\x80-\x9F][\x80-\xBF]".
  2431. "|\xF0[\x90-\xBF][\x80-\xBF]{2}".
  2432. "|[\xF1-\xF3][\x80-\xBF]{3}".
  2433. "|\xF4[\x80-\x8F][\x80-\xBF]{2}/s",
  2434. $part, $es_char_m, null, $es_pos + 1)) {
  2435. $es_char_m = $es_char_m[0];
  2436. } else {
  2437. $es_char_m = $es_char;
  2438. }
  2439. $string .= $this->hsc($es_char_m) . '</span>';
  2440. } else {
  2441. $es_char_m = $this->hsc($es_char);
  2442. }
  2443. $start = $es_pos + strlen($es_char_m) + 1;
  2444. } else {
  2445. $string .= $this->hsc($es_char) . '</span>';
  2446. $start = $es_pos + 2;
  2447. }
  2448. } else if ($next_escape_regexp_pos < $length &&
  2449. $next_escape_regexp_pos < $close_pos) {
  2450. $es_pos = $next_escape_regexp_pos;
  2451. //Add the stuff not in the string yet ...
  2452. $string .= $this->hsc(substr($part, $start, $es_pos - $start));
  2453. //Get the key and length of this match ...
  2454. $escape = $escape_regexp_cache_per_key[$next_escape_regexp_key];
  2455. $escape_str = substr($part, $es_pos, $escape['length']);
  2456. $escape_key = $escape['key'];
  2457. //Get the style for this escaped char ...
  2458. if (!$this->use_classes) {
  2459. $escape_char_attributes = ' style="' . $this->language_data['STYLES']['ESCAPE_CHAR'][$escape_key] . '"';
  2460. } else {
  2461. $escape_char_attributes = ' class="es' . $escape_key . '"';
  2462. }
  2463. //Add the style for the escape char ...
  2464. $string .= "<span$escape_char_attributes>" .
  2465. $this->hsc($escape_str) . '</span>';
  2466. $start = $es_pos + $escape['length'];
  2467. } else {
  2468. //Copy the remainder of the string ...
  2469. $string .= $this->hsc(substr($part, $start, $close_pos - $start + $char_len)) . '</span>';
  2470. $start = $close_pos + $char_len;
  2471. $string_open = false;
  2472. }
  2473. } while($string_open);
  2474. if ($check_linenumbers) {
  2475. // Are line numbers used? If, we should end the string before
  2476. // the newline and begin it again (so when <li>s are put in the source
  2477. // remains XHTML compliant)
  2478. // note to self: This opens up possibility of config files specifying
  2479. // that languages can/cannot have multiline strings???
  2480. $string = str_replace("\n", "</span>\n<span$string_attributes>", $string);
  2481. }
  2482. $result .= $string;
  2483. $string = '';
  2484. $i = $start - 1;
  2485. continue;
  2486. } else if ($this->lexic_permissions['STRINGS'] && $hq && $hq[0] == $char &&
  2487. substr($part, $i, $hq_strlen) == $hq && ($i != $next_comment_regexp_pos)) {
  2488. // The start of a hard quoted string
  2489. if (!$this->use_classes) {
  2490. $string_attributes = ' style="' . $this->language_data['STYLES']['STRINGS']['HARD'] . '"';
  2491. $escape_char_attributes = ' style="' . $this->language_data['STYLES']['ESCAPE_CHAR']['HARD'] . '"';
  2492. } else {
  2493. $string_attributes = ' class="st_h"';
  2494. $escape_char_attributes = ' class="es_h"';
  2495. }
  2496. // parse the stuff before this
  2497. $result .= $this->parse_non_string_part($stuff_to_parse);
  2498. $stuff_to_parse = '';
  2499. // now handle the string
  2500. $string = '';
  2501. // look for closing quote
  2502. $start = $i + $hq_strlen;
  2503. while ($close_pos = strpos($part, $this->language_data['HARDQUOTE'][1], $start)) {
  2504. $start = $close_pos + 1;
  2505. if ($this->lexic_permissions['ESCAPE_CHAR'] && $part[$close_pos - 1] == $this->language_data['HARDCHAR'] &&
  2506. (($i + $hq_strlen) != ($close_pos))) { //Support empty string for HQ escapes if Starter = Escape
  2507. // make sure this quote is not escaped
  2508. foreach ($this->language_data['HARDESCAPE'] as $hardescape) {
  2509. if (substr($part, $close_pos - 1, strlen($hardescape)) == $hardescape) {
  2510. // check wether this quote is escaped or if it is something like '\\'
  2511. $escape_char_pos = $close_pos - 1;
  2512. while ($escape_char_pos > 0
  2513. && $part[$escape_char_pos - 1] == $this->language_data['HARDCHAR']) {
  2514. --$escape_char_pos;
  2515. }
  2516. if (($close_pos - $escape_char_pos) & 1) {
  2517. // uneven number of escape chars => this quote is escaped
  2518. continue 2;
  2519. }
  2520. }
  2521. }
  2522. }
  2523. // found closing quote
  2524. break;
  2525. }
  2526. //Found the closing delimiter?
  2527. if (!$close_pos) {
  2528. // span till the end of this $part when no closing delimiter is found
  2529. $close_pos = $length;
  2530. }
  2531. //Get the actual string
  2532. $string = substr($part, $i, $close_pos - $i + 1);
  2533. $i = $close_pos;
  2534. // handle escape chars and encode html chars
  2535. // (special because when we have escape chars within our string they may not be escaped)
  2536. if ($this->lexic_permissions['ESCAPE_CHAR'] && $this->language_data['ESCAPE_CHAR']) {
  2537. $start = 0;
  2538. $new_string = '';
  2539. while ($es_pos = strpos($string, $this->language_data['ESCAPE_CHAR'], $start)) {
  2540. // hmtl escape stuff before
  2541. $new_string .= $this->hsc(substr($string, $start, $es_pos - $start));
  2542. // check if this is a hard escape
  2543. foreach ($this->language_data['HARDESCAPE'] as $hardescape) {
  2544. if (substr($string, $es_pos, strlen($hardescape)) == $hardescape) {
  2545. // indeed, this is a hardescape
  2546. $new_string .= "<span$escape_char_attributes>" .
  2547. $this->hsc($hardescape) . '</span>';
  2548. $start = $es_pos + strlen($hardescape);
  2549. continue 2;
  2550. }
  2551. }
  2552. // not a hard escape, but a normal escape
  2553. // they come in pairs of two
  2554. $c = 0;
  2555. while (isset($string[$es_pos + $c]) && isset($string[$es_pos + $c + 1])
  2556. && $string[$es_pos + $c] == $this->language_data['ESCAPE_CHAR']
  2557. && $string[$es_pos + $c + 1] == $this->language_data['ESCAPE_CHAR']) {
  2558. $c += 2;
  2559. }
  2560. if ($c) {
  2561. $new_string .= "<span$escape_char_attributes>" .
  2562. str_repeat($escaped_escape_char, $c) .
  2563. '</span>';
  2564. $start = $es_pos + $c;
  2565. } else {
  2566. // this is just a single lonely escape char...
  2567. $new_string .= $escaped_escape_char;
  2568. $start = $es_pos + 1;
  2569. }
  2570. }
  2571. $string = $new_string . $this->hsc(substr($string, $start));
  2572. } else {
  2573. $string = $this->hsc($string);
  2574. }
  2575. if ($check_linenumbers) {
  2576. // Are line numbers used? If, we should end the string before
  2577. // the newline and begin it again (so when <li>s are put in the source
  2578. // remains XHTML compliant)
  2579. // note to self: This opens up possibility of config files specifying
  2580. // that languages can/cannot have multiline strings???
  2581. $string = str_replace("\n", "</span>\n<span$string_attributes>", $string);
  2582. }
  2583. $result .= "<span$string_attributes>" . $string . '</span>';
  2584. $string = '';
  2585. continue;
  2586. } else {
  2587. //Have a look for regexp comments
  2588. if ($i == $next_comment_regexp_pos) {
  2589. $COMMENT_MATCHED = true;
  2590. $comment = $comment_regexp_cache_per_key[$next_comment_regexp_key];
  2591. $test_str = $this->hsc(substr($part, $i, $comment['length']));
  2592. //@todo If remove important do remove here
  2593. if ($this->lexic_permissions['COMMENTS']['MULTI']) {
  2594. if (!$this->use_classes) {
  2595. $attributes = ' style="' . $this->language_data['STYLES']['COMMENTS'][$comment['key']] . '"';
  2596. } else {
  2597. $attributes = ' class="co' . $comment['key'] . '"';
  2598. }
  2599. $test_str = "<span$attributes>" . $test_str . "</span>";
  2600. // Short-cut through all the multiline code
  2601. if ($check_linenumbers) {
  2602. // strreplace to put close span and open span around multiline newlines
  2603. $test_str = str_replace(
  2604. "\n", "</span>\n<span$attributes>",
  2605. str_replace("\n ", "\n&nbsp;", $test_str)
  2606. );
  2607. }
  2608. }
  2609. $i += $comment['length'] - 1;
  2610. // parse the rest
  2611. $result .= $this->parse_non_string_part($stuff_to_parse);
  2612. $stuff_to_parse = '';
  2613. }
  2614. // If we haven't matched a regexp comment, try multi-line comments
  2615. if (!$COMMENT_MATCHED) {
  2616. // Is this a multiline comment?
  2617. if (!empty($this->language_data['COMMENT_MULTI']) && $next_comment_multi_pos < $i) {
  2618. $next_comment_multi_pos = $length;
  2619. foreach ($this->language_data['COMMENT_MULTI'] as $open => $close) {
  2620. $match_i = false;
  2621. if (isset($comment_multi_cache_per_key[$open]) &&
  2622. ($comment_multi_cache_per_key[$open] >= $i ||
  2623. $comment_multi_cache_per_key[$open] === false)) {
  2624. // we have already matched something
  2625. if ($comment_multi_cache_per_key[$open] === false) {
  2626. // this comment is never matched
  2627. continue;
  2628. }
  2629. $match_i = $comment_multi_cache_per_key[$open];
  2630. } else if (($match_i = stripos($part, $open, $i)) !== false) {
  2631. $comment_multi_cache_per_key[$open] = $match_i;
  2632. } else {
  2633. $comment_multi_cache_per_key[$open] = false;
  2634. continue;
  2635. }
  2636. if ($match_i !== false && $match_i < $next_comment_multi_pos) {
  2637. $next_comment_multi_pos = $match_i;
  2638. $next_open_comment_multi = $open;
  2639. if ($match_i === $i) {
  2640. break;
  2641. }
  2642. }
  2643. }
  2644. }
  2645. if ($i == $next_comment_multi_pos) {
  2646. $open = $next_open_comment_multi;
  2647. $close = $this->language_data['COMMENT_MULTI'][$open];
  2648. $open_strlen = strlen($open);
  2649. $close_strlen = strlen($close);
  2650. $COMMENT_MATCHED = true;
  2651. $test_str_match = $open;
  2652. //@todo If remove important do remove here
  2653. if ($this->lexic_permissions['COMMENTS']['MULTI'] ||
  2654. $open == GESHI_START_IMPORTANT) {
  2655. if ($open != GESHI_START_IMPORTANT) {
  2656. if (!$this->use_classes) {
  2657. $attributes = ' style="' . $this->language_data['STYLES']['COMMENTS']['MULTI'] . '"';
  2658. } else {
  2659. $attributes = ' class="coMULTI"';
  2660. }
  2661. $test_str = "<span$attributes>" . $this->hsc($open);
  2662. } else {
  2663. if (!$this->use_classes) {
  2664. $attributes = ' style="' . $this->important_styles . '"';
  2665. } else {
  2666. $attributes = ' class="imp"';
  2667. }
  2668. // We don't include the start of the comment if it's an
  2669. // "important" part
  2670. $test_str = "<span$attributes>";
  2671. }
  2672. } else {
  2673. $test_str = $this->hsc($open);
  2674. }
  2675. $close_pos = strpos( $part, $close, $i + $open_strlen );
  2676. if ($close_pos === false) {
  2677. $close_pos = $length;
  2678. }
  2679. // Short-cut through all the multiline code
  2680. $rest_of_comment = $this->hsc(substr($part, $i + $open_strlen, $close_pos - $i - $open_strlen + $close_strlen));
  2681. if (($this->lexic_permissions['COMMENTS']['MULTI'] ||
  2682. $test_str_match == GESHI_START_IMPORTANT) &&
  2683. $check_linenumbers) {
  2684. // strreplace to put close span and open span around multiline newlines
  2685. $test_str .= str_replace(
  2686. "\n", "</span>\n<span$attributes>",
  2687. str_replace("\n ", "\n&nbsp;", $rest_of_comment)
  2688. );
  2689. } else {
  2690. $test_str .= $rest_of_comment;
  2691. }
  2692. if ($this->lexic_permissions['COMMENTS']['MULTI'] ||
  2693. $test_str_match == GESHI_START_IMPORTANT) {
  2694. $test_str .= '</span>';
  2695. }
  2696. $i = $close_pos + $close_strlen - 1;
  2697. // parse the rest
  2698. $result .= $this->parse_non_string_part($stuff_to_parse);
  2699. $stuff_to_parse = '';
  2700. }
  2701. }
  2702. // If we haven't matched a multiline comment, try single-line comments
  2703. if (!$COMMENT_MATCHED) {
  2704. // cache potential single line comment occurances
  2705. if (!empty($this->language_data['COMMENT_SINGLE']) && $next_comment_single_pos < $i) {
  2706. $next_comment_single_pos = $length;
  2707. foreach ($this->language_data['COMMENT_SINGLE'] as $comment_key => $comment_mark) {
  2708. $match_i = false;
  2709. if (isset($comment_single_cache_per_key[$comment_key]) &&
  2710. ($comment_single_cache_per_key[$comment_key] >= $i ||
  2711. $comment_single_cache_per_key[$comment_key] === false)) {
  2712. // we have already matched something
  2713. if ($comment_single_cache_per_key[$comment_key] === false) {
  2714. // this comment is never matched
  2715. continue;
  2716. }
  2717. $match_i = $comment_single_cache_per_key[$comment_key];
  2718. } else if (
  2719. // case sensitive comments
  2720. ($this->language_data['CASE_SENSITIVE'][GESHI_COMMENTS] &&
  2721. ($match_i = stripos($part, $comment_mark, $i)) !== false) ||
  2722. // non case sensitive
  2723. (!$this->language_data['CASE_SENSITIVE'][GESHI_COMMENTS] &&
  2724. (($match_i = strpos($part, $comment_mark, $i)) !== false))) {
  2725. $comment_single_cache_per_key[$comment_key] = $match_i;
  2726. } else {
  2727. $comment_single_cache_per_key[$comment_key] = false;
  2728. continue;
  2729. }
  2730. if ($match_i !== false && $match_i < $next_comment_single_pos) {
  2731. $next_comment_single_pos = $match_i;
  2732. $next_comment_single_key = $comment_key;
  2733. if ($match_i === $i) {
  2734. break;
  2735. }
  2736. }
  2737. }
  2738. }
  2739. if ($next_comment_single_pos == $i) {
  2740. $comment_key = $next_comment_single_key;
  2741. $comment_mark = $this->language_data['COMMENT_SINGLE'][$comment_key];
  2742. $com_len = strlen($comment_mark);
  2743. // This check will find special variables like $# in bash
  2744. // or compiler directives of Delphi beginning {$
  2745. if ((empty($sc_disallowed_before) || ($i == 0) ||
  2746. (false === strpos($sc_disallowed_before, $part[$i-1]))) &&
  2747. (empty($sc_disallowed_after) || ($length <= $i + $com_len) ||
  2748. (false === strpos($sc_disallowed_after, $part[$i + $com_len]))))
  2749. {
  2750. // this is a valid comment
  2751. $COMMENT_MATCHED = true;
  2752. if ($this->lexic_permissions['COMMENTS'][$comment_key]) {
  2753. if (!$this->use_classes) {
  2754. $attributes = ' style="' . $this->language_data['STYLES']['COMMENTS'][$comment_key] . '"';
  2755. } else {
  2756. $attributes = ' class="co' . $comment_key . '"';
  2757. }
  2758. $test_str = "<span$attributes>" . $this->hsc($this->change_case($comment_mark));
  2759. } else {
  2760. $test_str = $this->hsc($comment_mark);
  2761. }
  2762. //Check if this comment is the last in the source
  2763. $close_pos = strpos($part, "\n", $i);
  2764. $oops = false;
  2765. if ($close_pos === false) {
  2766. $close_pos = $length;
  2767. $oops = true;
  2768. }
  2769. $test_str .= $this->hsc(substr($part, $i + $com_len, $close_pos - $i - $com_len));
  2770. if ($this->lexic_permissions['COMMENTS'][$comment_key]) {
  2771. $test_str .= "</span>";
  2772. }
  2773. // Take into account that the comment might be the last in the source
  2774. if (!$oops) {
  2775. $test_str .= "\n";
  2776. }
  2777. $i = $close_pos;
  2778. // parse the rest
  2779. $result .= $this->parse_non_string_part($stuff_to_parse);
  2780. $stuff_to_parse = '';
  2781. }
  2782. }
  2783. }
  2784. }
  2785. // Where are we adding this char?
  2786. if (!$COMMENT_MATCHED) {
  2787. $stuff_to_parse .= $char;
  2788. } else {
  2789. $result .= $test_str;
  2790. unset($test_str);
  2791. $COMMENT_MATCHED = false;
  2792. }
  2793. }
  2794. // Parse the last bit
  2795. $result .= $this->parse_non_string_part($stuff_to_parse);
  2796. $stuff_to_parse = '';
  2797. } else {
  2798. $result .= $this->hsc($part);
  2799. }
  2800. // Close the <span> that surrounds the block
  2801. if ($STRICTATTRS != '') {
  2802. $result = str_replace("\n", "</span>\n<span$STRICTATTRS>", $result);
  2803. $result .= '</span>';
  2804. }
  2805. $endresult .= $result;
  2806. unset($part, $parts[$key], $result);
  2807. }
  2808. //This fix is related to SF#1923020, but has to be applied regardless of
  2809. //actually highlighting symbols.
  2810. /** NOTE: memorypeak #3 */
  2811. $endresult = str_replace(array('<SEMI>', '<PIPE>'), array(';', '|'), $endresult);
  2812. // // Parse the last stuff (redundant?)
  2813. // $result .= $this->parse_non_string_part($stuff_to_parse);
  2814. // Lop off the very first and last spaces
  2815. // $result = substr($result, 1, -1);
  2816. // We're finished: stop timing
  2817. $this->set_time($start_time, microtime());
  2818. $this->finalise($endresult);
  2819. return $endresult;
  2820. }
  2821. /**
  2822. * Swaps out spaces and tabs for HTML indentation. Not needed if
  2823. * the code is in a pre block...
  2824. *
  2825. * @param string The source to indent (reference!)
  2826. * @since 1.0.0
  2827. * @access private
  2828. */
  2829. function indent(&$result) {
  2830. /// Replace tabs with the correct number of spaces
  2831. if (false !== strpos($result, "\t")) {
  2832. $lines = explode("\n", $result);
  2833. $result = null;//Save memory while we process the lines individually
  2834. $tab_width = $this->get_real_tab_width();
  2835. $tab_string = '&nbsp;' . str_repeat(' ', $tab_width);
  2836. for ($key = 0, $n = count($lines); $key < $n; $key++) {
  2837. $line = $lines[$key];
  2838. if (false === strpos($line, "\t")) {
  2839. continue;
  2840. }
  2841. $pos = 0;
  2842. $length = strlen($line);
  2843. $lines[$key] = ''; // reduce memory
  2844. $IN_TAG = false;
  2845. for ($i = 0; $i < $length; ++$i) {
  2846. $char = $line[$i];
  2847. // Simple engine to work out whether we're in a tag.
  2848. // If we are we modify $pos. This is so we ignore HTML
  2849. // in the line and only workout the tab replacement
  2850. // via the actual content of the string
  2851. // This test could be improved to include strings in the
  2852. // html so that < or > would be allowed in user's styles
  2853. // (e.g. quotes: '<' '>'; or similar)
  2854. if ($IN_TAG) {
  2855. if ('>' == $char) {
  2856. $IN_TAG = false;
  2857. }
  2858. $lines[$key] .= $char;
  2859. } else if ('<' == $char) {
  2860. $IN_TAG = true;
  2861. $lines[$key] .= '<';
  2862. } else if ('&' == $char) {
  2863. $substr = substr($line, $i + 3, 5);
  2864. $posi = strpos($substr, ';');
  2865. if (false === $posi) {
  2866. ++$pos;
  2867. } else {
  2868. $pos -= $posi+2;
  2869. }
  2870. $lines[$key] .= $char;
  2871. } else if ("\t" == $char) {
  2872. $str = '';
  2873. // OPTIMISE - move $strs out. Make an array:
  2874. // $tabs = array(
  2875. // 1 => '&nbsp;',
  2876. // 2 => '&nbsp; ',
  2877. // 3 => '&nbsp; &nbsp;' etc etc
  2878. // to use instead of building a string every time
  2879. $tab_end_width = $tab_width - ($pos % $tab_width); //Moved out of the look as it doesn't change within the loop
  2880. if (($pos & 1) || 1 == $tab_end_width) {
  2881. $str .= substr($tab_string, 6, $tab_end_width);
  2882. } else {
  2883. $str .= substr($tab_string, 0, $tab_end_width+5);
  2884. }
  2885. $lines[$key] .= $str;
  2886. $pos += $tab_end_width;
  2887. if (false === strpos($line, "\t", $i + 1)) {
  2888. $lines[$key] .= substr($line, $i + 1);
  2889. break;
  2890. }
  2891. } else if (0 == $pos && ' ' == $char) {
  2892. $lines[$key] .= '&nbsp;';
  2893. ++$pos;
  2894. } else {
  2895. $lines[$key] .= $char;
  2896. ++$pos;
  2897. }
  2898. }
  2899. }
  2900. $result = implode("\n", $lines);
  2901. unset($lines);//We don't need the lines separated beyond this --- free them!
  2902. }
  2903. // Other whitespace
  2904. // BenBE: Fix to reduce the number of replacements to be done
  2905. $result = preg_replace('/^ /m', '&nbsp;', $result);
  2906. $result = str_replace(' ', ' &nbsp;', $result);
  2907. if ($this->line_numbers == GESHI_NO_LINE_NUMBERS && $this->header_type != GESHI_HEADER_PRE_TABLE) {
  2908. if ($this->line_ending === null) {
  2909. $result = nl2br($result);
  2910. } else {
  2911. $result = str_replace("\n", $this->line_ending, $result);
  2912. }
  2913. }
  2914. }
  2915. /**
  2916. * Changes the case of a keyword for those languages where a change is asked for
  2917. *
  2918. * @param string The keyword to change the case of
  2919. * @return string The keyword with its case changed
  2920. * @since 1.0.0
  2921. * @access private
  2922. */
  2923. function change_case($instr) {
  2924. switch ($this->language_data['CASE_KEYWORDS']) {
  2925. case GESHI_CAPS_UPPER:
  2926. return strtoupper($instr);
  2927. case GESHI_CAPS_LOWER:
  2928. return strtolower($instr);
  2929. default:
  2930. return $instr;
  2931. }
  2932. }
  2933. /**
  2934. * Handles replacements of keywords to include markup and links if requested
  2935. *
  2936. * @param string The keyword to add the Markup to
  2937. * @return The HTML for the match found
  2938. * @since 1.0.8
  2939. * @access private
  2940. *
  2941. * @todo Get rid of ender in keyword links
  2942. */
  2943. function handle_keyword_replace($match) {
  2944. $k = $this->_kw_replace_group;
  2945. $keyword = $match[0];
  2946. $before = '';
  2947. $after = '';
  2948. if ($this->keyword_links) {
  2949. // Keyword links have been ebabled
  2950. if (isset($this->language_data['URLS'][$k]) &&
  2951. $this->language_data['URLS'][$k] != '') {
  2952. // There is a base group for this keyword
  2953. // Old system: strtolower
  2954. //$keyword = ( $this->language_data['CASE_SENSITIVE'][$group] ) ? $keyword : strtolower($keyword);
  2955. // New system: get keyword from language file to get correct case
  2956. if (!$this->language_data['CASE_SENSITIVE'][$k] &&
  2957. strpos($this->language_data['URLS'][$k], '{FNAME}') !== false) {
  2958. foreach ($this->language_data['KEYWORDS'][$k] as $word) {
  2959. if (strcasecmp($word, $keyword) == 0) {
  2960. break;
  2961. }
  2962. }
  2963. } else {
  2964. $word = $keyword;
  2965. }
  2966. $before = '<|UR1|"' .
  2967. str_replace(
  2968. array(
  2969. '{FNAME}',
  2970. '{FNAMEL}',
  2971. '{FNAMEU}',
  2972. '.'),
  2973. array(
  2974. str_replace('+', '%20', urlencode($this->hsc($word))),
  2975. str_replace('+', '%20', urlencode($this->hsc(strtolower($word)))),
  2976. str_replace('+', '%20', urlencode($this->hsc(strtoupper($word)))),
  2977. '<DOT>'),
  2978. $this->language_data['URLS'][$k]
  2979. ) . '">';
  2980. $after = '</a>';
  2981. }
  2982. }
  2983. return $before . '<|/'. $k .'/>' . $this->change_case($keyword) . '|>' . $after;
  2984. }
  2985. /**
  2986. * handles regular expressions highlighting-definitions with callback functions
  2987. *
  2988. * @note this is a callback, don't use it directly
  2989. *
  2990. * @param array the matches array
  2991. * @return The highlighted string
  2992. * @since 1.0.8
  2993. * @access private
  2994. */
  2995. function handle_regexps_callback($matches) {
  2996. // before: "' style=\"' . call_user_func(\"$func\", '\\1') . '\"\\1|>'",
  2997. return ' style="' . call_user_func($this->language_data['STYLES']['REGEXPS'][$this->_rx_key], $matches[1]) . '"'. $matches[1] . '|>';
  2998. }
  2999. /**
  3000. * handles newlines in REGEXPS matches. Set the _hmr_* vars before calling this
  3001. *
  3002. * @note this is a callback, don't use it directly
  3003. *
  3004. * @param array the matches array
  3005. * @return string
  3006. * @since 1.0.8
  3007. * @access private
  3008. */
  3009. function handle_multiline_regexps($matches) {
  3010. $before = $this->_hmr_before;
  3011. $after = $this->_hmr_after;
  3012. if ($this->_hmr_replace) {
  3013. $replace = $this->_hmr_replace;
  3014. $search = array();
  3015. foreach (array_keys($matches) as $k) {
  3016. $search[] = '\\' . $k;
  3017. }
  3018. $before = str_replace($search, $matches, $before);
  3019. $after = str_replace($search, $matches, $after);
  3020. $replace = str_replace($search, $matches, $replace);
  3021. } else {
  3022. $replace = $matches[0];
  3023. }
  3024. return $before
  3025. . '<|!REG3XP' . $this->_hmr_key .'!>'
  3026. . str_replace("\n", "|>\n<|!REG3XP" . $this->_hmr_key . '!>', $replace)
  3027. . '|>'
  3028. . $after;
  3029. }
  3030. /**
  3031. * Takes a string that has no strings or comments in it, and highlights
  3032. * stuff like keywords, numbers and methods.
  3033. *
  3034. * @param string The string to parse for keyword, numbers etc.
  3035. * @since 1.0.0
  3036. * @access private
  3037. * @todo BUGGY! Why? Why not build string and return?
  3038. */
  3039. function parse_non_string_part($stuff_to_parse) {
  3040. $stuff_to_parse = ' ' . $this->hsc($stuff_to_parse);
  3041. // Highlight keywords
  3042. $disallowed_before = "(?<![a-zA-Z0-9\$_\|\#|^&";
  3043. $disallowed_after = "(?![a-zA-Z0-9_\|%\\-&;";
  3044. if ($this->lexic_permissions['STRINGS']) {
  3045. $quotemarks = preg_quote(implode($this->language_data['QUOTEMARKS']), '/');
  3046. $disallowed_before .= $quotemarks;
  3047. $disallowed_after .= $quotemarks;
  3048. }
  3049. $disallowed_before .= "])";
  3050. $disallowed_after .= "])";
  3051. $parser_control_pergroup = false;
  3052. if (isset($this->language_data['PARSER_CONTROL'])) {
  3053. if (isset($this->language_data['PARSER_CONTROL']['KEYWORDS'])) {
  3054. $x = 0; // check wether per-keyword-group parser_control is enabled
  3055. if (isset($this->language_data['PARSER_CONTROL']['KEYWORDS']['DISALLOWED_BEFORE'])) {
  3056. $disallowed_before = $this->language_data['PARSER_CONTROL']['KEYWORDS']['DISALLOWED_BEFORE'];
  3057. ++$x;
  3058. }
  3059. if (isset($this->language_data['PARSER_CONTROL']['KEYWORDS']['DISALLOWED_AFTER'])) {
  3060. $disallowed_after = $this->language_data['PARSER_CONTROL']['KEYWORDS']['DISALLOWED_AFTER'];
  3061. ++$x;
  3062. }
  3063. $parser_control_pergroup = (count($this->language_data['PARSER_CONTROL']['KEYWORDS']) - $x) > 0;
  3064. }
  3065. }
  3066. foreach (array_keys($this->language_data['KEYWORDS']) as $k) {
  3067. if (!isset($this->lexic_permissions['KEYWORDS'][$k]) ||
  3068. $this->lexic_permissions['KEYWORDS'][$k]) {
  3069. $case_sensitive = $this->language_data['CASE_SENSITIVE'][$k];
  3070. $modifiers = $case_sensitive ? '' : 'i';
  3071. // NEW in 1.0.8 - per-keyword-group parser control
  3072. $disallowed_before_local = $disallowed_before;
  3073. $disallowed_after_local = $disallowed_after;
  3074. if ($parser_control_pergroup && isset($this->language_data['PARSER_CONTROL']['KEYWORDS'][$k])) {
  3075. if (isset($this->language_data['PARSER_CONTROL']['KEYWORDS'][$k]['DISALLOWED_BEFORE'])) {
  3076. $disallowed_before_local =
  3077. $this->language_data['PARSER_CONTROL']['KEYWORDS'][$k]['DISALLOWED_BEFORE'];
  3078. }
  3079. if (isset($this->language_data['PARSER_CONTROL']['KEYWORDS'][$k]['DISALLOWED_AFTER'])) {
  3080. $disallowed_after_local =
  3081. $this->language_data['PARSER_CONTROL']['KEYWORDS'][$k]['DISALLOWED_AFTER'];
  3082. }
  3083. }
  3084. $this->_kw_replace_group = $k;
  3085. //NEW in 1.0.8, the cached regexp list
  3086. // since we don't want PHP / PCRE to crash due to too large patterns we split them into smaller chunks
  3087. for ($set = 0, $set_length = count($this->language_data['CACHED_KEYWORD_LISTS'][$k]); $set < $set_length; ++$set) {
  3088. $keywordset =& $this->language_data['CACHED_KEYWORD_LISTS'][$k][$set];
  3089. // Might make a more unique string for putting the number in soon
  3090. // Basically, we don't put the styles in yet because then the styles themselves will
  3091. // get highlighted if the language has a CSS keyword in it (like CSS, for example ;))
  3092. $stuff_to_parse = preg_replace_callback(
  3093. "/$disallowed_before_local({$keywordset})(?!\<DOT\>(?:htm|php|aspx?))$disallowed_after_local/$modifiers",
  3094. array($this, 'handle_keyword_replace'),
  3095. $stuff_to_parse
  3096. );
  3097. }
  3098. }
  3099. }
  3100. // Regular expressions
  3101. foreach ($this->language_data['REGEXPS'] as $key => $regexp) {
  3102. if ($this->lexic_permissions['REGEXPS'][$key]) {
  3103. if (is_array($regexp)) {
  3104. if ($this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3105. // produce valid HTML when we match multiple lines
  3106. $this->_hmr_replace = $regexp[GESHI_REPLACE];
  3107. $this->_hmr_before = $regexp[GESHI_BEFORE];
  3108. $this->_hmr_key = $key;
  3109. $this->_hmr_after = $regexp[GESHI_AFTER];
  3110. $stuff_to_parse = preg_replace_callback(
  3111. "/" . $regexp[GESHI_SEARCH] . "/{$regexp[GESHI_MODIFIERS]}",
  3112. array($this, 'handle_multiline_regexps'),
  3113. $stuff_to_parse);
  3114. $this->_hmr_replace = false;
  3115. $this->_hmr_before = '';
  3116. $this->_hmr_after = '';
  3117. } else {
  3118. $stuff_to_parse = preg_replace(
  3119. '/' . $regexp[GESHI_SEARCH] . '/' . $regexp[GESHI_MODIFIERS],
  3120. $regexp[GESHI_BEFORE] . '<|!REG3XP'. $key .'!>' . $regexp[GESHI_REPLACE] . '|>' . $regexp[GESHI_AFTER],
  3121. $stuff_to_parse);
  3122. }
  3123. } else {
  3124. if ($this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3125. // produce valid HTML when we match multiple lines
  3126. $this->_hmr_key = $key;
  3127. $stuff_to_parse = preg_replace_callback( "/(" . $regexp . ")/",
  3128. array($this, 'handle_multiline_regexps'), $stuff_to_parse);
  3129. $this->_hmr_key = '';
  3130. } else {
  3131. $stuff_to_parse = preg_replace( "/(" . $regexp . ")/", "<|!REG3XP$key!>\\1|>", $stuff_to_parse);
  3132. }
  3133. }
  3134. }
  3135. }
  3136. // Highlight numbers. As of 1.0.8 we support different types of numbers
  3137. $numbers_found = false;
  3138. if ($this->lexic_permissions['NUMBERS'] && preg_match($this->language_data['PARSER_CONTROL']['NUMBERS']['PRECHECK_RX'], $stuff_to_parse )) {
  3139. $numbers_found = true;
  3140. //For each of the formats ...
  3141. foreach($this->language_data['NUMBERS_RXCACHE'] as $id => $regexp) {
  3142. //Check if it should be highlighted ...
  3143. $stuff_to_parse = preg_replace($regexp, "<|/NUM!$id/>\\1|>", $stuff_to_parse);
  3144. }
  3145. }
  3146. //
  3147. // Now that's all done, replace /[number]/ with the correct styles
  3148. //
  3149. foreach (array_keys($this->language_data['KEYWORDS']) as $k) {
  3150. if (!$this->use_classes) {
  3151. $attributes = ' style="' .
  3152. (isset($this->language_data['STYLES']['KEYWORDS'][$k]) ?
  3153. $this->language_data['STYLES']['KEYWORDS'][$k] : "") . '"';
  3154. } else {
  3155. $attributes = ' class="kw' . $k . '"';
  3156. }
  3157. $stuff_to_parse = str_replace("<|/$k/>", "<|$attributes>", $stuff_to_parse);
  3158. }
  3159. if ($numbers_found) {
  3160. // Put number styles in
  3161. foreach($this->language_data['NUMBERS_RXCACHE'] as $id => $regexp) {
  3162. //Commented out for now, as this needs some review ...
  3163. // if ($numbers_permissions & $id) {
  3164. //Get the appropriate style ...
  3165. //Checking for unset styles is done by the style cache builder ...
  3166. if (!$this->use_classes) {
  3167. $attributes = ' style="' . $this->language_data['STYLES']['NUMBERS'][$id] . '"';
  3168. } else {
  3169. $attributes = ' class="nu'.$id.'"';
  3170. }
  3171. //Set in the correct styles ...
  3172. $stuff_to_parse = str_replace("/NUM!$id/", $attributes, $stuff_to_parse);
  3173. // }
  3174. }
  3175. }
  3176. // Highlight methods and fields in objects
  3177. if ($this->lexic_permissions['METHODS'] && $this->language_data['OOLANG']) {
  3178. $oolang_spaces = "[\s]*";
  3179. $oolang_before = "";
  3180. $oolang_after = "[a-zA-Z][a-zA-Z0-9_]*";
  3181. if (isset($this->language_data['PARSER_CONTROL'])) {
  3182. if (isset($this->language_data['PARSER_CONTROL']['OOLANG'])) {
  3183. if (isset($this->language_data['PARSER_CONTROL']['OOLANG']['MATCH_BEFORE'])) {
  3184. $oolang_before = $this->language_data['PARSER_CONTROL']['OOLANG']['MATCH_BEFORE'];
  3185. }
  3186. if (isset($this->language_data['PARSER_CONTROL']['OOLANG']['MATCH_AFTER'])) {
  3187. $oolang_after = $this->language_data['PARSER_CONTROL']['OOLANG']['MATCH_AFTER'];
  3188. }
  3189. if (isset($this->language_data['PARSER_CONTROL']['OOLANG']['MATCH_SPACES'])) {
  3190. $oolang_spaces = $this->language_data['PARSER_CONTROL']['OOLANG']['MATCH_SPACES'];
  3191. }
  3192. }
  3193. }
  3194. foreach ($this->language_data['OBJECT_SPLITTERS'] as $key => $splitter) {
  3195. if (false !== strpos($stuff_to_parse, $splitter)) {
  3196. if (!$this->use_classes) {
  3197. $attributes = ' style="' . $this->language_data['STYLES']['METHODS'][$key] . '"';
  3198. } else {
  3199. $attributes = ' class="me' . $key . '"';
  3200. }
  3201. $stuff_to_parse = preg_replace("/($oolang_before)(" . preg_quote($this->language_data['OBJECT_SPLITTERS'][$key], '/') . ")($oolang_spaces)($oolang_after)/", "\\1\\2\\3<|$attributes>\\4|>", $stuff_to_parse);
  3202. }
  3203. }
  3204. }
  3205. //
  3206. // Highlight brackets. Yes, I've tried adding a semi-colon to this list.
  3207. // You try it, and see what happens ;)
  3208. // TODO: Fix lexic permissions not converting entities if shouldn't
  3209. // be highlighting regardless
  3210. //
  3211. if ($this->lexic_permissions['BRACKETS']) {
  3212. $stuff_to_parse = str_replace( $this->language_data['CACHE_BRACKET_MATCH'],
  3213. $this->language_data['CACHE_BRACKET_REPLACE'], $stuff_to_parse );
  3214. }
  3215. //FIX for symbol highlighting ...
  3216. if ($this->lexic_permissions['SYMBOLS'] && !empty($this->language_data['SYMBOLS'])) {
  3217. //Get all matches and throw away those witin a block that is already highlighted... (i.e. matched by a regexp)
  3218. $n_symbols = preg_match_all("/<\|(?:<DOT>|[^>])+>(?:(?!\|>).*?)\|>|<\/a>|(?:" . $this->language_data['SYMBOL_SEARCH'] . ")+(?![^<]+?>)/", $stuff_to_parse, $pot_symbols, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
  3219. $global_offset = 0;
  3220. for ($s_id = 0; $s_id < $n_symbols; ++$s_id) {
  3221. $symbol_match = $pot_symbols[$s_id][0][0];
  3222. if (strpos($symbol_match, '<') !== false || strpos($symbol_match, '>') !== false) {
  3223. // already highlighted blocks _must_ include either < or >
  3224. // so if this conditional applies, we have to skip this match
  3225. // BenBE: UNLESS the block contains <SEMI> or <PIPE>
  3226. if(strpos($symbol_match, '<SEMI>') === false &&
  3227. strpos($symbol_match, '<PIPE>') === false) {
  3228. continue;
  3229. }
  3230. }
  3231. // if we reach this point, we have a valid match which needs to be highlighted
  3232. $symbol_length = strlen($symbol_match);
  3233. $symbol_offset = $pot_symbols[$s_id][0][1];
  3234. unset($pot_symbols[$s_id]);
  3235. $symbol_end = $symbol_length + $symbol_offset;
  3236. $symbol_hl = "";
  3237. // if we have multiple styles, we have to handle them properly
  3238. if ($this->language_data['MULTIPLE_SYMBOL_GROUPS']) {
  3239. $old_sym = -1;
  3240. // Split the current stuff to replace into its atomic symbols ...
  3241. preg_match_all("/" . $this->language_data['SYMBOL_SEARCH'] . "/", $symbol_match, $sym_match_syms, PREG_PATTERN_ORDER);
  3242. foreach ($sym_match_syms[0] as $sym_ms) {
  3243. //Check if consequtive symbols belong to the same group to save output ...
  3244. if (isset($this->language_data['SYMBOL_DATA'][$sym_ms])
  3245. && ($this->language_data['SYMBOL_DATA'][$sym_ms] != $old_sym)) {
  3246. if (-1 != $old_sym) {
  3247. $symbol_hl .= "|>";
  3248. }
  3249. $old_sym = $this->language_data['SYMBOL_DATA'][$sym_ms];
  3250. if (!$this->use_classes) {
  3251. $symbol_hl .= '<| style="' . $this->language_data['STYLES']['SYMBOLS'][$old_sym] . '">';
  3252. } else {
  3253. $symbol_hl .= '<| class="sy' . $old_sym . '">';
  3254. }
  3255. }
  3256. $symbol_hl .= $sym_ms;
  3257. }
  3258. unset($sym_match_syms);
  3259. //Close remaining tags and insert the replacement at the right position ...
  3260. //Take caution if symbol_hl is empty to avoid doubled closing spans.
  3261. if (-1 != $old_sym) {
  3262. $symbol_hl .= "|>";
  3263. }
  3264. } else {
  3265. if (!$this->use_classes) {
  3266. $symbol_hl = '<| style="' . $this->language_data['STYLES']['SYMBOLS'][0] . '">';
  3267. } else {
  3268. $symbol_hl = '<| class="sy0">';
  3269. }
  3270. $symbol_hl .= $symbol_match . '|>';
  3271. }
  3272. $stuff_to_parse = substr_replace($stuff_to_parse, $symbol_hl, $symbol_offset + $global_offset, $symbol_length);
  3273. // since we replace old text with something of different size,
  3274. // we'll have to keep track of the differences
  3275. $global_offset += strlen($symbol_hl) - $symbol_length;
  3276. }
  3277. }
  3278. //FIX for symbol highlighting ...
  3279. // Add class/style for regexps
  3280. foreach (array_keys($this->language_data['REGEXPS']) as $key) {
  3281. if ($this->lexic_permissions['REGEXPS'][$key]) {
  3282. if (is_callable($this->language_data['STYLES']['REGEXPS'][$key])) {
  3283. $this->_rx_key = $key;
  3284. $stuff_to_parse = preg_replace_callback("/!REG3XP$key!(.*)\|>/U",
  3285. array($this, 'handle_regexps_callback'),
  3286. $stuff_to_parse);
  3287. } else {
  3288. if (!$this->use_classes) {
  3289. $attributes = ' style="' . $this->language_data['STYLES']['REGEXPS'][$key] . '"';
  3290. } else {
  3291. if (is_array($this->language_data['REGEXPS'][$key]) &&
  3292. array_key_exists(GESHI_CLASS, $this->language_data['REGEXPS'][$key])) {
  3293. $attributes = ' class="' .
  3294. $this->language_data['REGEXPS'][$key][GESHI_CLASS] . '"';
  3295. } else {
  3296. $attributes = ' class="re' . $key . '"';
  3297. }
  3298. }
  3299. $stuff_to_parse = str_replace("!REG3XP$key!", "$attributes", $stuff_to_parse);
  3300. }
  3301. }
  3302. }
  3303. // Replace <DOT> with . for urls
  3304. $stuff_to_parse = str_replace('<DOT>', '.', $stuff_to_parse);
  3305. // Replace <|UR1| with <a href= for urls also
  3306. if (isset($this->link_styles[GESHI_LINK])) {
  3307. if ($this->use_classes) {
  3308. $stuff_to_parse = str_replace('<|UR1|', '<a' . $this->link_target . ' href=', $stuff_to_parse);
  3309. } else {
  3310. $stuff_to_parse = str_replace('<|UR1|', '<a' . $this->link_target . ' style="' . $this->link_styles[GESHI_LINK] . '" href=', $stuff_to_parse);
  3311. }
  3312. } else {
  3313. $stuff_to_parse = str_replace('<|UR1|', '<a' . $this->link_target . ' href=', $stuff_to_parse);
  3314. }
  3315. //
  3316. // NOW we add the span thingy ;)
  3317. //
  3318. $stuff_to_parse = str_replace('<|', '<span', $stuff_to_parse);
  3319. $stuff_to_parse = str_replace ( '|>', '</span>', $stuff_to_parse );
  3320. return substr($stuff_to_parse, 1);
  3321. }
  3322. /**
  3323. * Sets the time taken to parse the code
  3324. *
  3325. * @param microtime The time when parsing started
  3326. * @param microtime The time when parsing ended
  3327. * @since 1.0.2
  3328. * @access private
  3329. */
  3330. function set_time($start_time, $end_time) {
  3331. $start = explode(' ', $start_time);
  3332. $end = explode(' ', $end_time);
  3333. $this->time = $end[0] + $end[1] - $start[0] - $start[1];
  3334. }
  3335. /**
  3336. * Gets the time taken to parse the code
  3337. *
  3338. * @return double The time taken to parse the code
  3339. * @since 1.0.2
  3340. */
  3341. function get_time() {
  3342. return $this->time;
  3343. }
  3344. /**
  3345. * Merges arrays recursively, overwriting values of the first array with values of later arrays
  3346. *
  3347. * @since 1.0.8
  3348. * @access private
  3349. */
  3350. function merge_arrays() {
  3351. $arrays = func_get_args();
  3352. $narrays = count($arrays);
  3353. // check arguments
  3354. // comment out if more performance is necessary (in this case the foreach loop will trigger a warning if the argument is not an array)
  3355. for ($i = 0; $i < $narrays; $i ++) {
  3356. if (!is_array($arrays[$i])) {
  3357. // also array_merge_recursive returns nothing in this case
  3358. trigger_error('Argument #' . ($i+1) . ' is not an array - trying to merge array with scalar! Returning false!', E_USER_WARNING);
  3359. return false;
  3360. }
  3361. }
  3362. // the first array is in the output set in every case
  3363. $ret = $arrays[0];
  3364. // merege $ret with the remaining arrays
  3365. for ($i = 1; $i < $narrays; $i ++) {
  3366. foreach ($arrays[$i] as $key => $value) {
  3367. if (is_array($value) && isset($ret[$key])) {
  3368. // if $ret[$key] is not an array you try to merge an scalar value with an array - the result is not defined (incompatible arrays)
  3369. // in this case the call will trigger an E_USER_WARNING and the $ret[$key] will be false.
  3370. $ret[$key] = $this->merge_arrays($ret[$key], $value);
  3371. } else {
  3372. $ret[$key] = $value;
  3373. }
  3374. }
  3375. }
  3376. return $ret;
  3377. }
  3378. /**
  3379. * Gets language information and stores it for later use
  3380. *
  3381. * @param string The filename of the language file you want to load
  3382. * @since 1.0.0
  3383. * @access private
  3384. * @todo Needs to load keys for lexic permissions for keywords, regexps etc
  3385. */
  3386. function load_language($file_name) {
  3387. if ($file_name == $this->loaded_language) {
  3388. // this file is already loaded!
  3389. return;
  3390. }
  3391. //Prepare some stuff before actually loading the language file
  3392. $this->loaded_language = $file_name;
  3393. $this->parse_cache_built = false;
  3394. $this->enable_highlighting();
  3395. $language_data = array();
  3396. //Load the language file
  3397. require $file_name;
  3398. // Perhaps some checking might be added here later to check that
  3399. // $language data is a valid thing but maybe not
  3400. $this->language_data = $language_data;
  3401. // Set strict mode if should be set
  3402. $this->strict_mode = $this->language_data['STRICT_MODE_APPLIES'];
  3403. // Set permissions for all lexics to true
  3404. // so they'll be highlighted by default
  3405. foreach (array_keys($this->language_data['KEYWORDS']) as $key) {
  3406. if (!empty($this->language_data['KEYWORDS'][$key])) {
  3407. $this->lexic_permissions['KEYWORDS'][$key] = true;
  3408. } else {
  3409. $this->lexic_permissions['KEYWORDS'][$key] = false;
  3410. }
  3411. }
  3412. foreach (array_keys($this->language_data['COMMENT_SINGLE']) as $key) {
  3413. $this->lexic_permissions['COMMENTS'][$key] = true;
  3414. }
  3415. foreach (array_keys($this->language_data['REGEXPS']) as $key) {
  3416. $this->lexic_permissions['REGEXPS'][$key] = true;
  3417. }
  3418. // for BenBE and future code reviews:
  3419. // we can use empty here since we only check for existance and emptiness of an array
  3420. // if it is not an array at all but rather false or null this will work as intended as well
  3421. // even if $this->language_data['PARSER_CONTROL'] is undefined this won't trigger a notice
  3422. if (!empty($this->language_data['PARSER_CONTROL']['ENABLE_FLAGS'])) {
  3423. foreach ($this->language_data['PARSER_CONTROL']['ENABLE_FLAGS'] as $flag => $value) {
  3424. // it's either true or false and maybe is true as well
  3425. $perm = $value !== GESHI_NEVER;
  3426. if ($flag == 'ALL') {
  3427. $this->enable_highlighting($perm);
  3428. continue;
  3429. }
  3430. if (!isset($this->lexic_permissions[$flag])) {
  3431. // unknown lexic permission
  3432. continue;
  3433. }
  3434. if (is_array($this->lexic_permissions[$flag])) {
  3435. foreach ($this->lexic_permissions[$flag] as $key => $val) {
  3436. $this->lexic_permissions[$flag][$key] = $perm;
  3437. }
  3438. } else {
  3439. $this->lexic_permissions[$flag] = $perm;
  3440. }
  3441. }
  3442. unset($this->language_data['PARSER_CONTROL']['ENABLE_FLAGS']);
  3443. }
  3444. //Fix: Problem where hardescapes weren't handled if no ESCAPE_CHAR was given
  3445. //You need to set one for HARDESCAPES only in this case.
  3446. if(!isset($this->language_data['HARDCHAR'])) {
  3447. $this->language_data['HARDCHAR'] = $this->language_data['ESCAPE_CHAR'];
  3448. }
  3449. //NEW in 1.0.8: Allow styles to be loaded from a separate file to override defaults
  3450. $style_filename = substr($file_name, 0, -4) . '.style.php';
  3451. if (is_readable($style_filename)) {
  3452. //Clear any style_data that could have been set before ...
  3453. if (isset($style_data)) {
  3454. unset($style_data);
  3455. }
  3456. //Read the Style Information from the style file
  3457. include $style_filename;
  3458. //Apply the new styles to our current language styles
  3459. if (isset($style_data) && is_array($style_data)) {
  3460. $this->language_data['STYLES'] =
  3461. $this->merge_arrays($this->language_data['STYLES'], $style_data);
  3462. }
  3463. }
  3464. }
  3465. /**
  3466. * Takes the parsed code and various options, and creates the HTML
  3467. * surrounding it to make it look nice.
  3468. *
  3469. * @param string The code already parsed (reference!)
  3470. * @since 1.0.0
  3471. * @access private
  3472. */
  3473. function finalise(&$parsed_code) {
  3474. // Remove end parts of important declarations
  3475. // This is BUGGY!! My fault for bad code: fix coming in 1.2
  3476. // @todo Remove this crap
  3477. if ($this->enable_important_blocks &&
  3478. (strpos($parsed_code, $this->hsc(GESHI_START_IMPORTANT)) === false)) {
  3479. $parsed_code = str_replace($this->hsc(GESHI_END_IMPORTANT), '', $parsed_code);
  3480. }
  3481. // Add HTML whitespace stuff if we're using the <div> header
  3482. if ($this->header_type != GESHI_HEADER_PRE && $this->header_type != GESHI_HEADER_PRE_VALID) {
  3483. $this->indent($parsed_code);
  3484. }
  3485. // purge some unnecessary stuff
  3486. /** NOTE: memorypeak #1 */
  3487. $parsed_code = preg_replace('#<span[^>]+>(\s*)</span>#', '\\1', $parsed_code);
  3488. // If we are using IDs for line numbers, there needs to be an overall
  3489. // ID set to prevent collisions.
  3490. if ($this->add_ids && !$this->overall_id) {
  3491. $this->overall_id = 'geshi-' . substr(md5(microtime()), 0, 4);
  3492. }
  3493. // Get code into lines
  3494. /** NOTE: memorypeak #2 */
  3495. $code = explode("\n", $parsed_code);
  3496. $parsed_code = $this->header();
  3497. // If we're using line numbers, we insert <li>s and appropriate
  3498. // markup to style them (otherwise we don't need to do anything)
  3499. if ($this->line_numbers != GESHI_NO_LINE_NUMBERS && $this->header_type != GESHI_HEADER_PRE_TABLE) {
  3500. // If we're using the <pre> header, we shouldn't add newlines because
  3501. // the <pre> will line-break them (and the <li>s already do this for us)
  3502. $ls = ($this->header_type != GESHI_HEADER_PRE && $this->header_type != GESHI_HEADER_PRE_VALID) ? "\n" : '';
  3503. // Set vars to defaults for following loop
  3504. $i = 0;
  3505. // Foreach line...
  3506. for ($i = 0, $n = count($code); $i < $n;) {
  3507. //Reset the attributes for a new line ...
  3508. $attrs = array();
  3509. // Make lines have at least one space in them if they're empty
  3510. // BenBE: Checking emptiness using trim instead of relying on blanks
  3511. if ('' == trim($code[$i])) {
  3512. $code[$i] = '&nbsp;';
  3513. }
  3514. // If this is a "special line"...
  3515. if ($this->line_numbers == GESHI_FANCY_LINE_NUMBERS &&
  3516. $i % $this->line_nth_row == ($this->line_nth_row - 1)) {
  3517. // Set the attributes to style the line
  3518. if ($this->use_classes) {
  3519. //$attr = ' class="li2"';
  3520. $attrs['class'][] = 'li2';
  3521. $def_attr = ' class="de2"';
  3522. } else {
  3523. //$attr = ' style="' . $this->line_style2 . '"';
  3524. $attrs['style'][] = $this->line_style2;
  3525. // This style "covers up" the special styles set for special lines
  3526. // so that styles applied to special lines don't apply to the actual
  3527. // code on that line
  3528. $def_attr = ' style="' . $this->code_style . '"';
  3529. }
  3530. } else {
  3531. if ($this->use_classes) {
  3532. //$attr = ' class="li1"';
  3533. $attrs['class'][] = 'li1';
  3534. $def_attr = ' class="de1"';
  3535. } else {
  3536. //$attr = ' style="' . $this->line_style1 . '"';
  3537. $attrs['style'][] = $this->line_style1;
  3538. $def_attr = ' style="' . $this->code_style . '"';
  3539. }
  3540. }
  3541. //Check which type of tag to insert for this line
  3542. if ($this->header_type == GESHI_HEADER_PRE_VALID) {
  3543. $start = "<pre$def_attr>";
  3544. $end = '</pre>';
  3545. } else {
  3546. // Span or div?
  3547. $start = "<div$def_attr>";
  3548. $end = '</div>';
  3549. }
  3550. ++$i;
  3551. // Are we supposed to use ids? If so, add them
  3552. if ($this->add_ids) {
  3553. $attrs['id'][] = "$this->overall_id-$i";
  3554. }
  3555. //Is this some line with extra styles???
  3556. if (in_array($i, $this->highlight_extra_lines)) {
  3557. if ($this->use_classes) {
  3558. if (isset($this->highlight_extra_lines_styles[$i])) {
  3559. $attrs['class'][] = "lx$i";
  3560. } else {
  3561. $attrs['class'][] = "ln-xtra";
  3562. }
  3563. } else {
  3564. array_push($attrs['style'], $this->get_line_style($i));
  3565. }
  3566. }
  3567. // Add in the line surrounded by appropriate list HTML
  3568. $attr_string = '';
  3569. foreach ($attrs as $key => $attr) {
  3570. $attr_string .= ' ' . $key . '="' . implode(' ', $attr) . '"';
  3571. }
  3572. $parsed_code .= "<li$attr_string>$start{$code[$i-1]}$end</li>$ls";
  3573. unset($code[$i - 1]);
  3574. }
  3575. } else {
  3576. $n = count($code);
  3577. if ($this->use_classes) {
  3578. $attributes = ' class="de1"';
  3579. } else {
  3580. $attributes = ' style="'. $this->code_style .'"';
  3581. }
  3582. if ($this->header_type == GESHI_HEADER_PRE_VALID) {
  3583. $parsed_code .= '<pre'. $attributes .'>';
  3584. } elseif ($this->header_type == GESHI_HEADER_PRE_TABLE) {
  3585. if ($this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3586. if ($this->use_classes) {
  3587. $attrs = ' class="ln"';
  3588. } else {
  3589. $attrs = ' style="'. $this->table_linenumber_style .'"';
  3590. }
  3591. $parsed_code .= '<td'.$attrs.'><pre'.$attributes.'>';
  3592. // get linenumbers
  3593. // we don't merge it with the for below, since it should be better for
  3594. // memory consumption this way
  3595. // @todo: but... actually it would still be somewhat nice to merge the two loops
  3596. // the mem peaks are at different positions
  3597. for ($i = 0; $i < $n; ++$i) {
  3598. $close = 0;
  3599. // fancy lines
  3600. if ($this->line_numbers == GESHI_FANCY_LINE_NUMBERS &&
  3601. $i % $this->line_nth_row == ($this->line_nth_row - 1)) {
  3602. // Set the attributes to style the line
  3603. if ($this->use_classes) {
  3604. $parsed_code .= '<span class="xtra li2"><span class="de2">';
  3605. } else {
  3606. // This style "covers up" the special styles set for special lines
  3607. // so that styles applied to special lines don't apply to the actual
  3608. // code on that line
  3609. $parsed_code .= '<span style="display:block;' . $this->line_style2 . '">'
  3610. .'<span style="' . $this->code_style .'">';
  3611. }
  3612. $close += 2;
  3613. }
  3614. //Is this some line with extra styles???
  3615. if (in_array($i + 1, $this->highlight_extra_lines)) {
  3616. if ($this->use_classes) {
  3617. if (isset($this->highlight_extra_lines_styles[$i])) {
  3618. $parsed_code .= "<span class=\"xtra lx$i\">";
  3619. } else {
  3620. $parsed_code .= "<span class=\"xtra ln-xtra\">";
  3621. }
  3622. } else {
  3623. $parsed_code .= "<span style=\"display:block;" . $this->get_line_style($i) . "\">";
  3624. }
  3625. ++$close;
  3626. }
  3627. $parsed_code .= $this->line_numbers_start + $i;
  3628. if ($close) {
  3629. $parsed_code .= str_repeat('</span>', $close);
  3630. } else if ($i != $n) {
  3631. $parsed_code .= "\n";
  3632. }
  3633. }
  3634. $parsed_code .= '</pre></td><td'.$attributes.'>';
  3635. }
  3636. $parsed_code .= '<pre'. $attributes .'>';
  3637. }
  3638. // No line numbers, but still need to handle highlighting lines extra.
  3639. // Have to use divs so the full width of the code is highlighted
  3640. $close = 0;
  3641. for ($i = 0; $i < $n; ++$i) {
  3642. // Make lines have at least one space in them if they're empty
  3643. // BenBE: Checking emptiness using trim instead of relying on blanks
  3644. if ('' == trim($code[$i])) {
  3645. $code[$i] = '&nbsp;';
  3646. }
  3647. // fancy lines
  3648. if ($this->line_numbers == GESHI_FANCY_LINE_NUMBERS &&
  3649. $i % $this->line_nth_row == ($this->line_nth_row - 1)) {
  3650. // Set the attributes to style the line
  3651. if ($this->use_classes) {
  3652. $parsed_code .= '<span class="xtra li2"><span class="de2">';
  3653. } else {
  3654. // This style "covers up" the special styles set for special lines
  3655. // so that styles applied to special lines don't apply to the actual
  3656. // code on that line
  3657. $parsed_code .= '<span style="display:block;' . $this->line_style2 . '">'
  3658. .'<span style="' . $this->code_style .'">';
  3659. }
  3660. $close += 2;
  3661. }
  3662. //Is this some line with extra styles???
  3663. if (in_array($i + 1, $this->highlight_extra_lines)) {
  3664. if ($this->use_classes) {
  3665. if (isset($this->highlight_extra_lines_styles[$i])) {
  3666. $parsed_code .= "<span class=\"xtra lx$i\">";
  3667. } else {
  3668. $parsed_code .= "<span class=\"xtra ln-xtra\">";
  3669. }
  3670. } else {
  3671. $parsed_code .= "<span style=\"display:block;" . $this->get_line_style($i) . "\">";
  3672. }
  3673. ++$close;
  3674. }
  3675. $parsed_code .= $code[$i];
  3676. if ($close) {
  3677. $parsed_code .= str_repeat('</span>', $close);
  3678. $close = 0;
  3679. }
  3680. elseif ($i + 1 < $n) {
  3681. $parsed_code .= "\n";
  3682. }
  3683. unset($code[$i]);
  3684. }
  3685. if ($this->header_type == GESHI_HEADER_PRE_VALID || $this->header_type == GESHI_HEADER_PRE_TABLE) {
  3686. $parsed_code .= '</pre>';
  3687. }
  3688. if ($this->header_type == GESHI_HEADER_PRE_TABLE && $this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3689. $parsed_code .= '</td>';
  3690. }
  3691. }
  3692. $parsed_code .= $this->footer();
  3693. }
  3694. /**
  3695. * Creates the header for the code block (with correct attributes)
  3696. *
  3697. * @return string The header for the code block
  3698. * @since 1.0.0
  3699. * @access private
  3700. */
  3701. function header() {
  3702. // Get attributes needed
  3703. /**
  3704. * @todo Document behaviour change - class is outputted regardless of whether
  3705. * we're using classes or not. Same with style
  3706. */
  3707. $attributes = ' class="' . $this->_genCSSName($this->language);
  3708. if ($this->overall_class != '') {
  3709. $attributes .= " ".$this->_genCSSName($this->overall_class);
  3710. }
  3711. $attributes .= '"';
  3712. if ($this->overall_id != '') {
  3713. $attributes .= " id=\"{$this->overall_id}\"";
  3714. }
  3715. if ($this->overall_style != '' && !$this->use_classes) {
  3716. $attributes .= ' style="' . $this->overall_style . '"';
  3717. }
  3718. $ol_attributes = '';
  3719. if ($this->line_numbers_start != 1) {
  3720. $ol_attributes .= ' start="' . $this->line_numbers_start . '"';
  3721. }
  3722. // Get the header HTML
  3723. $header = $this->header_content;
  3724. if ($header) {
  3725. if ($this->header_type == GESHI_HEADER_PRE || $this->header_type == GESHI_HEADER_PRE_VALID) {
  3726. $header = str_replace("\n", '', $header);
  3727. }
  3728. $header = $this->replace_keywords($header);
  3729. if ($this->use_classes) {
  3730. $attr = ' class="head"';
  3731. } else {
  3732. $attr = " style=\"{$this->header_content_style}\"";
  3733. }
  3734. if ($this->header_type == GESHI_HEADER_PRE_TABLE && $this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3735. $header = "<thead><tr><td colspan=\"2\" $attr>$header</td></tr></thead>";
  3736. } else {
  3737. $header = "<div$attr>$header</div>";
  3738. }
  3739. }
  3740. if (GESHI_HEADER_NONE == $this->header_type) {
  3741. if ($this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3742. return "$header<ol$attributes$ol_attributes>";
  3743. }
  3744. return $header . ($this->force_code_block ? '<div>' : '');
  3745. }
  3746. // Work out what to return and do it
  3747. if ($this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3748. if ($this->header_type == GESHI_HEADER_PRE) {
  3749. return "<pre$attributes>$header<ol$ol_attributes>";
  3750. } else if ($this->header_type == GESHI_HEADER_DIV ||
  3751. $this->header_type == GESHI_HEADER_PRE_VALID) {
  3752. return "<div$attributes>$header<ol$ol_attributes>";
  3753. } else if ($this->header_type == GESHI_HEADER_PRE_TABLE) {
  3754. return "<table$attributes>$header<tbody><tr class=\"li1\">";
  3755. }
  3756. } else {
  3757. if ($this->header_type == GESHI_HEADER_PRE) {
  3758. return "<pre$attributes>$header" .
  3759. ($this->force_code_block ? '<div>' : '');
  3760. } else {
  3761. return "<div$attributes>$header" .
  3762. ($this->force_code_block ? '<div>' : '');
  3763. }
  3764. }
  3765. }
  3766. /**
  3767. * Returns the footer for the code block.
  3768. *
  3769. * @return string The footer for the code block
  3770. * @since 1.0.0
  3771. * @access private
  3772. */
  3773. function footer() {
  3774. $footer = $this->footer_content;
  3775. if ($footer) {
  3776. if ($this->header_type == GESHI_HEADER_PRE) {
  3777. $footer = str_replace("\n", '', $footer);;
  3778. }
  3779. $footer = $this->replace_keywords($footer);
  3780. if ($this->use_classes) {
  3781. $attr = ' class="foot"';
  3782. } else {
  3783. $attr = " style=\"{$this->footer_content_style}\"";
  3784. }
  3785. if ($this->header_type == GESHI_HEADER_PRE_TABLE && $this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3786. $footer = "<tfoot><tr><td colspan=\"2\">$footer</td></tr></tfoot>";
  3787. } else {
  3788. $footer = "<div$attr>$footer</div>";
  3789. }
  3790. }
  3791. if (GESHI_HEADER_NONE == $this->header_type) {
  3792. return ($this->line_numbers != GESHI_NO_LINE_NUMBERS) ? '</ol>' . $footer : $footer;
  3793. }
  3794. if ($this->header_type == GESHI_HEADER_DIV || $this->header_type == GESHI_HEADER_PRE_VALID) {
  3795. if ($this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3796. return "</ol>$footer</div>";
  3797. }
  3798. return ($this->force_code_block ? '</div>' : '') .
  3799. "$footer</div>";
  3800. }
  3801. elseif ($this->header_type == GESHI_HEADER_PRE_TABLE) {
  3802. if ($this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3803. return "</tr></tbody>$footer</table>";
  3804. }
  3805. return ($this->force_code_block ? '</div>' : '') .
  3806. "$footer</div>";
  3807. }
  3808. else {
  3809. if ($this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3810. return "</ol>$footer</pre>";
  3811. }
  3812. return ($this->force_code_block ? '</div>' : '') .
  3813. "$footer</pre>";
  3814. }
  3815. }
  3816. /**
  3817. * Replaces certain keywords in the header and footer with
  3818. * certain configuration values
  3819. *
  3820. * @param string The header or footer content to do replacement on
  3821. * @return string The header or footer with replaced keywords
  3822. * @since 1.0.2
  3823. * @access private
  3824. */
  3825. function replace_keywords($instr) {
  3826. $keywords = $replacements = array();
  3827. $keywords[] = '<TIME>';
  3828. $keywords[] = '{TIME}';
  3829. $replacements[] = $replacements[] = number_format($time = $this->get_time(), 3);
  3830. $keywords[] = '<LANGUAGE>';
  3831. $keywords[] = '{LANGUAGE}';
  3832. $replacements[] = $replacements[] = $this->language_data['LANG_NAME'];
  3833. $keywords[] = '<VERSION>';
  3834. $keywords[] = '{VERSION}';
  3835. $replacements[] = $replacements[] = GESHI_VERSION;
  3836. $keywords[] = '<SPEED>';
  3837. $keywords[] = '{SPEED}';
  3838. if ($time <= 0) {
  3839. $speed = 'N/A';
  3840. } else {
  3841. $speed = strlen($this->source) / $time;
  3842. if ($speed >= 1024) {
  3843. $speed = sprintf("%.2f KB/s", $speed / 1024.0);
  3844. } else {
  3845. $speed = sprintf("%.0f B/s", $speed);
  3846. }
  3847. }
  3848. $replacements[] = $replacements[] = $speed;
  3849. return str_replace($keywords, $replacements, $instr);
  3850. }
  3851. /**
  3852. * Secure replacement for PHP built-in function htmlspecialchars().
  3853. *
  3854. * See ticket #427 (http://wush.net/trac/wikka/ticket/427) for the rationale
  3855. * for this replacement function.
  3856. *
  3857. * The INTERFACE for this function is almost the same as that for
  3858. * htmlspecialchars(), with the same default for quote style; however, there
  3859. * is no 'charset' parameter. The reason for this is as follows:
  3860. *
  3861. * The PHP docs say:
  3862. * "The third argument charset defines character set used in conversion."
  3863. *
  3864. * I suspect PHP's htmlspecialchars() is working at the byte-value level and
  3865. * thus _needs_ to know (or asssume) a character set because the special
  3866. * characters to be replaced could exist at different code points in
  3867. * different character sets. (If indeed htmlspecialchars() works at
  3868. * byte-value level that goes some way towards explaining why the
  3869. * vulnerability would exist in this function, too, and not only in
  3870. * htmlentities() which certainly is working at byte-value level.)
  3871. *
  3872. * This replacement function however works at character level and should
  3873. * therefore be "immune" to character set differences - so no charset
  3874. * parameter is needed or provided. If a third parameter is passed, it will
  3875. * be silently ignored.
  3876. *
  3877. * In the OUTPUT there is a minor difference in that we use '&#39;' instead
  3878. * of PHP's '&#039;' for a single quote: this provides compatibility with
  3879. * get_html_translation_table(HTML_SPECIALCHARS, ENT_QUOTES)
  3880. * (see comment by mikiwoz at yahoo dot co dot uk on
  3881. * http://php.net/htmlspecialchars); it also matches the entity definition
  3882. * for XML 1.0
  3883. * (http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_Special_characters).
  3884. * Like PHP we use a numeric character reference instead of '&apos;' for the
  3885. * single quote. For the other special characters we use the named entity
  3886. * references, as PHP is doing.
  3887. *
  3888. * @author {@link http://wikkawiki.org/JavaWoman Marjolein Katsma}
  3889. *
  3890. * @license http://www.gnu.org/copyleft/lgpl.html
  3891. * GNU Lesser General Public License
  3892. * @copyright Copyright 2007, {@link http://wikkawiki.org/CreditsPage
  3893. * Wikka Development Team}
  3894. *
  3895. * @access private
  3896. * @param string $string string to be converted
  3897. * @param integer $quote_style
  3898. * - ENT_COMPAT: escapes &, <, > and double quote (default)
  3899. * - ENT_NOQUOTES: escapes only &, < and >
  3900. * - ENT_QUOTES: escapes &, <, >, double and single quotes
  3901. * @return string converted string
  3902. * @since 1.0.7.18
  3903. */
  3904. function hsc($string, $quote_style = ENT_COMPAT) {
  3905. // init
  3906. static $aTransSpecchar = array(
  3907. '&' => '&amp;',
  3908. '"' => '&quot;',
  3909. '<' => '&lt;',
  3910. '>' => '&gt;',
  3911. //This fix is related to SF#1923020, but has to be applied
  3912. //regardless of actually highlighting symbols.
  3913. //Circumvent a bug with symbol highlighting
  3914. //This is required as ; would produce undesirable side-effects if it
  3915. //was not to be processed as an entity.
  3916. ';' => '<SEMI>', // Force ; to be processed as entity
  3917. '|' => '<PIPE>' // Force | to be processed as entity
  3918. ); // ENT_COMPAT set
  3919. switch ($quote_style) {
  3920. case ENT_NOQUOTES: // don't convert double quotes
  3921. unset($aTransSpecchar['"']);
  3922. break;
  3923. case ENT_QUOTES: // convert single quotes as well
  3924. $aTransSpecchar["'"] = '&#39;'; // (apos) htmlspecialchars() uses '&#039;'
  3925. break;
  3926. }
  3927. // return translated string
  3928. return strtr($string, $aTransSpecchar);
  3929. }
  3930. function _genCSSName($name){
  3931. return (is_numeric($name[0]) ? '_' : '') . $name;
  3932. }
  3933. /**
  3934. * Returns a stylesheet for the highlighted code. If $economy mode
  3935. * is true, we only return the stylesheet declarations that matter for
  3936. * this code block instead of the whole thing
  3937. *
  3938. * @param boolean Whether to use economy mode or not
  3939. * @return string A stylesheet built on the data for the current language
  3940. * @since 1.0.0
  3941. */
  3942. function get_stylesheet($economy_mode = true) {
  3943. // If there's an error, chances are that the language file
  3944. // won't have populated the language data file, so we can't
  3945. // risk getting a stylesheet...
  3946. if ($this->error) {
  3947. return '';
  3948. }
  3949. //Check if the style rearrangements have been processed ...
  3950. //This also does some preprocessing to check which style groups are useable ...
  3951. if(!isset($this->language_data['NUMBERS_CACHE'])) {
  3952. $this->build_style_cache();
  3953. }
  3954. // First, work out what the selector should be. If there's an ID,
  3955. // that should be used, the same for a class. Otherwise, a selector
  3956. // of '' means that these styles will be applied anywhere
  3957. if ($this->overall_id) {
  3958. $selector = '#' . $this->_genCSSName($this->overall_id);
  3959. } else {
  3960. $selector = '.' . $this->_genCSSName($this->language);
  3961. if ($this->overall_class) {
  3962. $selector .= '.' . $this->_genCSSName($this->overall_class);
  3963. }
  3964. }
  3965. $selector .= ' ';
  3966. // Header of the stylesheet
  3967. if (!$economy_mode) {
  3968. $stylesheet = "/**\n".
  3969. " * GeSHi Dynamically Generated Stylesheet\n".
  3970. " * --------------------------------------\n".
  3971. " * Dynamically generated stylesheet for {$this->language}\n".
  3972. " * CSS class: {$this->overall_class}, CSS id: {$this->overall_id}\n".
  3973. " * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann\n" .
  3974. " * (http://qbnz.com/highlighter/ and http://geshi.org/)\n".
  3975. " * --------------------------------------\n".
  3976. " */\n";
  3977. } else {
  3978. $stylesheet = "/**\n".
  3979. " * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann\n" .
  3980. " * (http://qbnz.com/highlighter/ and http://geshi.org/)\n".
  3981. " */\n";
  3982. }
  3983. // Set the <ol> to have no effect at all if there are line numbers
  3984. // (<ol>s have margins that should be destroyed so all layout is
  3985. // controlled by the set_overall_style method, which works on the
  3986. // <pre> or <div> container). Additionally, set default styles for lines
  3987. if (!$economy_mode || $this->line_numbers != GESHI_NO_LINE_NUMBERS) {
  3988. //$stylesheet .= "$selector, {$selector}ol, {$selector}ol li {margin: 0;}\n";
  3989. $stylesheet .= "$selector.de1, $selector.de2 {{$this->code_style}}\n";
  3990. }
  3991. // Add overall styles
  3992. // note: neglect economy_mode, empty styles are meaningless
  3993. if ($this->overall_style != '') {
  3994. $stylesheet .= "$selector {{$this->overall_style}}\n";
  3995. }
  3996. // Add styles for links
  3997. // note: economy mode does not make _any_ sense here
  3998. // either the style is empty and thus no selector is needed
  3999. // or the appropriate key is given.
  4000. foreach ($this->link_styles as $key => $style) {
  4001. if ($style != '') {
  4002. switch ($key) {
  4003. case GESHI_LINK:
  4004. $stylesheet .= "{$selector}a:link {{$style}}\n";
  4005. break;
  4006. case GESHI_HOVER:
  4007. $stylesheet .= "{$selector}a:hover {{$style}}\n";
  4008. break;
  4009. case GESHI_ACTIVE:
  4010. $stylesheet .= "{$selector}a:active {{$style}}\n";
  4011. break;
  4012. case GESHI_VISITED:
  4013. $stylesheet .= "{$selector}a:visited {{$style}}\n";
  4014. break;
  4015. }
  4016. }
  4017. }
  4018. // Header and footer
  4019. // note: neglect economy_mode, empty styles are meaningless
  4020. if ($this->header_content_style != '') {
  4021. $stylesheet .= "$selector.head {{$this->header_content_style}}\n";
  4022. }
  4023. if ($this->footer_content_style != '') {
  4024. $stylesheet .= "$selector.foot {{$this->footer_content_style}}\n";
  4025. }
  4026. // Styles for important stuff
  4027. // note: neglect economy_mode, empty styles are meaningless
  4028. if ($this->important_styles != '') {
  4029. $stylesheet .= "$selector.imp {{$this->important_styles}}\n";
  4030. }
  4031. // Simple line number styles
  4032. if ((!$economy_mode || $this->line_numbers != GESHI_NO_LINE_NUMBERS) && $this->line_style1 != '') {
  4033. $stylesheet .= "{$selector}li, {$selector}.li1 {{$this->line_style1}}\n";
  4034. }
  4035. if ((!$economy_mode || $this->line_numbers != GESHI_NO_LINE_NUMBERS) && $this->table_linenumber_style != '') {
  4036. $stylesheet .= "{$selector}.ln {{$this->table_linenumber_style}}\n";
  4037. }
  4038. // If there is a style set for fancy line numbers, echo it out
  4039. if ((!$economy_mode || $this->line_numbers == GESHI_FANCY_LINE_NUMBERS) && $this->line_style2 != '') {
  4040. $stylesheet .= "{$selector}.li2 {{$this->line_style2}}\n";
  4041. }
  4042. // note: empty styles are meaningless
  4043. foreach ($this->language_data['STYLES']['KEYWORDS'] as $group => $styles) {
  4044. if ($styles != '' && (!$economy_mode ||
  4045. (isset($this->lexic_permissions['KEYWORDS'][$group]) &&
  4046. $this->lexic_permissions['KEYWORDS'][$group]))) {
  4047. $stylesheet .= "$selector.kw$group {{$styles}}\n";
  4048. }
  4049. }
  4050. foreach ($this->language_data['STYLES']['COMMENTS'] as $group => $styles) {
  4051. if ($styles != '' && (!$economy_mode ||
  4052. (isset($this->lexic_permissions['COMMENTS'][$group]) &&
  4053. $this->lexic_permissions['COMMENTS'][$group]) ||
  4054. (!empty($this->language_data['COMMENT_REGEXP']) &&
  4055. !empty($this->language_data['COMMENT_REGEXP'][$group])))) {
  4056. $stylesheet .= "$selector.co$group {{$styles}}\n";
  4057. }
  4058. }
  4059. foreach ($this->language_data['STYLES']['ESCAPE_CHAR'] as $group => $styles) {
  4060. if ($styles != '' && (!$economy_mode || $this->lexic_permissions['ESCAPE_CHAR'])) {
  4061. // NEW: since 1.0.8 we have to handle hardescapes
  4062. if ($group === 'HARD') {
  4063. $group = '_h';
  4064. }
  4065. $stylesheet .= "$selector.es$group {{$styles}}\n";
  4066. }
  4067. }
  4068. foreach ($this->language_data['STYLES']['BRACKETS'] as $group => $styles) {
  4069. if ($styles != '' && (!$economy_mode || $this->lexic_permissions['BRACKETS'])) {
  4070. $stylesheet .= "$selector.br$group {{$styles}}\n";
  4071. }
  4072. }
  4073. foreach ($this->language_data['STYLES']['SYMBOLS'] as $group => $styles) {
  4074. if ($styles != '' && (!$economy_mode || $this->lexic_permissions['SYMBOLS'])) {
  4075. $stylesheet .= "$selector.sy$group {{$styles}}\n";
  4076. }
  4077. }
  4078. foreach ($this->language_data['STYLES']['STRINGS'] as $group => $styles) {
  4079. if ($styles != '' && (!$economy_mode || $this->lexic_permissions['STRINGS'])) {
  4080. // NEW: since 1.0.8 we have to handle hardquotes
  4081. if ($group === 'HARD') {
  4082. $group = '_h';
  4083. }
  4084. $stylesheet .= "$selector.st$group {{$styles}}\n";
  4085. }
  4086. }
  4087. foreach ($this->language_data['STYLES']['NUMBERS'] as $group => $styles) {
  4088. if ($styles != '' && (!$economy_mode || $this->lexic_permissions['NUMBERS'])) {
  4089. $stylesheet .= "$selector.nu$group {{$styles}}\n";
  4090. }
  4091. }
  4092. foreach ($this->language_data['STYLES']['METHODS'] as $group => $styles) {
  4093. if ($styles != '' && (!$economy_mode || $this->lexic_permissions['METHODS'])) {
  4094. $stylesheet .= "$selector.me$group {{$styles}}\n";
  4095. }
  4096. }
  4097. // note: neglect economy_mode, empty styles are meaningless
  4098. foreach ($this->language_data['STYLES']['SCRIPT'] as $group => $styles) {
  4099. if ($styles != '') {
  4100. $stylesheet .= "$selector.sc$group {{$styles}}\n";
  4101. }
  4102. }
  4103. foreach ($this->language_data['STYLES']['REGEXPS'] as $group => $styles) {
  4104. if ($styles != '' && (!$economy_mode ||
  4105. (isset($this->lexic_permissions['REGEXPS'][$group]) &&
  4106. $this->lexic_permissions['REGEXPS'][$group]))) {
  4107. if (is_array($this->language_data['REGEXPS'][$group]) &&
  4108. array_key_exists(GESHI_CLASS, $this->language_data['REGEXPS'][$group])) {
  4109. $stylesheet .= "$selector.";
  4110. $stylesheet .= $this->language_data['REGEXPS'][$group][GESHI_CLASS];
  4111. $stylesheet .= " {{$styles}}\n";
  4112. } else {
  4113. $stylesheet .= "$selector.re$group {{$styles}}\n";
  4114. }
  4115. }
  4116. }
  4117. // Styles for lines being highlighted extra
  4118. if (!$economy_mode || (count($this->highlight_extra_lines)!=count($this->highlight_extra_lines_styles))) {
  4119. $stylesheet .= "{$selector}.ln-xtra, {$selector}li.ln-xtra, {$selector}div.ln-xtra {{$this->highlight_extra_lines_style}}\n";
  4120. }
  4121. $stylesheet .= "{$selector}span.xtra { display:block; }\n";
  4122. foreach ($this->highlight_extra_lines_styles as $lineid => $linestyle) {
  4123. $stylesheet .= "{$selector}.lx$lineid, {$selector}li.lx$lineid, {$selector}div.lx$lineid {{$linestyle}}\n";
  4124. }
  4125. return $stylesheet;
  4126. }
  4127. /**
  4128. * Get's the style that is used for the specified line
  4129. *
  4130. * @param int The line number information is requested for
  4131. * @access private
  4132. * @since 1.0.7.21
  4133. */
  4134. function get_line_style($line) {
  4135. //$style = null;
  4136. $style = null;
  4137. if (isset($this->highlight_extra_lines_styles[$line])) {
  4138. $style = $this->highlight_extra_lines_styles[$line];
  4139. } else { // if no "extra" style assigned
  4140. $style = $this->highlight_extra_lines_style;
  4141. }
  4142. return $style;
  4143. }
  4144. /**
  4145. * this functions creates an optimized regular expression list
  4146. * of an array of strings.
  4147. *
  4148. * Example:
  4149. * <code>$list = array('faa', 'foo', 'foobar');
  4150. * => string 'f(aa|oo(bar)?)'</code>
  4151. *
  4152. * @param $list array of (unquoted) strings
  4153. * @param $regexp_delimiter your regular expression delimiter, @see preg_quote()
  4154. * @return string for regular expression
  4155. * @author Milian Wolff <mail@milianw.de>
  4156. * @since 1.0.8
  4157. * @access private
  4158. */
  4159. function optimize_regexp_list($list, $regexp_delimiter = '/') {
  4160. $regex_chars = array('.', '\\', '+', '-', '*', '?', '[', '^', ']', '$',
  4161. '(', ')', '{', '}', '=', '!', '<', '>', '|', ':', $regexp_delimiter);
  4162. sort($list);
  4163. $regexp_list = array('');
  4164. $num_subpatterns = 0;
  4165. $list_key = 0;
  4166. // the tokens which we will use to generate the regexp list
  4167. $tokens = array();
  4168. $prev_keys = array();
  4169. // go through all entries of the list and generate the token list
  4170. $cur_len = 0;
  4171. for ($i = 0, $i_max = count($list); $i < $i_max; ++$i) {
  4172. if ($cur_len > GESHI_MAX_PCRE_LENGTH) {
  4173. // seems like the length of this pcre is growing exorbitantly
  4174. $regexp_list[++$list_key] = $this->_optimize_regexp_list_tokens_to_string($tokens);
  4175. $num_subpatterns = substr_count($regexp_list[$list_key], '(?:');
  4176. $tokens = array();
  4177. $cur_len = 0;
  4178. }
  4179. $level = 0;
  4180. $entry = preg_quote((string) $list[$i], $regexp_delimiter);
  4181. $pointer = &$tokens;
  4182. // properly assign the new entry to the correct position in the token array
  4183. // possibly generate smaller common denominator keys
  4184. while (true) {
  4185. // get the common denominator
  4186. if (isset($prev_keys[$level])) {
  4187. if ($prev_keys[$level] == $entry) {
  4188. // this is a duplicate entry, skip it
  4189. continue 2;
  4190. }
  4191. $char = 0;
  4192. while (isset($entry[$char]) && isset($prev_keys[$level][$char])
  4193. && $entry[$char] == $prev_keys[$level][$char]) {
  4194. ++$char;
  4195. }
  4196. if ($char > 0) {
  4197. // this entry has at least some chars in common with the current key
  4198. if ($char == strlen($prev_keys[$level])) {
  4199. // current key is totally matched, i.e. this entry has just some bits appended
  4200. $pointer = &$pointer[$prev_keys[$level]];
  4201. } else {
  4202. // only part of the keys match
  4203. $new_key_part1 = substr($prev_keys[$level], 0, $char);
  4204. $new_key_part2 = substr($prev_keys[$level], $char);
  4205. if (in_array($new_key_part1[0], $regex_chars)
  4206. || in_array($new_key_part2[0], $regex_chars)) {
  4207. // this is bad, a regex char as first character
  4208. $pointer[$entry] = array('' => true);
  4209. array_splice($prev_keys, $level, count($prev_keys), $entry);
  4210. $cur_len += strlen($entry);
  4211. continue;
  4212. } else {
  4213. // relocate previous tokens
  4214. $pointer[$new_key_part1] = array($new_key_part2 => $pointer[$prev_keys[$level]]);
  4215. unset($pointer[$prev_keys[$level]]);
  4216. $pointer = &$pointer[$new_key_part1];
  4217. // recreate key index
  4218. array_splice($prev_keys, $level, count($prev_keys), array($new_key_part1, $new_key_part2));
  4219. $cur_len += strlen($new_key_part2);
  4220. }
  4221. }
  4222. ++$level;
  4223. $entry = substr($entry, $char);
  4224. continue;
  4225. }
  4226. // else: fall trough, i.e. no common denominator was found
  4227. }
  4228. if ($level == 0 && !empty($tokens)) {
  4229. // we can dump current tokens into the string and throw them away afterwards
  4230. $new_entry = $this->_optimize_regexp_list_tokens_to_string($tokens);
  4231. $new_subpatterns = substr_count($new_entry, '(?:');
  4232. if (GESHI_MAX_PCRE_SUBPATTERNS && $num_subpatterns + $new_subpatterns > GESHI_MAX_PCRE_SUBPATTERNS) {
  4233. $regexp_list[++$list_key] = $new_entry;
  4234. $num_subpatterns = $new_subpatterns;
  4235. } else {
  4236. if (!empty($regexp_list[$list_key])) {
  4237. $new_entry = '|' . $new_entry;
  4238. }
  4239. $regexp_list[$list_key] .= $new_entry;
  4240. $num_subpatterns += $new_subpatterns;
  4241. }
  4242. $tokens = array();
  4243. $cur_len = 0;
  4244. }
  4245. // no further common denominator found
  4246. $pointer[$entry] = array('' => true);
  4247. array_splice($prev_keys, $level, count($prev_keys), $entry);
  4248. $cur_len += strlen($entry);
  4249. break;
  4250. }
  4251. unset($list[$i]);
  4252. }
  4253. // make sure the last tokens get converted as well
  4254. $new_entry = $this->_optimize_regexp_list_tokens_to_string($tokens);
  4255. if (GESHI_MAX_PCRE_SUBPATTERNS && $num_subpatterns + substr_count($new_entry, '(?:') > GESHI_MAX_PCRE_SUBPATTERNS) {
  4256. if ( !empty($regexp_list[$list_key]) ) {
  4257. ++$list_key;
  4258. }
  4259. $regexp_list[$list_key] = $new_entry;
  4260. } else {
  4261. if (!empty($regexp_list[$list_key])) {
  4262. $new_entry = '|' . $new_entry;
  4263. }
  4264. $regexp_list[$list_key] .= $new_entry;
  4265. }
  4266. return $regexp_list;
  4267. }
  4268. /**
  4269. * this function creates the appropriate regexp string of an token array
  4270. * you should not call this function directly, @see $this->optimize_regexp_list().
  4271. *
  4272. * @param &$tokens array of tokens
  4273. * @param $recursed bool to know wether we recursed or not
  4274. * @return string
  4275. * @author Milian Wolff <mail@milianw.de>
  4276. * @since 1.0.8
  4277. * @access private
  4278. */
  4279. function _optimize_regexp_list_tokens_to_string(&$tokens, $recursed = false) {
  4280. $list = '';
  4281. foreach ($tokens as $token => $sub_tokens) {
  4282. $list .= $token;
  4283. $close_entry = isset($sub_tokens['']);
  4284. unset($sub_tokens['']);
  4285. if (!empty($sub_tokens)) {
  4286. $list .= '(?:' . $this->_optimize_regexp_list_tokens_to_string($sub_tokens, true) . ')';
  4287. if ($close_entry) {
  4288. // make sub_tokens optional
  4289. $list .= '?';
  4290. }
  4291. }
  4292. $list .= '|';
  4293. }
  4294. if (!$recursed) {
  4295. // do some optimizations
  4296. // common trailing strings
  4297. // BUGGY!
  4298. //$list = preg_replace_callback('#(?<=^|\:|\|)\w+?(\w+)(?:\|.+\1)+(?=\|)#', create_function(
  4299. // '$matches', 'return "(?:" . preg_replace("#" . preg_quote($matches[1], "#") . "(?=\||$)#", "", $matches[0]) . ")" . $matches[1];'), $list);
  4300. // (?:p)? => p?
  4301. $list = preg_replace('#\(\?\:(.)\)\?#', '\1?', $list);
  4302. // (?:a|b|c|d|...)? => [abcd...]?
  4303. // TODO: a|bb|c => [ac]|bb
  4304. static $callback_2;
  4305. if (!isset($callback_2)) {
  4306. $callback_2 = create_function('$matches', 'return "[" . str_replace("|", "", $matches[1]) . "]";');
  4307. }
  4308. $list = preg_replace_callback('#\(\?\:((?:.\|)+.)\)#', $callback_2, $list);
  4309. }
  4310. // return $list without trailing pipe
  4311. return substr($list, 0, -1);
  4312. }
  4313. } // End Class GeSHi
  4314. if (!function_exists('geshi_highlight')) {
  4315. /**
  4316. * Easy way to highlight stuff. Behaves just like highlight_string
  4317. *
  4318. * @param string The code to highlight
  4319. * @param string The language to highlight the code in
  4320. * @param string The path to the language files. You can leave this blank if you need
  4321. * as from version 1.0.7 the path should be automatically detected
  4322. * @param boolean Whether to return the result or to echo
  4323. * @return string The code highlighted (if $return is true)
  4324. * @since 1.0.2
  4325. */
  4326. function geshi_highlight($string, $language, $path = null, $return = false) {
  4327. $geshi = new GeSHi($string, $language, $path);
  4328. $geshi->set_header_type(GESHI_HEADER_NONE);
  4329. if ($return) {
  4330. return '<code>' . $geshi->parse_code() . '</code>';
  4331. }
  4332. echo '<code>' . $geshi->parse_code() . '</code>';
  4333. if ($geshi->error()) {
  4334. return false;
  4335. }
  4336. return true;
  4337. }
  4338. }
  4339. ?>