KXStudio Website https://kx.studio/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

geshi.php 200KB

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