Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

3 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364
  1. <?php
  2. /**
  3. * Main WordPress Formatting API.
  4. *
  5. * Handles many functions for formatting output.
  6. *
  7. * @package WordPress
  8. */
  9. /**
  10. * Replaces common plain text characters into formatted entities
  11. *
  12. * As an example,
  13. *
  14. * 'cause today's effort makes it worth tomorrow's "holiday" ...
  15. *
  16. * Becomes:
  17. *
  18. * &#8217;cause today&#8217;s effort makes it worth tomorrow&#8217;s &#8220;holiday&#8221; &#8230;
  19. *
  20. * Code within certain html blocks are skipped.
  21. *
  22. * Do not use this function before the {@see 'init'} action hook; everything will break.
  23. *
  24. * @since 0.71
  25. *
  26. * @global array $wp_cockneyreplace Array of formatted entities for certain common phrases
  27. * @global array $shortcode_tags
  28. * @staticvar array $static_characters
  29. * @staticvar array $static_replacements
  30. * @staticvar array $dynamic_characters
  31. * @staticvar array $dynamic_replacements
  32. * @staticvar array $default_no_texturize_tags
  33. * @staticvar array $default_no_texturize_shortcodes
  34. * @staticvar bool $run_texturize
  35. *
  36. * @param string $text The text to be formatted
  37. * @param bool $reset Set to true for unit testing. Translated patterns will reset.
  38. * @return string The string replaced with html entities
  39. */
  40. function wptexturize( $text, $reset = false ) {
  41. global $wp_cockneyreplace, $shortcode_tags;
  42. static $static_characters = null,
  43. $static_replacements = null,
  44. $dynamic_characters = null,
  45. $dynamic_replacements = null,
  46. $default_no_texturize_tags = null,
  47. $default_no_texturize_shortcodes = null,
  48. $run_texturize = true,
  49. $apos = null,
  50. $prime = null,
  51. $double_prime = null,
  52. $opening_quote = null,
  53. $closing_quote = null,
  54. $opening_single_quote = null,
  55. $closing_single_quote = null,
  56. $open_q_flag = '<!--oq-->',
  57. $open_sq_flag = '<!--osq-->',
  58. $apos_flag = '<!--apos-->';
  59. // If there's nothing to do, just stop.
  60. if ( empty( $text ) || false === $run_texturize ) {
  61. return $text;
  62. }
  63. // Set up static variables. Run once only.
  64. if ( $reset || ! isset( $static_characters ) ) {
  65. /**
  66. * Filters whether to skip running wptexturize().
  67. *
  68. * Passing false to the filter will effectively short-circuit wptexturize().
  69. * returning the original text passed to the function instead.
  70. *
  71. * The filter runs only once, the first time wptexturize() is called.
  72. *
  73. * @since 4.0.0
  74. *
  75. * @see wptexturize()
  76. *
  77. * @param bool $run_texturize Whether to short-circuit wptexturize().
  78. */
  79. $run_texturize = apply_filters( 'run_wptexturize', $run_texturize );
  80. if ( false === $run_texturize ) {
  81. return $text;
  82. }
  83. /* translators: opening curly double quote */
  84. $opening_quote = _x( '&#8220;', 'opening curly double quote' );
  85. /* translators: closing curly double quote */
  86. $closing_quote = _x( '&#8221;', 'closing curly double quote' );
  87. /* translators: apostrophe, for example in 'cause or can't */
  88. $apos = _x( '&#8217;', 'apostrophe' );
  89. /* translators: prime, for example in 9' (nine feet) */
  90. $prime = _x( '&#8242;', 'prime' );
  91. /* translators: double prime, for example in 9" (nine inches) */
  92. $double_prime = _x( '&#8243;', 'double prime' );
  93. /* translators: opening curly single quote */
  94. $opening_single_quote = _x( '&#8216;', 'opening curly single quote' );
  95. /* translators: closing curly single quote */
  96. $closing_single_quote = _x( '&#8217;', 'closing curly single quote' );
  97. /* translators: en dash */
  98. $en_dash = _x( '&#8211;', 'en dash' );
  99. /* translators: em dash */
  100. $em_dash = _x( '&#8212;', 'em dash' );
  101. $default_no_texturize_tags = array('pre', 'code', 'kbd', 'style', 'script', 'tt');
  102. $default_no_texturize_shortcodes = array('code');
  103. // if a plugin has provided an autocorrect array, use it
  104. if ( isset($wp_cockneyreplace) ) {
  105. $cockney = array_keys( $wp_cockneyreplace );
  106. $cockneyreplace = array_values( $wp_cockneyreplace );
  107. } else {
  108. /* translators: This is a comma-separated list of words that defy the syntax of quotations in normal use,
  109. * for example... 'We do not have enough words yet' ... is a typical quoted phrase. But when we write
  110. * lines of code 'til we have enough of 'em, then we need to insert apostrophes instead of quotes.
  111. */
  112. $cockney = explode( ',', _x( "'tain't,'twere,'twas,'tis,'twill,'til,'bout,'nuff,'round,'cause,'em",
  113. 'Comma-separated list of words to texturize in your language' ) );
  114. $cockneyreplace = explode( ',', _x( '&#8217;tain&#8217;t,&#8217;twere,&#8217;twas,&#8217;tis,&#8217;twill,&#8217;til,&#8217;bout,&#8217;nuff,&#8217;round,&#8217;cause,&#8217;em',
  115. 'Comma-separated list of replacement words in your language' ) );
  116. }
  117. $static_characters = array_merge( array( '...', '``', '\'\'', ' (tm)' ), $cockney );
  118. $static_replacements = array_merge( array( '&#8230;', $opening_quote, $closing_quote, ' &#8482;' ), $cockneyreplace );
  119. // Pattern-based replacements of characters.
  120. // Sort the remaining patterns into several arrays for performance tuning.
  121. $dynamic_characters = array( 'apos' => array(), 'quote' => array(), 'dash' => array() );
  122. $dynamic_replacements = array( 'apos' => array(), 'quote' => array(), 'dash' => array() );
  123. $dynamic = array();
  124. $spaces = wp_spaces_regexp();
  125. // '99' and '99" are ambiguous among other patterns; assume it's an abbreviated year at the end of a quotation.
  126. if ( "'" !== $apos || "'" !== $closing_single_quote ) {
  127. $dynamic[ '/\'(\d\d)\'(?=\Z|[.,:;!?)}\-\]]|&gt;|' . $spaces . ')/' ] = $apos_flag . '$1' . $closing_single_quote;
  128. }
  129. if ( "'" !== $apos || '"' !== $closing_quote ) {
  130. $dynamic[ '/\'(\d\d)"(?=\Z|[.,:;!?)}\-\]]|&gt;|' . $spaces . ')/' ] = $apos_flag . '$1' . $closing_quote;
  131. }
  132. // '99 '99s '99's (apostrophe) But never '9 or '99% or '999 or '99.0.
  133. if ( "'" !== $apos ) {
  134. $dynamic[ '/\'(?=\d\d(?:\Z|(?![%\d]|[.,]\d)))/' ] = $apos_flag;
  135. }
  136. // Quoted Numbers like '0.42'
  137. if ( "'" !== $opening_single_quote && "'" !== $closing_single_quote ) {
  138. $dynamic[ '/(?<=\A|' . $spaces . ')\'(\d[.,\d]*)\'/' ] = $open_sq_flag . '$1' . $closing_single_quote;
  139. }
  140. // Single quote at start, or preceded by (, {, <, [, ", -, or spaces.
  141. if ( "'" !== $opening_single_quote ) {
  142. $dynamic[ '/(?<=\A|[([{"\-]|&lt;|' . $spaces . ')\'/' ] = $open_sq_flag;
  143. }
  144. // Apostrophe in a word. No spaces, double apostrophes, or other punctuation.
  145. if ( "'" !== $apos ) {
  146. $dynamic[ '/(?<!' . $spaces . ')\'(?!\Z|[.,:;!?"\'(){}[\]\-]|&[lg]t;|' . $spaces . ')/' ] = $apos_flag;
  147. }
  148. $dynamic_characters['apos'] = array_keys( $dynamic );
  149. $dynamic_replacements['apos'] = array_values( $dynamic );
  150. $dynamic = array();
  151. // Quoted Numbers like "42"
  152. if ( '"' !== $opening_quote && '"' !== $closing_quote ) {
  153. $dynamic[ '/(?<=\A|' . $spaces . ')"(\d[.,\d]*)"/' ] = $open_q_flag . '$1' . $closing_quote;
  154. }
  155. // Double quote at start, or preceded by (, {, <, [, -, or spaces, and not followed by spaces.
  156. if ( '"' !== $opening_quote ) {
  157. $dynamic[ '/(?<=\A|[([{\-]|&lt;|' . $spaces . ')"(?!' . $spaces . ')/' ] = $open_q_flag;
  158. }
  159. $dynamic_characters['quote'] = array_keys( $dynamic );
  160. $dynamic_replacements['quote'] = array_values( $dynamic );
  161. $dynamic = array();
  162. // Dashes and spaces
  163. $dynamic[ '/---/' ] = $em_dash;
  164. $dynamic[ '/(?<=^|' . $spaces . ')--(?=$|' . $spaces . ')/' ] = $em_dash;
  165. $dynamic[ '/(?<!xn)--/' ] = $en_dash;
  166. $dynamic[ '/(?<=^|' . $spaces . ')-(?=$|' . $spaces . ')/' ] = $en_dash;
  167. $dynamic_characters['dash'] = array_keys( $dynamic );
  168. $dynamic_replacements['dash'] = array_values( $dynamic );
  169. }
  170. // Must do this every time in case plugins use these filters in a context sensitive manner
  171. /**
  172. * Filters the list of HTML elements not to texturize.
  173. *
  174. * @since 2.8.0
  175. *
  176. * @param array $default_no_texturize_tags An array of HTML element names.
  177. */
  178. $no_texturize_tags = apply_filters( 'no_texturize_tags', $default_no_texturize_tags );
  179. /**
  180. * Filters the list of shortcodes not to texturize.
  181. *
  182. * @since 2.8.0
  183. *
  184. * @param array $default_no_texturize_shortcodes An array of shortcode names.
  185. */
  186. $no_texturize_shortcodes = apply_filters( 'no_texturize_shortcodes', $default_no_texturize_shortcodes );
  187. $no_texturize_tags_stack = array();
  188. $no_texturize_shortcodes_stack = array();
  189. // Look for shortcodes and HTML elements.
  190. preg_match_all( '@\[/?([^<>&/\[\]\x00-\x20=]++)@', $text, $matches );
  191. $tagnames = array_intersect( array_keys( $shortcode_tags ), $matches[1] );
  192. $found_shortcodes = ! empty( $tagnames );
  193. $shortcode_regex = $found_shortcodes ? _get_wptexturize_shortcode_regex( $tagnames ) : '';
  194. $regex = _get_wptexturize_split_regex( $shortcode_regex );
  195. $textarr = preg_split( $regex, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
  196. foreach ( $textarr as &$curl ) {
  197. // Only call _wptexturize_pushpop_element if $curl is a delimiter.
  198. $first = $curl[0];
  199. if ( '<' === $first ) {
  200. if ( '<!--' === substr( $curl, 0, 4 ) ) {
  201. // This is an HTML comment delimiter.
  202. continue;
  203. } else {
  204. // This is an HTML element delimiter.
  205. // Replace each & with &#038; unless it already looks like an entity.
  206. $curl = preg_replace( '/&(?!#(?:\d+|x[a-f0-9]+);|[a-z1-4]{1,8};)/i', '&#038;', $curl );
  207. _wptexturize_pushpop_element( $curl, $no_texturize_tags_stack, $no_texturize_tags );
  208. }
  209. } elseif ( '' === trim( $curl ) ) {
  210. // This is a newline between delimiters. Performance improves when we check this.
  211. continue;
  212. } elseif ( '[' === $first && $found_shortcodes && 1 === preg_match( '/^' . $shortcode_regex . '$/', $curl ) ) {
  213. // This is a shortcode delimiter.
  214. if ( '[[' !== substr( $curl, 0, 2 ) && ']]' !== substr( $curl, -2 ) ) {
  215. // Looks like a normal shortcode.
  216. _wptexturize_pushpop_element( $curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes );
  217. } else {
  218. // Looks like an escaped shortcode.
  219. continue;
  220. }
  221. } elseif ( empty( $no_texturize_shortcodes_stack ) && empty( $no_texturize_tags_stack ) ) {
  222. // This is neither a delimiter, nor is this content inside of no_texturize pairs. Do texturize.
  223. $curl = str_replace( $static_characters, $static_replacements, $curl );
  224. if ( false !== strpos( $curl, "'" ) ) {
  225. $curl = preg_replace( $dynamic_characters['apos'], $dynamic_replacements['apos'], $curl );
  226. $curl = wptexturize_primes( $curl, "'", $prime, $open_sq_flag, $closing_single_quote );
  227. $curl = str_replace( $apos_flag, $apos, $curl );
  228. $curl = str_replace( $open_sq_flag, $opening_single_quote, $curl );
  229. }
  230. if ( false !== strpos( $curl, '"' ) ) {
  231. $curl = preg_replace( $dynamic_characters['quote'], $dynamic_replacements['quote'], $curl );
  232. $curl = wptexturize_primes( $curl, '"', $double_prime, $open_q_flag, $closing_quote );
  233. $curl = str_replace( $open_q_flag, $opening_quote, $curl );
  234. }
  235. if ( false !== strpos( $curl, '-' ) ) {
  236. $curl = preg_replace( $dynamic_characters['dash'], $dynamic_replacements['dash'], $curl );
  237. }
  238. // 9x9 (times), but never 0x9999
  239. if ( 1 === preg_match( '/(?<=\d)x\d/', $curl ) ) {
  240. // Searching for a digit is 10 times more expensive than for the x, so we avoid doing this one!
  241. $curl = preg_replace( '/\b(\d(?(?<=0)[\d\.,]+|[\d\.,]*))x(\d[\d\.,]*)\b/', '$1&#215;$2', $curl );
  242. }
  243. // Replace each & with &#038; unless it already looks like an entity.
  244. $curl = preg_replace( '/&(?!#(?:\d+|x[a-f0-9]+);|[a-z1-4]{1,8};)/i', '&#038;', $curl );
  245. }
  246. }
  247. return implode( '', $textarr );
  248. }
  249. /**
  250. * Implements a logic tree to determine whether or not "7'." represents seven feet,
  251. * then converts the special char into either a prime char or a closing quote char.
  252. *
  253. * @since 4.3.0
  254. *
  255. * @param string $haystack The plain text to be searched.
  256. * @param string $needle The character to search for such as ' or ".
  257. * @param string $prime The prime char to use for replacement.
  258. * @param string $open_quote The opening quote char. Opening quote replacement must be
  259. * accomplished already.
  260. * @param string $close_quote The closing quote char to use for replacement.
  261. * @return string The $haystack value after primes and quotes replacements.
  262. */
  263. function wptexturize_primes( $haystack, $needle, $prime, $open_quote, $close_quote ) {
  264. $spaces = wp_spaces_regexp();
  265. $flag = '<!--wp-prime-or-quote-->';
  266. $quote_pattern = "/$needle(?=\\Z|[.,:;!?)}\\-\\]]|&gt;|" . $spaces . ")/";
  267. $prime_pattern = "/(?<=\\d)$needle/";
  268. $flag_after_digit = "/(?<=\\d)$flag/";
  269. $flag_no_digit = "/(?<!\\d)$flag/";
  270. $sentences = explode( $open_quote, $haystack );
  271. foreach ( $sentences as $key => &$sentence ) {
  272. if ( false === strpos( $sentence, $needle ) ) {
  273. continue;
  274. } elseif ( 0 !== $key && 0 === substr_count( $sentence, $close_quote ) ) {
  275. $sentence = preg_replace( $quote_pattern, $flag, $sentence, -1, $count );
  276. if ( $count > 1 ) {
  277. // This sentence appears to have multiple closing quotes. Attempt Vulcan logic.
  278. $sentence = preg_replace( $flag_no_digit, $close_quote, $sentence, -1, $count2 );
  279. if ( 0 === $count2 ) {
  280. // Try looking for a quote followed by a period.
  281. $count2 = substr_count( $sentence, "$flag." );
  282. if ( $count2 > 0 ) {
  283. // Assume the rightmost quote-period match is the end of quotation.
  284. $pos = strrpos( $sentence, "$flag." );
  285. } else {
  286. // When all else fails, make the rightmost candidate a closing quote.
  287. // This is most likely to be problematic in the context of bug #18549.
  288. $pos = strrpos( $sentence, $flag );
  289. }
  290. $sentence = substr_replace( $sentence, $close_quote, $pos, strlen( $flag ) );
  291. }
  292. // Use conventional replacement on any remaining primes and quotes.
  293. $sentence = preg_replace( $prime_pattern, $prime, $sentence );
  294. $sentence = preg_replace( $flag_after_digit, $prime, $sentence );
  295. $sentence = str_replace( $flag, $close_quote, $sentence );
  296. } elseif ( 1 == $count ) {
  297. // Found only one closing quote candidate, so give it priority over primes.
  298. $sentence = str_replace( $flag, $close_quote, $sentence );
  299. $sentence = preg_replace( $prime_pattern, $prime, $sentence );
  300. } else {
  301. // No closing quotes found. Just run primes pattern.
  302. $sentence = preg_replace( $prime_pattern, $prime, $sentence );
  303. }
  304. } else {
  305. $sentence = preg_replace( $prime_pattern, $prime, $sentence );
  306. $sentence = preg_replace( $quote_pattern, $close_quote, $sentence );
  307. }
  308. if ( '"' == $needle && false !== strpos( $sentence, '"' ) ) {
  309. $sentence = str_replace( '"', $close_quote, $sentence );
  310. }
  311. }
  312. return implode( $open_quote, $sentences );
  313. }
  314. /**
  315. * Search for disabled element tags. Push element to stack on tag open and pop
  316. * on tag close.
  317. *
  318. * Assumes first char of $text is tag opening and last char is tag closing.
  319. * Assumes second char of $text is optionally '/' to indicate closing as in </html>.
  320. *
  321. * @since 2.9.0
  322. * @access private
  323. *
  324. * @param string $text Text to check. Must be a tag like `<html>` or `[shortcode]`.
  325. * @param array $stack List of open tag elements.
  326. * @param array $disabled_elements The tag names to match against. Spaces are not allowed in tag names.
  327. */
  328. function _wptexturize_pushpop_element( $text, &$stack, $disabled_elements ) {
  329. // Is it an opening tag or closing tag?
  330. if ( isset( $text[1] ) && '/' !== $text[1] ) {
  331. $opening_tag = true;
  332. $name_offset = 1;
  333. } elseif ( 0 == count( $stack ) ) {
  334. // Stack is empty. Just stop.
  335. return;
  336. } else {
  337. $opening_tag = false;
  338. $name_offset = 2;
  339. }
  340. // Parse out the tag name.
  341. $space = strpos( $text, ' ' );
  342. if ( false === $space ) {
  343. $space = -1;
  344. } else {
  345. $space -= $name_offset;
  346. }
  347. $tag = substr( $text, $name_offset, $space );
  348. // Handle disabled tags.
  349. if ( in_array( $tag, $disabled_elements ) ) {
  350. if ( $opening_tag ) {
  351. /*
  352. * This disables texturize until we find a closing tag of our type
  353. * (e.g. <pre>) even if there was invalid nesting before that
  354. *
  355. * Example: in the case <pre>sadsadasd</code>"baba"</pre>
  356. * "baba" won't be texturize
  357. */
  358. array_push( $stack, $tag );
  359. } elseif ( end( $stack ) == $tag ) {
  360. array_pop( $stack );
  361. }
  362. }
  363. }
  364. /**
  365. * Replaces double line-breaks with paragraph elements.
  366. *
  367. * A group of regex replaces used to identify text formatted with newlines and
  368. * replace double line-breaks with HTML paragraph tags. The remaining line-breaks
  369. * after conversion become <<br />> tags, unless $br is set to '0' or 'false'.
  370. *
  371. * @since 0.71
  372. *
  373. * @param string $pee The text which has to be formatted.
  374. * @param bool $br Optional. If set, this will convert all remaining line-breaks
  375. * after paragraphing. Default true.
  376. * @return string Text which has been converted into correct paragraph tags.
  377. */
  378. function wpautop( $pee, $br = true ) {
  379. $pre_tags = array();
  380. if ( trim($pee) === '' )
  381. return '';
  382. // Just to make things a little easier, pad the end.
  383. $pee = $pee . "\n";
  384. /*
  385. * Pre tags shouldn't be touched by autop.
  386. * Replace pre tags with placeholders and bring them back after autop.
  387. */
  388. if ( strpos($pee, '<pre') !== false ) {
  389. $pee_parts = explode( '</pre>', $pee );
  390. $last_pee = array_pop($pee_parts);
  391. $pee = '';
  392. $i = 0;
  393. foreach ( $pee_parts as $pee_part ) {
  394. $start = strpos($pee_part, '<pre');
  395. // Malformed html?
  396. if ( $start === false ) {
  397. $pee .= $pee_part;
  398. continue;
  399. }
  400. $name = "<pre wp-pre-tag-$i></pre>";
  401. $pre_tags[$name] = substr( $pee_part, $start ) . '</pre>';
  402. $pee .= substr( $pee_part, 0, $start ) . $name;
  403. $i++;
  404. }
  405. $pee .= $last_pee;
  406. }
  407. // Change multiple <br>s into two line breaks, which will turn into paragraphs.
  408. $pee = preg_replace('|<br\s*/?>\s*<br\s*/?>|', "\n\n", $pee);
  409. $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)';
  410. // Add a double line break above block-level opening tags.
  411. $pee = preg_replace('!(<' . $allblocks . '[\s/>])!', "\n\n$1", $pee);
  412. // Add a double line break below block-level closing tags.
  413. $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
  414. // Standardize newline characters to "\n".
  415. $pee = str_replace(array("\r\n", "\r"), "\n", $pee);
  416. // Find newlines in all elements and add placeholders.
  417. $pee = wp_replace_in_html_tags( $pee, array( "\n" => " <!-- wpnl --> " ) );
  418. // Collapse line breaks before and after <option> elements so they don't get autop'd.
  419. if ( strpos( $pee, '<option' ) !== false ) {
  420. $pee = preg_replace( '|\s*<option|', '<option', $pee );
  421. $pee = preg_replace( '|</option>\s*|', '</option>', $pee );
  422. }
  423. /*
  424. * Collapse line breaks inside <object> elements, before <param> and <embed> elements
  425. * so they don't get autop'd.
  426. */
  427. if ( strpos( $pee, '</object>' ) !== false ) {
  428. $pee = preg_replace( '|(<object[^>]*>)\s*|', '$1', $pee );
  429. $pee = preg_replace( '|\s*</object>|', '</object>', $pee );
  430. $pee = preg_replace( '%\s*(</?(?:param|embed)[^>]*>)\s*%', '$1', $pee );
  431. }
  432. /*
  433. * Collapse line breaks inside <audio> and <video> elements,
  434. * before and after <source> and <track> elements.
  435. */
  436. if ( strpos( $pee, '<source' ) !== false || strpos( $pee, '<track' ) !== false ) {
  437. $pee = preg_replace( '%([<\[](?:audio|video)[^>\]]*[>\]])\s*%', '$1', $pee );
  438. $pee = preg_replace( '%\s*([<\[]/(?:audio|video)[>\]])%', '$1', $pee );
  439. $pee = preg_replace( '%\s*(<(?:source|track)[^>]*>)\s*%', '$1', $pee );
  440. }
  441. // Collapse line breaks before and after <figcaption> elements.
  442. if ( strpos( $pee, '<figcaption' ) !== false ) {
  443. $pee = preg_replace( '|\s*(<figcaption[^>]*>)|', '$1', $pee );
  444. $pee = preg_replace( '|</figcaption>\s*|', '</figcaption>', $pee );
  445. }
  446. // Remove more than two contiguous line breaks.
  447. $pee = preg_replace("/\n\n+/", "\n\n", $pee);
  448. // Split up the contents into an array of strings, separated by double line breaks.
  449. $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
  450. // Reset $pee prior to rebuilding.
  451. $pee = '';
  452. // Rebuild the content as a string, wrapping every bit with a <p>.
  453. foreach ( $pees as $tinkle ) {
  454. $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
  455. }
  456. // Under certain strange conditions it could create a P of entirely whitespace.
  457. $pee = preg_replace('|<p>\s*</p>|', '', $pee);
  458. // Add a closing <p> inside <div>, <address>, or <form> tag if missing.
  459. $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
  460. // If an opening or closing block element tag is wrapped in a <p>, unwrap it.
  461. $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
  462. // In some cases <li> may get wrapped in <p>, fix them.
  463. $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee);
  464. // If a <blockquote> is wrapped with a <p>, move it inside the <blockquote>.
  465. $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
  466. $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
  467. // If an opening or closing block element tag is preceded by an opening <p> tag, remove it.
  468. $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
  469. // If an opening or closing block element tag is followed by a closing <p> tag, remove it.
  470. $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
  471. // Optionally insert line breaks.
  472. if ( $br ) {
  473. // Replace newlines that shouldn't be touched with a placeholder.
  474. $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
  475. // Normalize <br>
  476. $pee = str_replace( array( '<br>', '<br/>' ), '<br />', $pee );
  477. // Replace any new line characters that aren't preceded by a <br /> with a <br />.
  478. $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee);
  479. // Replace newline placeholders with newlines.
  480. $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
  481. }
  482. // If a <br /> tag is after an opening or closing block tag, remove it.
  483. $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
  484. // If a <br /> tag is before a subset of opening or closing block tags, remove it.
  485. $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
  486. $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
  487. // Replace placeholder <pre> tags with their original content.
  488. if ( !empty($pre_tags) )
  489. $pee = str_replace(array_keys($pre_tags), array_values($pre_tags), $pee);
  490. // Restore newlines in all elements.
  491. if ( false !== strpos( $pee, '<!-- wpnl -->' ) ) {
  492. $pee = str_replace( array( ' <!-- wpnl --> ', '<!-- wpnl -->' ), "\n", $pee );
  493. }
  494. return $pee;
  495. }
  496. /**
  497. * Separate HTML elements and comments from the text.
  498. *
  499. * @since 4.2.4
  500. *
  501. * @param string $input The text which has to be formatted.
  502. * @return array The formatted text.
  503. */
  504. function wp_html_split( $input ) {
  505. return preg_split( get_html_split_regex(), $input, -1, PREG_SPLIT_DELIM_CAPTURE );
  506. }
  507. /**
  508. * Retrieve the regular expression for an HTML element.
  509. *
  510. * @since 4.4.0
  511. *
  512. * @return string The regular expression
  513. */
  514. function get_html_split_regex() {
  515. static $regex;
  516. if ( ! isset( $regex ) ) {
  517. $comments =
  518. '!' // Start of comment, after the <.
  519. . '(?:' // Unroll the loop: Consume everything until --> is found.
  520. . '-(?!->)' // Dash not followed by end of comment.
  521. . '[^\-]*+' // Consume non-dashes.
  522. . ')*+' // Loop possessively.
  523. . '(?:-->)?'; // End of comment. If not found, match all input.
  524. $cdata =
  525. '!\[CDATA\[' // Start of comment, after the <.
  526. . '[^\]]*+' // Consume non-].
  527. . '(?:' // Unroll the loop: Consume everything until ]]> is found.
  528. . '](?!]>)' // One ] not followed by end of comment.
  529. . '[^\]]*+' // Consume non-].
  530. . ')*+' // Loop possessively.
  531. . '(?:]]>)?'; // End of comment. If not found, match all input.
  532. $escaped =
  533. '(?=' // Is the element escaped?
  534. . '!--'
  535. . '|'
  536. . '!\[CDATA\['
  537. . ')'
  538. . '(?(?=!-)' // If yes, which type?
  539. . $comments
  540. . '|'
  541. . $cdata
  542. . ')';
  543. $regex =
  544. '/(' // Capture the entire match.
  545. . '<' // Find start of element.
  546. . '(?' // Conditional expression follows.
  547. . $escaped // Find end of escaped element.
  548. . '|' // ... else ...
  549. . '[^>]*>?' // Find end of normal element.
  550. . ')'
  551. . ')/';
  552. }
  553. return $regex;
  554. }
  555. /**
  556. * Retrieve the combined regular expression for HTML and shortcodes.
  557. *
  558. * @access private
  559. * @ignore
  560. * @internal This function will be removed in 4.5.0 per Shortcode API Roadmap.
  561. * @since 4.4.0
  562. *
  563. * @param string $shortcode_regex The result from _get_wptexturize_shortcode_regex(). Optional.
  564. * @return string The regular expression
  565. */
  566. function _get_wptexturize_split_regex( $shortcode_regex = '' ) {
  567. static $html_regex;
  568. if ( ! isset( $html_regex ) ) {
  569. $comment_regex =
  570. '!' // Start of comment, after the <.
  571. . '(?:' // Unroll the loop: Consume everything until --> is found.
  572. . '-(?!->)' // Dash not followed by end of comment.
  573. . '[^\-]*+' // Consume non-dashes.
  574. . ')*+' // Loop possessively.
  575. . '(?:-->)?'; // End of comment. If not found, match all input.
  576. $html_regex = // Needs replaced with wp_html_split() per Shortcode API Roadmap.
  577. '<' // Find start of element.
  578. . '(?(?=!--)' // Is this a comment?
  579. . $comment_regex // Find end of comment.
  580. . '|'
  581. . '[^>]*>?' // Find end of element. If not found, match all input.
  582. . ')';
  583. }
  584. if ( empty( $shortcode_regex ) ) {
  585. $regex = '/(' . $html_regex . ')/';
  586. } else {
  587. $regex = '/(' . $html_regex . '|' . $shortcode_regex . ')/';
  588. }
  589. return $regex;
  590. }
  591. /**
  592. * Retrieve the regular expression for shortcodes.
  593. *
  594. * @access private
  595. * @ignore
  596. * @internal This function will be removed in 4.5.0 per Shortcode API Roadmap.
  597. * @since 4.4.0
  598. *
  599. * @param array $tagnames List of shortcodes to find.
  600. * @return string The regular expression
  601. */
  602. function _get_wptexturize_shortcode_regex( $tagnames ) {
  603. $tagregexp = join( '|', array_map( 'preg_quote', $tagnames ) );
  604. $tagregexp = "(?:$tagregexp)(?=[\\s\\]\\/])"; // Excerpt of get_shortcode_regex().
  605. $regex =
  606. '\[' // Find start of shortcode.
  607. . '[\/\[]?' // Shortcodes may begin with [/ or [[
  608. . $tagregexp // Only match registered shortcodes, because performance.
  609. . '(?:'
  610. . '[^\[\]<>]+' // Shortcodes do not contain other shortcodes. Quantifier critical.
  611. . '|'
  612. . '<[^\[\]>]*>' // HTML elements permitted. Prevents matching ] before >.
  613. . ')*+' // Possessive critical.
  614. . '\]' // Find end of shortcode.
  615. . '\]?'; // Shortcodes may end with ]]
  616. return $regex;
  617. }
  618. /**
  619. * Replace characters or phrases within HTML elements only.
  620. *
  621. * @since 4.2.3
  622. *
  623. * @param string $haystack The text which has to be formatted.
  624. * @param array $replace_pairs In the form array('from' => 'to', ...).
  625. * @return string The formatted text.
  626. */
  627. function wp_replace_in_html_tags( $haystack, $replace_pairs ) {
  628. // Find all elements.
  629. $textarr = wp_html_split( $haystack );
  630. $changed = false;
  631. // Optimize when searching for one item.
  632. if ( 1 === count( $replace_pairs ) ) {
  633. // Extract $needle and $replace.
  634. foreach ( $replace_pairs as $needle => $replace );
  635. // Loop through delimiters (elements) only.
  636. for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
  637. if ( false !== strpos( $textarr[$i], $needle ) ) {
  638. $textarr[$i] = str_replace( $needle, $replace, $textarr[$i] );
  639. $changed = true;
  640. }
  641. }
  642. } else {
  643. // Extract all $needles.
  644. $needles = array_keys( $replace_pairs );
  645. // Loop through delimiters (elements) only.
  646. for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
  647. foreach ( $needles as $needle ) {
  648. if ( false !== strpos( $textarr[$i], $needle ) ) {
  649. $textarr[$i] = strtr( $textarr[$i], $replace_pairs );
  650. $changed = true;
  651. // After one strtr() break out of the foreach loop and look at next element.
  652. break;
  653. }
  654. }
  655. }
  656. }
  657. if ( $changed ) {
  658. $haystack = implode( $textarr );
  659. }
  660. return $haystack;
  661. }
  662. /**
  663. * Newline preservation help function for wpautop
  664. *
  665. * @since 3.1.0
  666. * @access private
  667. *
  668. * @param array $matches preg_replace_callback matches array
  669. * @return string
  670. */
  671. function _autop_newline_preservation_helper( $matches ) {
  672. return str_replace( "\n", "<WPPreserveNewline />", $matches[0] );
  673. }
  674. /**
  675. * Don't auto-p wrap shortcodes that stand alone
  676. *
  677. * Ensures that shortcodes are not wrapped in `<p>...</p>`.
  678. *
  679. * @since 2.9.0
  680. *
  681. * @global array $shortcode_tags
  682. *
  683. * @param string $pee The content.
  684. * @return string The filtered content.
  685. */
  686. function shortcode_unautop( $pee ) {
  687. global $shortcode_tags;
  688. if ( empty( $shortcode_tags ) || !is_array( $shortcode_tags ) ) {
  689. return $pee;
  690. }
  691. $tagregexp = join( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
  692. $spaces = wp_spaces_regexp();
  693. $pattern =
  694. '/'
  695. . '<p>' // Opening paragraph
  696. . '(?:' . $spaces . ')*+' // Optional leading whitespace
  697. . '(' // 1: The shortcode
  698. . '\\[' // Opening bracket
  699. . "($tagregexp)" // 2: Shortcode name
  700. . '(?![\\w-])' // Not followed by word character or hyphen
  701. // Unroll the loop: Inside the opening shortcode tag
  702. . '[^\\]\\/]*' // Not a closing bracket or forward slash
  703. . '(?:'
  704. . '\\/(?!\\])' // A forward slash not followed by a closing bracket
  705. . '[^\\]\\/]*' // Not a closing bracket or forward slash
  706. . ')*?'
  707. . '(?:'
  708. . '\\/\\]' // Self closing tag and closing bracket
  709. . '|'
  710. . '\\]' // Closing bracket
  711. . '(?:' // Unroll the loop: Optionally, anything between the opening and closing shortcode tags
  712. . '[^\\[]*+' // Not an opening bracket
  713. . '(?:'
  714. . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
  715. . '[^\\[]*+' // Not an opening bracket
  716. . ')*+'
  717. . '\\[\\/\\2\\]' // Closing shortcode tag
  718. . ')?'
  719. . ')'
  720. . ')'
  721. . '(?:' . $spaces . ')*+' // optional trailing whitespace
  722. . '<\\/p>' // closing paragraph
  723. . '/';
  724. return preg_replace( $pattern, '$1', $pee );
  725. }
  726. /**
  727. * Checks to see if a string is utf8 encoded.
  728. *
  729. * NOTE: This function checks for 5-Byte sequences, UTF8
  730. * has Bytes Sequences with a maximum length of 4.
  731. *
  732. * @author bmorel at ssi dot fr (modified)
  733. * @since 1.2.1
  734. *
  735. * @param string $str The string to be checked
  736. * @return bool True if $str fits a UTF-8 model, false otherwise.
  737. */
  738. function seems_utf8( $str ) {
  739. mbstring_binary_safe_encoding();
  740. $length = strlen($str);
  741. reset_mbstring_encoding();
  742. for ($i=0; $i < $length; $i++) {
  743. $c = ord($str[$i]);
  744. if ($c < 0x80) $n = 0; // 0bbbbbbb
  745. elseif (($c & 0xE0) == 0xC0) $n=1; // 110bbbbb
  746. elseif (($c & 0xF0) == 0xE0) $n=2; // 1110bbbb
  747. elseif (($c & 0xF8) == 0xF0) $n=3; // 11110bbb
  748. elseif (($c & 0xFC) == 0xF8) $n=4; // 111110bb
  749. elseif (($c & 0xFE) == 0xFC) $n=5; // 1111110b
  750. else return false; // Does not match any model
  751. for ($j=0; $j<$n; $j++) { // n bytes matching 10bbbbbb follow ?
  752. if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
  753. return false;
  754. }
  755. }
  756. return true;
  757. }
  758. /**
  759. * Converts a number of special characters into their HTML entities.
  760. *
  761. * Specifically deals with: &, <, >, ", and '.
  762. *
  763. * $quote_style can be set to ENT_COMPAT to encode " to
  764. * &quot;, or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
  765. *
  766. * @since 1.2.2
  767. * @access private
  768. *
  769. * @staticvar string $_charset
  770. *
  771. * @param string $string The text which is to be encoded.
  772. * @param int|string $quote_style Optional. Converts double quotes if set to ENT_COMPAT,
  773. * both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES.
  774. * Also compatible with old values; converting single quotes if set to 'single',
  775. * double if set to 'double' or both if otherwise set.
  776. * Default is ENT_NOQUOTES.
  777. * @param string $charset Optional. The character encoding of the string. Default is false.
  778. * @param bool $double_encode Optional. Whether to encode existing html entities. Default is false.
  779. * @return string The encoded text with HTML entities.
  780. */
  781. function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
  782. $string = (string) $string;
  783. if ( 0 === strlen( $string ) )
  784. return '';
  785. // Don't bother if there are no specialchars - saves some processing
  786. if ( ! preg_match( '/[&<>"\']/', $string ) )
  787. return $string;
  788. // Account for the previous behaviour of the function when the $quote_style is not an accepted value
  789. if ( empty( $quote_style ) )
  790. $quote_style = ENT_NOQUOTES;
  791. elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
  792. $quote_style = ENT_QUOTES;
  793. // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
  794. if ( ! $charset ) {
  795. static $_charset = null;
  796. if ( ! isset( $_charset ) ) {
  797. $alloptions = wp_load_alloptions();
  798. $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
  799. }
  800. $charset = $_charset;
  801. }
  802. if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) )
  803. $charset = 'UTF-8';
  804. $_quote_style = $quote_style;
  805. if ( $quote_style === 'double' ) {
  806. $quote_style = ENT_COMPAT;
  807. $_quote_style = ENT_COMPAT;
  808. } elseif ( $quote_style === 'single' ) {
  809. $quote_style = ENT_NOQUOTES;
  810. }
  811. if ( ! $double_encode ) {
  812. // Guarantee every &entity; is valid, convert &garbage; into &amp;garbage;
  813. // This is required for PHP < 5.4.0 because ENT_HTML401 flag is unavailable.
  814. $string = wp_kses_normalize_entities( $string );
  815. }
  816. $string = @htmlspecialchars( $string, $quote_style, $charset, $double_encode );
  817. // Back-compat.
  818. if ( 'single' === $_quote_style )
  819. $string = str_replace( "'", '&#039;', $string );
  820. return $string;
  821. }
  822. /**
  823. * Converts a number of HTML entities into their special characters.
  824. *
  825. * Specifically deals with: &, <, >, ", and '.
  826. *
  827. * $quote_style can be set to ENT_COMPAT to decode " entities,
  828. * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
  829. *
  830. * @since 2.8.0
  831. *
  832. * @param string $string The text which is to be decoded.
  833. * @param string|int $quote_style Optional. Converts double quotes if set to ENT_COMPAT,
  834. * both single and double if set to ENT_QUOTES or
  835. * none if set to ENT_NOQUOTES.
  836. * Also compatible with old _wp_specialchars() values;
  837. * converting single quotes if set to 'single',
  838. * double if set to 'double' or both if otherwise set.
  839. * Default is ENT_NOQUOTES.
  840. * @return string The decoded text without HTML entities.
  841. */
  842. function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
  843. $string = (string) $string;
  844. if ( 0 === strlen( $string ) ) {
  845. return '';
  846. }
  847. // Don't bother if there are no entities - saves a lot of processing
  848. if ( strpos( $string, '&' ) === false ) {
  849. return $string;
  850. }
  851. // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
  852. if ( empty( $quote_style ) ) {
  853. $quote_style = ENT_NOQUOTES;
  854. } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
  855. $quote_style = ENT_QUOTES;
  856. }
  857. // More complete than get_html_translation_table( HTML_SPECIALCHARS )
  858. $single = array( '&#039;' => '\'', '&#x27;' => '\'' );
  859. $single_preg = array( '/&#0*39;/' => '&#039;', '/&#x0*27;/i' => '&#x27;' );
  860. $double = array( '&quot;' => '"', '&#034;' => '"', '&#x22;' => '"' );
  861. $double_preg = array( '/&#0*34;/' => '&#034;', '/&#x0*22;/i' => '&#x22;' );
  862. $others = array( '&lt;' => '<', '&#060;' => '<', '&gt;' => '>', '&#062;' => '>', '&amp;' => '&', '&#038;' => '&', '&#x26;' => '&' );
  863. $others_preg = array( '/&#0*60;/' => '&#060;', '/&#0*62;/' => '&#062;', '/&#0*38;/' => '&#038;', '/&#x0*26;/i' => '&#x26;' );
  864. if ( $quote_style === ENT_QUOTES ) {
  865. $translation = array_merge( $single, $double, $others );
  866. $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
  867. } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
  868. $translation = array_merge( $double, $others );
  869. $translation_preg = array_merge( $double_preg, $others_preg );
  870. } elseif ( $quote_style === 'single' ) {
  871. $translation = array_merge( $single, $others );
  872. $translation_preg = array_merge( $single_preg, $others_preg );
  873. } elseif ( $quote_style === ENT_NOQUOTES ) {
  874. $translation = $others;
  875. $translation_preg = $others_preg;
  876. }
  877. // Remove zero padding on numeric entities
  878. $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
  879. // Replace characters according to translation table
  880. return strtr( $string, $translation );
  881. }
  882. /**
  883. * Checks for invalid UTF8 in a string.
  884. *
  885. * @since 2.8.0
  886. *
  887. * @staticvar bool $is_utf8
  888. * @staticvar bool $utf8_pcre
  889. *
  890. * @param string $string The text which is to be checked.
  891. * @param bool $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
  892. * @return string The checked text.
  893. */
  894. function wp_check_invalid_utf8( $string, $strip = false ) {
  895. $string = (string) $string;
  896. if ( 0 === strlen( $string ) ) {
  897. return '';
  898. }
  899. // Store the site charset as a static to avoid multiple calls to get_option()
  900. static $is_utf8 = null;
  901. if ( ! isset( $is_utf8 ) ) {
  902. $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
  903. }
  904. if ( ! $is_utf8 ) {
  905. return $string;
  906. }
  907. // Check for support for utf8 in the installed PCRE library once and store the result in a static
  908. static $utf8_pcre = null;
  909. if ( ! isset( $utf8_pcre ) ) {
  910. $utf8_pcre = @preg_match( '/^./u', 'a' );
  911. }
  912. // We can't demand utf8 in the PCRE installation, so just return the string in those cases
  913. if ( !$utf8_pcre ) {
  914. return $string;
  915. }
  916. // preg_match fails when it encounters invalid UTF8 in $string
  917. if ( 1 === @preg_match( '/^./us', $string ) ) {
  918. return $string;
  919. }
  920. // Attempt to strip the bad chars if requested (not recommended)
  921. if ( $strip && function_exists( 'iconv' ) ) {
  922. return iconv( 'utf-8', 'utf-8', $string );
  923. }
  924. return '';
  925. }
  926. /**
  927. * Encode the Unicode values to be used in the URI.
  928. *
  929. * @since 1.5.0
  930. *
  931. * @param string $utf8_string
  932. * @param int $length Max length of the string
  933. * @return string String with Unicode encoded for URI.
  934. */
  935. function utf8_uri_encode( $utf8_string, $length = 0 ) {
  936. $unicode = '';
  937. $values = array();
  938. $num_octets = 1;
  939. $unicode_length = 0;
  940. mbstring_binary_safe_encoding();
  941. $string_length = strlen( $utf8_string );
  942. reset_mbstring_encoding();
  943. for ($i = 0; $i < $string_length; $i++ ) {
  944. $value = ord( $utf8_string[ $i ] );
  945. if ( $value < 128 ) {
  946. if ( $length && ( $unicode_length >= $length ) )
  947. break;
  948. $unicode .= chr($value);
  949. $unicode_length++;
  950. } else {
  951. if ( count( $values ) == 0 ) {
  952. if ( $value < 224 ) {
  953. $num_octets = 2;
  954. } elseif ( $value < 240 ) {
  955. $num_octets = 3;
  956. } else {
  957. $num_octets = 4;
  958. }
  959. }
  960. $values[] = $value;
  961. if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
  962. break;
  963. if ( count( $values ) == $num_octets ) {
  964. for ( $j = 0; $j < $num_octets; $j++ ) {
  965. $unicode .= '%' . dechex( $values[ $j ] );
  966. }
  967. $unicode_length += $num_octets * 3;
  968. $values = array();
  969. $num_octets = 1;
  970. }
  971. }
  972. }
  973. return $unicode;
  974. }
  975. /**
  976. * Converts all accent characters to ASCII characters.
  977. *
  978. * If there are no accent characters, then the string given is just returned.
  979. *
  980. * **Accent characters converted:**
  981. *
  982. * Currency signs:
  983. *
  984. * | Code | Glyph | Replacement | Description |
  985. * | -------- | ----- | ----------- | ------------------- |
  986. * | U+00A3 | £ | (empty) | British Pound sign |
  987. * | U+20AC | € | E | Euro sign |
  988. *
  989. * Decompositions for Latin-1 Supplement:
  990. *
  991. * | Code | Glyph | Replacement | Description |
  992. * | ------- | ----- | ----------- | -------------------------------------- |
  993. * | U+00AA | ª | a | Feminine ordinal indicator |
  994. * | U+00BA | º | o | Masculine ordinal indicator |
  995. * | U+00C0 | À | A | Latin capital letter A with grave |
  996. * | U+00C1 | Á | A | Latin capital letter A with acute |
  997. * | U+00C2 | Â | A | Latin capital letter A with circumflex |
  998. * | U+00C3 | Ã | A | Latin capital letter A with tilde |
  999. * | U+00C4 | Ä | A | Latin capital letter A with diaeresis |
  1000. * | U+00C5 | Å | A | Latin capital letter A with ring above |
  1001. * | U+00C6 | Æ | AE | Latin capital letter AE |
  1002. * | U+00C7 | Ç | C | Latin capital letter C with cedilla |
  1003. * | U+00C8 | È | E | Latin capital letter E with grave |
  1004. * | U+00C9 | É | E | Latin capital letter E with acute |
  1005. * | U+00CA | Ê | E | Latin capital letter E with circumflex |
  1006. * | U+00CB | Ë | E | Latin capital letter E with diaeresis |
  1007. * | U+00CC | Ì | I | Latin capital letter I with grave |
  1008. * | U+00CD | Í | I | Latin capital letter I with acute |
  1009. * | U+00CE | Î | I | Latin capital letter I with circumflex |
  1010. * | U+00CF | Ï | I | Latin capital letter I with diaeresis |
  1011. * | U+00D0 | Ð | D | Latin capital letter Eth |
  1012. * | U+00D1 | Ñ | N | Latin capital letter N with tilde |
  1013. * | U+00D2 | Ò | O | Latin capital letter O with grave |
  1014. * | U+00D3 | Ó | O | Latin capital letter O with acute |
  1015. * | U+00D4 | Ô | O | Latin capital letter O with circumflex |
  1016. * | U+00D5 | Õ | O | Latin capital letter O with tilde |
  1017. * | U+00D6 | Ö | O | Latin capital letter O with diaeresis |
  1018. * | U+00D8 | Ø | O | Latin capital letter O with stroke |
  1019. * | U+00D9 | Ù | U | Latin capital letter U with grave |
  1020. * | U+00DA | Ú | U | Latin capital letter U with acute |
  1021. * | U+00DB | Û | U | Latin capital letter U with circumflex |
  1022. * | U+00DC | Ü | U | Latin capital letter U with diaeresis |
  1023. * | U+00DD | Ý | Y | Latin capital letter Y with acute |
  1024. * | U+00DE | Þ | TH | Latin capital letter Thorn |
  1025. * | U+00DF | ß | s | Latin small letter sharp s |
  1026. * | U+00E0 | à | a | Latin small letter a with grave |
  1027. * | U+00E1 | á | a | Latin small letter a with acute |
  1028. * | U+00E2 | â | a | Latin small letter a with circumflex |
  1029. * | U+00E3 | ã | a | Latin small letter a with tilde |
  1030. * | U+00E4 | ä | a | Latin small letter a with diaeresis |
  1031. * | U+00E5 | å | a | Latin small letter a with ring above |
  1032. * | U+00E6 | æ | ae | Latin small letter ae |
  1033. * | U+00E7 | ç | c | Latin small letter c with cedilla |
  1034. * | U+00E8 | è | e | Latin small letter e with grave |
  1035. * | U+00E9 | é | e | Latin small letter e with acute |
  1036. * | U+00EA | ê | e | Latin small letter e with circumflex |
  1037. * | U+00EB | ë | e | Latin small letter e with diaeresis |
  1038. * | U+00EC | ì | i | Latin small letter i with grave |
  1039. * | U+00ED | í | i | Latin small letter i with acute |
  1040. * | U+00EE | î | i | Latin small letter i with circumflex |
  1041. * | U+00EF | ï | i | Latin small letter i with diaeresis |
  1042. * | U+00F0 | ð | d | Latin small letter Eth |
  1043. * | U+00F1 | ñ | n | Latin small letter n with tilde |
  1044. * | U+00F2 | ò | o | Latin small letter o with grave |
  1045. * | U+00F3 | ó | o | Latin small letter o with acute |
  1046. * | U+00F4 | ô | o | Latin small letter o with circumflex |
  1047. * | U+00F5 | õ | o | Latin small letter o with tilde |
  1048. * | U+00F6 | ö | o | Latin small letter o with diaeresis |
  1049. * | U+00F8 | ø | o | Latin small letter o with stroke |
  1050. * | U+00F9 | ù | u | Latin small letter u with grave |
  1051. * | U+00FA | ú | u | Latin small letter u with acute |
  1052. * | U+00FB | û | u | Latin small letter u with circumflex |
  1053. * | U+00FC | ü | u | Latin small letter u with diaeresis |
  1054. * | U+00FD | ý | y | Latin small letter y with acute |
  1055. * | U+00FE | þ | th | Latin small letter Thorn |
  1056. * | U+00FF | ÿ | y | Latin small letter y with diaeresis |
  1057. *
  1058. * Decompositions for Latin Extended-A:
  1059. *
  1060. * | Code | Glyph | Replacement | Description |
  1061. * | ------- | ----- | ----------- | ------------------------------------------------- |
  1062. * | U+0100 | Ā | A | Latin capital letter A with macron |
  1063. * | U+0101 | ā | a | Latin small letter a with macron |
  1064. * | U+0102 | Ă | A | Latin capital letter A with breve |
  1065. * | U+0103 | ă | a | Latin small letter a with breve |
  1066. * | U+0104 | Ą | A | Latin capital letter A with ogonek |
  1067. * | U+0105 | ą | a | Latin small letter a with ogonek |
  1068. * | U+01006 | Ć | C | Latin capital letter C with acute |
  1069. * | U+0107 | ć | c | Latin small letter c with acute |
  1070. * | U+0108 | Ĉ | C | Latin capital letter C with circumflex |
  1071. * | U+0109 | ĉ | c | Latin small letter c with circumflex |
  1072. * | U+010A | Ċ | C | Latin capital letter C with dot above |
  1073. * | U+010B | ċ | c | Latin small letter c with dot above |
  1074. * | U+010C | Č | C | Latin capital letter C with caron |
  1075. * | U+010D | č | c | Latin small letter c with caron |
  1076. * | U+010E | Ď | D | Latin capital letter D with caron |
  1077. * | U+010F | ď | d | Latin small letter d with caron |
  1078. * | U+0110 | Đ | D | Latin capital letter D with stroke |
  1079. * | U+0111 | đ | d | Latin small letter d with stroke |
  1080. * | U+0112 | Ē | E | Latin capital letter E with macron |
  1081. * | U+0113 | ē | e | Latin small letter e with macron |
  1082. * | U+0114 | Ĕ | E | Latin capital letter E with breve |
  1083. * | U+0115 | ĕ | e | Latin small letter e with breve |
  1084. * | U+0116 | Ė | E | Latin capital letter E with dot above |
  1085. * | U+0117 | ė | e | Latin small letter e with dot above |
  1086. * | U+0118 | Ę | E | Latin capital letter E with ogonek |
  1087. * | U+0119 | ę | e | Latin small letter e with ogonek |
  1088. * | U+011A | Ě | E | Latin capital letter E with caron |
  1089. * | U+011B | ě | e | Latin small letter e with caron |
  1090. * | U+011C | Ĝ | G | Latin capital letter G with circumflex |
  1091. * | U+011D | ĝ | g | Latin small letter g with circumflex |
  1092. * | U+011E | Ğ | G | Latin capital letter G with breve |
  1093. * | U+011F | ğ | g | Latin small letter g with breve |
  1094. * | U+0120 | Ġ | G | Latin capital letter G with dot above |
  1095. * | U+0121 | ġ | g | Latin small letter g with dot above |
  1096. * | U+0122 | Ģ | G | Latin capital letter G with cedilla |
  1097. * | U+0123 | ģ | g | Latin small letter g with cedilla |
  1098. * | U+0124 | Ĥ | H | Latin capital letter H with circumflex |
  1099. * | U+0125 | ĥ | h | Latin small letter h with circumflex |
  1100. * | U+0126 | Ħ | H | Latin capital letter H with stroke |
  1101. * | U+0127 | ħ | h | Latin small letter h with stroke |
  1102. * | U+0128 | Ĩ | I | Latin capital letter I with tilde |
  1103. * | U+0129 | ĩ | i | Latin small letter i with tilde |
  1104. * | U+012A | Ī | I | Latin capital letter I with macron |
  1105. * | U+012B | ī | i | Latin small letter i with macron |
  1106. * | U+012C | Ĭ | I | Latin capital letter I with breve |
  1107. * | U+012D | ĭ | i | Latin small letter i with breve |
  1108. * | U+012E | Į | I | Latin capital letter I with ogonek |
  1109. * | U+012F | į | i | Latin small letter i with ogonek |
  1110. * | U+0130 | İ | I | Latin capital letter I with dot above |
  1111. * | U+0131 | ı | i | Latin small letter dotless i |
  1112. * | U+0132 | IJ | IJ | Latin capital ligature IJ |
  1113. * | U+0133 | ij | ij | Latin small ligature ij |
  1114. * | U+0134 | Ĵ | J | Latin capital letter J with circumflex |
  1115. * | U+0135 | ĵ | j | Latin small letter j with circumflex |
  1116. * | U+0136 | Ķ | K | Latin capital letter K with cedilla |
  1117. * | U+0137 | ķ | k | Latin small letter k with cedilla |
  1118. * | U+0138 | ĸ | k | Latin small letter Kra |
  1119. * | U+0139 | Ĺ | L | Latin capital letter L with acute |
  1120. * | U+013A | ĺ | l | Latin small letter l with acute |
  1121. * | U+013B | Ļ | L | Latin capital letter L with cedilla |
  1122. * | U+013C | ļ | l | Latin small letter l with cedilla |
  1123. * | U+013D | Ľ | L | Latin capital letter L with caron |
  1124. * | U+013E | ľ | l | Latin small letter l with caron |
  1125. * | U+013F | Ŀ | L | Latin capital letter L with middle dot |
  1126. * | U+0140 | ŀ | l | Latin small letter l with middle dot |
  1127. * | U+0141 | Ł | L | Latin capital letter L with stroke |
  1128. * | U+0142 | ł | l | Latin small letter l with stroke |
  1129. * | U+0143 | Ń | N | Latin capital letter N with acute |
  1130. * | U+0144 | ń | n | Latin small letter N with acute |
  1131. * | U+0145 | Ņ | N | Latin capital letter N with cedilla |
  1132. * | U+0146 | ņ | n | Latin small letter n with cedilla |
  1133. * | U+0147 | Ň | N | Latin capital letter N with caron |
  1134. * | U+0148 | ň | n | Latin small letter n with caron |
  1135. * | U+0149 | ʼn | n | Latin small letter n preceded by apostrophe |
  1136. * | U+014A | Ŋ | N | Latin capital letter Eng |
  1137. * | U+014B | ŋ | n | Latin small letter Eng |
  1138. * | U+014C | Ō | O | Latin capital letter O with macron |
  1139. * | U+014D | ō | o | Latin small letter o with macron |
  1140. * | U+014E | Ŏ | O | Latin capital letter O with breve |
  1141. * | U+014F | ŏ | o | Latin small letter o with breve |
  1142. * | U+0150 | Ő | O | Latin capital letter O with double acute |
  1143. * | U+0151 | ő | o | Latin small letter o with double acute |
  1144. * | U+0152 | Œ | OE | Latin capital ligature OE |
  1145. * | U+0153 | œ | oe | Latin small ligature oe |
  1146. * | U+0154 | Ŕ | R | Latin capital letter R with acute |
  1147. * | U+0155 | ŕ | r | Latin small letter r with acute |
  1148. * | U+0156 | Ŗ | R | Latin capital letter R with cedilla |
  1149. * | U+0157 | ŗ | r | Latin small letter r with cedilla |
  1150. * | U+0158 | Ř | R | Latin capital letter R with caron |
  1151. * | U+0159 | ř | r | Latin small letter r with caron |
  1152. * | U+015A | Ś | S | Latin capital letter S with acute |
  1153. * | U+015B | ś | s | Latin small letter s with acute |
  1154. * | U+015C | Ŝ | S | Latin capital letter S with circumflex |
  1155. * | U+015D | ŝ | s | Latin small letter s with circumflex |
  1156. * | U+015E | Ş | S | Latin capital letter S with cedilla |
  1157. * | U+015F | ş | s | Latin small letter s with cedilla |
  1158. * | U+0160 | Š | S | Latin capital letter S with caron |
  1159. * | U+0161 | š | s | Latin small letter s with caron |
  1160. * | U+0162 | Ţ | T | Latin capital letter T with cedilla |
  1161. * | U+0163 | ţ | t | Latin small letter t with cedilla |
  1162. * | U+0164 | Ť | T | Latin capital letter T with caron |
  1163. * | U+0165 | ť | t | Latin small letter t with caron |
  1164. * | U+0166 | Ŧ | T | Latin capital letter T with stroke |
  1165. * | U+0167 | ŧ | t | Latin small letter t with stroke |
  1166. * | U+0168 | Ũ | U | Latin capital letter U with tilde |
  1167. * | U+0169 | ũ | u | Latin small letter u with tilde |
  1168. * | U+016A | Ū | U | Latin capital letter U with macron |
  1169. * | U+016B | ū | u | Latin small letter u with macron |
  1170. * | U+016C | Ŭ | U | Latin capital letter U with breve |
  1171. * | U+016D | ŭ | u | Latin small letter u with breve |
  1172. * | U+016E | Ů | U | Latin capital letter U with ring above |
  1173. * | U+016F | ů | u | Latin small letter u with ring above |
  1174. * | U+0170 | Ű | U | Latin capital letter U with double acute |
  1175. * | U+0171 | ű | u | Latin small letter u with double acute |
  1176. * | U+0172 | Ų | U | Latin capital letter U with ogonek |
  1177. * | U+0173 | ų | u | Latin small letter u with ogonek |
  1178. * | U+0174 | Ŵ | W | Latin capital letter W with circumflex |
  1179. * | U+0175 | ŵ | w | Latin small letter w with circumflex |
  1180. * | U+0176 | Ŷ | Y | Latin capital letter Y with circumflex |
  1181. * | U+0177 | ŷ | y | Latin small letter y with circumflex |
  1182. * | U+0178 | Ÿ | Y | Latin capital letter Y with diaeresis |
  1183. * | U+0179 | Ź | Z | Latin capital letter Z with acute |
  1184. * | U+017A | ź | z | Latin small letter z with acute |
  1185. * | U+017B | Ż | Z | Latin capital letter Z with dot above |
  1186. * | U+017C | ż | z | Latin small letter z with dot above |
  1187. * | U+017D | Ž | Z | Latin capital letter Z with caron |
  1188. * | U+017E | ž | z | Latin small letter z with caron |
  1189. * | U+017F | ſ | s | Latin small letter long s |
  1190. * | U+01A0 | Ơ | O | Latin capital letter O with horn |
  1191. * | U+01A1 | ơ | o | Latin small letter o with horn |
  1192. * | U+01AF | Ư | U | Latin capital letter U with horn |
  1193. * | U+01B0 | ư | u | Latin small letter u with horn |
  1194. * | U+01CD | Ǎ | A | Latin capital letter A with caron |
  1195. * | U+01CE | ǎ | a | Latin small letter a with caron |
  1196. * | U+01CF | Ǐ | I | Latin capital letter I with caron |
  1197. * | U+01D0 | ǐ | i | Latin small letter i with caron |
  1198. * | U+01D1 | Ǒ | O | Latin capital letter O with caron |
  1199. * | U+01D2 | ǒ | o | Latin small letter o with caron |
  1200. * | U+01D3 | Ǔ | U | Latin capital letter U with caron |
  1201. * | U+01D4 | ǔ | u | Latin small letter u with caron |
  1202. * | U+01D5 | Ǖ | U | Latin capital letter U with diaeresis and macron |
  1203. * | U+01D6 | ǖ | u | Latin small letter u with diaeresis and macron |
  1204. * | U+01D7 | Ǘ | U | Latin capital letter U with diaeresis and acute |
  1205. * | U+01D8 | ǘ | u | Latin small letter u with diaeresis and acute |
  1206. * | U+01D9 | Ǚ | U | Latin capital letter U with diaeresis and caron |
  1207. * | U+01DA | ǚ | u | Latin small letter u with diaeresis and caron |
  1208. * | U+01DB | Ǜ | U | Latin capital letter U with diaeresis and grave |
  1209. * | U+01DC | ǜ | u | Latin small letter u with diaeresis and grave |
  1210. *
  1211. * Decompositions for Latin Extended-B:
  1212. *
  1213. * | Code | Glyph | Replacement | Description |
  1214. * | -------- | ----- | ----------- | ----------------------------------------- |
  1215. * | U+0218 | Ș | S | Latin capital letter S with comma below |
  1216. * | U+0219 | ș | s | Latin small letter s with comma below |
  1217. * | U+021A | Ț | T | Latin capital letter T with comma below |
  1218. * | U+021B | ț | t | Latin small letter t with comma below |
  1219. *
  1220. * Vowels with diacritic (Chinese, Hanyu Pinyin):
  1221. *
  1222. * | Code | Glyph | Replacement | Description |
  1223. * | -------- | ----- | ----------- | ----------------------------------------------------- |
  1224. * | U+0251 | ɑ | a | Latin small letter alpha |
  1225. * | U+1EA0 | Ạ | A | Latin capital letter A with dot below |
  1226. * | U+1EA1 | ạ | a | Latin small letter a with dot below |
  1227. * | U+1EA2 | Ả | A | Latin capital letter A with hook above |
  1228. * | U+1EA3 | ả | a | Latin small letter a with hook above |
  1229. * | U+1EA4 | Ấ | A | Latin capital letter A with circumflex and acute |
  1230. * | U+1EA5 | ấ | a | Latin small letter a with circumflex and acute |
  1231. * | U+1EA6 | Ầ | A | Latin capital letter A with circumflex and grave |
  1232. * | U+1EA7 | ầ | a | Latin small letter a with circumflex and grave |
  1233. * | U+1EA8 | Ẩ | A | Latin capital letter A with circumflex and hook above |
  1234. * | U+1EA9 | ẩ | a | Latin small letter a with circumflex and hook above |
  1235. * | U+1EAA | Ẫ | A | Latin capital letter A with circumflex and tilde |
  1236. * | U+1EAB | ẫ | a | Latin small letter a with circumflex and tilde |
  1237. * | U+1EA6 | Ậ | A | Latin capital letter A with circumflex and dot below |
  1238. * | U+1EAD | ậ | a | Latin small letter a with circumflex and dot below |
  1239. * | U+1EAE | Ắ | A | Latin capital letter A with breve and acute |
  1240. * | U+1EAF | ắ | a | Latin small letter a with breve and acute |
  1241. * | U+1EB0 | Ằ | A | Latin capital letter A with breve and grave |
  1242. * | U+1EB1 | ằ | a | Latin small letter a with breve and grave |
  1243. * | U+1EB2 | Ẳ | A | Latin capital letter A with breve and hook above |
  1244. * | U+1EB3 | ẳ | a | Latin small letter a with breve and hook above |
  1245. * | U+1EB4 | Ẵ | A | Latin capital letter A with breve and tilde |
  1246. * | U+1EB5 | ẵ | a | Latin small letter a with breve and tilde |
  1247. * | U+1EB6 | Ặ | A | Latin capital letter A with breve and dot below |
  1248. * | U+1EB7 | ặ | a | Latin small letter a with breve and dot below |
  1249. * | U+1EB8 | Ẹ | E | Latin capital letter E with dot below |
  1250. * | U+1EB9 | ẹ | e | Latin small letter e with dot below |
  1251. * | U+1EBA | Ẻ | E | Latin capital letter E with hook above |
  1252. * | U+1EBB | ẻ | e | Latin small letter e with hook above |
  1253. * | U+1EBC | Ẽ | E | Latin capital letter E with tilde |
  1254. * | U+1EBD | ẽ | e | Latin small letter e with tilde |
  1255. * | U+1EBE | Ế | E | Latin capital letter E with circumflex and acute |
  1256. * | U+1EBF | ế | e | Latin small letter e with circumflex and acute |
  1257. * | U+1EC0 | Ề | E | Latin capital letter E with circumflex and grave |
  1258. * | U+1EC1 | ề | e | Latin small letter e with circumflex and grave |
  1259. * | U+1EC2 | Ể | E | Latin capital letter E with circumflex and hook above |
  1260. * | U+1EC3 | ể | e | Latin small letter e with circumflex and hook above |
  1261. * | U+1EC4 | Ễ | E | Latin capital letter E with circumflex and tilde |
  1262. * | U+1EC5 | ễ | e | Latin small letter e with circumflex and tilde |
  1263. * | U+1EC6 | Ệ | E | Latin capital letter E with circumflex and dot below |
  1264. * | U+1EC7 | ệ | e | Latin small letter e with circumflex and dot below |
  1265. * | U+1EC8 | Ỉ | I | Latin capital letter I with hook above |
  1266. * | U+1EC9 | ỉ | i | Latin small letter i with hook above |
  1267. * | U+1ECA | Ị | I | Latin capital letter I with dot below |
  1268. * | U+1ECB | ị | i | Latin small letter i with dot below |
  1269. * | U+1ECC | Ọ | O | Latin capital letter O with dot below |
  1270. * | U+1ECD | ọ | o | Latin small letter o with dot below |
  1271. * | U+1ECE | Ỏ | O | Latin capital letter O with hook above |
  1272. * | U+1ECF | ỏ | o | Latin small letter o with hook above |
  1273. * | U+1ED0 | Ố | O | Latin capital letter O with circumflex and acute |
  1274. * | U+1ED1 | ố | o | Latin small letter o with circumflex and acute |
  1275. * | U+1ED2 | Ồ | O | Latin capital letter O with circumflex and grave |
  1276. * | U+1ED3 | ồ | o | Latin small letter o with circumflex and grave |
  1277. * | U+1ED4 | Ổ | O | Latin capital letter O with circumflex and hook above |
  1278. * | U+1ED5 | ổ | o | Latin small letter o with circumflex and hook above |
  1279. * | U+1ED6 | Ỗ | O | Latin capital letter O with circumflex and tilde |
  1280. * | U+1ED7 | ỗ | o | Latin small letter o with circumflex and tilde |
  1281. * | U+1ED8 | Ộ | O | Latin capital letter O with circumflex and dot below |
  1282. * | U+1ED9 | ộ | o | Latin small letter o with circumflex and dot below |
  1283. * | U+1EDA | Ớ | O | Latin capital letter O with horn and acute |
  1284. * | U+1EDB | ớ | o | Latin small letter o with horn and acute |
  1285. * | U+1EDC | Ờ | O | Latin capital letter O with horn and grave |
  1286. * | U+1EDD | ờ | o | Latin small letter o with horn and grave |
  1287. * | U+1EDE | Ở | O | Latin capital letter O with horn and hook above |
  1288. * | U+1EDF | ở | o | Latin small letter o with horn and hook above |
  1289. * | U+1EE0 | Ỡ | O | Latin capital letter O with horn and tilde |
  1290. * | U+1EE1 | ỡ | o | Latin small letter o with horn and tilde |
  1291. * | U+1EE2 | Ợ | O | Latin capital letter O with horn and dot below |
  1292. * | U+1EE3 | ợ | o | Latin small letter o with horn and dot below |
  1293. * | U+1EE4 | Ụ | U | Latin capital letter U with dot below |
  1294. * | U+1EE5 | ụ | u | Latin small letter u with dot below |
  1295. * | U+1EE6 | Ủ | U | Latin capital letter U with hook above |
  1296. * | U+1EE7 | ủ | u | Latin small letter u with hook above |
  1297. * | U+1EE8 | Ứ | U | Latin capital letter U with horn and acute |
  1298. * | U+1EE9 | ứ | u | Latin small letter u with horn and acute |
  1299. * | U+1EEA | Ừ | U | Latin capital letter U with horn and grave |
  1300. * | U+1EEB | ừ | u | Latin small letter u with horn and grave |
  1301. * | U+1EEC | Ử | U | Latin capital letter U with horn and hook above |
  1302. * | U+1EED | ử | u | Latin small letter u with horn and hook above |
  1303. * | U+1EEE | Ữ | U | Latin capital letter U with horn and tilde |
  1304. * | U+1EEF | ữ | u | Latin small letter u with horn and tilde |
  1305. * | U+1EF0 | Ự | U | Latin capital letter U with horn and dot below |
  1306. * | U+1EF1 | ự | u | Latin small letter u with horn and dot below |
  1307. * | U+1EF2 | Ỳ | Y | Latin capital letter Y with grave |
  1308. * | U+1EF3 | ỳ | y | Latin small letter y with grave |
  1309. * | U+1EF4 | Ỵ | Y | Latin capital letter Y with dot below |
  1310. * | U+1EF5 | ỵ | y | Latin small letter y with dot below |
  1311. * | U+1EF6 | Ỷ | Y | Latin capital letter Y with hook above |
  1312. * | U+1EF7 | ỷ | y | Latin small letter y with hook above |
  1313. * | U+1EF8 | Ỹ | Y | Latin capital letter Y with tilde |
  1314. * | U+1EF9 | ỹ | y | Latin small letter y with tilde |
  1315. *
  1316. * German (`de_DE`), German formal (`de_DE_formal`), German (Switzerland) formal (`de_CH`),
  1317. * and German (Switzerland) informal (`de_CH_informal`) locales:
  1318. *
  1319. * | Code | Glyph | Replacement | Description |
  1320. * | -------- | ----- | ----------- | --------------------------------------- |
  1321. * | U+00C4 | Ä | Ae | Latin capital letter A with diaeresis |
  1322. * | U+00E4 | ä | ae | Latin small letter a with diaeresis |
  1323. * | U+00D6 | Ö | Oe | Latin capital letter O with diaeresis |
  1324. * | U+00F6 | ö | oe | Latin small letter o with diaeresis |
  1325. * | U+00DC | Ü | Ue | Latin capital letter U with diaeresis |
  1326. * | U+00FC | ü | ue | Latin small letter u with diaeresis |
  1327. * | U+00DF | ß | ss | Latin small letter sharp s |
  1328. *
  1329. * Danish (`da_DK`) locale:
  1330. *
  1331. * | Code | Glyph | Replacement | Description |
  1332. * | -------- | ----- | ----------- | --------------------------------------- |
  1333. * | U+00C6 | Æ | Ae | Latin capital letter AE |
  1334. * | U+00E6 | æ | ae | Latin small letter ae |
  1335. * | U+00D8 | Ø | Oe | Latin capital letter O with stroke |
  1336. * | U+00F8 | ø | oe | Latin small letter o with stroke |
  1337. * | U+00C5 | Å | Aa | Latin capital letter A with ring above |
  1338. * | U+00E5 | å | aa | Latin small letter a with ring above |
  1339. *
  1340. * Catalan (`ca`) locale:
  1341. *
  1342. * | Code | Glyph | Replacement | Description |
  1343. * | -------- | ----- | ----------- | --------------------------------------- |
  1344. * | U+00B7 | l·l | ll | Flown dot (between two Ls) |
  1345. *
  1346. * Serbian (`sr_RS`) locale:
  1347. *
  1348. * | Code | Glyph | Replacement | Description |
  1349. * | -------- | ----- | ----------- | --------------------------------------- |
  1350. * | U+0110 | Đ | DJ | Latin capital letter D with stroke |
  1351. * | U+0111 | đ | dj | Latin small letter d with stroke |
  1352. *
  1353. * @since 1.2.1
  1354. * @since 4.6.0 Added locale support for `de_CH`, `de_CH_informal`, and `ca`.
  1355. * @since 4.7.0 Added locale support for `sr_RS`.
  1356. *
  1357. * @param string $string Text that might have accent characters
  1358. * @return string Filtered string with replaced "nice" characters.
  1359. */
  1360. function remove_accents( $string ) {
  1361. if ( !preg_match('/[\x80-\xff]/', $string) )
  1362. return $string;
  1363. if (seems_utf8($string)) {
  1364. $chars = array(
  1365. // Decompositions for Latin-1 Supplement
  1366. 'ª' => 'a', 'º' => 'o',
  1367. 'À' => 'A', 'Á' => 'A',
  1368. 'Â' => 'A', 'Ã' => 'A',
  1369. 'Ä' => 'A', 'Å' => 'A',
  1370. 'Æ' => 'AE','Ç' => 'C',
  1371. 'È' => 'E', 'É' => 'E',
  1372. 'Ê' => 'E', 'Ë' => 'E',
  1373. 'Ì' => 'I', 'Í' => 'I',
  1374. 'Î' => 'I', 'Ï' => 'I',
  1375. 'Ð' => 'D', 'Ñ' => 'N',
  1376. 'Ò' => 'O', 'Ó' => 'O',
  1377. 'Ô' => 'O', 'Õ' => 'O',
  1378. 'Ö' => 'O', 'Ù' => 'U',
  1379. 'Ú' => 'U', 'Û' => 'U',
  1380. 'Ü' => 'U', 'Ý' => 'Y',
  1381. 'Þ' => 'TH','ß' => 's',
  1382. 'à' => 'a', 'á' => 'a',
  1383. 'â' => 'a', 'ã' => 'a',
  1384. 'ä' => 'a', 'å' => 'a',
  1385. 'æ' => 'ae','ç' => 'c',
  1386. 'è' => 'e', 'é' => 'e',
  1387. 'ê' => 'e', 'ë' => 'e',
  1388. 'ì' => 'i', 'í' => 'i',
  1389. 'î' => 'i', 'ï' => 'i',
  1390. 'ð' => 'd', 'ñ' => 'n',
  1391. 'ò' => 'o', 'ó' => 'o',
  1392. 'ô' => 'o', 'õ' => 'o',
  1393. 'ö' => 'o', 'ø' => 'o',
  1394. 'ù' => 'u', 'ú' => 'u',
  1395. 'û' => 'u', 'ü' => 'u',
  1396. 'ý' => 'y', 'þ' => 'th',
  1397. 'ÿ' => 'y', 'Ø' => 'O',
  1398. // Decompositions for Latin Extended-A
  1399. 'Ā' => 'A', 'ā' => 'a',
  1400. 'Ă' => 'A', 'ă' => 'a',
  1401. 'Ą' => 'A', 'ą' => 'a',
  1402. 'Ć' => 'C', 'ć' => 'c',
  1403. 'Ĉ' => 'C', 'ĉ' => 'c',
  1404. 'Ċ' => 'C', 'ċ' => 'c',
  1405. 'Č' => 'C', 'č' => 'c',
  1406. 'Ď' => 'D', 'ď' => 'd',
  1407. 'Đ' => 'D', 'đ' => 'd',
  1408. 'Ē' => 'E', 'ē' => 'e',
  1409. 'Ĕ' => 'E', 'ĕ' => 'e',
  1410. 'Ė' => 'E', 'ė' => 'e',
  1411. 'Ę' => 'E', 'ę' => 'e',
  1412. 'Ě' => 'E', 'ě' => 'e',
  1413. 'Ĝ' => 'G', 'ĝ' => 'g',
  1414. 'Ğ' => 'G', 'ğ' => 'g',
  1415. 'Ġ' => 'G', 'ġ' => 'g',
  1416. 'Ģ' => 'G', 'ģ' => 'g',
  1417. 'Ĥ' => 'H', 'ĥ' => 'h',
  1418. 'Ħ' => 'H', 'ħ' => 'h',
  1419. 'Ĩ' => 'I', 'ĩ' => 'i',
  1420. 'Ī' => 'I', 'ī' => 'i',
  1421. 'Ĭ' => 'I', 'ĭ' => 'i',
  1422. 'Į' => 'I', 'į' => 'i',
  1423. 'İ' => 'I', 'ı' => 'i',
  1424. 'IJ' => 'IJ','ij' => 'ij',
  1425. 'Ĵ' => 'J', 'ĵ' => 'j',
  1426. 'Ķ' => 'K', 'ķ' => 'k',
  1427. 'ĸ' => 'k', 'Ĺ' => 'L',
  1428. 'ĺ' => 'l', 'Ļ' => 'L',
  1429. 'ļ' => 'l', 'Ľ' => 'L',
  1430. 'ľ' => 'l', 'Ŀ' => 'L',
  1431. 'ŀ' => 'l', 'Ł' => 'L',
  1432. 'ł' => 'l', 'Ń' => 'N',
  1433. 'ń' => 'n', 'Ņ' => 'N',
  1434. 'ņ' => 'n', 'Ň' => 'N',
  1435. 'ň' => 'n', 'ʼn' => 'n',
  1436. 'Ŋ' => 'N', 'ŋ' => 'n',
  1437. 'Ō' => 'O', 'ō' => 'o',
  1438. 'Ŏ' => 'O', 'ŏ' => 'o',
  1439. 'Ő' => 'O', 'ő' => 'o',
  1440. 'Œ' => 'OE','œ' => 'oe',
  1441. 'Ŕ' => 'R','ŕ' => 'r',
  1442. 'Ŗ' => 'R','ŗ' => 'r',
  1443. 'Ř' => 'R','ř' => 'r',
  1444. 'Ś' => 'S','ś' => 's',
  1445. 'Ŝ' => 'S','ŝ' => 's',
  1446. 'Ş' => 'S','ş' => 's',
  1447. 'Š' => 'S', 'š' => 's',
  1448. 'Ţ' => 'T', 'ţ' => 't',
  1449. 'Ť' => 'T', 'ť' => 't',
  1450. 'Ŧ' => 'T', 'ŧ' => 't',
  1451. 'Ũ' => 'U', 'ũ' => 'u',
  1452. 'Ū' => 'U', 'ū' => 'u',
  1453. 'Ŭ' => 'U', 'ŭ' => 'u',
  1454. 'Ů' => 'U', 'ů' => 'u',
  1455. 'Ű' => 'U', 'ű' => 'u',
  1456. 'Ų' => 'U', 'ų' => 'u',
  1457. 'Ŵ' => 'W', 'ŵ' => 'w',
  1458. 'Ŷ' => 'Y', 'ŷ' => 'y',
  1459. 'Ÿ' => 'Y', 'Ź' => 'Z',
  1460. 'ź' => 'z', 'Ż' => 'Z',
  1461. 'ż' => 'z', 'Ž' => 'Z',
  1462. 'ž' => 'z', 'ſ' => 's',
  1463. // Decompositions for Latin Extended-B
  1464. 'Ș' => 'S', 'ș' => 's',
  1465. 'Ț' => 'T', 'ț' => 't',
  1466. // Euro Sign
  1467. '€' => 'E',
  1468. // GBP (Pound) Sign
  1469. '£' => '',
  1470. // Vowels with diacritic (Vietnamese)
  1471. // unmarked
  1472. 'Ơ' => 'O', 'ơ' => 'o',
  1473. 'Ư' => 'U', 'ư' => 'u',
  1474. // grave accent
  1475. 'Ầ' => 'A', 'ầ' => 'a',
  1476. 'Ằ' => 'A', 'ằ' => 'a',
  1477. 'Ề' => 'E', 'ề' => 'e',
  1478. 'Ồ' => 'O', 'ồ' => 'o',
  1479. 'Ờ' => 'O', 'ờ' => 'o',
  1480. 'Ừ' => 'U', 'ừ' => 'u',
  1481. 'Ỳ' => 'Y', 'ỳ' => 'y',
  1482. // hook
  1483. 'Ả' => 'A', 'ả' => 'a',
  1484. 'Ẩ' => 'A', 'ẩ' => 'a',
  1485. 'Ẳ' => 'A', 'ẳ' => 'a',
  1486. 'Ẻ' => 'E', 'ẻ' => 'e',
  1487. 'Ể' => 'E', 'ể' => 'e',
  1488. 'Ỉ' => 'I', 'ỉ' => 'i',
  1489. 'Ỏ' => 'O', 'ỏ' => 'o',
  1490. 'Ổ' => 'O', 'ổ' => 'o',
  1491. 'Ở' => 'O', 'ở' => 'o',
  1492. 'Ủ' => 'U', 'ủ' => 'u',
  1493. 'Ử' => 'U', 'ử' => 'u',
  1494. 'Ỷ' => 'Y', 'ỷ' => 'y',
  1495. // tilde
  1496. 'Ẫ' => 'A', 'ẫ' => 'a',
  1497. 'Ẵ' => 'A', 'ẵ' => 'a',
  1498. 'Ẽ' => 'E', 'ẽ' => 'e',
  1499. 'Ễ' => 'E', 'ễ' => 'e',
  1500. 'Ỗ' => 'O', 'ỗ' => 'o',
  1501. 'Ỡ' => 'O', 'ỡ' => 'o',
  1502. 'Ữ' => 'U', 'ữ' => 'u',
  1503. 'Ỹ' => 'Y', 'ỹ' => 'y',
  1504. // acute accent
  1505. 'Ấ' => 'A', 'ấ' => 'a',
  1506. 'Ắ' => 'A', 'ắ' => 'a',
  1507. 'Ế' => 'E', 'ế' => 'e',
  1508. 'Ố' => 'O', 'ố' => 'o',
  1509. 'Ớ' => 'O', 'ớ' => 'o',
  1510. 'Ứ' => 'U', 'ứ' => 'u',
  1511. // dot below
  1512. 'Ạ' => 'A', 'ạ' => 'a',
  1513. 'Ậ' => 'A', 'ậ' => 'a',
  1514. 'Ặ' => 'A', 'ặ' => 'a',
  1515. 'Ẹ' => 'E', 'ẹ' => 'e',
  1516. 'Ệ' => 'E', 'ệ' => 'e',
  1517. 'Ị' => 'I', 'ị' => 'i',
  1518. 'Ọ' => 'O', 'ọ' => 'o',
  1519. 'Ộ' => 'O', 'ộ' => 'o',
  1520. 'Ợ' => 'O', 'ợ' => 'o',
  1521. 'Ụ' => 'U', 'ụ' => 'u',
  1522. 'Ự' => 'U', 'ự' => 'u',
  1523. 'Ỵ' => 'Y', 'ỵ' => 'y',
  1524. // Vowels with diacritic (Chinese, Hanyu Pinyin)
  1525. 'ɑ' => 'a',
  1526. // macron
  1527. 'Ǖ' => 'U', 'ǖ' => 'u',
  1528. // acute accent
  1529. 'Ǘ' => 'U', 'ǘ' => 'u',
  1530. // caron
  1531. 'Ǎ' => 'A', 'ǎ' => 'a',
  1532. 'Ǐ' => 'I', 'ǐ' => 'i',
  1533. 'Ǒ' => 'O', 'ǒ' => 'o',
  1534. 'Ǔ' => 'U', 'ǔ' => 'u',
  1535. 'Ǚ' => 'U', 'ǚ' => 'u',
  1536. // grave accent
  1537. 'Ǜ' => 'U', 'ǜ' => 'u',
  1538. );
  1539. // Used for locale-specific rules
  1540. $locale = get_locale();
  1541. if ( 'de_DE' == $locale || 'de_DE_formal' == $locale || 'de_CH' == $locale || 'de_CH_informal' == $locale ) {
  1542. $chars[ 'Ä' ] = 'Ae';
  1543. $chars[ 'ä' ] = 'ae';
  1544. $chars[ 'Ö' ] = 'Oe';
  1545. $chars[ 'ö' ] = 'oe';
  1546. $chars[ 'Ü' ] = 'Ue';
  1547. $chars[ 'ü' ] = 'ue';
  1548. $chars[ 'ß' ] = 'ss';
  1549. } elseif ( 'da_DK' === $locale ) {
  1550. $chars[ 'Æ' ] = 'Ae';
  1551. $chars[ 'æ' ] = 'ae';
  1552. $chars[ 'Ø' ] = 'Oe';
  1553. $chars[ 'ø' ] = 'oe';
  1554. $chars[ 'Å' ] = 'Aa';
  1555. $chars[ 'å' ] = 'aa';
  1556. } elseif ( 'ca' === $locale ) {
  1557. $chars[ 'l·l' ] = 'll';
  1558. } elseif ( 'sr_RS' === $locale ) {
  1559. $chars[ 'Đ' ] = 'DJ';
  1560. $chars[ 'đ' ] = 'dj';
  1561. }
  1562. $string = strtr($string, $chars);
  1563. } else {
  1564. $chars = array();
  1565. // Assume ISO-8859-1 if not UTF-8
  1566. $chars['in'] = "\x80\x83\x8a\x8e\x9a\x9e"
  1567. ."\x9f\xa2\xa5\xb5\xc0\xc1\xc2"
  1568. ."\xc3\xc4\xc5\xc7\xc8\xc9\xca"
  1569. ."\xcb\xcc\xcd\xce\xcf\xd1\xd2"
  1570. ."\xd3\xd4\xd5\xd6\xd8\xd9\xda"
  1571. ."\xdb\xdc\xdd\xe0\xe1\xe2\xe3"
  1572. ."\xe4\xe5\xe7\xe8\xe9\xea\xeb"
  1573. ."\xec\xed\xee\xef\xf1\xf2\xf3"
  1574. ."\xf4\xf5\xf6\xf8\xf9\xfa\xfb"
  1575. ."\xfc\xfd\xff";
  1576. $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
  1577. $string = strtr($string, $chars['in'], $chars['out']);
  1578. $double_chars = array();
  1579. $double_chars['in'] = array("\x8c", "\x9c", "\xc6", "\xd0", "\xde", "\xdf", "\xe6", "\xf0", "\xfe");
  1580. $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
  1581. $string = str_replace($double_chars['in'], $double_chars['out'], $string);
  1582. }
  1583. return $string;
  1584. }
  1585. /**
  1586. * Sanitizes a filename, replacing whitespace with dashes.
  1587. *
  1588. * Removes special characters that are illegal in filenames on certain
  1589. * operating systems and special characters requiring special escaping
  1590. * to manipulate at the command line. Replaces spaces and consecutive
  1591. * dashes with a single dash. Trims period, dash and underscore from beginning
  1592. * and end of filename. It is not guaranteed that this function will return a
  1593. * filename that is allowed to be uploaded.
  1594. *
  1595. * @since 2.1.0
  1596. *
  1597. * @param string $filename The filename to be sanitized
  1598. * @return string The sanitized filename
  1599. */
  1600. function sanitize_file_name( $filename ) {
  1601. $filename_raw = $filename;
  1602. $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", "%", "+", chr(0));
  1603. /**
  1604. * Filters the list of characters to remove from a filename.
  1605. *
  1606. * @since 2.8.0
  1607. *
  1608. * @param array $special_chars Characters to remove.
  1609. * @param string $filename_raw Filename as it was passed into sanitize_file_name().
  1610. */
  1611. $special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );
  1612. $filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
  1613. $filename = str_replace( $special_chars, '', $filename );
  1614. $filename = str_replace( array( '%20', '+' ), '-', $filename );
  1615. $filename = preg_replace( '/[\r\n\t -]+/', '-', $filename );
  1616. $filename = trim( $filename, '.-_' );
  1617. if ( false === strpos( $filename, '.' ) ) {
  1618. $mime_types = wp_get_mime_types();
  1619. $filetype = wp_check_filetype( 'test.' . $filename, $mime_types );
  1620. if ( $filetype['ext'] === $filename ) {
  1621. $filename = 'unnamed-file.' . $filetype['ext'];
  1622. }
  1623. }
  1624. // Split the filename into a base and extension[s]
  1625. $parts = explode('.', $filename);
  1626. // Return if only one extension
  1627. if ( count( $parts ) <= 2 ) {
  1628. /**
  1629. * Filters a sanitized filename string.
  1630. *
  1631. * @since 2.8.0
  1632. *
  1633. * @param string $filename Sanitized filename.
  1634. * @param string $filename_raw The filename prior to sanitization.
  1635. */
  1636. return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
  1637. }
  1638. // Process multiple extensions
  1639. $filename = array_shift($parts);
  1640. $extension = array_pop($parts);
  1641. $mimes = get_allowed_mime_types();
  1642. /*
  1643. * Loop over any intermediate extensions. Postfix them with a trailing underscore
  1644. * if they are a 2 - 5 character long alpha string not in the extension whitelist.
  1645. */
  1646. foreach ( (array) $parts as $part) {
  1647. $filename .= '.' . $part;
  1648. if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
  1649. $allowed = false;
  1650. foreach ( $mimes as $ext_preg => $mime_match ) {
  1651. $ext_preg = '!^(' . $ext_preg . ')$!i';
  1652. if ( preg_match( $ext_preg, $part ) ) {
  1653. $allowed = true;
  1654. break;
  1655. }
  1656. }
  1657. if ( !$allowed )
  1658. $filename .= '_';
  1659. }
  1660. }
  1661. $filename .= '.' . $extension;
  1662. /** This filter is documented in wp-includes/formatting.php */
  1663. return apply_filters('sanitize_file_name', $filename, $filename_raw);
  1664. }
  1665. /**
  1666. * Sanitizes a username, stripping out unsafe characters.
  1667. *
  1668. * Removes tags, octets, entities, and if strict is enabled, will only keep
  1669. * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
  1670. * raw username (the username in the parameter), and the value of $strict as
  1671. * parameters for the {@see 'sanitize_user'} filter.
  1672. *
  1673. * @since 2.0.0
  1674. *
  1675. * @param string $username The username to be sanitized.
  1676. * @param bool $strict If set limits $username to specific characters. Default false.
  1677. * @return string The sanitized username, after passing through filters.
  1678. */
  1679. function sanitize_user( $username, $strict = false ) {
  1680. $raw_username = $username;
  1681. $username = wp_strip_all_tags( $username );
  1682. $username = remove_accents( $username );
  1683. // Kill octets
  1684. $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
  1685. $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
  1686. // If strict, reduce to ASCII for max portability.
  1687. if ( $strict )
  1688. $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
  1689. $username = trim( $username );
  1690. // Consolidate contiguous whitespace
  1691. $username = preg_replace( '|\s+|', ' ', $username );
  1692. /**
  1693. * Filters a sanitized username string.
  1694. *
  1695. * @since 2.0.1
  1696. *
  1697. * @param string $username Sanitized username.
  1698. * @param string $raw_username The username prior to sanitization.
  1699. * @param bool $strict Whether to limit the sanitization to specific characters. Default false.
  1700. */
  1701. return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
  1702. }
  1703. /**
  1704. * Sanitizes a string key.
  1705. *
  1706. * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
  1707. *
  1708. * @since 3.0.0
  1709. *
  1710. * @param string $key String key
  1711. * @return string Sanitized key
  1712. */
  1713. function sanitize_key( $key ) {
  1714. $raw_key = $key;
  1715. $key = strtolower( $key );
  1716. $key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
  1717. /**
  1718. * Filters a sanitized key string.
  1719. *
  1720. * @since 3.0.0
  1721. *
  1722. * @param string $key Sanitized key.
  1723. * @param string $raw_key The key prior to sanitization.
  1724. */
  1725. return apply_filters( 'sanitize_key', $key, $raw_key );
  1726. }
  1727. /**
  1728. * Sanitizes a title, or returns a fallback title.
  1729. *
  1730. * Specifically, HTML and PHP tags are stripped. Further actions can be added
  1731. * via the plugin API. If $title is empty and $fallback_title is set, the latter
  1732. * will be used.
  1733. *
  1734. * @since 1.0.0
  1735. *
  1736. * @param string $title The string to be sanitized.
  1737. * @param string $fallback_title Optional. A title to use if $title is empty.
  1738. * @param string $context Optional. The operation for which the string is sanitized
  1739. * @return string The sanitized string.
  1740. */
  1741. function sanitize_title( $title, $fallback_title = '', $context = 'save' ) {
  1742. $raw_title = $title;
  1743. if ( 'save' == $context )
  1744. $title = remove_accents($title);
  1745. /**
  1746. * Filters a sanitized title string.
  1747. *
  1748. * @since 1.2.0
  1749. *
  1750. * @param string $title Sanitized title.
  1751. * @param string $raw_title The title prior to sanitization.
  1752. * @param string $context The context for which the title is being sanitized.
  1753. */
  1754. $title = apply_filters( 'sanitize_title', $title, $raw_title, $context );
  1755. if ( '' === $title || false === $title )
  1756. $title = $fallback_title;
  1757. return $title;
  1758. }
  1759. /**
  1760. * Sanitizes a title with the 'query' context.
  1761. *
  1762. * Used for querying the database for a value from URL.
  1763. *
  1764. * @since 3.1.0
  1765. *
  1766. * @param string $title The string to be sanitized.
  1767. * @return string The sanitized string.
  1768. */
  1769. function sanitize_title_for_query( $title ) {
  1770. return sanitize_title( $title, '', 'query' );
  1771. }
  1772. /**
  1773. * Sanitizes a title, replacing whitespace and a few other characters with dashes.
  1774. *
  1775. * Limits the output to alphanumeric characters, underscore (_) and dash (-).
  1776. * Whitespace becomes a dash.
  1777. *
  1778. * @since 1.2.0
  1779. *
  1780. * @param string $title The title to be sanitized.
  1781. * @param string $raw_title Optional. Not used.
  1782. * @param string $context Optional. The operation for which the string is sanitized.
  1783. * @return string The sanitized title.
  1784. */
  1785. function sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
  1786. $title = strip_tags($title);
  1787. // Preserve escaped octets.
  1788. $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
  1789. // Remove percent signs that are not part of an octet.
  1790. $title = str_replace('%', '', $title);
  1791. // Restore octets.
  1792. $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
  1793. if (seems_utf8($title)) {
  1794. if (function_exists('mb_strtolower')) {
  1795. $title = mb_strtolower($title, 'UTF-8');
  1796. }
  1797. $title = utf8_uri_encode($title, 200);
  1798. }
  1799. $title = strtolower($title);
  1800. if ( 'save' == $context ) {
  1801. // Convert nbsp, ndash and mdash to hyphens
  1802. $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
  1803. // Convert nbsp, ndash and mdash HTML entities to hyphens
  1804. $title = str_replace( array( '&nbsp;', '&#160;', '&ndash;', '&#8211;', '&mdash;', '&#8212;' ), '-', $title );
  1805. // Strip these characters entirely
  1806. $title = str_replace( array(
  1807. // iexcl and iquest
  1808. '%c2%a1', '%c2%bf',
  1809. // angle quotes
  1810. '%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
  1811. // curly quotes
  1812. '%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
  1813. '%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
  1814. // copy, reg, deg, hellip and trade
  1815. '%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
  1816. // acute accents
  1817. '%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
  1818. // grave accent, macron, caron
  1819. '%cc%80', '%cc%84', '%cc%8c',
  1820. ), '', $title );
  1821. // Convert times to x
  1822. $title = str_replace( '%c3%97', 'x', $title );
  1823. }
  1824. $title = preg_replace('/&.+?;/', '', $title); // kill entities
  1825. $title = str_replace('.', '-', $title);
  1826. $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
  1827. $title = preg_replace('/\s+/', '-', $title);
  1828. $title = preg_replace('|-+|', '-', $title);
  1829. $title = trim($title, '-');
  1830. return $title;
  1831. }
  1832. /**
  1833. * Ensures a string is a valid SQL 'order by' clause.
  1834. *
  1835. * Accepts one or more columns, with or without a sort order (ASC / DESC).
  1836. * e.g. 'column_1', 'column_1, column_2', 'column_1 ASC, column_2 DESC' etc.
  1837. *
  1838. * Also accepts 'RAND()'.
  1839. *
  1840. * @since 2.5.1
  1841. *
  1842. * @param string $orderby Order by clause to be validated.
  1843. * @return string|false Returns $orderby if valid, false otherwise.
  1844. */
  1845. function sanitize_sql_orderby( $orderby ) {
  1846. if ( preg_match( '/^\s*(([a-z0-9_]+|`[a-z0-9_]+`)(\s+(ASC|DESC))?\s*(,\s*(?=[a-z0-9_`])|$))+$/i', $orderby ) || preg_match( '/^\s*RAND\(\s*\)\s*$/i', $orderby ) ) {
  1847. return $orderby;
  1848. }
  1849. return false;
  1850. }
  1851. /**
  1852. * Sanitizes an HTML classname to ensure it only contains valid characters.
  1853. *
  1854. * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
  1855. * string then it will return the alternative value supplied.
  1856. *
  1857. * @todo Expand to support the full range of CDATA that a class attribute can contain.
  1858. *
  1859. * @since 2.8.0
  1860. *
  1861. * @param string $class The classname to be sanitized
  1862. * @param string $fallback Optional. The value to return if the sanitization ends up as an empty string.
  1863. * Defaults to an empty string.
  1864. * @return string The sanitized value
  1865. */
  1866. function sanitize_html_class( $class, $fallback = '' ) {
  1867. //Strip out any % encoded octets
  1868. $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
  1869. //Limit to A-Z,a-z,0-9,_,-
  1870. $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
  1871. if ( '' == $sanitized && $fallback ) {
  1872. return sanitize_html_class( $fallback );
  1873. }
  1874. /**
  1875. * Filters a sanitized HTML class string.
  1876. *
  1877. * @since 2.8.0
  1878. *
  1879. * @param string $sanitized The sanitized HTML class.
  1880. * @param string $class HTML class before sanitization.
  1881. * @param string $fallback The fallback string.
  1882. */
  1883. return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
  1884. }
  1885. /**
  1886. * Converts lone & characters into `&#038;` (a.k.a. `&amp;`)
  1887. *
  1888. * @since 0.71
  1889. *
  1890. * @param string $content String of characters to be converted.
  1891. * @param string $deprecated Not used.
  1892. * @return string Converted string.
  1893. */
  1894. function convert_chars( $content, $deprecated = '' ) {
  1895. if ( ! empty( $deprecated ) ) {
  1896. _deprecated_argument( __FUNCTION__, '0.71' );
  1897. }
  1898. if ( strpos( $content, '&' ) !== false ) {
  1899. $content = preg_replace( '/&([^#])(?![a-z1-4]{1,8};)/i', '&#038;$1', $content );
  1900. }
  1901. return $content;
  1902. }
  1903. /**
  1904. * Converts invalid Unicode references range to valid range.
  1905. *
  1906. * @since 4.3.0
  1907. *
  1908. * @param string $content String with entities that need converting.
  1909. * @return string Converted string.
  1910. */
  1911. function convert_invalid_entities( $content ) {
  1912. $wp_htmltranswinuni = array(
  1913. '&#128;' => '&#8364;', // the Euro sign
  1914. '&#129;' => '',
  1915. '&#130;' => '&#8218;', // these are Windows CP1252 specific characters
  1916. '&#131;' => '&#402;', // they would look weird on non-Windows browsers
  1917. '&#132;' => '&#8222;',
  1918. '&#133;' => '&#8230;',
  1919. '&#134;' => '&#8224;',
  1920. '&#135;' => '&#8225;',
  1921. '&#136;' => '&#710;',
  1922. '&#137;' => '&#8240;',
  1923. '&#138;' => '&#352;',
  1924. '&#139;' => '&#8249;',
  1925. '&#140;' => '&#338;',
  1926. '&#141;' => '',
  1927. '&#142;' => '&#381;',
  1928. '&#143;' => '',
  1929. '&#144;' => '',
  1930. '&#145;' => '&#8216;',
  1931. '&#146;' => '&#8217;',
  1932. '&#147;' => '&#8220;',
  1933. '&#148;' => '&#8221;',
  1934. '&#149;' => '&#8226;',
  1935. '&#150;' => '&#8211;',
  1936. '&#151;' => '&#8212;',
  1937. '&#152;' => '&#732;',
  1938. '&#153;' => '&#8482;',
  1939. '&#154;' => '&#353;',
  1940. '&#155;' => '&#8250;',
  1941. '&#156;' => '&#339;',
  1942. '&#157;' => '',
  1943. '&#158;' => '&#382;',
  1944. '&#159;' => '&#376;'
  1945. );
  1946. if ( strpos( $content, '&#1' ) !== false ) {
  1947. $content = strtr( $content, $wp_htmltranswinuni );
  1948. }
  1949. return $content;
  1950. }
  1951. /**
  1952. * Balances tags if forced to, or if the 'use_balanceTags' option is set to true.
  1953. *
  1954. * @since 0.71
  1955. *
  1956. * @param string $text Text to be balanced
  1957. * @param bool $force If true, forces balancing, ignoring the value of the option. Default false.
  1958. * @return string Balanced text
  1959. */
  1960. function balanceTags( $text, $force = false ) {
  1961. if ( $force || get_option('use_balanceTags') == 1 ) {
  1962. return force_balance_tags( $text );
  1963. } else {
  1964. return $text;
  1965. }
  1966. }
  1967. /**
  1968. * Balances tags of string using a modified stack.
  1969. *
  1970. * @since 2.0.4
  1971. *
  1972. * @author Leonard Lin <leonard@acm.org>
  1973. * @license GPL
  1974. * @copyright November 4, 2001
  1975. * @version 1.1
  1976. * @todo Make better - change loop condition to $text in 1.2
  1977. * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
  1978. * 1.1 Fixed handling of append/stack pop order of end text
  1979. * Added Cleaning Hooks
  1980. * 1.0 First Version
  1981. *
  1982. * @param string $text Text to be balanced.
  1983. * @return string Balanced text.
  1984. */
  1985. function force_balance_tags( $text ) {
  1986. $tagstack = array();
  1987. $stacksize = 0;
  1988. $tagqueue = '';
  1989. $newtext = '';
  1990. // Known single-entity/self-closing tags
  1991. $single_tags = array( 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source' );
  1992. // Tags that can be immediately nested within themselves
  1993. $nestable_tags = array( 'blockquote', 'div', 'object', 'q', 'span' );
  1994. // WP bug fix for comments - in case you REALLY meant to type '< !--'
  1995. $text = str_replace('< !--', '< !--', $text);
  1996. // WP bug fix for LOVE <3 (and other situations with '<' before a number)
  1997. $text = preg_replace('#<([0-9]{1})#', '&lt;$1', $text);
  1998. while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
  1999. $newtext .= $tagqueue;
  2000. $i = strpos($text, $regex[0]);
  2001. $l = strlen($regex[0]);
  2002. // clear the shifter
  2003. $tagqueue = '';
  2004. // Pop or Push
  2005. if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
  2006. $tag = strtolower(substr($regex[1],1));
  2007. // if too many closing tags
  2008. if ( $stacksize <= 0 ) {
  2009. $tag = '';
  2010. // or close to be safe $tag = '/' . $tag;
  2011. }
  2012. // if stacktop value = tag close value then pop
  2013. elseif ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
  2014. $tag = '</' . $tag . '>'; // Close Tag
  2015. // Pop
  2016. array_pop( $tagstack );
  2017. $stacksize--;
  2018. } else { // closing tag not at top, search for it
  2019. for ( $j = $stacksize-1; $j >= 0; $j-- ) {
  2020. if ( $tagstack[$j] == $tag ) {
  2021. // add tag to tagqueue
  2022. for ( $k = $stacksize-1; $k >= $j; $k--) {
  2023. $tagqueue .= '</' . array_pop( $tagstack ) . '>';
  2024. $stacksize--;
  2025. }
  2026. break;
  2027. }
  2028. }
  2029. $tag = '';
  2030. }
  2031. } else { // Begin Tag
  2032. $tag = strtolower($regex[1]);
  2033. // Tag Cleaning
  2034. // If it's an empty tag "< >", do nothing
  2035. if ( '' == $tag ) {
  2036. // do nothing
  2037. }
  2038. // ElseIf it presents itself as a self-closing tag...
  2039. elseif ( substr( $regex[2], -1 ) == '/' ) {
  2040. // ...but it isn't a known single-entity self-closing tag, then don't let it be treated as such and
  2041. // immediately close it with a closing tag (the tag will encapsulate no text as a result)
  2042. if ( ! in_array( $tag, $single_tags ) )
  2043. $regex[2] = trim( substr( $regex[2], 0, -1 ) ) . "></$tag";
  2044. }
  2045. // ElseIf it's a known single-entity tag but it doesn't close itself, do so
  2046. elseif ( in_array($tag, $single_tags) ) {
  2047. $regex[2] .= '/';
  2048. }
  2049. // Else it's not a single-entity tag
  2050. else {
  2051. // If the top of the stack is the same as the tag we want to push, close previous tag
  2052. if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
  2053. $tagqueue = '</' . array_pop( $tagstack ) . '>';
  2054. $stacksize--;
  2055. }
  2056. $stacksize = array_push( $tagstack, $tag );
  2057. }
  2058. // Attributes
  2059. $attributes = $regex[2];
  2060. if ( ! empty( $attributes ) && $attributes[0] != '>' )
  2061. $attributes = ' ' . $attributes;
  2062. $tag = '<' . $tag . $attributes . '>';
  2063. //If already queuing a close tag, then put this tag on, too
  2064. if ( !empty($tagqueue) ) {
  2065. $tagqueue .= $tag;
  2066. $tag = '';
  2067. }
  2068. }
  2069. $newtext .= substr($text, 0, $i) . $tag;
  2070. $text = substr($text, $i + $l);
  2071. }
  2072. // Clear Tag Queue
  2073. $newtext .= $tagqueue;
  2074. // Add Remaining text
  2075. $newtext .= $text;
  2076. // Empty Stack
  2077. while( $x = array_pop($tagstack) )
  2078. $newtext .= '</' . $x . '>'; // Add remaining tags to close
  2079. // WP fix for the bug with HTML comments
  2080. $newtext = str_replace("< !--","<!--",$newtext);
  2081. $newtext = str_replace("< !--","< !--",$newtext);
  2082. return $newtext;
  2083. }
  2084. /**
  2085. * Acts on text which is about to be edited.
  2086. *
  2087. * The $content is run through esc_textarea(), which uses htmlspecialchars()
  2088. * to convert special characters to HTML entities. If `$richedit` is set to true,
  2089. * it is simply a holder for the {@see 'format_to_edit'} filter.
  2090. *
  2091. * @since 0.71
  2092. * @since 4.4.0 The `$richedit` parameter was renamed to `$rich_text` for clarity.
  2093. *
  2094. * @param string $content The text about to be edited.
  2095. * @param bool $rich_text Optional. Whether `$content` should be considered rich text,
  2096. * in which case it would not be passed through esc_textarea().
  2097. * Default false.
  2098. * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
  2099. */
  2100. function format_to_edit( $content, $rich_text = false ) {
  2101. /**
  2102. * Filters the text to be formatted for editing.
  2103. *
  2104. * @since 1.2.0
  2105. *
  2106. * @param string $content The text, prior to formatting for editing.
  2107. */
  2108. $content = apply_filters( 'format_to_edit', $content );
  2109. if ( ! $rich_text )
  2110. $content = esc_textarea( $content );
  2111. return $content;
  2112. }
  2113. /**
  2114. * Add leading zeros when necessary.
  2115. *
  2116. * If you set the threshold to '4' and the number is '10', then you will get
  2117. * back '0010'. If you set the threshold to '4' and the number is '5000', then you
  2118. * will get back '5000'.
  2119. *
  2120. * Uses sprintf to append the amount of zeros based on the $threshold parameter
  2121. * and the size of the number. If the number is large enough, then no zeros will
  2122. * be appended.
  2123. *
  2124. * @since 0.71
  2125. *
  2126. * @param int $number Number to append zeros to if not greater than threshold.
  2127. * @param int $threshold Digit places number needs to be to not have zeros added.
  2128. * @return string Adds leading zeros to number if needed.
  2129. */
  2130. function zeroise( $number, $threshold ) {
  2131. return sprintf( '%0' . $threshold . 's', $number );
  2132. }
  2133. /**
  2134. * Adds backslashes before letters and before a number at the start of a string.
  2135. *
  2136. * @since 0.71
  2137. *
  2138. * @param string $string Value to which backslashes will be added.
  2139. * @return string String with backslashes inserted.
  2140. */
  2141. function backslashit( $string ) {
  2142. if ( isset( $string[0] ) && $string[0] >= '0' && $string[0] <= '9' )
  2143. $string = '\\\\' . $string;
  2144. return addcslashes( $string, 'A..Za..z' );
  2145. }
  2146. /**
  2147. * Appends a trailing slash.
  2148. *
  2149. * Will remove trailing forward and backslashes if it exists already before adding
  2150. * a trailing forward slash. This prevents double slashing a string or path.
  2151. *
  2152. * The primary use of this is for paths and thus should be used for paths. It is
  2153. * not restricted to paths and offers no specific path support.
  2154. *
  2155. * @since 1.2.0
  2156. *
  2157. * @param string $string What to add the trailing slash to.
  2158. * @return string String with trailing slash added.
  2159. */
  2160. function trailingslashit( $string ) {
  2161. return untrailingslashit( $string ) . '/';
  2162. }
  2163. /**
  2164. * Removes trailing forward slashes and backslashes if they exist.
  2165. *
  2166. * The primary use of this is for paths and thus should be used for paths. It is
  2167. * not restricted to paths and offers no specific path support.
  2168. *
  2169. * @since 2.2.0
  2170. *
  2171. * @param string $string What to remove the trailing slashes from.
  2172. * @return string String without the trailing slashes.
  2173. */
  2174. function untrailingslashit( $string ) {
  2175. return rtrim( $string, '/\\' );
  2176. }
  2177. /**
  2178. * Adds slashes to escape strings.
  2179. *
  2180. * Slashes will first be removed if magic_quotes_gpc is set, see {@link
  2181. * https://secure.php.net/magic_quotes} for more details.
  2182. *
  2183. * @since 0.71
  2184. *
  2185. * @param string $gpc The string returned from HTTP request data.
  2186. * @return string Returns a string escaped with slashes.
  2187. */
  2188. function addslashes_gpc($gpc) {
  2189. if ( get_magic_quotes_gpc() )
  2190. $gpc = stripslashes($gpc);
  2191. return wp_slash($gpc);
  2192. }
  2193. /**
  2194. * Navigates through an array, object, or scalar, and removes slashes from the values.
  2195. *
  2196. * @since 2.0.0
  2197. *
  2198. * @param mixed $value The value to be stripped.
  2199. * @return mixed Stripped value.
  2200. */
  2201. function stripslashes_deep( $value ) {
  2202. return map_deep( $value, 'stripslashes_from_strings_only' );
  2203. }
  2204. /**
  2205. * Callback function for `stripslashes_deep()` which strips slashes from strings.
  2206. *
  2207. * @since 4.4.0
  2208. *
  2209. * @param mixed $value The array or string to be stripped.
  2210. * @return mixed $value The stripped value.
  2211. */
  2212. function stripslashes_from_strings_only( $value ) {
  2213. return is_string( $value ) ? stripslashes( $value ) : $value;
  2214. }
  2215. /**
  2216. * Navigates through an array, object, or scalar, and encodes the values to be used in a URL.
  2217. *
  2218. * @since 2.2.0
  2219. *
  2220. * @param mixed $value The array or string to be encoded.
  2221. * @return mixed $value The encoded value.
  2222. */
  2223. function urlencode_deep( $value ) {
  2224. return map_deep( $value, 'urlencode' );
  2225. }
  2226. /**
  2227. * Navigates through an array, object, or scalar, and raw-encodes the values to be used in a URL.
  2228. *
  2229. * @since 3.4.0
  2230. *
  2231. * @param mixed $value The array or string to be encoded.
  2232. * @return mixed $value The encoded value.
  2233. */
  2234. function rawurlencode_deep( $value ) {
  2235. return map_deep( $value, 'rawurlencode' );
  2236. }
  2237. /**
  2238. * Navigates through an array, object, or scalar, and decodes URL-encoded values
  2239. *
  2240. * @since 4.4.0
  2241. *
  2242. * @param mixed $value The array or string to be decoded.
  2243. * @return mixed $value The decoded value.
  2244. */
  2245. function urldecode_deep( $value ) {
  2246. return map_deep( $value, 'urldecode' );
  2247. }
  2248. /**
  2249. * Converts email addresses characters to HTML entities to block spam bots.
  2250. *
  2251. * @since 0.71
  2252. *
  2253. * @param string $email_address Email address.
  2254. * @param int $hex_encoding Optional. Set to 1 to enable hex encoding.
  2255. * @return string Converted email address.
  2256. */
  2257. function antispambot( $email_address, $hex_encoding = 0 ) {
  2258. $email_no_spam_address = '';
  2259. for ( $i = 0, $len = strlen( $email_address ); $i < $len; $i++ ) {
  2260. $j = rand( 0, 1 + $hex_encoding );
  2261. if ( $j == 0 ) {
  2262. $email_no_spam_address .= '&#' . ord( $email_address[$i] ) . ';';
  2263. } elseif ( $j == 1 ) {
  2264. $email_no_spam_address .= $email_address[$i];
  2265. } elseif ( $j == 2 ) {
  2266. $email_no_spam_address .= '%' . zeroise( dechex( ord( $email_address[$i] ) ), 2 );
  2267. }
  2268. }
  2269. return str_replace( '@', '&#64;', $email_no_spam_address );
  2270. }
  2271. /**
  2272. * Callback to convert URI match to HTML A element.
  2273. *
  2274. * This function was backported from 2.5.0 to 2.3.2. Regex callback for make_clickable().
  2275. *
  2276. * @since 2.3.2
  2277. * @access private
  2278. *
  2279. * @param array $matches Single Regex Match.
  2280. * @return string HTML A element with URI address.
  2281. */
  2282. function _make_url_clickable_cb( $matches ) {
  2283. $url = $matches[2];
  2284. if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
  2285. // If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL.
  2286. // Then we can let the parenthesis balancer do its thing below.
  2287. $url .= $matches[3];
  2288. $suffix = '';
  2289. } else {
  2290. $suffix = $matches[3];
  2291. }
  2292. // Include parentheses in the URL only if paired
  2293. while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
  2294. $suffix = strrchr( $url, ')' ) . $suffix;
  2295. $url = substr( $url, 0, strrpos( $url, ')' ) );
  2296. }
  2297. $url = esc_url($url);
  2298. if ( empty($url) )
  2299. return $matches[0];
  2300. return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
  2301. }
  2302. /**
  2303. * Callback to convert URL match to HTML A element.
  2304. *
  2305. * This function was backported from 2.5.0 to 2.3.2. Regex callback for make_clickable().
  2306. *
  2307. * @since 2.3.2
  2308. * @access private
  2309. *
  2310. * @param array $matches Single Regex Match.
  2311. * @return string HTML A element with URL address.
  2312. */
  2313. function _make_web_ftp_clickable_cb( $matches ) {
  2314. $ret = '';
  2315. $dest = $matches[2];
  2316. $dest = 'http://' . $dest;
  2317. // removed trailing [.,;:)] from URL
  2318. if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
  2319. $ret = substr($dest, -1);
  2320. $dest = substr($dest, 0, strlen($dest)-1);
  2321. }
  2322. $dest = esc_url($dest);
  2323. if ( empty($dest) )
  2324. return $matches[0];
  2325. return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
  2326. }
  2327. /**
  2328. * Callback to convert email address match to HTML A element.
  2329. *
  2330. * This function was backported from 2.5.0 to 2.3.2. Regex callback for make_clickable().
  2331. *
  2332. * @since 2.3.2
  2333. * @access private
  2334. *
  2335. * @param array $matches Single Regex Match.
  2336. * @return string HTML A element with email address.
  2337. */
  2338. function _make_email_clickable_cb( $matches ) {
  2339. $email = $matches[2] . '@' . $matches[3];
  2340. return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
  2341. }
  2342. /**
  2343. * Convert plaintext URI to HTML links.
  2344. *
  2345. * Converts URI, www and ftp, and email addresses. Finishes by fixing links
  2346. * within links.
  2347. *
  2348. * @since 0.71
  2349. *
  2350. * @param string $text Content to convert URIs.
  2351. * @return string Content with converted URIs.
  2352. */
  2353. function make_clickable( $text ) {
  2354. $r = '';
  2355. $textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // split out HTML tags
  2356. $nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>
  2357. foreach ( $textarr as $piece ) {
  2358. if ( preg_match( '|^<code[\s>]|i', $piece ) || preg_match( '|^<pre[\s>]|i', $piece ) || preg_match( '|^<script[\s>]|i', $piece ) || preg_match( '|^<style[\s>]|i', $piece ) )
  2359. $nested_code_pre++;
  2360. elseif ( $nested_code_pre && ( '</code>' === strtolower( $piece ) || '</pre>' === strtolower( $piece ) || '</script>' === strtolower( $piece ) || '</style>' === strtolower( $piece ) ) )
  2361. $nested_code_pre--;
  2362. if ( $nested_code_pre || empty( $piece ) || ( $piece[0] === '<' && ! preg_match( '|^<\s*[\w]{1,20}+://|', $piece ) ) ) {
  2363. $r .= $piece;
  2364. continue;
  2365. }
  2366. // Long strings might contain expensive edge cases ...
  2367. if ( 10000 < strlen( $piece ) ) {
  2368. // ... break it up
  2369. foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses
  2370. if ( 2101 < strlen( $chunk ) ) {
  2371. $r .= $chunk; // Too big, no whitespace: bail.
  2372. } else {
  2373. $r .= make_clickable( $chunk );
  2374. }
  2375. }
  2376. } else {
  2377. $ret = " $piece "; // Pad with whitespace to simplify the regexes
  2378. $url_clickable = '~
  2379. ([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation
  2380. ( # 2: URL
  2381. [\\w]{1,20}+:// # Scheme and hier-part prefix
  2382. (?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long
  2383. [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character
  2384. (?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
  2385. [\'.,;:!?)] # Punctuation URL character
  2386. [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
  2387. )*
  2388. )
  2389. (\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing)
  2390. ~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character.
  2391. // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
  2392. $ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret );
  2393. $ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
  2394. $ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
  2395. $ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
  2396. $r .= $ret;
  2397. }
  2398. }
  2399. // Cleanup of accidental links within links
  2400. return preg_replace( '#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r );
  2401. }
  2402. /**
  2403. * Breaks a string into chunks by splitting at whitespace characters.
  2404. * The length of each returned chunk is as close to the specified length goal as possible,
  2405. * with the caveat that each chunk includes its trailing delimiter.
  2406. * Chunks longer than the goal are guaranteed to not have any inner whitespace.
  2407. *
  2408. * Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
  2409. *
  2410. * Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
  2411. *
  2412. * _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) ==
  2413. * array (
  2414. * 0 => '1234 67890 ', // 11 characters: Perfect split
  2415. * 1 => '1234 ', // 5 characters: '1234 67890a' was too long
  2416. * 2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long
  2417. * 3 => '1234 890 ', // 11 characters: Perfect split
  2418. * 4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long
  2419. * 5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split
  2420. * 6 => ' 45678 ', // 11 characters: Perfect split
  2421. * 7 => '1 3 5 7 90 ', // 11 characters: End of $string
  2422. * );
  2423. *
  2424. * @since 3.4.0
  2425. * @access private
  2426. *
  2427. * @param string $string The string to split.
  2428. * @param int $goal The desired chunk length.
  2429. * @return array Numeric array of chunks.
  2430. */
  2431. function _split_str_by_whitespace( $string, $goal ) {
  2432. $chunks = array();
  2433. $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
  2434. while ( $goal < strlen( $string_nullspace ) ) {
  2435. $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
  2436. if ( false === $pos ) {
  2437. $pos = strpos( $string_nullspace, "\000", $goal + 1 );
  2438. if ( false === $pos ) {
  2439. break;
  2440. }
  2441. }
  2442. $chunks[] = substr( $string, 0, $pos + 1 );
  2443. $string = substr( $string, $pos + 1 );
  2444. $string_nullspace = substr( $string_nullspace, $pos + 1 );
  2445. }
  2446. if ( $string ) {
  2447. $chunks[] = $string;
  2448. }
  2449. return $chunks;
  2450. }
  2451. /**
  2452. * Adds rel nofollow string to all HTML A elements in content.
  2453. *
  2454. * @since 1.5.0
  2455. *
  2456. * @param string $text Content that may contain HTML A elements.
  2457. * @return string Converted content.
  2458. */
  2459. function wp_rel_nofollow( $text ) {
  2460. // This is a pre save filter, so text is already escaped.
  2461. $text = stripslashes($text);
  2462. $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
  2463. return wp_slash( $text );
  2464. }
  2465. /**
  2466. * Callback to add rel=nofollow string to HTML A element.
  2467. *
  2468. * Will remove already existing rel="nofollow" and rel='nofollow' from the
  2469. * string to prevent from invalidating (X)HTML.
  2470. *
  2471. * @since 2.3.0
  2472. *
  2473. * @param array $matches Single Match
  2474. * @return string HTML A Element with rel nofollow.
  2475. */
  2476. function wp_rel_nofollow_callback( $matches ) {
  2477. $text = $matches[1];
  2478. $atts = shortcode_parse_atts( $matches[1] );
  2479. $rel = 'nofollow';
  2480. if ( preg_match( '%href=["\'](' . preg_quote( set_url_scheme( home_url(), 'http' ) ) . ')%i', $text ) ||
  2481. preg_match( '%href=["\'](' . preg_quote( set_url_scheme( home_url(), 'https' ) ) . ')%i', $text )
  2482. ) {
  2483. return "<a $text>";
  2484. }
  2485. if ( ! empty( $atts['rel'] ) ) {
  2486. $parts = array_map( 'trim', explode( ' ', $atts['rel'] ) );
  2487. if ( false === array_search( 'nofollow', $parts ) ) {
  2488. $parts[] = 'nofollow';
  2489. }
  2490. $rel = implode( ' ', $parts );
  2491. unset( $atts['rel'] );
  2492. $html = '';
  2493. foreach ( $atts as $name => $value ) {
  2494. $html .= "{$name}=\"$value\" ";
  2495. }
  2496. $text = trim( $html );
  2497. }
  2498. return "<a $text rel=\"$rel\">";
  2499. }
  2500. /**
  2501. * Convert one smiley code to the icon graphic file equivalent.
  2502. *
  2503. * Callback handler for convert_smilies().
  2504. *
  2505. * Looks up one smiley code in the $wpsmiliestrans global array and returns an
  2506. * `<img>` string for that smiley.
  2507. *
  2508. * @since 2.8.0
  2509. *
  2510. * @global array $wpsmiliestrans
  2511. *
  2512. * @param array $matches Single match. Smiley code to convert to image.
  2513. * @return string Image string for smiley.
  2514. */
  2515. function translate_smiley( $matches ) {
  2516. global $wpsmiliestrans;
  2517. if ( count( $matches ) == 0 )
  2518. return '';
  2519. $smiley = trim( reset( $matches ) );
  2520. $img = $wpsmiliestrans[ $smiley ];
  2521. $matches = array();
  2522. $ext = preg_match( '/\.([^.]+)$/', $img, $matches ) ? strtolower( $matches[1] ) : false;
  2523. $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
  2524. // Don't convert smilies that aren't images - they're probably emoji.
  2525. if ( ! in_array( $ext, $image_exts ) ) {
  2526. return $img;
  2527. }
  2528. /**
  2529. * Filters the Smiley image URL before it's used in the image element.
  2530. *
  2531. * @since 2.9.0
  2532. *
  2533. * @param string $smiley_url URL for the smiley image.
  2534. * @param string $img Filename for the smiley image.
  2535. * @param string $site_url Site URL, as returned by site_url().
  2536. */
  2537. $src_url = apply_filters( 'smilies_src', includes_url( "images/smilies/$img" ), $img, site_url() );
  2538. return sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', esc_url( $src_url ), esc_attr( $smiley ) );
  2539. }
  2540. /**
  2541. * Convert text equivalent of smilies to images.
  2542. *
  2543. * Will only convert smilies if the option 'use_smilies' is true and the global
  2544. * used in the function isn't empty.
  2545. *
  2546. * @since 0.71
  2547. *
  2548. * @global string|array $wp_smiliessearch
  2549. *
  2550. * @param string $text Content to convert smilies from text.
  2551. * @return string Converted content with text smilies replaced with images.
  2552. */
  2553. function convert_smilies( $text ) {
  2554. global $wp_smiliessearch;
  2555. $output = '';
  2556. if ( get_option( 'use_smilies' ) && ! empty( $wp_smiliessearch ) ) {
  2557. // HTML loop taken from texturize function, could possible be consolidated
  2558. $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // capture the tags as well as in between
  2559. $stop = count( $textarr );// loop stuff
  2560. // Ignore proessing of specific tags
  2561. $tags_to_ignore = 'code|pre|style|script|textarea';
  2562. $ignore_block_element = '';
  2563. for ( $i = 0; $i < $stop; $i++ ) {
  2564. $content = $textarr[$i];
  2565. // If we're in an ignore block, wait until we find its closing tag
  2566. if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
  2567. $ignore_block_element = $matches[1];
  2568. }
  2569. // If it's not a tag and not in ignore block
  2570. if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
  2571. $content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content );
  2572. }
  2573. // did we exit ignore block
  2574. if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
  2575. $ignore_block_element = '';
  2576. }
  2577. $output .= $content;
  2578. }
  2579. } else {
  2580. // return default text.
  2581. $output = $text;
  2582. }
  2583. return $output;
  2584. }
  2585. /**
  2586. * Verifies that an email is valid.
  2587. *
  2588. * Does not grok i18n domains. Not RFC compliant.
  2589. *
  2590. * @since 0.71
  2591. *
  2592. * @param string $email Email address to verify.
  2593. * @param bool $deprecated Deprecated.
  2594. * @return string|bool Either false or the valid email address.
  2595. */
  2596. function is_email( $email, $deprecated = false ) {
  2597. if ( ! empty( $deprecated ) )
  2598. _deprecated_argument( __FUNCTION__, '3.0.0' );
  2599. // Test for the minimum length the email can be
  2600. if ( strlen( $email ) < 3 ) {
  2601. /**
  2602. * Filters whether an email address is valid.
  2603. *
  2604. * This filter is evaluated under several different contexts, such as 'email_too_short',
  2605. * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
  2606. * 'domain_no_periods', 'sub_hyphen_limits', 'sub_invalid_chars', or no specific context.
  2607. *
  2608. * @since 2.8.0
  2609. *
  2610. * @param bool $is_email Whether the email address has passed the is_email() checks. Default false.
  2611. * @param string $email The email address being checked.
  2612. * @param string $context Context under which the email was tested.
  2613. */
  2614. return apply_filters( 'is_email', false, $email, 'email_too_short' );
  2615. }
  2616. // Test for an @ character after the first position
  2617. if ( strpos( $email, '@', 1 ) === false ) {
  2618. /** This filter is documented in wp-includes/formatting.php */
  2619. return apply_filters( 'is_email', false, $email, 'email_no_at' );
  2620. }
  2621. // Split out the local and domain parts
  2622. list( $local, $domain ) = explode( '@', $email, 2 );
  2623. // LOCAL PART
  2624. // Test for invalid characters
  2625. if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
  2626. /** This filter is documented in wp-includes/formatting.php */
  2627. return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
  2628. }
  2629. // DOMAIN PART
  2630. // Test for sequences of periods
  2631. if ( preg_match( '/\.{2,}/', $domain ) ) {
  2632. /** This filter is documented in wp-includes/formatting.php */
  2633. return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
  2634. }
  2635. // Test for leading and trailing periods and whitespace
  2636. if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
  2637. /** This filter is documented in wp-includes/formatting.php */
  2638. return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
  2639. }
  2640. // Split the domain into subs
  2641. $subs = explode( '.', $domain );
  2642. // Assume the domain will have at least two subs
  2643. if ( 2 > count( $subs ) ) {
  2644. /** This filter is documented in wp-includes/formatting.php */
  2645. return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
  2646. }
  2647. // Loop through each sub
  2648. foreach ( $subs as $sub ) {
  2649. // Test for leading and trailing hyphens and whitespace
  2650. if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
  2651. /** This filter is documented in wp-includes/formatting.php */
  2652. return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
  2653. }
  2654. // Test for invalid characters
  2655. if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
  2656. /** This filter is documented in wp-includes/formatting.php */
  2657. return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
  2658. }
  2659. }
  2660. // Congratulations your email made it!
  2661. /** This filter is documented in wp-includes/formatting.php */
  2662. return apply_filters( 'is_email', $email, $email, null );
  2663. }
  2664. /**
  2665. * Convert to ASCII from email subjects.
  2666. *
  2667. * @since 1.2.0
  2668. *
  2669. * @param string $string Subject line
  2670. * @return string Converted string to ASCII
  2671. */
  2672. function wp_iso_descrambler( $string ) {
  2673. /* this may only work with iso-8859-1, I'm afraid */
  2674. if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
  2675. return $string;
  2676. } else {
  2677. $subject = str_replace('_', ' ', $matches[2]);
  2678. return preg_replace_callback( '#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject );
  2679. }
  2680. }
  2681. /**
  2682. * Helper function to convert hex encoded chars to ASCII
  2683. *
  2684. * @since 3.1.0
  2685. * @access private
  2686. *
  2687. * @param array $match The preg_replace_callback matches array
  2688. * @return string Converted chars
  2689. */
  2690. function _wp_iso_convert( $match ) {
  2691. return chr( hexdec( strtolower( $match[1] ) ) );
  2692. }
  2693. /**
  2694. * Returns a date in the GMT equivalent.
  2695. *
  2696. * Requires and returns a date in the Y-m-d H:i:s format. If there is a
  2697. * timezone_string available, the date is assumed to be in that timezone,
  2698. * otherwise it simply subtracts the value of the 'gmt_offset' option. Return
  2699. * format can be overridden using the $format parameter.
  2700. *
  2701. * @since 1.2.0
  2702. *
  2703. * @param string $string The date to be converted.
  2704. * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
  2705. * @return string GMT version of the date provided.
  2706. */
  2707. function get_gmt_from_date( $string, $format = 'Y-m-d H:i:s' ) {
  2708. $tz = get_option( 'timezone_string' );
  2709. if ( $tz ) {
  2710. $datetime = date_create( $string, new DateTimeZone( $tz ) );
  2711. if ( ! $datetime ) {
  2712. return gmdate( $format, 0 );
  2713. }
  2714. $datetime->setTimezone( new DateTimeZone( 'UTC' ) );
  2715. $string_gmt = $datetime->format( $format );
  2716. } else {
  2717. if ( ! preg_match( '#([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})#', $string, $matches ) ) {
  2718. $datetime = strtotime( $string );
  2719. if ( false === $datetime ) {
  2720. return gmdate( $format, 0 );
  2721. }
  2722. return gmdate( $format, $datetime );
  2723. }
  2724. $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
  2725. $string_gmt = gmdate( $format, $string_time - get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
  2726. }
  2727. return $string_gmt;
  2728. }
  2729. /**
  2730. * Converts a GMT date into the correct format for the blog.
  2731. *
  2732. * Requires and returns a date in the Y-m-d H:i:s format. If there is a
  2733. * timezone_string available, the returned date is in that timezone, otherwise
  2734. * it simply adds the value of gmt_offset. Return format can be overridden
  2735. * using the $format parameter
  2736. *
  2737. * @since 1.2.0
  2738. *
  2739. * @param string $string The date to be converted.
  2740. * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
  2741. * @return string Formatted date relative to the timezone / GMT offset.
  2742. */
  2743. function get_date_from_gmt( $string, $format = 'Y-m-d H:i:s' ) {
  2744. $tz = get_option( 'timezone_string' );
  2745. if ( $tz ) {
  2746. $datetime = date_create( $string, new DateTimeZone( 'UTC' ) );
  2747. if ( ! $datetime )
  2748. return date( $format, 0 );
  2749. $datetime->setTimezone( new DateTimeZone( $tz ) );
  2750. $string_localtime = $datetime->format( $format );
  2751. } else {
  2752. if ( ! preg_match('#([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})#', $string, $matches) )
  2753. return date( $format, 0 );
  2754. $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
  2755. $string_localtime = gmdate( $format, $string_time + get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
  2756. }
  2757. return $string_localtime;
  2758. }
  2759. /**
  2760. * Computes an offset in seconds from an iso8601 timezone.
  2761. *
  2762. * @since 1.5.0
  2763. *
  2764. * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
  2765. * @return int|float The offset in seconds.
  2766. */
  2767. function iso8601_timezone_to_offset( $timezone ) {
  2768. // $timezone is either 'Z' or '[+|-]hhmm'
  2769. if ($timezone == 'Z') {
  2770. $offset = 0;
  2771. } else {
  2772. $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
  2773. $hours = intval(substr($timezone, 1, 2));
  2774. $minutes = intval(substr($timezone, 3, 4)) / 60;
  2775. $offset = $sign * HOUR_IN_SECONDS * ($hours + $minutes);
  2776. }
  2777. return $offset;
  2778. }
  2779. /**
  2780. * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
  2781. *
  2782. * @since 1.5.0
  2783. *
  2784. * @param string $date_string Date and time in ISO 8601 format {@link https://en.wikipedia.org/wiki/ISO_8601}.
  2785. * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
  2786. * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
  2787. */
  2788. function iso8601_to_datetime( $date_string, $timezone = 'user' ) {
  2789. $timezone = strtolower($timezone);
  2790. if ($timezone == 'gmt') {
  2791. preg_match('#([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(Z|[\+|\-][0-9]{2,4}){0,1}#', $date_string, $date_bits);
  2792. if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
  2793. $offset = iso8601_timezone_to_offset($date_bits[7]);
  2794. } else { // we don't have a timezone, so we assume user local timezone (not server's!)
  2795. $offset = HOUR_IN_SECONDS * get_option('gmt_offset');
  2796. }
  2797. $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
  2798. $timestamp -= $offset;
  2799. return gmdate('Y-m-d H:i:s', $timestamp);
  2800. } elseif ($timezone == 'user') {
  2801. return preg_replace('#([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(Z|[\+|\-][0-9]{2,4}){0,1}#', '$1-$2-$3 $4:$5:$6', $date_string);
  2802. }
  2803. }
  2804. /**
  2805. * Strips out all characters that are not allowable in an email.
  2806. *
  2807. * @since 1.5.0
  2808. *
  2809. * @param string $email Email address to filter.
  2810. * @return string Filtered email address.
  2811. */
  2812. function sanitize_email( $email ) {
  2813. // Test for the minimum length the email can be
  2814. if ( strlen( $email ) < 3 ) {
  2815. /**
  2816. * Filters a sanitized email address.
  2817. *
  2818. * This filter is evaluated under several contexts, including 'email_too_short',
  2819. * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
  2820. * 'domain_no_periods', 'domain_no_valid_subs', or no context.
  2821. *
  2822. * @since 2.8.0
  2823. *
  2824. * @param string $email The sanitized email address.
  2825. * @param string $email The email address, as provided to sanitize_email().
  2826. * @param string $message A message to pass to the user.
  2827. */
  2828. return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
  2829. }
  2830. // Test for an @ character after the first position
  2831. if ( strpos( $email, '@', 1 ) === false ) {
  2832. /** This filter is documented in wp-includes/formatting.php */
  2833. return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
  2834. }
  2835. // Split out the local and domain parts
  2836. list( $local, $domain ) = explode( '@', $email, 2 );
  2837. // LOCAL PART
  2838. // Test for invalid characters
  2839. $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
  2840. if ( '' === $local ) {
  2841. /** This filter is documented in wp-includes/formatting.php */
  2842. return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
  2843. }
  2844. // DOMAIN PART
  2845. // Test for sequences of periods
  2846. $domain = preg_replace( '/\.{2,}/', '', $domain );
  2847. if ( '' === $domain ) {
  2848. /** This filter is documented in wp-includes/formatting.php */
  2849. return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
  2850. }
  2851. // Test for leading and trailing periods and whitespace
  2852. $domain = trim( $domain, " \t\n\r\0\x0B." );
  2853. if ( '' === $domain ) {
  2854. /** This filter is documented in wp-includes/formatting.php */
  2855. return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
  2856. }
  2857. // Split the domain into subs
  2858. $subs = explode( '.', $domain );
  2859. // Assume the domain will have at least two subs
  2860. if ( 2 > count( $subs ) ) {
  2861. /** This filter is documented in wp-includes/formatting.php */
  2862. return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
  2863. }
  2864. // Create an array that will contain valid subs
  2865. $new_subs = array();
  2866. // Loop through each sub
  2867. foreach ( $subs as $sub ) {
  2868. // Test for leading and trailing hyphens
  2869. $sub = trim( $sub, " \t\n\r\0\x0B-" );
  2870. // Test for invalid characters
  2871. $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
  2872. // If there's anything left, add it to the valid subs
  2873. if ( '' !== $sub ) {
  2874. $new_subs[] = $sub;
  2875. }
  2876. }
  2877. // If there aren't 2 or more valid subs
  2878. if ( 2 > count( $new_subs ) ) {
  2879. /** This filter is documented in wp-includes/formatting.php */
  2880. return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
  2881. }
  2882. // Join valid subs into the new domain
  2883. $domain = join( '.', $new_subs );
  2884. // Put the email back together
  2885. $email = $local . '@' . $domain;
  2886. // Congratulations your email made it!
  2887. /** This filter is documented in wp-includes/formatting.php */
  2888. return apply_filters( 'sanitize_email', $email, $email, null );
  2889. }
  2890. /**
  2891. * Determines the difference between two timestamps.
  2892. *
  2893. * The difference is returned in a human readable format such as "1 hour",
  2894. * "5 mins", "2 days".
  2895. *
  2896. * @since 1.5.0
  2897. *
  2898. * @param int $from Unix timestamp from which the difference begins.
  2899. * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
  2900. * @return string Human readable time difference.
  2901. */
  2902. function human_time_diff( $from, $to = '' ) {
  2903. if ( empty( $to ) ) {
  2904. $to = time();
  2905. }
  2906. $diff = (int) abs( $to - $from );
  2907. if ( $diff < HOUR_IN_SECONDS ) {
  2908. $mins = round( $diff / MINUTE_IN_SECONDS );
  2909. if ( $mins <= 1 )
  2910. $mins = 1;
  2911. /* translators: Time difference between two dates, in minutes (min=minute). 1: Number of minutes */
  2912. $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
  2913. } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
  2914. $hours = round( $diff / HOUR_IN_SECONDS );
  2915. if ( $hours <= 1 )
  2916. $hours = 1;
  2917. /* translators: Time difference between two dates, in hours. 1: Number of hours */
  2918. $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
  2919. } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
  2920. $days = round( $diff / DAY_IN_SECONDS );
  2921. if ( $days <= 1 )
  2922. $days = 1;
  2923. /* translators: Time difference between two dates, in days. 1: Number of days */
  2924. $since = sprintf( _n( '%s day', '%s days', $days ), $days );
  2925. } elseif ( $diff < MONTH_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
  2926. $weeks = round( $diff / WEEK_IN_SECONDS );
  2927. if ( $weeks <= 1 )
  2928. $weeks = 1;
  2929. /* translators: Time difference between two dates, in weeks. 1: Number of weeks */
  2930. $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
  2931. } elseif ( $diff < YEAR_IN_SECONDS && $diff >= MONTH_IN_SECONDS ) {
  2932. $months = round( $diff / MONTH_IN_SECONDS );
  2933. if ( $months <= 1 )
  2934. $months = 1;
  2935. /* translators: Time difference between two dates, in months. 1: Number of months */
  2936. $since = sprintf( _n( '%s month', '%s months', $months ), $months );
  2937. } elseif ( $diff >= YEAR_IN_SECONDS ) {
  2938. $years = round( $diff / YEAR_IN_SECONDS );
  2939. if ( $years <= 1 )
  2940. $years = 1;
  2941. /* translators: Time difference between two dates, in years. 1: Number of years */
  2942. $since = sprintf( _n( '%s year', '%s years', $years ), $years );
  2943. }
  2944. /**
  2945. * Filters the human readable difference between two timestamps.
  2946. *
  2947. * @since 4.0.0
  2948. *
  2949. * @param string $since The difference in human readable text.
  2950. * @param int $diff The difference in seconds.
  2951. * @param int $from Unix timestamp from which the difference begins.
  2952. * @param int $to Unix timestamp to end the time difference.
  2953. */
  2954. return apply_filters( 'human_time_diff', $since, $diff, $from, $to );
  2955. }
  2956. /**
  2957. * Generates an excerpt from the content, if needed.
  2958. *
  2959. * The excerpt word amount will be 55 words and if the amount is greater than
  2960. * that, then the string ' [&hellip;]' will be appended to the excerpt. If the string
  2961. * is less than 55 words, then the content will be returned as is.
  2962. *
  2963. * The 55 word limit can be modified by plugins/themes using the {@see 'excerpt_length'} filter
  2964. * The ' [&hellip;]' string can be modified by plugins/themes using the {@see 'excerpt_more'} filter
  2965. *
  2966. * @since 1.5.0
  2967. *
  2968. * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
  2969. * @return string The excerpt.
  2970. */
  2971. function wp_trim_excerpt( $text = '' ) {
  2972. $raw_excerpt = $text;
  2973. if ( '' == $text ) {
  2974. $text = get_the_content('');
  2975. $text = strip_shortcodes( $text );
  2976. /** This filter is documented in wp-includes/post-template.php */
  2977. $text = apply_filters( 'the_content', $text );
  2978. $text = str_replace(']]>', ']]&gt;', $text);
  2979. /**
  2980. * Filters the number of words in an excerpt.
  2981. *
  2982. * @since 2.7.0
  2983. *
  2984. * @param int $number The number of words. Default 55.
  2985. */
  2986. $excerpt_length = apply_filters( 'excerpt_length', 55 );
  2987. /**
  2988. * Filters the string in the "more" link displayed after a trimmed excerpt.
  2989. *
  2990. * @since 2.9.0
  2991. *
  2992. * @param string $more_string The string shown within the more link.
  2993. */
  2994. $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[&hellip;]' );
  2995. $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
  2996. }
  2997. /**
  2998. * Filters the trimmed excerpt string.
  2999. *
  3000. * @since 2.8.0
  3001. *
  3002. * @param string $text The trimmed text.
  3003. * @param string $raw_excerpt The text prior to trimming.
  3004. */
  3005. return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
  3006. }
  3007. /**
  3008. * Trims text to a certain number of words.
  3009. *
  3010. * This function is localized. For languages that count 'words' by the individual
  3011. * character (such as East Asian languages), the $num_words argument will apply
  3012. * to the number of individual characters.
  3013. *
  3014. * @since 3.3.0
  3015. *
  3016. * @param string $text Text to trim.
  3017. * @param int $num_words Number of words. Default 55.
  3018. * @param string $more Optional. What to append if $text needs to be trimmed. Default '&hellip;'.
  3019. * @return string Trimmed text.
  3020. */
  3021. function wp_trim_words( $text, $num_words = 55, $more = null ) {
  3022. if ( null === $more ) {
  3023. $more = __( '&hellip;' );
  3024. }
  3025. $original_text = $text;
  3026. $text = wp_strip_all_tags( $text );
  3027. /*
  3028. * translators: If your word count is based on single characters (e.g. East Asian characters),
  3029. * enter 'characters_excluding_spaces' or 'characters_including_spaces'. Otherwise, enter 'words'.
  3030. * Do not translate into your own language.
  3031. */
  3032. if ( strpos( _x( 'words', 'Word count type. Do not translate!' ), 'characters' ) === 0 && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
  3033. $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
  3034. preg_match_all( '/./u', $text, $words_array );
  3035. $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
  3036. $sep = '';
  3037. } else {
  3038. $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
  3039. $sep = ' ';
  3040. }
  3041. if ( count( $words_array ) > $num_words ) {
  3042. array_pop( $words_array );
  3043. $text = implode( $sep, $words_array );
  3044. $text = $text . $more;
  3045. } else {
  3046. $text = implode( $sep, $words_array );
  3047. }
  3048. /**
  3049. * Filters the text content after words have been trimmed.
  3050. *
  3051. * @since 3.3.0
  3052. *
  3053. * @param string $text The trimmed text.
  3054. * @param int $num_words The number of words to trim the text to. Default 5.
  3055. * @param string $more An optional string to append to the end of the trimmed text, e.g. &hellip;.
  3056. * @param string $original_text The text before it was trimmed.
  3057. */
  3058. return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
  3059. }
  3060. /**
  3061. * Converts named entities into numbered entities.
  3062. *
  3063. * @since 1.5.1
  3064. *
  3065. * @param string $text The text within which entities will be converted.
  3066. * @return string Text with converted entities.
  3067. */
  3068. function ent2ncr( $text ) {
  3069. /**
  3070. * Filters text before named entities are converted into numbered entities.
  3071. *
  3072. * A non-null string must be returned for the filter to be evaluated.
  3073. *
  3074. * @since 3.3.0
  3075. *
  3076. * @param null $converted_text The text to be converted. Default null.
  3077. * @param string $text The text prior to entity conversion.
  3078. */
  3079. $filtered = apply_filters( 'pre_ent2ncr', null, $text );
  3080. if ( null !== $filtered )
  3081. return $filtered;
  3082. $to_ncr = array(
  3083. '&quot;' => '&#34;',
  3084. '&amp;' => '&#38;',
  3085. '&lt;' => '&#60;',
  3086. '&gt;' => '&#62;',
  3087. '|' => '&#124;',
  3088. '&nbsp;' => '&#160;',
  3089. '&iexcl;' => '&#161;',
  3090. '&cent;' => '&#162;',
  3091. '&pound;' => '&#163;',
  3092. '&curren;' => '&#164;',
  3093. '&yen;' => '&#165;',
  3094. '&brvbar;' => '&#166;',
  3095. '&brkbar;' => '&#166;',
  3096. '&sect;' => '&#167;',
  3097. '&uml;' => '&#168;',
  3098. '&die;' => '&#168;',
  3099. '&copy;' => '&#169;',
  3100. '&ordf;' => '&#170;',
  3101. '&laquo;' => '&#171;',
  3102. '&not;' => '&#172;',
  3103. '&shy;' => '&#173;',
  3104. '&reg;' => '&#174;',
  3105. '&macr;' => '&#175;',
  3106. '&hibar;' => '&#175;',
  3107. '&deg;' => '&#176;',
  3108. '&plusmn;' => '&#177;',
  3109. '&sup2;' => '&#178;',
  3110. '&sup3;' => '&#179;',
  3111. '&acute;' => '&#180;',
  3112. '&micro;' => '&#181;',
  3113. '&para;' => '&#182;',
  3114. '&middot;' => '&#183;',
  3115. '&cedil;' => '&#184;',
  3116. '&sup1;' => '&#185;',
  3117. '&ordm;' => '&#186;',
  3118. '&raquo;' => '&#187;',
  3119. '&frac14;' => '&#188;',
  3120. '&frac12;' => '&#189;',
  3121. '&frac34;' => '&#190;',
  3122. '&iquest;' => '&#191;',
  3123. '&Agrave;' => '&#192;',
  3124. '&Aacute;' => '&#193;',
  3125. '&Acirc;' => '&#194;',
  3126. '&Atilde;' => '&#195;',
  3127. '&Auml;' => '&#196;',
  3128. '&Aring;' => '&#197;',
  3129. '&AElig;' => '&#198;',
  3130. '&Ccedil;' => '&#199;',
  3131. '&Egrave;' => '&#200;',
  3132. '&Eacute;' => '&#201;',
  3133. '&Ecirc;' => '&#202;',
  3134. '&Euml;' => '&#203;',
  3135. '&Igrave;' => '&#204;',
  3136. '&Iacute;' => '&#205;',
  3137. '&Icirc;' => '&#206;',
  3138. '&Iuml;' => '&#207;',
  3139. '&ETH;' => '&#208;',
  3140. '&Ntilde;' => '&#209;',
  3141. '&Ograve;' => '&#210;',
  3142. '&Oacute;' => '&#211;',
  3143. '&Ocirc;' => '&#212;',
  3144. '&Otilde;' => '&#213;',
  3145. '&Ouml;' => '&#214;',
  3146. '&times;' => '&#215;',
  3147. '&Oslash;' => '&#216;',
  3148. '&Ugrave;' => '&#217;',
  3149. '&Uacute;' => '&#218;',
  3150. '&Ucirc;' => '&#219;',
  3151. '&Uuml;' => '&#220;',
  3152. '&Yacute;' => '&#221;',
  3153. '&THORN;' => '&#222;',
  3154. '&szlig;' => '&#223;',
  3155. '&agrave;' => '&#224;',
  3156. '&aacute;' => '&#225;',
  3157. '&acirc;' => '&#226;',
  3158. '&atilde;' => '&#227;',
  3159. '&auml;' => '&#228;',
  3160. '&aring;' => '&#229;',
  3161. '&aelig;' => '&#230;',
  3162. '&ccedil;' => '&#231;',
  3163. '&egrave;' => '&#232;',
  3164. '&eacute;' => '&#233;',
  3165. '&ecirc;' => '&#234;',
  3166. '&euml;' => '&#235;',
  3167. '&igrave;' => '&#236;',
  3168. '&iacute;' => '&#237;',
  3169. '&icirc;' => '&#238;',
  3170. '&iuml;' => '&#239;',
  3171. '&eth;' => '&#240;',
  3172. '&ntilde;' => '&#241;',
  3173. '&ograve;' => '&#242;',
  3174. '&oacute;' => '&#243;',
  3175. '&ocirc;' => '&#244;',
  3176. '&otilde;' => '&#245;',
  3177. '&ouml;' => '&#246;',
  3178. '&divide;' => '&#247;',
  3179. '&oslash;' => '&#248;',
  3180. '&ugrave;' => '&#249;',
  3181. '&uacute;' => '&#250;',
  3182. '&ucirc;' => '&#251;',
  3183. '&uuml;' => '&#252;',
  3184. '&yacute;' => '&#253;',
  3185. '&thorn;' => '&#254;',
  3186. '&yuml;' => '&#255;',
  3187. '&OElig;' => '&#338;',
  3188. '&oelig;' => '&#339;',
  3189. '&Scaron;' => '&#352;',
  3190. '&scaron;' => '&#353;',
  3191. '&Yuml;' => '&#376;',
  3192. '&fnof;' => '&#402;',
  3193. '&circ;' => '&#710;',
  3194. '&tilde;' => '&#732;',
  3195. '&Alpha;' => '&#913;',
  3196. '&Beta;' => '&#914;',
  3197. '&Gamma;' => '&#915;',
  3198. '&Delta;' => '&#916;',
  3199. '&Epsilon;' => '&#917;',
  3200. '&Zeta;' => '&#918;',
  3201. '&Eta;' => '&#919;',
  3202. '&Theta;' => '&#920;',
  3203. '&Iota;' => '&#921;',
  3204. '&Kappa;' => '&#922;',
  3205. '&Lambda;' => '&#923;',
  3206. '&Mu;' => '&#924;',
  3207. '&Nu;' => '&#925;',
  3208. '&Xi;' => '&#926;',
  3209. '&Omicron;' => '&#927;',
  3210. '&Pi;' => '&#928;',
  3211. '&Rho;' => '&#929;',
  3212. '&Sigma;' => '&#931;',
  3213. '&Tau;' => '&#932;',
  3214. '&Upsilon;' => '&#933;',
  3215. '&Phi;' => '&#934;',
  3216. '&Chi;' => '&#935;',
  3217. '&Psi;' => '&#936;',
  3218. '&Omega;' => '&#937;',
  3219. '&alpha;' => '&#945;',
  3220. '&beta;' => '&#946;',
  3221. '&gamma;' => '&#947;',
  3222. '&delta;' => '&#948;',
  3223. '&epsilon;' => '&#949;',
  3224. '&zeta;' => '&#950;',
  3225. '&eta;' => '&#951;',
  3226. '&theta;' => '&#952;',
  3227. '&iota;' => '&#953;',
  3228. '&kappa;' => '&#954;',
  3229. '&lambda;' => '&#955;',
  3230. '&mu;' => '&#956;',
  3231. '&nu;' => '&#957;',
  3232. '&xi;' => '&#958;',
  3233. '&omicron;' => '&#959;',
  3234. '&pi;' => '&#960;',
  3235. '&rho;' => '&#961;',
  3236. '&sigmaf;' => '&#962;',
  3237. '&sigma;' => '&#963;',
  3238. '&tau;' => '&#964;',
  3239. '&upsilon;' => '&#965;',
  3240. '&phi;' => '&#966;',
  3241. '&chi;' => '&#967;',
  3242. '&psi;' => '&#968;',
  3243. '&omega;' => '&#969;',
  3244. '&thetasym;' => '&#977;',
  3245. '&upsih;' => '&#978;',
  3246. '&piv;' => '&#982;',
  3247. '&ensp;' => '&#8194;',
  3248. '&emsp;' => '&#8195;',
  3249. '&thinsp;' => '&#8201;',
  3250. '&zwnj;' => '&#8204;',
  3251. '&zwj;' => '&#8205;',
  3252. '&lrm;' => '&#8206;',
  3253. '&rlm;' => '&#8207;',
  3254. '&ndash;' => '&#8211;',
  3255. '&mdash;' => '&#8212;',
  3256. '&lsquo;' => '&#8216;',
  3257. '&rsquo;' => '&#8217;',
  3258. '&sbquo;' => '&#8218;',
  3259. '&ldquo;' => '&#8220;',
  3260. '&rdquo;' => '&#8221;',
  3261. '&bdquo;' => '&#8222;',
  3262. '&dagger;' => '&#8224;',
  3263. '&Dagger;' => '&#8225;',
  3264. '&bull;' => '&#8226;',
  3265. '&hellip;' => '&#8230;',
  3266. '&permil;' => '&#8240;',
  3267. '&prime;' => '&#8242;',
  3268. '&Prime;' => '&#8243;',
  3269. '&lsaquo;' => '&#8249;',
  3270. '&rsaquo;' => '&#8250;',
  3271. '&oline;' => '&#8254;',
  3272. '&frasl;' => '&#8260;',
  3273. '&euro;' => '&#8364;',
  3274. '&image;' => '&#8465;',
  3275. '&weierp;' => '&#8472;',
  3276. '&real;' => '&#8476;',
  3277. '&trade;' => '&#8482;',
  3278. '&alefsym;' => '&#8501;',
  3279. '&crarr;' => '&#8629;',
  3280. '&lArr;' => '&#8656;',
  3281. '&uArr;' => '&#8657;',
  3282. '&rArr;' => '&#8658;',
  3283. '&dArr;' => '&#8659;',
  3284. '&hArr;' => '&#8660;',
  3285. '&forall;' => '&#8704;',
  3286. '&part;' => '&#8706;',
  3287. '&exist;' => '&#8707;',
  3288. '&empty;' => '&#8709;',
  3289. '&nabla;' => '&#8711;',
  3290. '&isin;' => '&#8712;',
  3291. '&notin;' => '&#8713;',
  3292. '&ni;' => '&#8715;',
  3293. '&prod;' => '&#8719;',
  3294. '&sum;' => '&#8721;',
  3295. '&minus;' => '&#8722;',
  3296. '&lowast;' => '&#8727;',
  3297. '&radic;' => '&#8730;',
  3298. '&prop;' => '&#8733;',
  3299. '&infin;' => '&#8734;',
  3300. '&ang;' => '&#8736;',
  3301. '&and;' => '&#8743;',
  3302. '&or;' => '&#8744;',
  3303. '&cap;' => '&#8745;',
  3304. '&cup;' => '&#8746;',
  3305. '&int;' => '&#8747;',
  3306. '&there4;' => '&#8756;',
  3307. '&sim;' => '&#8764;',
  3308. '&cong;' => '&#8773;',
  3309. '&asymp;' => '&#8776;',
  3310. '&ne;' => '&#8800;',
  3311. '&equiv;' => '&#8801;',
  3312. '&le;' => '&#8804;',
  3313. '&ge;' => '&#8805;',
  3314. '&sub;' => '&#8834;',
  3315. '&sup;' => '&#8835;',
  3316. '&nsub;' => '&#8836;',
  3317. '&sube;' => '&#8838;',
  3318. '&supe;' => '&#8839;',
  3319. '&oplus;' => '&#8853;',
  3320. '&otimes;' => '&#8855;',
  3321. '&perp;' => '&#8869;',
  3322. '&sdot;' => '&#8901;',
  3323. '&lceil;' => '&#8968;',
  3324. '&rceil;' => '&#8969;',
  3325. '&lfloor;' => '&#8970;',
  3326. '&rfloor;' => '&#8971;',
  3327. '&lang;' => '&#9001;',
  3328. '&rang;' => '&#9002;',
  3329. '&larr;' => '&#8592;',
  3330. '&uarr;' => '&#8593;',
  3331. '&rarr;' => '&#8594;',
  3332. '&darr;' => '&#8595;',
  3333. '&harr;' => '&#8596;',
  3334. '&loz;' => '&#9674;',
  3335. '&spades;' => '&#9824;',
  3336. '&clubs;' => '&#9827;',
  3337. '&hearts;' => '&#9829;',
  3338. '&diams;' => '&#9830;'
  3339. );
  3340. return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
  3341. }
  3342. /**
  3343. * Formats text for the editor.
  3344. *
  3345. * Generally the browsers treat everything inside a textarea as text, but
  3346. * it is still a good idea to HTML entity encode `<`, `>` and `&` in the content.
  3347. *
  3348. * The filter {@see 'format_for_editor'} is applied here. If `$text` is empty the
  3349. * filter will be applied to an empty string.
  3350. *
  3351. * @since 4.3.0
  3352. *
  3353. * @see _WP_Editors::editor()
  3354. *
  3355. * @param string $text The text to be formatted.
  3356. * @param string $default_editor The default editor for the current user.
  3357. * It is usually either 'html' or 'tinymce'.
  3358. * @return string The formatted text after filter is applied.
  3359. */
  3360. function format_for_editor( $text, $default_editor = null ) {
  3361. if ( $text ) {
  3362. $text = htmlspecialchars( $text, ENT_NOQUOTES, get_option( 'blog_charset' ) );
  3363. }
  3364. /**
  3365. * Filters the text after it is formatted for the editor.
  3366. *
  3367. * @since 4.3.0
  3368. *
  3369. * @param string $text The formatted text.
  3370. * @param string $default_editor The default editor for the current user.
  3371. * It is usually either 'html' or 'tinymce'.
  3372. */
  3373. return apply_filters( 'format_for_editor', $text, $default_editor );
  3374. }
  3375. /**
  3376. * Perform a deep string replace operation to ensure the values in $search are no longer present
  3377. *
  3378. * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
  3379. * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
  3380. * str_replace would return
  3381. *
  3382. * @since 2.8.1
  3383. * @access private
  3384. *
  3385. * @param string|array $search The value being searched for, otherwise known as the needle.
  3386. * An array may be used to designate multiple needles.
  3387. * @param string $subject The string being searched and replaced on, otherwise known as the haystack.
  3388. * @return string The string with the replaced svalues.
  3389. */
  3390. function _deep_replace( $search, $subject ) {
  3391. $subject = (string) $subject;
  3392. $count = 1;
  3393. while ( $count ) {
  3394. $subject = str_replace( $search, '', $subject, $count );
  3395. }
  3396. return $subject;
  3397. }
  3398. /**
  3399. * Escapes data for use in a MySQL query.
  3400. *
  3401. * Usually you should prepare queries using wpdb::prepare().
  3402. * Sometimes, spot-escaping is required or useful. One example
  3403. * is preparing an array for use in an IN clause.
  3404. *
  3405. * @since 2.8.0
  3406. *
  3407. * @global wpdb $wpdb WordPress database abstraction object.
  3408. *
  3409. * @param string|array $data Unescaped data
  3410. * @return string|array Escaped data
  3411. */
  3412. function esc_sql( $data ) {
  3413. global $wpdb;
  3414. return $wpdb->_escape( $data );
  3415. }
  3416. /**
  3417. * Checks and cleans a URL.
  3418. *
  3419. * A number of characters are removed from the URL. If the URL is for displaying
  3420. * (the default behaviour) ampersands are also replaced. The {@see 'clean_url'} filter
  3421. * is applied to the returned cleaned URL.
  3422. *
  3423. * @since 2.8.0
  3424. *
  3425. * @param string $url The URL to be cleaned.
  3426. * @param array $protocols Optional. An array of acceptable protocols.
  3427. * Defaults to return value of wp_allowed_protocols()
  3428. * @param string $_context Private. Use esc_url_raw() for database usage.
  3429. * @return string The cleaned $url after the {@see 'clean_url'} filter is applied.
  3430. */
  3431. function esc_url( $url, $protocols = null, $_context = 'display' ) {
  3432. $original_url = $url;
  3433. if ( '' == $url )
  3434. return $url;
  3435. $url = str_replace( ' ', '%20', $url );
  3436. $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\[\]\\x80-\\xff]|i', '', $url);
  3437. if ( '' === $url ) {
  3438. return $url;
  3439. }
  3440. if ( 0 !== stripos( $url, 'mailto:' ) ) {
  3441. $strip = array('%0d', '%0a', '%0D', '%0A');
  3442. $url = _deep_replace($strip, $url);
  3443. }
  3444. $url = str_replace(';//', '://', $url);
  3445. /* If the URL doesn't appear to contain a scheme, we
  3446. * presume it needs http:// prepended (unless a relative
  3447. * link starting with /, # or ? or a php file).
  3448. */
  3449. if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
  3450. ! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
  3451. $url = 'http://' . $url;
  3452. // Replace ampersands and single quotes only when displaying.
  3453. if ( 'display' == $_context ) {
  3454. $url = wp_kses_normalize_entities( $url );
  3455. $url = str_replace( '&amp;', '&#038;', $url );
  3456. $url = str_replace( "'", '&#039;', $url );
  3457. }
  3458. if ( ( false !== strpos( $url, '[' ) ) || ( false !== strpos( $url, ']' ) ) ) {
  3459. $parsed = wp_parse_url( $url );
  3460. $front = '';
  3461. if ( isset( $parsed['scheme'] ) ) {
  3462. $front .= $parsed['scheme'] . '://';
  3463. } elseif ( '/' === $url[0] ) {
  3464. $front .= '//';
  3465. }
  3466. if ( isset( $parsed['user'] ) ) {
  3467. $front .= $parsed['user'];
  3468. }
  3469. if ( isset( $parsed['pass'] ) ) {
  3470. $front .= ':' . $parsed['pass'];
  3471. }
  3472. if ( isset( $parsed['user'] ) || isset( $parsed['pass'] ) ) {
  3473. $front .= '@';
  3474. }
  3475. if ( isset( $parsed['host'] ) ) {
  3476. $front .= $parsed['host'];
  3477. }
  3478. if ( isset( $parsed['port'] ) ) {
  3479. $front .= ':' . $parsed['port'];
  3480. }
  3481. $end_dirty = str_replace( $front, '', $url );
  3482. $end_clean = str_replace( array( '[', ']' ), array( '%5B', '%5D' ), $end_dirty );
  3483. $url = str_replace( $end_dirty, $end_clean, $url );
  3484. }
  3485. if ( '/' === $url[0] ) {
  3486. $good_protocol_url = $url;
  3487. } else {
  3488. if ( ! is_array( $protocols ) )
  3489. $protocols = wp_allowed_protocols();
  3490. $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
  3491. if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
  3492. return '';
  3493. }
  3494. /**
  3495. * Filters a string cleaned and escaped for output as a URL.
  3496. *
  3497. * @since 2.3.0
  3498. *
  3499. * @param string $good_protocol_url The cleaned URL to be returned.
  3500. * @param string $original_url The URL prior to cleaning.
  3501. * @param string $_context If 'display', replace ampersands and single quotes only.
  3502. */
  3503. return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
  3504. }
  3505. /**
  3506. * Performs esc_url() for database usage.
  3507. *
  3508. * @since 2.8.0
  3509. *
  3510. * @param string $url The URL to be cleaned.
  3511. * @param array $protocols An array of acceptable protocols.
  3512. * @return string The cleaned URL.
  3513. */
  3514. function esc_url_raw( $url, $protocols = null ) {
  3515. return esc_url( $url, $protocols, 'db' );
  3516. }
  3517. /**
  3518. * Convert entities, while preserving already-encoded entities.
  3519. *
  3520. * @link https://secure.php.net/htmlentities Borrowed from the PHP Manual user notes.
  3521. *
  3522. * @since 1.2.2
  3523. *
  3524. * @param string $myHTML The text to be converted.
  3525. * @return string Converted text.
  3526. */
  3527. function htmlentities2( $myHTML ) {
  3528. $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
  3529. $translation_table[chr(38)] = '&';
  3530. return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&amp;", strtr($myHTML, $translation_table) );
  3531. }
  3532. /**
  3533. * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
  3534. *
  3535. * Escapes text strings for echoing in JS. It is intended to be used for inline JS
  3536. * (in a tag attribute, for example onclick="..."). Note that the strings have to
  3537. * be in single quotes. The {@see 'js_escape'} filter is also applied here.
  3538. *
  3539. * @since 2.8.0
  3540. *
  3541. * @param string $text The text to be escaped.
  3542. * @return string Escaped text.
  3543. */
  3544. function esc_js( $text ) {
  3545. $safe_text = wp_check_invalid_utf8( $text );
  3546. $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
  3547. $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
  3548. $safe_text = str_replace( "\r", '', $safe_text );
  3549. $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
  3550. /**
  3551. * Filters a string cleaned and escaped for output in JavaScript.
  3552. *
  3553. * Text passed to esc_js() is stripped of invalid or special characters,
  3554. * and properly slashed for output.
  3555. *
  3556. * @since 2.0.6
  3557. *
  3558. * @param string $safe_text The text after it has been escaped.
  3559. * @param string $text The text prior to being escaped.
  3560. */
  3561. return apply_filters( 'js_escape', $safe_text, $text );
  3562. }
  3563. /**
  3564. * Escaping for HTML blocks.
  3565. *
  3566. * @since 2.8.0
  3567. *
  3568. * @param string $text
  3569. * @return string
  3570. */
  3571. function esc_html( $text ) {
  3572. $safe_text = wp_check_invalid_utf8( $text );
  3573. $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
  3574. /**
  3575. * Filters a string cleaned and escaped for output in HTML.
  3576. *
  3577. * Text passed to esc_html() is stripped of invalid or special characters
  3578. * before output.
  3579. *
  3580. * @since 2.8.0
  3581. *
  3582. * @param string $safe_text The text after it has been escaped.
  3583. * @param string $text The text prior to being escaped.
  3584. */
  3585. return apply_filters( 'esc_html', $safe_text, $text );
  3586. }
  3587. /**
  3588. * Escaping for HTML attributes.
  3589. *
  3590. * @since 2.8.0
  3591. *
  3592. * @param string $text
  3593. * @return string
  3594. */
  3595. function esc_attr( $text ) {
  3596. $safe_text = wp_check_invalid_utf8( $text );
  3597. $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
  3598. /**
  3599. * Filters a string cleaned and escaped for output in an HTML attribute.
  3600. *
  3601. * Text passed to esc_attr() is stripped of invalid or special characters
  3602. * before output.
  3603. *
  3604. * @since 2.0.6
  3605. *
  3606. * @param string $safe_text The text after it has been escaped.
  3607. * @param string $text The text prior to being escaped.
  3608. */
  3609. return apply_filters( 'attribute_escape', $safe_text, $text );
  3610. }
  3611. /**
  3612. * Escaping for textarea values.
  3613. *
  3614. * @since 3.1.0
  3615. *
  3616. * @param string $text
  3617. * @return string
  3618. */
  3619. function esc_textarea( $text ) {
  3620. $safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
  3621. /**
  3622. * Filters a string cleaned and escaped for output in a textarea element.
  3623. *
  3624. * @since 3.1.0
  3625. *
  3626. * @param string $safe_text The text after it has been escaped.
  3627. * @param string $text The text prior to being escaped.
  3628. */
  3629. return apply_filters( 'esc_textarea', $safe_text, $text );
  3630. }
  3631. /**
  3632. * Escape an HTML tag name.
  3633. *
  3634. * @since 2.5.0
  3635. *
  3636. * @param string $tag_name
  3637. * @return string
  3638. */
  3639. function tag_escape( $tag_name ) {
  3640. $safe_tag = strtolower( preg_replace('/[^a-zA-Z0-9_:]/', '', $tag_name) );
  3641. /**
  3642. * Filters a string cleaned and escaped for output as an HTML tag.
  3643. *
  3644. * @since 2.8.0
  3645. *
  3646. * @param string $safe_tag The tag name after it has been escaped.
  3647. * @param string $tag_name The text before it was escaped.
  3648. */
  3649. return apply_filters( 'tag_escape', $safe_tag, $tag_name );
  3650. }
  3651. /**
  3652. * Convert full URL paths to absolute paths.
  3653. *
  3654. * Removes the http or https protocols and the domain. Keeps the path '/' at the
  3655. * beginning, so it isn't a true relative link, but from the web root base.
  3656. *
  3657. * @since 2.1.0
  3658. * @since 4.1.0 Support was added for relative URLs.
  3659. *
  3660. * @param string $link Full URL path.
  3661. * @return string Absolute path.
  3662. */
  3663. function wp_make_link_relative( $link ) {
  3664. return preg_replace( '|^(https?:)?//[^/]+(/?.*)|i', '$2', $link );
  3665. }
  3666. /**
  3667. * Sanitises various option values based on the nature of the option.
  3668. *
  3669. * This is basically a switch statement which will pass $value through a number
  3670. * of functions depending on the $option.
  3671. *
  3672. * @since 2.0.5
  3673. *
  3674. * @global wpdb $wpdb WordPress database abstraction object.
  3675. *
  3676. * @param string $option The name of the option.
  3677. * @param string $value The unsanitised value.
  3678. * @return string Sanitized value.
  3679. */
  3680. function sanitize_option( $option, $value ) {
  3681. global $wpdb;
  3682. $original_value = $value;
  3683. $error = '';
  3684. switch ( $option ) {
  3685. case 'admin_email' :
  3686. case 'new_admin_email' :
  3687. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
  3688. if ( is_wp_error( $value ) ) {
  3689. $error = $value->get_error_message();
  3690. } else {
  3691. $value = sanitize_email( $value );
  3692. if ( ! is_email( $value ) ) {
  3693. $error = __( 'The email address entered did not appear to be a valid email address. Please enter a valid email address.' );
  3694. }
  3695. }
  3696. break;
  3697. case 'thumbnail_size_w':
  3698. case 'thumbnail_size_h':
  3699. case 'medium_size_w':
  3700. case 'medium_size_h':
  3701. case 'medium_large_size_w':
  3702. case 'medium_large_size_h':
  3703. case 'large_size_w':
  3704. case 'large_size_h':
  3705. case 'mailserver_port':
  3706. case 'comment_max_links':
  3707. case 'page_on_front':
  3708. case 'page_for_posts':
  3709. case 'rss_excerpt_length':
  3710. case 'default_category':
  3711. case 'default_email_category':
  3712. case 'default_link_category':
  3713. case 'close_comments_days_old':
  3714. case 'comments_per_page':
  3715. case 'thread_comments_depth':
  3716. case 'users_can_register':
  3717. case 'start_of_week':
  3718. case 'site_icon':
  3719. $value = absint( $value );
  3720. break;
  3721. case 'posts_per_page':
  3722. case 'posts_per_rss':
  3723. $value = (int) $value;
  3724. if ( empty($value) )
  3725. $value = 1;
  3726. if ( $value < -1 )
  3727. $value = abs($value);
  3728. break;
  3729. case 'default_ping_status':
  3730. case 'default_comment_status':
  3731. // Options that if not there have 0 value but need to be something like "closed"
  3732. if ( $value == '0' || $value == '')
  3733. $value = 'closed';
  3734. break;
  3735. case 'blogdescription':
  3736. case 'blogname':
  3737. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
  3738. if ( $value !== $original_value ) {
  3739. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', wp_encode_emoji( $original_value ) );
  3740. }
  3741. if ( is_wp_error( $value ) ) {
  3742. $error = $value->get_error_message();
  3743. } else {
  3744. $value = esc_html( $value );
  3745. }
  3746. break;
  3747. case 'blog_charset':
  3748. $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
  3749. break;
  3750. case 'blog_public':
  3751. // This is the value if the settings checkbox is not checked on POST. Don't rely on this.
  3752. if ( null === $value )
  3753. $value = 1;
  3754. else
  3755. $value = intval( $value );
  3756. break;
  3757. case 'date_format':
  3758. case 'time_format':
  3759. case 'mailserver_url':
  3760. case 'mailserver_login':
  3761. case 'mailserver_pass':
  3762. case 'upload_path':
  3763. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
  3764. if ( is_wp_error( $value ) ) {
  3765. $error = $value->get_error_message();
  3766. } else {
  3767. $value = strip_tags( $value );
  3768. $value = wp_kses_data( $value );
  3769. }
  3770. break;
  3771. case 'ping_sites':
  3772. $value = explode( "\n", $value );
  3773. $value = array_filter( array_map( 'trim', $value ) );
  3774. $value = array_filter( array_map( 'esc_url_raw', $value ) );
  3775. $value = implode( "\n", $value );
  3776. break;
  3777. case 'gmt_offset':
  3778. $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
  3779. break;
  3780. case 'siteurl':
  3781. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
  3782. if ( is_wp_error( $value ) ) {
  3783. $error = $value->get_error_message();
  3784. } else {
  3785. if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
  3786. $value = esc_url_raw( $value );
  3787. } else {
  3788. $error = __( 'The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.' );
  3789. }
  3790. }
  3791. break;
  3792. case 'home':
  3793. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
  3794. if ( is_wp_error( $value ) ) {
  3795. $error = $value->get_error_message();
  3796. } else {
  3797. if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
  3798. $value = esc_url_raw( $value );
  3799. } else {
  3800. $error = __( 'The Site address you entered did not appear to be a valid URL. Please enter a valid URL.' );
  3801. }
  3802. }
  3803. break;
  3804. case 'WPLANG':
  3805. $allowed = get_available_languages();
  3806. if ( ! is_multisite() && defined( 'WPLANG' ) && '' !== WPLANG && 'en_US' !== WPLANG ) {
  3807. $allowed[] = WPLANG;
  3808. }
  3809. if ( ! in_array( $value, $allowed ) && ! empty( $value ) ) {
  3810. $value = get_option( $option );
  3811. }
  3812. break;
  3813. case 'illegal_names':
  3814. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
  3815. if ( is_wp_error( $value ) ) {
  3816. $error = $value->get_error_message();
  3817. } else {
  3818. if ( ! is_array( $value ) )
  3819. $value = explode( ' ', $value );
  3820. $value = array_values( array_filter( array_map( 'trim', $value ) ) );
  3821. if ( ! $value )
  3822. $value = '';
  3823. }
  3824. break;
  3825. case 'limited_email_domains':
  3826. case 'banned_email_domains':
  3827. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
  3828. if ( is_wp_error( $value ) ) {
  3829. $error = $value->get_error_message();
  3830. } else {
  3831. if ( ! is_array( $value ) )
  3832. $value = explode( "\n", $value );
  3833. $domains = array_values( array_filter( array_map( 'trim', $value ) ) );
  3834. $value = array();
  3835. foreach ( $domains as $domain ) {
  3836. if ( ! preg_match( '/(--|\.\.)/', $domain ) && preg_match( '|^([a-zA-Z0-9-\.])+$|', $domain ) ) {
  3837. $value[] = $domain;
  3838. }
  3839. }
  3840. if ( ! $value )
  3841. $value = '';
  3842. }
  3843. break;
  3844. case 'timezone_string':
  3845. $allowed_zones = timezone_identifiers_list();
  3846. if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
  3847. $error = __( 'The timezone you have entered is not valid. Please select a valid timezone.' );
  3848. }
  3849. break;
  3850. case 'permalink_structure':
  3851. case 'category_base':
  3852. case 'tag_base':
  3853. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
  3854. if ( is_wp_error( $value ) ) {
  3855. $error = $value->get_error_message();
  3856. } else {
  3857. $value = esc_url_raw( $value );
  3858. $value = str_replace( 'http://', '', $value );
  3859. }
  3860. if ( 'permalink_structure' === $option && '' !== $value && ! preg_match( '/%[^\/%]+%/', $value ) ) {
  3861. $error = sprintf(
  3862. /* translators: %s: Codex URL */
  3863. __( 'A structure tag is required when using custom permalinks. <a href="%s">Learn more</a>' ),
  3864. __( 'https://codex.wordpress.org/Using_Permalinks#Choosing_your_permalink_structure' )
  3865. );
  3866. }
  3867. break;
  3868. case 'default_role' :
  3869. if ( ! get_role( $value ) && get_role( 'subscriber' ) )
  3870. $value = 'subscriber';
  3871. break;
  3872. case 'moderation_keys':
  3873. case 'blacklist_keys':
  3874. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
  3875. if ( is_wp_error( $value ) ) {
  3876. $error = $value->get_error_message();
  3877. } else {
  3878. $value = explode( "\n", $value );
  3879. $value = array_filter( array_map( 'trim', $value ) );
  3880. $value = array_unique( $value );
  3881. $value = implode( "\n", $value );
  3882. }
  3883. break;
  3884. }
  3885. if ( ! empty( $error ) ) {
  3886. $value = get_option( $option );
  3887. if ( function_exists( 'add_settings_error' ) ) {
  3888. add_settings_error( $option, "invalid_{$option}", $error );
  3889. }
  3890. }
  3891. /**
  3892. * Filters an option value following sanitization.
  3893. *
  3894. * @since 2.3.0
  3895. * @since 4.3.0 Added the `$original_value` parameter.
  3896. *
  3897. * @param string $value The sanitized option value.
  3898. * @param string $option The option name.
  3899. * @param string $original_value The original value passed to the function.
  3900. */
  3901. return apply_filters( "sanitize_option_{$option}", $value, $option, $original_value );
  3902. }
  3903. /**
  3904. * Maps a function to all non-iterable elements of an array or an object.
  3905. *
  3906. * This is similar to `array_walk_recursive()` but acts upon objects too.
  3907. *
  3908. * @since 4.4.0
  3909. *
  3910. * @param mixed $value The array, object, or scalar.
  3911. * @param callable $callback The function to map onto $value.
  3912. * @return mixed The value with the callback applied to all non-arrays and non-objects inside it.
  3913. */
  3914. function map_deep( $value, $callback ) {
  3915. if ( is_array( $value ) ) {
  3916. foreach ( $value as $index => $item ) {
  3917. $value[ $index ] = map_deep( $item, $callback );
  3918. }
  3919. } elseif ( is_object( $value ) ) {
  3920. $object_vars = get_object_vars( $value );
  3921. foreach ( $object_vars as $property_name => $property_value ) {
  3922. $value->$property_name = map_deep( $property_value, $callback );
  3923. }
  3924. } else {
  3925. $value = call_user_func( $callback, $value );
  3926. }
  3927. return $value;
  3928. }
  3929. /**
  3930. * Parses a string into variables to be stored in an array.
  3931. *
  3932. * Uses {@link https://secure.php.net/parse_str parse_str()} and stripslashes if
  3933. * {@link https://secure.php.net/magic_quotes magic_quotes_gpc} is on.
  3934. *
  3935. * @since 2.2.1
  3936. *
  3937. * @param string $string The string to be parsed.
  3938. * @param array $array Variables will be stored in this array.
  3939. */
  3940. function wp_parse_str( $string, &$array ) {
  3941. parse_str( $string, $array );
  3942. if ( get_magic_quotes_gpc() )
  3943. $array = stripslashes_deep( $array );
  3944. /**
  3945. * Filters the array of variables derived from a parsed string.
  3946. *
  3947. * @since 2.3.0
  3948. *
  3949. * @param array $array The array populated with variables.
  3950. */
  3951. $array = apply_filters( 'wp_parse_str', $array );
  3952. }
  3953. /**
  3954. * Convert lone less than signs.
  3955. *
  3956. * KSES already converts lone greater than signs.
  3957. *
  3958. * @since 2.3.0
  3959. *
  3960. * @param string $text Text to be converted.
  3961. * @return string Converted text.
  3962. */
  3963. function wp_pre_kses_less_than( $text ) {
  3964. return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
  3965. }
  3966. /**
  3967. * Callback function used by preg_replace.
  3968. *
  3969. * @since 2.3.0
  3970. *
  3971. * @param array $matches Populated by matches to preg_replace.
  3972. * @return string The text returned after esc_html if needed.
  3973. */
  3974. function wp_pre_kses_less_than_callback( $matches ) {
  3975. if ( false === strpos($matches[0], '>') )
  3976. return esc_html($matches[0]);
  3977. return $matches[0];
  3978. }
  3979. /**
  3980. * WordPress implementation of PHP sprintf() with filters.
  3981. *
  3982. * @since 2.5.0
  3983. * @link https://secure.php.net/sprintf
  3984. *
  3985. * @param string $pattern The string which formatted args are inserted.
  3986. * @param mixed $args ,... Arguments to be formatted into the $pattern string.
  3987. * @return string The formatted string.
  3988. */
  3989. function wp_sprintf( $pattern ) {
  3990. $args = func_get_args();
  3991. $len = strlen($pattern);
  3992. $start = 0;
  3993. $result = '';
  3994. $arg_index = 0;
  3995. while ( $len > $start ) {
  3996. // Last character: append and break
  3997. if ( strlen($pattern) - 1 == $start ) {
  3998. $result .= substr($pattern, -1);
  3999. break;
  4000. }
  4001. // Literal %: append and continue
  4002. if ( substr($pattern, $start, 2) == '%%' ) {
  4003. $start += 2;
  4004. $result .= '%';
  4005. continue;
  4006. }
  4007. // Get fragment before next %
  4008. $end = strpos($pattern, '%', $start + 1);
  4009. if ( false === $end )
  4010. $end = $len;
  4011. $fragment = substr($pattern, $start, $end - $start);
  4012. // Fragment has a specifier
  4013. if ( $pattern[$start] == '%' ) {
  4014. // Find numbered arguments or take the next one in order
  4015. if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
  4016. $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
  4017. $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
  4018. } else {
  4019. ++$arg_index;
  4020. $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
  4021. }
  4022. /**
  4023. * Filters a fragment from the pattern passed to wp_sprintf().
  4024. *
  4025. * If the fragment is unchanged, then sprintf() will be run on the fragment.
  4026. *
  4027. * @since 2.5.0
  4028. *
  4029. * @param string $fragment A fragment from the pattern.
  4030. * @param string $arg The argument.
  4031. */
  4032. $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
  4033. if ( $_fragment != $fragment )
  4034. $fragment = $_fragment;
  4035. else
  4036. $fragment = sprintf($fragment, strval($arg) );
  4037. }
  4038. // Append to result and move to next fragment
  4039. $result .= $fragment;
  4040. $start = $end;
  4041. }
  4042. return $result;
  4043. }
  4044. /**
  4045. * Localize list items before the rest of the content.
  4046. *
  4047. * The '%l' must be at the first characters can then contain the rest of the
  4048. * content. The list items will have ', ', ', and', and ' and ' added depending
  4049. * on the amount of list items in the $args parameter.
  4050. *
  4051. * @since 2.5.0
  4052. *
  4053. * @param string $pattern Content containing '%l' at the beginning.
  4054. * @param array $args List items to prepend to the content and replace '%l'.
  4055. * @return string Localized list items and rest of the content.
  4056. */
  4057. function wp_sprintf_l( $pattern, $args ) {
  4058. // Not a match
  4059. if ( substr($pattern, 0, 2) != '%l' )
  4060. return $pattern;
  4061. // Nothing to work with
  4062. if ( empty($args) )
  4063. return '';
  4064. /**
  4065. * Filters the translated delimiters used by wp_sprintf_l().
  4066. * Placeholders (%s) are included to assist translators and then
  4067. * removed before the array of strings reaches the filter.
  4068. *
  4069. * Please note: Ampersands and entities should be avoided here.
  4070. *
  4071. * @since 2.5.0
  4072. *
  4073. * @param array $delimiters An array of translated delimiters.
  4074. */
  4075. $l = apply_filters( 'wp_sprintf_l', array(
  4076. /* translators: used to join items in a list with more than 2 items */
  4077. 'between' => sprintf( __('%s, %s'), '', '' ),
  4078. /* translators: used to join last two items in a list with more than 2 times */
  4079. 'between_last_two' => sprintf( __('%s, and %s'), '', '' ),
  4080. /* translators: used to join items in a list with only 2 items */
  4081. 'between_only_two' => sprintf( __('%s and %s'), '', '' ),
  4082. ) );
  4083. $args = (array) $args;
  4084. $result = array_shift($args);
  4085. if ( count($args) == 1 )
  4086. $result .= $l['between_only_two'] . array_shift($args);
  4087. // Loop when more than two args
  4088. $i = count($args);
  4089. while ( $i ) {
  4090. $arg = array_shift($args);
  4091. $i--;
  4092. if ( 0 == $i )
  4093. $result .= $l['between_last_two'] . $arg;
  4094. else
  4095. $result .= $l['between'] . $arg;
  4096. }
  4097. return $result . substr($pattern, 2);
  4098. }
  4099. /**
  4100. * Safely extracts not more than the first $count characters from html string.
  4101. *
  4102. * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
  4103. * be counted as one character. For example &amp; will be counted as 4, &lt; as
  4104. * 3, etc.
  4105. *
  4106. * @since 2.5.0
  4107. *
  4108. * @param string $str String to get the excerpt from.
  4109. * @param int $count Maximum number of characters to take.
  4110. * @param string $more Optional. What to append if $str needs to be trimmed. Defaults to empty string.
  4111. * @return string The excerpt.
  4112. */
  4113. function wp_html_excerpt( $str, $count, $more = null ) {
  4114. if ( null === $more )
  4115. $more = '';
  4116. $str = wp_strip_all_tags( $str, true );
  4117. $excerpt = mb_substr( $str, 0, $count );
  4118. // remove part of an entity at the end
  4119. $excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );
  4120. if ( $str != $excerpt )
  4121. $excerpt = trim( $excerpt ) . $more;
  4122. return $excerpt;
  4123. }
  4124. /**
  4125. * Add a Base url to relative links in passed content.
  4126. *
  4127. * By default it supports the 'src' and 'href' attributes. However this can be
  4128. * changed via the 3rd param.
  4129. *
  4130. * @since 2.7.0
  4131. *
  4132. * @global string $_links_add_base
  4133. *
  4134. * @param string $content String to search for links in.
  4135. * @param string $base The base URL to prefix to links.
  4136. * @param array $attrs The attributes which should be processed.
  4137. * @return string The processed content.
  4138. */
  4139. function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
  4140. global $_links_add_base;
  4141. $_links_add_base = $base;
  4142. $attrs = implode('|', (array)$attrs);
  4143. return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
  4144. }
  4145. /**
  4146. * Callback to add a base url to relative links in passed content.
  4147. *
  4148. * @since 2.7.0
  4149. * @access private
  4150. *
  4151. * @global string $_links_add_base
  4152. *
  4153. * @param string $m The matched link.
  4154. * @return string The processed link.
  4155. */
  4156. function _links_add_base( $m ) {
  4157. global $_links_add_base;
  4158. //1 = attribute name 2 = quotation mark 3 = URL
  4159. return $m[1] . '=' . $m[2] .
  4160. ( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ?
  4161. $m[3] :
  4162. WP_Http::make_absolute_url( $m[3], $_links_add_base )
  4163. )
  4164. . $m[2];
  4165. }
  4166. /**
  4167. * Adds a Target attribute to all links in passed content.
  4168. *
  4169. * This function by default only applies to `<a>` tags, however this can be
  4170. * modified by the 3rd param.
  4171. *
  4172. * *NOTE:* Any current target attributed will be stripped and replaced.
  4173. *
  4174. * @since 2.7.0
  4175. *
  4176. * @global string $_links_add_target
  4177. *
  4178. * @param string $content String to search for links in.
  4179. * @param string $target The Target to add to the links.
  4180. * @param array $tags An array of tags to apply to.
  4181. * @return string The processed content.
  4182. */
  4183. function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
  4184. global $_links_add_target;
  4185. $_links_add_target = $target;
  4186. $tags = implode('|', (array)$tags);
  4187. return preg_replace_callback( "!<($tags)([^>]*)>!i", '_links_add_target', $content );
  4188. }
  4189. /**
  4190. * Callback to add a target attribute to all links in passed content.
  4191. *
  4192. * @since 2.7.0
  4193. * @access private
  4194. *
  4195. * @global string $_links_add_target
  4196. *
  4197. * @param string $m The matched link.
  4198. * @return string The processed link.
  4199. */
  4200. function _links_add_target( $m ) {
  4201. global $_links_add_target;
  4202. $tag = $m[1];
  4203. $link = preg_replace('|( target=([\'"])(.*?)\2)|i', '', $m[2]);
  4204. return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
  4205. }
  4206. /**
  4207. * Normalize EOL characters and strip duplicate whitespace.
  4208. *
  4209. * @since 2.7.0
  4210. *
  4211. * @param string $str The string to normalize.
  4212. * @return string The normalized string.
  4213. */
  4214. function normalize_whitespace( $str ) {
  4215. $str = trim( $str );
  4216. $str = str_replace( "\r", "\n", $str );
  4217. $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
  4218. return $str;
  4219. }
  4220. /**
  4221. * Properly strip all HTML tags including script and style
  4222. *
  4223. * This differs from strip_tags() because it removes the contents of
  4224. * the `<script>` and `<style>` tags. E.g. `strip_tags( '<script>something</script>' )`
  4225. * will return 'something'. wp_strip_all_tags will return ''
  4226. *
  4227. * @since 2.9.0
  4228. *
  4229. * @param string $string String containing HTML tags
  4230. * @param bool $remove_breaks Optional. Whether to remove left over line breaks and white space chars
  4231. * @return string The processed string.
  4232. */
  4233. function wp_strip_all_tags($string, $remove_breaks = false) {
  4234. $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
  4235. $string = strip_tags($string);
  4236. if ( $remove_breaks )
  4237. $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
  4238. return trim( $string );
  4239. }
  4240. /**
  4241. * Sanitizes a string from user input or from the database.
  4242. *
  4243. * - Checks for invalid UTF-8,
  4244. * - Converts single `<` characters to entities
  4245. * - Strips all tags
  4246. * - Removes line breaks, tabs, and extra whitespace
  4247. * - Strips octets
  4248. *
  4249. * @since 2.9.0
  4250. *
  4251. * @see sanitize_textarea_field()
  4252. * @see wp_check_invalid_utf8()
  4253. * @see wp_strip_all_tags()
  4254. *
  4255. * @param string $str String to sanitize.
  4256. * @return string Sanitized string.
  4257. */
  4258. function sanitize_text_field( $str ) {
  4259. $filtered = _sanitize_text_fields( $str, false );
  4260. /**
  4261. * Filters a sanitized text field string.
  4262. *
  4263. * @since 2.9.0
  4264. *
  4265. * @param string $filtered The sanitized string.
  4266. * @param string $str The string prior to being sanitized.
  4267. */
  4268. return apply_filters( 'sanitize_text_field', $filtered, $str );
  4269. }
  4270. /**
  4271. * Sanitizes a multiline string from user input or from the database.
  4272. *
  4273. * The function is like sanitize_text_field(), but preserves
  4274. * new lines (\n) and other whitespace, which are legitimate
  4275. * input in textarea elements.
  4276. *
  4277. * @see sanitize_text_field()
  4278. *
  4279. * @since 4.7.0
  4280. *
  4281. * @param string $str String to sanitize.
  4282. * @return string Sanitized string.
  4283. */
  4284. function sanitize_textarea_field( $str ) {
  4285. $filtered = _sanitize_text_fields( $str, true );
  4286. /**
  4287. * Filters a sanitized textarea field string.
  4288. *
  4289. * @since 4.7.0
  4290. *
  4291. * @param string $filtered The sanitized string.
  4292. * @param string $str The string prior to being sanitized.
  4293. */
  4294. return apply_filters( 'sanitize_textarea_field', $filtered, $str );
  4295. }
  4296. /**
  4297. * Internal helper function to sanitize a string from user input or from the db
  4298. *
  4299. * @since 4.7.0
  4300. * @access private
  4301. *
  4302. * @param string $str String to sanitize.
  4303. * @param bool $keep_newlines optional Whether to keep newlines. Default: false.
  4304. * @return string Sanitized string.
  4305. */
  4306. function _sanitize_text_fields( $str, $keep_newlines = false ) {
  4307. $filtered = wp_check_invalid_utf8( $str );
  4308. if ( strpos($filtered, '<') !== false ) {
  4309. $filtered = wp_pre_kses_less_than( $filtered );
  4310. // This will strip extra whitespace for us.
  4311. $filtered = wp_strip_all_tags( $filtered, false );
  4312. // Use html entities in a special case to make sure no later
  4313. // newline stripping stage could lead to a functional tag
  4314. $filtered = str_replace("<\n", "&lt;\n", $filtered);
  4315. }
  4316. if ( ! $keep_newlines ) {
  4317. $filtered = preg_replace( '/[\r\n\t ]+/', ' ', $filtered );
  4318. }
  4319. $filtered = trim( $filtered );
  4320. $found = false;
  4321. while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
  4322. $filtered = str_replace($match[0], '', $filtered);
  4323. $found = true;
  4324. }
  4325. if ( $found ) {
  4326. // Strip out the whitespace that may now exist after removing the octets.
  4327. $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
  4328. }
  4329. return $filtered;
  4330. }
  4331. /**
  4332. * i18n friendly version of basename()
  4333. *
  4334. * @since 3.1.0
  4335. *
  4336. * @param string $path A path.
  4337. * @param string $suffix If the filename ends in suffix this will also be cut off.
  4338. * @return string
  4339. */
  4340. function wp_basename( $path, $suffix = '' ) {
  4341. return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) );
  4342. }
  4343. /**
  4344. * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
  4345. *
  4346. * Violating our coding standards for a good function name.
  4347. *
  4348. * @since 3.0.0
  4349. *
  4350. * @staticvar string|false $dblq
  4351. *
  4352. * @param string $text The text to be modified.
  4353. * @return string The modified text.
  4354. */
  4355. function capital_P_dangit( $text ) {
  4356. // Simple replacement for titles
  4357. $current_filter = current_filter();
  4358. if ( 'the_title' === $current_filter || 'wp_title' === $current_filter )
  4359. return str_replace( 'Wordpress', 'WordPress', $text );
  4360. // Still here? Use the more judicious replacement
  4361. static $dblq = false;
  4362. if ( false === $dblq ) {
  4363. $dblq = _x( '&#8220;', 'opening curly double quote' );
  4364. }
  4365. return str_replace(
  4366. array( ' Wordpress', '&#8216;Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
  4367. array( ' WordPress', '&#8216;WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
  4368. $text );
  4369. }
  4370. /**
  4371. * Sanitize a mime type
  4372. *
  4373. * @since 3.1.3
  4374. *
  4375. * @param string $mime_type Mime type
  4376. * @return string Sanitized mime type
  4377. */
  4378. function sanitize_mime_type( $mime_type ) {
  4379. $sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type );
  4380. /**
  4381. * Filters a mime type following sanitization.
  4382. *
  4383. * @since 3.1.3
  4384. *
  4385. * @param string $sani_mime_type The sanitized mime type.
  4386. * @param string $mime_type The mime type prior to sanitization.
  4387. */
  4388. return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );
  4389. }
  4390. /**
  4391. * Sanitize space or carriage return separated URLs that are used to send trackbacks.
  4392. *
  4393. * @since 3.4.0
  4394. *
  4395. * @param string $to_ping Space or carriage return separated URLs
  4396. * @return string URLs starting with the http or https protocol, separated by a carriage return.
  4397. */
  4398. function sanitize_trackback_urls( $to_ping ) {
  4399. $urls_to_ping = preg_split( '/[\r\n\t ]/', trim( $to_ping ), -1, PREG_SPLIT_NO_EMPTY );
  4400. foreach ( $urls_to_ping as $k => $url ) {
  4401. if ( !preg_match( '#^https?://.#i', $url ) )
  4402. unset( $urls_to_ping[$k] );
  4403. }
  4404. $urls_to_ping = array_map( 'esc_url_raw', $urls_to_ping );
  4405. $urls_to_ping = implode( "\n", $urls_to_ping );
  4406. /**
  4407. * Filters a list of trackback URLs following sanitization.
  4408. *
  4409. * The string returned here consists of a space or carriage return-delimited list
  4410. * of trackback URLs.
  4411. *
  4412. * @since 3.4.0
  4413. *
  4414. * @param string $urls_to_ping Sanitized space or carriage return separated URLs.
  4415. * @param string $to_ping Space or carriage return separated URLs before sanitization.
  4416. */
  4417. return apply_filters( 'sanitize_trackback_urls', $urls_to_ping, $to_ping );
  4418. }
  4419. /**
  4420. * Add slashes to a string or array of strings.
  4421. *
  4422. * This should be used when preparing data for core API that expects slashed data.
  4423. * This should not be used to escape data going directly into an SQL query.
  4424. *
  4425. * @since 3.6.0
  4426. *
  4427. * @param string|array $value String or array of strings to slash.
  4428. * @return string|array Slashed $value
  4429. */
  4430. function wp_slash( $value ) {
  4431. if ( is_array( $value ) ) {
  4432. foreach ( $value as $k => $v ) {
  4433. if ( is_array( $v ) ) {
  4434. $value[$k] = wp_slash( $v );
  4435. } else {
  4436. $value[$k] = addslashes( $v );
  4437. }
  4438. }
  4439. } else {
  4440. $value = addslashes( $value );
  4441. }
  4442. return $value;
  4443. }
  4444. /**
  4445. * Remove slashes from a string or array of strings.
  4446. *
  4447. * This should be used to remove slashes from data passed to core API that
  4448. * expects data to be unslashed.
  4449. *
  4450. * @since 3.6.0
  4451. *
  4452. * @param string|array $value String or array of strings to unslash.
  4453. * @return string|array Unslashed $value
  4454. */
  4455. function wp_unslash( $value ) {
  4456. return stripslashes_deep( $value );
  4457. }
  4458. /**
  4459. * Extract and return the first URL from passed content.
  4460. *
  4461. * @since 3.6.0
  4462. *
  4463. * @param string $content A string which might contain a URL.
  4464. * @return string|false The found URL.
  4465. */
  4466. function get_url_in_content( $content ) {
  4467. if ( empty( $content ) ) {
  4468. return false;
  4469. }
  4470. if ( preg_match( '/<a\s[^>]*?href=([\'"])(.+?)\1/is', $content, $matches ) ) {
  4471. return esc_url_raw( $matches[2] );
  4472. }
  4473. return false;
  4474. }
  4475. /**
  4476. * Returns the regexp for common whitespace characters.
  4477. *
  4478. * By default, spaces include new lines, tabs, nbsp entities, and the UTF-8 nbsp.
  4479. * This is designed to replace the PCRE \s sequence. In ticket #22692, that
  4480. * sequence was found to be unreliable due to random inclusion of the A0 byte.
  4481. *
  4482. * @since 4.0.0
  4483. *
  4484. * @staticvar string $spaces
  4485. *
  4486. * @return string The spaces regexp.
  4487. */
  4488. function wp_spaces_regexp() {
  4489. static $spaces = '';
  4490. if ( empty( $spaces ) ) {
  4491. /**
  4492. * Filters the regexp for common whitespace characters.
  4493. *
  4494. * This string is substituted for the \s sequence as needed in regular
  4495. * expressions. For websites not written in English, different characters
  4496. * may represent whitespace. For websites not encoded in UTF-8, the 0xC2 0xA0
  4497. * sequence may not be in use.
  4498. *
  4499. * @since 4.0.0
  4500. *
  4501. * @param string $spaces Regexp pattern for matching common whitespace characters.
  4502. */
  4503. $spaces = apply_filters( 'wp_spaces_regexp', '[\r\n\t ]|\xC2\xA0|&nbsp;' );
  4504. }
  4505. return $spaces;
  4506. }
  4507. /**
  4508. * Print the important emoji-related styles.
  4509. *
  4510. * @since 4.2.0
  4511. *
  4512. * @staticvar bool $printed
  4513. */
  4514. function print_emoji_styles() {
  4515. static $printed = false;
  4516. if ( $printed ) {
  4517. return;
  4518. }
  4519. $printed = true;
  4520. ?>
  4521. <style type="text/css">
  4522. img.wp-smiley,
  4523. img.emoji {
  4524. display: inline !important;
  4525. border: none !important;
  4526. box-shadow: none !important;
  4527. height: 1em !important;
  4528. width: 1em !important;
  4529. margin: 0 .07em !important;
  4530. vertical-align: -0.1em !important;
  4531. background: none !important;
  4532. padding: 0 !important;
  4533. }
  4534. </style>
  4535. <?php
  4536. }
  4537. /**
  4538. * Print the inline Emoji detection script if it is not already printed.
  4539. *
  4540. * @since 4.2.0
  4541. * @staticvar bool $printed
  4542. */
  4543. function print_emoji_detection_script() {
  4544. static $printed = false;
  4545. if ( $printed ) {
  4546. return;
  4547. }
  4548. $printed = true;
  4549. _print_emoji_detection_script();
  4550. }
  4551. /**
  4552. * Prints inline Emoji dection script
  4553. *
  4554. * @ignore
  4555. * @since 4.6.0
  4556. * @access private
  4557. */
  4558. function _print_emoji_detection_script() {
  4559. $settings = array(
  4560. /**
  4561. * Filters the URL where emoji png images are hosted.
  4562. *
  4563. * @since 4.2.0
  4564. *
  4565. * @param string The emoji base URL for png images.
  4566. */
  4567. 'baseUrl' => apply_filters( 'emoji_url', 'https://s.w.org/images/core/emoji/2.2.1/72x72/' ),
  4568. /**
  4569. * Filters the extension of the emoji png files.
  4570. *
  4571. * @since 4.2.0
  4572. *
  4573. * @param string The emoji extension for png files. Default .png.
  4574. */
  4575. 'ext' => apply_filters( 'emoji_ext', '.png' ),
  4576. /**
  4577. * Filters the URL where emoji SVG images are hosted.
  4578. *
  4579. * @since 4.6.0
  4580. *
  4581. * @param string The emoji base URL for svg images.
  4582. */
  4583. 'svgUrl' => apply_filters( 'emoji_svg_url', 'https://s.w.org/images/core/emoji/2.2.1/svg/' ),
  4584. /**
  4585. * Filters the extension of the emoji SVG files.
  4586. *
  4587. * @since 4.6.0
  4588. *
  4589. * @param string The emoji extension for svg files. Default .svg.
  4590. */
  4591. 'svgExt' => apply_filters( 'emoji_svg_ext', '.svg' ),
  4592. );
  4593. $version = 'ver=' . get_bloginfo( 'version' );
  4594. if ( SCRIPT_DEBUG ) {
  4595. $settings['source'] = array(
  4596. /** This filter is documented in wp-includes/class.wp-scripts.php */
  4597. 'wpemoji' => apply_filters( 'script_loader_src', includes_url( "js/wp-emoji.js?$version" ), 'wpemoji' ),
  4598. /** This filter is documented in wp-includes/class.wp-scripts.php */
  4599. 'twemoji' => apply_filters( 'script_loader_src', includes_url( "js/twemoji.js?$version" ), 'twemoji' ),
  4600. );
  4601. ?>
  4602. <script type="text/javascript">
  4603. window._wpemojiSettings = <?php echo wp_json_encode( $settings ); ?>;
  4604. <?php readfile( ABSPATH . WPINC . "/js/wp-emoji-loader.js" ); ?>
  4605. </script>
  4606. <?php
  4607. } else {
  4608. $settings['source'] = array(
  4609. /** This filter is documented in wp-includes/class.wp-scripts.php */
  4610. 'concatemoji' => apply_filters( 'script_loader_src', includes_url( "js/wp-emoji-release.min.js?$version" ), 'concatemoji' ),
  4611. );
  4612. /*
  4613. * If you're looking at a src version of this file, you'll see an "include"
  4614. * statement below. This is used by the `grunt build` process to directly
  4615. * include a minified version of wp-emoji-loader.js, instead of using the
  4616. * readfile() method from above.
  4617. *
  4618. * If you're looking at a build version of this file, you'll see a string of
  4619. * minified JavaScript. If you need to debug it, please turn on SCRIPT_DEBUG
  4620. * and edit wp-emoji-loader.js directly.
  4621. */
  4622. ?>
  4623. <script type="text/javascript">
  4624. window._wpemojiSettings = <?php echo wp_json_encode( $settings ); ?>;
  4625. !function(a,b,c){function d(a){var b,c,d,e,f=String.fromCharCode;if(!k||!k.fillText)return!1;switch(k.clearRect(0,0,j.width,j.height),k.textBaseline="top",k.font="600 32px Arial",a){case"flag":return k.fillText(f(55356,56826,55356,56819),0,0),!(j.toDataURL().length<3e3)&&(k.clearRect(0,0,j.width,j.height),k.fillText(f(55356,57331,65039,8205,55356,57096),0,0),b=j.toDataURL(),k.clearRect(0,0,j.width,j.height),k.fillText(f(55356,57331,55356,57096),0,0),c=j.toDataURL(),b!==c);case"emoji4":return k.fillText(f(55357,56425,55356,57341,8205,55357,56507),0,0),d=j.toDataURL(),k.clearRect(0,0,j.width,j.height),k.fillText(f(55357,56425,55356,57341,55357,56507),0,0),e=j.toDataURL(),d!==e}return!1}function e(a){var c=b.createElement("script");c.src=a,c.defer=c.type="text/javascript",b.getElementsByTagName("head")[0].appendChild(c)}var f,g,h,i,j=b.createElement("canvas"),k=j.getContext&&j.getContext("2d");for(i=Array("flag","emoji4"),c.supports={everything:!0,everythingExceptFlag:!0},h=0;h<i.length;h++)c.supports[i[h]]=d(i[h]),c.supports.everything=c.supports.everything&&c.supports[i[h]],"flag"!==i[h]&&(c.supports.everythingExceptFlag=c.supports.everythingExceptFlag&&c.supports[i[h]]);c.supports.everythingExceptFlag=c.supports.everythingExceptFlag&&!c.supports.flag,c.DOMReady=!1,c.readyCallback=function(){c.DOMReady=!0},c.supports.everything||(g=function(){c.readyCallback()},b.addEventListener?(b.addEventListener("DOMContentLoaded",g,!1),a.addEventListener("load",g,!1)):(a.attachEvent("onload",g),b.attachEvent("onreadystatechange",function(){"complete"===b.readyState&&c.readyCallback()})),f=c.source||{},f.concatemoji?e(f.concatemoji):f.wpemoji&&f.twemoji&&(e(f.twemoji),e(f.wpemoji)))}(window,document,window._wpemojiSettings);
  4626. </script>
  4627. <?php
  4628. }
  4629. }
  4630. /**
  4631. * Convert any 4 byte emoji in a string to their equivalent HTML entity.
  4632. *
  4633. * Currently, only Unicode 7 emoji are supported. Skin tone modifiers are allowed,
  4634. * all other Unicode 8 emoji will be added when the spec is finalised.
  4635. *
  4636. * This allows us to store emoji in a DB using the utf8 character set.
  4637. *
  4638. * @since 4.2.0
  4639. *
  4640. * @param string $content The content to encode.
  4641. * @return string The encoded content.
  4642. */
  4643. function wp_encode_emoji( $content ) {
  4644. if ( function_exists( 'mb_convert_encoding' ) ) {
  4645. $regex = '/(
  4646. \x23\xE2\x83\xA3 # Digits
  4647. [\x30-\x39]\xE2\x83\xA3
  4648. | \xF0\x9F[\x85-\x88][\xA6-\xBF] # Enclosed characters
  4649. | \xF0\x9F[\x8C-\x97][\x80-\xBF] # Misc
  4650. | \xF0\x9F\x98[\x80-\xBF] # Smilies
  4651. | \xF0\x9F\x99[\x80-\x8F]
  4652. | \xF0\x9F\x9A[\x80-\xBF] # Transport and map symbols
  4653. )/x';
  4654. $matches = array();
  4655. if ( preg_match_all( $regex, $content, $matches ) ) {
  4656. if ( ! empty( $matches[1] ) ) {
  4657. foreach ( $matches[1] as $emoji ) {
  4658. /*
  4659. * UTF-32's hex encoding is the same as HTML's hex encoding.
  4660. * So, by converting the emoji from UTF-8 to UTF-32, we magically
  4661. * get the correct hex encoding.
  4662. */
  4663. $unpacked = unpack( 'H*', mb_convert_encoding( $emoji, 'UTF-32', 'UTF-8' ) );
  4664. if ( isset( $unpacked[1] ) ) {
  4665. $entity = '&#x' . ltrim( $unpacked[1], '0' ) . ';';
  4666. $content = str_replace( $emoji, $entity, $content );
  4667. }
  4668. }
  4669. }
  4670. }
  4671. }
  4672. return $content;
  4673. }
  4674. /**
  4675. * Convert emoji to a static img element.
  4676. *
  4677. * @since 4.2.0
  4678. *
  4679. * @param string $text The content to encode.
  4680. * @return string The encoded content.
  4681. */
  4682. function wp_staticize_emoji( $text ) {
  4683. $text = wp_encode_emoji( $text );
  4684. /** This filter is documented in wp-includes/formatting.php */
  4685. $cdn_url = apply_filters( 'emoji_url', 'https://s.w.org/images/core/emoji/2.2.1/72x72/' );
  4686. /** This filter is documented in wp-includes/formatting.php */
  4687. $ext = apply_filters( 'emoji_ext', '.png' );
  4688. $output = '';
  4689. /*
  4690. * HTML loop taken from smiley function, which was taken from texturize function.
  4691. * It'll never be consolidated.
  4692. *
  4693. * First, capture the tags as well as in between.
  4694. */
  4695. $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
  4696. $stop = count( $textarr );
  4697. // Ignore processing of specific tags.
  4698. $tags_to_ignore = 'code|pre|style|script|textarea';
  4699. $ignore_block_element = '';
  4700. for ( $i = 0; $i < $stop; $i++ ) {
  4701. $content = $textarr[$i];
  4702. // If we're in an ignore block, wait until we find its closing tag.
  4703. if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
  4704. $ignore_block_element = $matches[1];
  4705. }
  4706. // If it's not a tag and not in ignore block.
  4707. if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
  4708. $matches = array();
  4709. if ( preg_match_all( '/(&#x1f1(e[6-9a-f]|f[0-9a-f]);){2}/', $content, $matches ) ) {
  4710. if ( ! empty( $matches[0] ) ) {
  4711. foreach ( $matches[0] as $flag ) {
  4712. $chars = str_replace( array( '&#x', ';'), '', $flag );
  4713. list( $char1, $char2 ) = str_split( $chars, 5 );
  4714. $entity = sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', $cdn_url . $char1 . '-' . $char2 . $ext, html_entity_decode( $flag ) );
  4715. $content = str_replace( $flag, $entity, $content );
  4716. }
  4717. }
  4718. }
  4719. // Loosely match the Emoji Unicode range.
  4720. $regex = '/(&#x[2-3][0-9a-f]{3};|&#x1f[1-6][0-9a-f]{2};)/';
  4721. $matches = array();
  4722. if ( preg_match_all( $regex, $content, $matches ) ) {
  4723. if ( ! empty( $matches[1] ) ) {
  4724. foreach ( $matches[1] as $emoji ) {
  4725. $char = str_replace( array( '&#x', ';'), '', $emoji );
  4726. $entity = sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', $cdn_url . $char . $ext, html_entity_decode( $emoji ) );
  4727. $content = str_replace( $emoji, $entity, $content );
  4728. }
  4729. }
  4730. }
  4731. }
  4732. // Did we exit ignore block.
  4733. if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
  4734. $ignore_block_element = '';
  4735. }
  4736. $output .= $content;
  4737. }
  4738. return $output;
  4739. }
  4740. /**
  4741. * Convert emoji in emails into static images.
  4742. *
  4743. * @since 4.2.0
  4744. *
  4745. * @param array $mail The email data array.
  4746. * @return array The email data array, with emoji in the message staticized.
  4747. */
  4748. function wp_staticize_emoji_for_email( $mail ) {
  4749. if ( ! isset( $mail['message'] ) ) {
  4750. return $mail;
  4751. }
  4752. /*
  4753. * We can only transform the emoji into images if it's a text/html email.
  4754. * To do that, here's a cut down version of the same process that happens
  4755. * in wp_mail() - get the Content-Type from the headers, if there is one,
  4756. * then pass it through the wp_mail_content_type filter, in case a plugin
  4757. * is handling changing the Content-Type.
  4758. */
  4759. $headers = array();
  4760. if ( isset( $mail['headers'] ) ) {
  4761. if ( is_array( $mail['headers'] ) ) {
  4762. $headers = $mail['headers'];
  4763. } else {
  4764. $headers = explode( "\n", str_replace( "\r\n", "\n", $mail['headers'] ) );
  4765. }
  4766. }
  4767. foreach ( $headers as $header ) {
  4768. if ( strpos($header, ':') === false ) {
  4769. continue;
  4770. }
  4771. // Explode them out.
  4772. list( $name, $content ) = explode( ':', trim( $header ), 2 );
  4773. // Cleanup crew.
  4774. $name = trim( $name );
  4775. $content = trim( $content );
  4776. if ( 'content-type' === strtolower( $name ) ) {
  4777. if ( strpos( $content, ';' ) !== false ) {
  4778. list( $type, $charset ) = explode( ';', $content );
  4779. $content_type = trim( $type );
  4780. } else {
  4781. $content_type = trim( $content );
  4782. }
  4783. break;
  4784. }
  4785. }
  4786. // Set Content-Type if we don't have a content-type from the input headers.
  4787. if ( ! isset( $content_type ) ) {
  4788. $content_type = 'text/plain';
  4789. }
  4790. /** This filter is documented in wp-includes/pluggable.php */
  4791. $content_type = apply_filters( 'wp_mail_content_type', $content_type );
  4792. if ( 'text/html' === $content_type ) {
  4793. $mail['message'] = wp_staticize_emoji( $mail['message'] );
  4794. }
  4795. return $mail;
  4796. }
  4797. /**
  4798. * Shorten a URL, to be used as link text.
  4799. *
  4800. * @since 1.2.0
  4801. * @since 4.4.0 Moved to wp-includes/formatting.php from wp-admin/includes/misc.php and added $length param.
  4802. *
  4803. * @param string $url URL to shorten.
  4804. * @param int $length Optional. Maximum length of the shortened URL. Default 35 characters.
  4805. * @return string Shortened URL.
  4806. */
  4807. function url_shorten( $url, $length = 35 ) {
  4808. $stripped = str_replace( array( 'https://', 'http://', 'www.' ), '', $url );
  4809. $short_url = untrailingslashit( $stripped );
  4810. if ( strlen( $short_url ) > $length ) {
  4811. $short_url = substr( $short_url, 0, $length - 3 ) . '&hellip;';
  4812. }
  4813. return $short_url;
  4814. }
  4815. /**
  4816. * Sanitizes a hex color.
  4817. *
  4818. * Returns either '', a 3 or 6 digit hex color (with #), or nothing.
  4819. * For sanitizing values without a #, see sanitize_hex_color_no_hash().
  4820. *
  4821. * @since 3.4.0
  4822. *
  4823. * @param string $color
  4824. * @return string|void
  4825. */
  4826. function sanitize_hex_color( $color ) {
  4827. if ( '' === $color ) {
  4828. return '';
  4829. }
  4830. // 3 or 6 hex digits, or the empty string.
  4831. if ( preg_match('|^#([A-Fa-f0-9]{3}){1,2}$|', $color ) ) {
  4832. return $color;
  4833. }
  4834. }
  4835. /**
  4836. * Sanitizes a hex color without a hash. Use sanitize_hex_color() when possible.
  4837. *
  4838. * Saving hex colors without a hash puts the burden of adding the hash on the
  4839. * UI, which makes it difficult to use or upgrade to other color types such as
  4840. * rgba, hsl, rgb, and html color names.
  4841. *
  4842. * Returns either '', a 3 or 6 digit hex color (without a #), or null.
  4843. *
  4844. * @since 3.4.0
  4845. *
  4846. * @param string $color
  4847. * @return string|null
  4848. */
  4849. function sanitize_hex_color_no_hash( $color ) {
  4850. $color = ltrim( $color, '#' );
  4851. if ( '' === $color ) {
  4852. return '';
  4853. }
  4854. return sanitize_hex_color( '#' . $color ) ? $color : null;
  4855. }
  4856. /**
  4857. * Ensures that any hex color is properly hashed.
  4858. * Otherwise, returns value untouched.
  4859. *
  4860. * This method should only be necessary if using sanitize_hex_color_no_hash().
  4861. *
  4862. * @since 3.4.0
  4863. *
  4864. * @param string $color
  4865. * @return string
  4866. */
  4867. function maybe_hash_hex_color( $color ) {
  4868. if ( $unhashed = sanitize_hex_color_no_hash( $color ) ) {
  4869. return '#' . $unhashed;
  4870. }
  4871. return $color;
  4872. }