formatting.php 186 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366
  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`) and Bosnian (`bs_BA`) locales:
  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. * @since 4.8.0 Added locale support for `bs_BA`.
  1357. *
  1358. * @param string $string Text that might have accent characters
  1359. * @return string Filtered string with replaced "nice" characters.
  1360. */
  1361. function remove_accents( $string ) {
  1362. if ( !preg_match('/[\x80-\xff]/', $string) )
  1363. return $string;
  1364. if (seems_utf8($string)) {
  1365. $chars = array(
  1366. // Decompositions for Latin-1 Supplement
  1367. 'ª' => 'a', 'º' => 'o',
  1368. 'À' => 'A', 'Á' => 'A',
  1369. 'Â' => 'A', 'Ã' => 'A',
  1370. 'Ä' => 'A', 'Å' => 'A',
  1371. 'Æ' => 'AE','Ç' => 'C',
  1372. 'È' => 'E', 'É' => 'E',
  1373. 'Ê' => 'E', 'Ë' => 'E',
  1374. 'Ì' => 'I', 'Í' => 'I',
  1375. 'Î' => 'I', 'Ï' => 'I',
  1376. 'Ð' => 'D', 'Ñ' => 'N',
  1377. 'Ò' => 'O', 'Ó' => 'O',
  1378. 'Ô' => 'O', 'Õ' => 'O',
  1379. 'Ö' => 'O', 'Ù' => 'U',
  1380. 'Ú' => 'U', 'Û' => 'U',
  1381. 'Ü' => 'U', 'Ý' => 'Y',
  1382. 'Þ' => 'TH','ß' => 's',
  1383. 'à' => 'a', 'á' => 'a',
  1384. 'â' => 'a', 'ã' => 'a',
  1385. 'ä' => 'a', 'å' => 'a',
  1386. 'æ' => 'ae','ç' => 'c',
  1387. 'è' => 'e', 'é' => 'e',
  1388. 'ê' => 'e', 'ë' => 'e',
  1389. 'ì' => 'i', 'í' => 'i',
  1390. 'î' => 'i', 'ï' => 'i',
  1391. 'ð' => 'd', 'ñ' => 'n',
  1392. 'ò' => 'o', 'ó' => 'o',
  1393. 'ô' => 'o', 'õ' => 'o',
  1394. 'ö' => 'o', 'ø' => 'o',
  1395. 'ù' => 'u', 'ú' => 'u',
  1396. 'û' => 'u', 'ü' => 'u',
  1397. 'ý' => 'y', 'þ' => 'th',
  1398. 'ÿ' => 'y', 'Ø' => 'O',
  1399. // Decompositions for Latin Extended-A
  1400. 'Ā' => 'A', 'ā' => 'a',
  1401. 'Ă' => 'A', 'ă' => 'a',
  1402. 'Ą' => 'A', 'ą' => 'a',
  1403. 'Ć' => 'C', 'ć' => 'c',
  1404. 'Ĉ' => 'C', 'ĉ' => 'c',
  1405. 'Ċ' => 'C', 'ċ' => 'c',
  1406. 'Č' => 'C', 'č' => 'c',
  1407. 'Ď' => 'D', 'ď' => 'd',
  1408. 'Đ' => 'D', 'đ' => 'd',
  1409. 'Ē' => 'E', 'ē' => 'e',
  1410. 'Ĕ' => 'E', 'ĕ' => 'e',
  1411. 'Ė' => 'E', 'ė' => 'e',
  1412. 'Ę' => 'E', 'ę' => 'e',
  1413. 'Ě' => 'E', 'ě' => 'e',
  1414. 'Ĝ' => 'G', 'ĝ' => 'g',
  1415. 'Ğ' => 'G', 'ğ' => 'g',
  1416. 'Ġ' => 'G', 'ġ' => 'g',
  1417. 'Ģ' => 'G', 'ģ' => 'g',
  1418. 'Ĥ' => 'H', 'ĥ' => 'h',
  1419. 'Ħ' => 'H', 'ħ' => 'h',
  1420. 'Ĩ' => 'I', 'ĩ' => 'i',
  1421. 'Ī' => 'I', 'ī' => 'i',
  1422. 'Ĭ' => 'I', 'ĭ' => 'i',
  1423. 'Į' => 'I', 'į' => 'i',
  1424. 'İ' => 'I', 'ı' => 'i',
  1425. 'IJ' => 'IJ','ij' => 'ij',
  1426. 'Ĵ' => 'J', 'ĵ' => 'j',
  1427. 'Ķ' => 'K', 'ķ' => 'k',
  1428. 'ĸ' => 'k', 'Ĺ' => 'L',
  1429. 'ĺ' => 'l', 'Ļ' => 'L',
  1430. 'ļ' => 'l', 'Ľ' => 'L',
  1431. 'ľ' => 'l', 'Ŀ' => 'L',
  1432. 'ŀ' => 'l', 'Ł' => 'L',
  1433. 'ł' => 'l', 'Ń' => 'N',
  1434. 'ń' => 'n', 'Ņ' => 'N',
  1435. 'ņ' => 'n', 'Ň' => 'N',
  1436. 'ň' => 'n', 'ʼn' => 'n',
  1437. 'Ŋ' => 'N', 'ŋ' => 'n',
  1438. 'Ō' => 'O', 'ō' => 'o',
  1439. 'Ŏ' => 'O', 'ŏ' => 'o',
  1440. 'Ő' => 'O', 'ő' => 'o',
  1441. 'Œ' => 'OE','œ' => 'oe',
  1442. 'Ŕ' => 'R','ŕ' => 'r',
  1443. 'Ŗ' => 'R','ŗ' => 'r',
  1444. 'Ř' => 'R','ř' => 'r',
  1445. 'Ś' => 'S','ś' => 's',
  1446. 'Ŝ' => 'S','ŝ' => 's',
  1447. 'Ş' => 'S','ş' => 's',
  1448. 'Š' => 'S', 'š' => 's',
  1449. 'Ţ' => 'T', 'ţ' => 't',
  1450. 'Ť' => 'T', 'ť' => 't',
  1451. 'Ŧ' => 'T', 'ŧ' => 't',
  1452. 'Ũ' => 'U', 'ũ' => 'u',
  1453. 'Ū' => 'U', 'ū' => 'u',
  1454. 'Ŭ' => 'U', 'ŭ' => 'u',
  1455. 'Ů' => 'U', 'ů' => 'u',
  1456. 'Ű' => 'U', 'ű' => 'u',
  1457. 'Ų' => 'U', 'ų' => 'u',
  1458. 'Ŵ' => 'W', 'ŵ' => 'w',
  1459. 'Ŷ' => 'Y', 'ŷ' => 'y',
  1460. 'Ÿ' => 'Y', 'Ź' => 'Z',
  1461. 'ź' => 'z', 'Ż' => 'Z',
  1462. 'ż' => 'z', 'Ž' => 'Z',
  1463. 'ž' => 'z', 'ſ' => 's',
  1464. // Decompositions for Latin Extended-B
  1465. 'Ș' => 'S', 'ș' => 's',
  1466. 'Ț' => 'T', 'ț' => 't',
  1467. // Euro Sign
  1468. '€' => 'E',
  1469. // GBP (Pound) Sign
  1470. '£' => '',
  1471. // Vowels with diacritic (Vietnamese)
  1472. // unmarked
  1473. 'Ơ' => 'O', 'ơ' => 'o',
  1474. 'Ư' => 'U', 'ư' => 'u',
  1475. // grave accent
  1476. 'Ầ' => 'A', 'ầ' => 'a',
  1477. 'Ằ' => 'A', 'ằ' => 'a',
  1478. 'Ề' => 'E', 'ề' => 'e',
  1479. 'Ồ' => 'O', 'ồ' => 'o',
  1480. 'Ờ' => 'O', 'ờ' => 'o',
  1481. 'Ừ' => 'U', 'ừ' => 'u',
  1482. 'Ỳ' => 'Y', 'ỳ' => 'y',
  1483. // hook
  1484. 'Ả' => 'A', 'ả' => 'a',
  1485. 'Ẩ' => 'A', 'ẩ' => 'a',
  1486. 'Ẳ' => 'A', 'ẳ' => 'a',
  1487. 'Ẻ' => 'E', 'ẻ' => 'e',
  1488. 'Ể' => 'E', 'ể' => 'e',
  1489. 'Ỉ' => 'I', 'ỉ' => 'i',
  1490. 'Ỏ' => 'O', 'ỏ' => 'o',
  1491. 'Ổ' => 'O', 'ổ' => 'o',
  1492. 'Ở' => 'O', 'ở' => 'o',
  1493. 'Ủ' => 'U', 'ủ' => 'u',
  1494. 'Ử' => 'U', 'ử' => 'u',
  1495. 'Ỷ' => 'Y', 'ỷ' => 'y',
  1496. // tilde
  1497. 'Ẫ' => 'A', 'ẫ' => 'a',
  1498. 'Ẵ' => 'A', 'ẵ' => 'a',
  1499. 'Ẽ' => 'E', 'ẽ' => 'e',
  1500. 'Ễ' => 'E', 'ễ' => 'e',
  1501. 'Ỗ' => 'O', 'ỗ' => 'o',
  1502. 'Ỡ' => 'O', 'ỡ' => 'o',
  1503. 'Ữ' => 'U', 'ữ' => 'u',
  1504. 'Ỹ' => 'Y', 'ỹ' => 'y',
  1505. // acute accent
  1506. 'Ấ' => 'A', 'ấ' => 'a',
  1507. 'Ắ' => 'A', 'ắ' => 'a',
  1508. 'Ế' => 'E', 'ế' => 'e',
  1509. 'Ố' => 'O', 'ố' => 'o',
  1510. 'Ớ' => 'O', 'ớ' => 'o',
  1511. 'Ứ' => 'U', 'ứ' => 'u',
  1512. // dot below
  1513. 'Ạ' => 'A', 'ạ' => 'a',
  1514. 'Ậ' => 'A', 'ậ' => 'a',
  1515. 'Ặ' => 'A', 'ặ' => 'a',
  1516. 'Ẹ' => 'E', 'ẹ' => 'e',
  1517. 'Ệ' => 'E', 'ệ' => 'e',
  1518. 'Ị' => 'I', 'ị' => 'i',
  1519. 'Ọ' => 'O', 'ọ' => 'o',
  1520. 'Ộ' => 'O', 'ộ' => 'o',
  1521. 'Ợ' => 'O', 'ợ' => 'o',
  1522. 'Ụ' => 'U', 'ụ' => 'u',
  1523. 'Ự' => 'U', 'ự' => 'u',
  1524. 'Ỵ' => 'Y', 'ỵ' => 'y',
  1525. // Vowels with diacritic (Chinese, Hanyu Pinyin)
  1526. 'ɑ' => 'a',
  1527. // macron
  1528. 'Ǖ' => 'U', 'ǖ' => 'u',
  1529. // acute accent
  1530. 'Ǘ' => 'U', 'ǘ' => 'u',
  1531. // caron
  1532. 'Ǎ' => 'A', 'ǎ' => 'a',
  1533. 'Ǐ' => 'I', 'ǐ' => 'i',
  1534. 'Ǒ' => 'O', 'ǒ' => 'o',
  1535. 'Ǔ' => 'U', 'ǔ' => 'u',
  1536. 'Ǚ' => 'U', 'ǚ' => 'u',
  1537. // grave accent
  1538. 'Ǜ' => 'U', 'ǜ' => 'u',
  1539. );
  1540. // Used for locale-specific rules
  1541. $locale = get_locale();
  1542. if ( 'de_DE' == $locale || 'de_DE_formal' == $locale || 'de_CH' == $locale || 'de_CH_informal' == $locale ) {
  1543. $chars[ 'Ä' ] = 'Ae';
  1544. $chars[ 'ä' ] = 'ae';
  1545. $chars[ 'Ö' ] = 'Oe';
  1546. $chars[ 'ö' ] = 'oe';
  1547. $chars[ 'Ü' ] = 'Ue';
  1548. $chars[ 'ü' ] = 'ue';
  1549. $chars[ 'ß' ] = 'ss';
  1550. } elseif ( 'da_DK' === $locale ) {
  1551. $chars[ 'Æ' ] = 'Ae';
  1552. $chars[ 'æ' ] = 'ae';
  1553. $chars[ 'Ø' ] = 'Oe';
  1554. $chars[ 'ø' ] = 'oe';
  1555. $chars[ 'Å' ] = 'Aa';
  1556. $chars[ 'å' ] = 'aa';
  1557. } elseif ( 'ca' === $locale ) {
  1558. $chars[ 'l·l' ] = 'll';
  1559. } elseif ( 'sr_RS' === $locale || 'bs_BA' === $locale ) {
  1560. $chars[ 'Đ' ] = 'DJ';
  1561. $chars[ 'đ' ] = 'dj';
  1562. }
  1563. $string = strtr($string, $chars);
  1564. } else {
  1565. $chars = array();
  1566. // Assume ISO-8859-1 if not UTF-8
  1567. $chars['in'] = "\x80\x83\x8a\x8e\x9a\x9e"
  1568. ."\x9f\xa2\xa5\xb5\xc0\xc1\xc2"
  1569. ."\xc3\xc4\xc5\xc7\xc8\xc9\xca"
  1570. ."\xcb\xcc\xcd\xce\xcf\xd1\xd2"
  1571. ."\xd3\xd4\xd5\xd6\xd8\xd9\xda"
  1572. ."\xdb\xdc\xdd\xe0\xe1\xe2\xe3"
  1573. ."\xe4\xe5\xe7\xe8\xe9\xea\xeb"
  1574. ."\xec\xed\xee\xef\xf1\xf2\xf3"
  1575. ."\xf4\xf5\xf6\xf8\xf9\xfa\xfb"
  1576. ."\xfc\xfd\xff";
  1577. $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
  1578. $string = strtr($string, $chars['in'], $chars['out']);
  1579. $double_chars = array();
  1580. $double_chars['in'] = array("\x8c", "\x9c", "\xc6", "\xd0", "\xde", "\xdf", "\xe6", "\xf0", "\xfe");
  1581. $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
  1582. $string = str_replace($double_chars['in'], $double_chars['out'], $string);
  1583. }
  1584. return $string;
  1585. }
  1586. /**
  1587. * Sanitizes a filename, replacing whitespace with dashes.
  1588. *
  1589. * Removes special characters that are illegal in filenames on certain
  1590. * operating systems and special characters requiring special escaping
  1591. * to manipulate at the command line. Replaces spaces and consecutive
  1592. * dashes with a single dash. Trims period, dash and underscore from beginning
  1593. * and end of filename. It is not guaranteed that this function will return a
  1594. * filename that is allowed to be uploaded.
  1595. *
  1596. * @since 2.1.0
  1597. *
  1598. * @param string $filename The filename to be sanitized
  1599. * @return string The sanitized filename
  1600. */
  1601. function sanitize_file_name( $filename ) {
  1602. $filename_raw = $filename;
  1603. $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", "%", "+", chr(0));
  1604. /**
  1605. * Filters the list of characters to remove from a filename.
  1606. *
  1607. * @since 2.8.0
  1608. *
  1609. * @param array $special_chars Characters to remove.
  1610. * @param string $filename_raw Filename as it was passed into sanitize_file_name().
  1611. */
  1612. $special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );
  1613. $filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
  1614. $filename = str_replace( $special_chars, '', $filename );
  1615. $filename = str_replace( array( '%20', '+' ), '-', $filename );
  1616. $filename = preg_replace( '/[\r\n\t -]+/', '-', $filename );
  1617. $filename = trim( $filename, '.-_' );
  1618. if ( false === strpos( $filename, '.' ) ) {
  1619. $mime_types = wp_get_mime_types();
  1620. $filetype = wp_check_filetype( 'test.' . $filename, $mime_types );
  1621. if ( $filetype['ext'] === $filename ) {
  1622. $filename = 'unnamed-file.' . $filetype['ext'];
  1623. }
  1624. }
  1625. // Split the filename into a base and extension[s]
  1626. $parts = explode('.', $filename);
  1627. // Return if only one extension
  1628. if ( count( $parts ) <= 2 ) {
  1629. /**
  1630. * Filters a sanitized filename string.
  1631. *
  1632. * @since 2.8.0
  1633. *
  1634. * @param string $filename Sanitized filename.
  1635. * @param string $filename_raw The filename prior to sanitization.
  1636. */
  1637. return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
  1638. }
  1639. // Process multiple extensions
  1640. $filename = array_shift($parts);
  1641. $extension = array_pop($parts);
  1642. $mimes = get_allowed_mime_types();
  1643. /*
  1644. * Loop over any intermediate extensions. Postfix them with a trailing underscore
  1645. * if they are a 2 - 5 character long alpha string not in the extension whitelist.
  1646. */
  1647. foreach ( (array) $parts as $part) {
  1648. $filename .= '.' . $part;
  1649. if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
  1650. $allowed = false;
  1651. foreach ( $mimes as $ext_preg => $mime_match ) {
  1652. $ext_preg = '!^(' . $ext_preg . ')$!i';
  1653. if ( preg_match( $ext_preg, $part ) ) {
  1654. $allowed = true;
  1655. break;
  1656. }
  1657. }
  1658. if ( !$allowed )
  1659. $filename .= '_';
  1660. }
  1661. }
  1662. $filename .= '.' . $extension;
  1663. /** This filter is documented in wp-includes/formatting.php */
  1664. return apply_filters('sanitize_file_name', $filename, $filename_raw);
  1665. }
  1666. /**
  1667. * Sanitizes a username, stripping out unsafe characters.
  1668. *
  1669. * Removes tags, octets, entities, and if strict is enabled, will only keep
  1670. * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
  1671. * raw username (the username in the parameter), and the value of $strict as
  1672. * parameters for the {@see 'sanitize_user'} filter.
  1673. *
  1674. * @since 2.0.0
  1675. *
  1676. * @param string $username The username to be sanitized.
  1677. * @param bool $strict If set limits $username to specific characters. Default false.
  1678. * @return string The sanitized username, after passing through filters.
  1679. */
  1680. function sanitize_user( $username, $strict = false ) {
  1681. $raw_username = $username;
  1682. $username = wp_strip_all_tags( $username );
  1683. $username = remove_accents( $username );
  1684. // Kill octets
  1685. $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
  1686. $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
  1687. // If strict, reduce to ASCII for max portability.
  1688. if ( $strict )
  1689. $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
  1690. $username = trim( $username );
  1691. // Consolidate contiguous whitespace
  1692. $username = preg_replace( '|\s+|', ' ', $username );
  1693. /**
  1694. * Filters a sanitized username string.
  1695. *
  1696. * @since 2.0.1
  1697. *
  1698. * @param string $username Sanitized username.
  1699. * @param string $raw_username The username prior to sanitization.
  1700. * @param bool $strict Whether to limit the sanitization to specific characters. Default false.
  1701. */
  1702. return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
  1703. }
  1704. /**
  1705. * Sanitizes a string key.
  1706. *
  1707. * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
  1708. *
  1709. * @since 3.0.0
  1710. *
  1711. * @param string $key String key
  1712. * @return string Sanitized key
  1713. */
  1714. function sanitize_key( $key ) {
  1715. $raw_key = $key;
  1716. $key = strtolower( $key );
  1717. $key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
  1718. /**
  1719. * Filters a sanitized key string.
  1720. *
  1721. * @since 3.0.0
  1722. *
  1723. * @param string $key Sanitized key.
  1724. * @param string $raw_key The key prior to sanitization.
  1725. */
  1726. return apply_filters( 'sanitize_key', $key, $raw_key );
  1727. }
  1728. /**
  1729. * Sanitizes a title, or returns a fallback title.
  1730. *
  1731. * Specifically, HTML and PHP tags are stripped. Further actions can be added
  1732. * via the plugin API. If $title is empty and $fallback_title is set, the latter
  1733. * will be used.
  1734. *
  1735. * @since 1.0.0
  1736. *
  1737. * @param string $title The string to be sanitized.
  1738. * @param string $fallback_title Optional. A title to use if $title is empty.
  1739. * @param string $context Optional. The operation for which the string is sanitized
  1740. * @return string The sanitized string.
  1741. */
  1742. function sanitize_title( $title, $fallback_title = '', $context = 'save' ) {
  1743. $raw_title = $title;
  1744. if ( 'save' == $context )
  1745. $title = remove_accents($title);
  1746. /**
  1747. * Filters a sanitized title string.
  1748. *
  1749. * @since 1.2.0
  1750. *
  1751. * @param string $title Sanitized title.
  1752. * @param string $raw_title The title prior to sanitization.
  1753. * @param string $context The context for which the title is being sanitized.
  1754. */
  1755. $title = apply_filters( 'sanitize_title', $title, $raw_title, $context );
  1756. if ( '' === $title || false === $title )
  1757. $title = $fallback_title;
  1758. return $title;
  1759. }
  1760. /**
  1761. * Sanitizes a title with the 'query' context.
  1762. *
  1763. * Used for querying the database for a value from URL.
  1764. *
  1765. * @since 3.1.0
  1766. *
  1767. * @param string $title The string to be sanitized.
  1768. * @return string The sanitized string.
  1769. */
  1770. function sanitize_title_for_query( $title ) {
  1771. return sanitize_title( $title, '', 'query' );
  1772. }
  1773. /**
  1774. * Sanitizes a title, replacing whitespace and a few other characters with dashes.
  1775. *
  1776. * Limits the output to alphanumeric characters, underscore (_) and dash (-).
  1777. * Whitespace becomes a dash.
  1778. *
  1779. * @since 1.2.0
  1780. *
  1781. * @param string $title The title to be sanitized.
  1782. * @param string $raw_title Optional. Not used.
  1783. * @param string $context Optional. The operation for which the string is sanitized.
  1784. * @return string The sanitized title.
  1785. */
  1786. function sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
  1787. $title = strip_tags($title);
  1788. // Preserve escaped octets.
  1789. $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
  1790. // Remove percent signs that are not part of an octet.
  1791. $title = str_replace('%', '', $title);
  1792. // Restore octets.
  1793. $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
  1794. if (seems_utf8($title)) {
  1795. if (function_exists('mb_strtolower')) {
  1796. $title = mb_strtolower($title, 'UTF-8');
  1797. }
  1798. $title = utf8_uri_encode($title, 200);
  1799. }
  1800. $title = strtolower($title);
  1801. if ( 'save' == $context ) {
  1802. // Convert nbsp, ndash and mdash to hyphens
  1803. $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
  1804. // Convert nbsp, ndash and mdash HTML entities to hyphens
  1805. $title = str_replace( array( '&nbsp;', '&#160;', '&ndash;', '&#8211;', '&mdash;', '&#8212;' ), '-', $title );
  1806. // Strip these characters entirely
  1807. $title = str_replace( array(
  1808. // iexcl and iquest
  1809. '%c2%a1', '%c2%bf',
  1810. // angle quotes
  1811. '%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
  1812. // curly quotes
  1813. '%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
  1814. '%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
  1815. // copy, reg, deg, hellip and trade
  1816. '%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
  1817. // acute accents
  1818. '%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
  1819. // grave accent, macron, caron
  1820. '%cc%80', '%cc%84', '%cc%8c',
  1821. ), '', $title );
  1822. // Convert times to x
  1823. $title = str_replace( '%c3%97', 'x', $title );
  1824. }
  1825. $title = preg_replace('/&.+?;/', '', $title); // kill entities
  1826. $title = str_replace('.', '-', $title);
  1827. $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
  1828. $title = preg_replace('/\s+/', '-', $title);
  1829. $title = preg_replace('|-+|', '-', $title);
  1830. $title = trim($title, '-');
  1831. return $title;
  1832. }
  1833. /**
  1834. * Ensures a string is a valid SQL 'order by' clause.
  1835. *
  1836. * Accepts one or more columns, with or without a sort order (ASC / DESC).
  1837. * e.g. 'column_1', 'column_1, column_2', 'column_1 ASC, column_2 DESC' etc.
  1838. *
  1839. * Also accepts 'RAND()'.
  1840. *
  1841. * @since 2.5.1
  1842. *
  1843. * @param string $orderby Order by clause to be validated.
  1844. * @return string|false Returns $orderby if valid, false otherwise.
  1845. */
  1846. function sanitize_sql_orderby( $orderby ) {
  1847. 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 ) ) {
  1848. return $orderby;
  1849. }
  1850. return false;
  1851. }
  1852. /**
  1853. * Sanitizes an HTML classname to ensure it only contains valid characters.
  1854. *
  1855. * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
  1856. * string then it will return the alternative value supplied.
  1857. *
  1858. * @todo Expand to support the full range of CDATA that a class attribute can contain.
  1859. *
  1860. * @since 2.8.0
  1861. *
  1862. * @param string $class The classname to be sanitized
  1863. * @param string $fallback Optional. The value to return if the sanitization ends up as an empty string.
  1864. * Defaults to an empty string.
  1865. * @return string The sanitized value
  1866. */
  1867. function sanitize_html_class( $class, $fallback = '' ) {
  1868. //Strip out any % encoded octets
  1869. $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
  1870. //Limit to A-Z,a-z,0-9,_,-
  1871. $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
  1872. if ( '' == $sanitized && $fallback ) {
  1873. return sanitize_html_class( $fallback );
  1874. }
  1875. /**
  1876. * Filters a sanitized HTML class string.
  1877. *
  1878. * @since 2.8.0
  1879. *
  1880. * @param string $sanitized The sanitized HTML class.
  1881. * @param string $class HTML class before sanitization.
  1882. * @param string $fallback The fallback string.
  1883. */
  1884. return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
  1885. }
  1886. /**
  1887. * Converts lone & characters into `&#038;` (a.k.a. `&amp;`)
  1888. *
  1889. * @since 0.71
  1890. *
  1891. * @param string $content String of characters to be converted.
  1892. * @param string $deprecated Not used.
  1893. * @return string Converted string.
  1894. */
  1895. function convert_chars( $content, $deprecated = '' ) {
  1896. if ( ! empty( $deprecated ) ) {
  1897. _deprecated_argument( __FUNCTION__, '0.71' );
  1898. }
  1899. if ( strpos( $content, '&' ) !== false ) {
  1900. $content = preg_replace( '/&([^#])(?![a-z1-4]{1,8};)/i', '&#038;$1', $content );
  1901. }
  1902. return $content;
  1903. }
  1904. /**
  1905. * Converts invalid Unicode references range to valid range.
  1906. *
  1907. * @since 4.3.0
  1908. *
  1909. * @param string $content String with entities that need converting.
  1910. * @return string Converted string.
  1911. */
  1912. function convert_invalid_entities( $content ) {
  1913. $wp_htmltranswinuni = array(
  1914. '&#128;' => '&#8364;', // the Euro sign
  1915. '&#129;' => '',
  1916. '&#130;' => '&#8218;', // these are Windows CP1252 specific characters
  1917. '&#131;' => '&#402;', // they would look weird on non-Windows browsers
  1918. '&#132;' => '&#8222;',
  1919. '&#133;' => '&#8230;',
  1920. '&#134;' => '&#8224;',
  1921. '&#135;' => '&#8225;',
  1922. '&#136;' => '&#710;',
  1923. '&#137;' => '&#8240;',
  1924. '&#138;' => '&#352;',
  1925. '&#139;' => '&#8249;',
  1926. '&#140;' => '&#338;',
  1927. '&#141;' => '',
  1928. '&#142;' => '&#381;',
  1929. '&#143;' => '',
  1930. '&#144;' => '',
  1931. '&#145;' => '&#8216;',
  1932. '&#146;' => '&#8217;',
  1933. '&#147;' => '&#8220;',
  1934. '&#148;' => '&#8221;',
  1935. '&#149;' => '&#8226;',
  1936. '&#150;' => '&#8211;',
  1937. '&#151;' => '&#8212;',
  1938. '&#152;' => '&#732;',
  1939. '&#153;' => '&#8482;',
  1940. '&#154;' => '&#353;',
  1941. '&#155;' => '&#8250;',
  1942. '&#156;' => '&#339;',
  1943. '&#157;' => '',
  1944. '&#158;' => '&#382;',
  1945. '&#159;' => '&#376;'
  1946. );
  1947. if ( strpos( $content, '&#1' ) !== false ) {
  1948. $content = strtr( $content, $wp_htmltranswinuni );
  1949. }
  1950. return $content;
  1951. }
  1952. /**
  1953. * Balances tags if forced to, or if the 'use_balanceTags' option is set to true.
  1954. *
  1955. * @since 0.71
  1956. *
  1957. * @param string $text Text to be balanced
  1958. * @param bool $force If true, forces balancing, ignoring the value of the option. Default false.
  1959. * @return string Balanced text
  1960. */
  1961. function balanceTags( $text, $force = false ) {
  1962. if ( $force || get_option('use_balanceTags') == 1 ) {
  1963. return force_balance_tags( $text );
  1964. } else {
  1965. return $text;
  1966. }
  1967. }
  1968. /**
  1969. * Balances tags of string using a modified stack.
  1970. *
  1971. * @since 2.0.4
  1972. *
  1973. * @author Leonard Lin <leonard@acm.org>
  1974. * @license GPL
  1975. * @copyright November 4, 2001
  1976. * @version 1.1
  1977. * @todo Make better - change loop condition to $text in 1.2
  1978. * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
  1979. * 1.1 Fixed handling of append/stack pop order of end text
  1980. * Added Cleaning Hooks
  1981. * 1.0 First Version
  1982. *
  1983. * @param string $text Text to be balanced.
  1984. * @return string Balanced text.
  1985. */
  1986. function force_balance_tags( $text ) {
  1987. $tagstack = array();
  1988. $stacksize = 0;
  1989. $tagqueue = '';
  1990. $newtext = '';
  1991. // Known single-entity/self-closing tags
  1992. $single_tags = array( 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source' );
  1993. // Tags that can be immediately nested within themselves
  1994. $nestable_tags = array( 'blockquote', 'div', 'object', 'q', 'span' );
  1995. // WP bug fix for comments - in case you REALLY meant to type '< !--'
  1996. $text = str_replace('< !--', '< !--', $text);
  1997. // WP bug fix for LOVE <3 (and other situations with '<' before a number)
  1998. $text = preg_replace('#<([0-9]{1})#', '&lt;$1', $text);
  1999. while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
  2000. $newtext .= $tagqueue;
  2001. $i = strpos($text, $regex[0]);
  2002. $l = strlen($regex[0]);
  2003. // clear the shifter
  2004. $tagqueue = '';
  2005. // Pop or Push
  2006. if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
  2007. $tag = strtolower(substr($regex[1],1));
  2008. // if too many closing tags
  2009. if ( $stacksize <= 0 ) {
  2010. $tag = '';
  2011. // or close to be safe $tag = '/' . $tag;
  2012. }
  2013. // if stacktop value = tag close value then pop
  2014. elseif ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
  2015. $tag = '</' . $tag . '>'; // Close Tag
  2016. // Pop
  2017. array_pop( $tagstack );
  2018. $stacksize--;
  2019. } else { // closing tag not at top, search for it
  2020. for ( $j = $stacksize-1; $j >= 0; $j-- ) {
  2021. if ( $tagstack[$j] == $tag ) {
  2022. // add tag to tagqueue
  2023. for ( $k = $stacksize-1; $k >= $j; $k--) {
  2024. $tagqueue .= '</' . array_pop( $tagstack ) . '>';
  2025. $stacksize--;
  2026. }
  2027. break;
  2028. }
  2029. }
  2030. $tag = '';
  2031. }
  2032. } else { // Begin Tag
  2033. $tag = strtolower($regex[1]);
  2034. // Tag Cleaning
  2035. // If it's an empty tag "< >", do nothing
  2036. if ( '' == $tag ) {
  2037. // do nothing
  2038. }
  2039. // ElseIf it presents itself as a self-closing tag...
  2040. elseif ( substr( $regex[2], -1 ) == '/' ) {
  2041. // ...but it isn't a known single-entity self-closing tag, then don't let it be treated as such and
  2042. // immediately close it with a closing tag (the tag will encapsulate no text as a result)
  2043. if ( ! in_array( $tag, $single_tags ) )
  2044. $regex[2] = trim( substr( $regex[2], 0, -1 ) ) . "></$tag";
  2045. }
  2046. // ElseIf it's a known single-entity tag but it doesn't close itself, do so
  2047. elseif ( in_array($tag, $single_tags) ) {
  2048. $regex[2] .= '/';
  2049. }
  2050. // Else it's not a single-entity tag
  2051. else {
  2052. // If the top of the stack is the same as the tag we want to push, close previous tag
  2053. if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
  2054. $tagqueue = '</' . array_pop( $tagstack ) . '>';
  2055. $stacksize--;
  2056. }
  2057. $stacksize = array_push( $tagstack, $tag );
  2058. }
  2059. // Attributes
  2060. $attributes = $regex[2];
  2061. if ( ! empty( $attributes ) && $attributes[0] != '>' )
  2062. $attributes = ' ' . $attributes;
  2063. $tag = '<' . $tag . $attributes . '>';
  2064. //If already queuing a close tag, then put this tag on, too
  2065. if ( !empty($tagqueue) ) {
  2066. $tagqueue .= $tag;
  2067. $tag = '';
  2068. }
  2069. }
  2070. $newtext .= substr($text, 0, $i) . $tag;
  2071. $text = substr($text, $i + $l);
  2072. }
  2073. // Clear Tag Queue
  2074. $newtext .= $tagqueue;
  2075. // Add Remaining text
  2076. $newtext .= $text;
  2077. // Empty Stack
  2078. while( $x = array_pop($tagstack) )
  2079. $newtext .= '</' . $x . '>'; // Add remaining tags to close
  2080. // WP fix for the bug with HTML comments
  2081. $newtext = str_replace("< !--","<!--",$newtext);
  2082. $newtext = str_replace("< !--","< !--",$newtext);
  2083. return $newtext;
  2084. }
  2085. /**
  2086. * Acts on text which is about to be edited.
  2087. *
  2088. * The $content is run through esc_textarea(), which uses htmlspecialchars()
  2089. * to convert special characters to HTML entities. If `$richedit` is set to true,
  2090. * it is simply a holder for the {@see 'format_to_edit'} filter.
  2091. *
  2092. * @since 0.71
  2093. * @since 4.4.0 The `$richedit` parameter was renamed to `$rich_text` for clarity.
  2094. *
  2095. * @param string $content The text about to be edited.
  2096. * @param bool $rich_text Optional. Whether `$content` should be considered rich text,
  2097. * in which case it would not be passed through esc_textarea().
  2098. * Default false.
  2099. * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
  2100. */
  2101. function format_to_edit( $content, $rich_text = false ) {
  2102. /**
  2103. * Filters the text to be formatted for editing.
  2104. *
  2105. * @since 1.2.0
  2106. *
  2107. * @param string $content The text, prior to formatting for editing.
  2108. */
  2109. $content = apply_filters( 'format_to_edit', $content );
  2110. if ( ! $rich_text )
  2111. $content = esc_textarea( $content );
  2112. return $content;
  2113. }
  2114. /**
  2115. * Add leading zeros when necessary.
  2116. *
  2117. * If you set the threshold to '4' and the number is '10', then you will get
  2118. * back '0010'. If you set the threshold to '4' and the number is '5000', then you
  2119. * will get back '5000'.
  2120. *
  2121. * Uses sprintf to append the amount of zeros based on the $threshold parameter
  2122. * and the size of the number. If the number is large enough, then no zeros will
  2123. * be appended.
  2124. *
  2125. * @since 0.71
  2126. *
  2127. * @param int $number Number to append zeros to if not greater than threshold.
  2128. * @param int $threshold Digit places number needs to be to not have zeros added.
  2129. * @return string Adds leading zeros to number if needed.
  2130. */
  2131. function zeroise( $number, $threshold ) {
  2132. return sprintf( '%0' . $threshold . 's', $number );
  2133. }
  2134. /**
  2135. * Adds backslashes before letters and before a number at the start of a string.
  2136. *
  2137. * @since 0.71
  2138. *
  2139. * @param string $string Value to which backslashes will be added.
  2140. * @return string String with backslashes inserted.
  2141. */
  2142. function backslashit( $string ) {
  2143. if ( isset( $string[0] ) && $string[0] >= '0' && $string[0] <= '9' )
  2144. $string = '\\\\' . $string;
  2145. return addcslashes( $string, 'A..Za..z' );
  2146. }
  2147. /**
  2148. * Appends a trailing slash.
  2149. *
  2150. * Will remove trailing forward and backslashes if it exists already before adding
  2151. * a trailing forward slash. This prevents double slashing a string or path.
  2152. *
  2153. * The primary use of this is for paths and thus should be used for paths. It is
  2154. * not restricted to paths and offers no specific path support.
  2155. *
  2156. * @since 1.2.0
  2157. *
  2158. * @param string $string What to add the trailing slash to.
  2159. * @return string String with trailing slash added.
  2160. */
  2161. function trailingslashit( $string ) {
  2162. return untrailingslashit( $string ) . '/';
  2163. }
  2164. /**
  2165. * Removes trailing forward slashes and backslashes if they exist.
  2166. *
  2167. * The primary use of this is for paths and thus should be used for paths. It is
  2168. * not restricted to paths and offers no specific path support.
  2169. *
  2170. * @since 2.2.0
  2171. *
  2172. * @param string $string What to remove the trailing slashes from.
  2173. * @return string String without the trailing slashes.
  2174. */
  2175. function untrailingslashit( $string ) {
  2176. return rtrim( $string, '/\\' );
  2177. }
  2178. /**
  2179. * Adds slashes to escape strings.
  2180. *
  2181. * Slashes will first be removed if magic_quotes_gpc is set, see {@link
  2182. * https://secure.php.net/magic_quotes} for more details.
  2183. *
  2184. * @since 0.71
  2185. *
  2186. * @param string $gpc The string returned from HTTP request data.
  2187. * @return string Returns a string escaped with slashes.
  2188. */
  2189. function addslashes_gpc($gpc) {
  2190. if ( get_magic_quotes_gpc() )
  2191. $gpc = stripslashes($gpc);
  2192. return wp_slash($gpc);
  2193. }
  2194. /**
  2195. * Navigates through an array, object, or scalar, and removes slashes from the values.
  2196. *
  2197. * @since 2.0.0
  2198. *
  2199. * @param mixed $value The value to be stripped.
  2200. * @return mixed Stripped value.
  2201. */
  2202. function stripslashes_deep( $value ) {
  2203. return map_deep( $value, 'stripslashes_from_strings_only' );
  2204. }
  2205. /**
  2206. * Callback function for `stripslashes_deep()` which strips slashes from strings.
  2207. *
  2208. * @since 4.4.0
  2209. *
  2210. * @param mixed $value The array or string to be stripped.
  2211. * @return mixed $value The stripped value.
  2212. */
  2213. function stripslashes_from_strings_only( $value ) {
  2214. return is_string( $value ) ? stripslashes( $value ) : $value;
  2215. }
  2216. /**
  2217. * Navigates through an array, object, or scalar, and encodes the values to be used in a URL.
  2218. *
  2219. * @since 2.2.0
  2220. *
  2221. * @param mixed $value The array or string to be encoded.
  2222. * @return mixed $value The encoded value.
  2223. */
  2224. function urlencode_deep( $value ) {
  2225. return map_deep( $value, 'urlencode' );
  2226. }
  2227. /**
  2228. * Navigates through an array, object, or scalar, and raw-encodes the values to be used in a URL.
  2229. *
  2230. * @since 3.4.0
  2231. *
  2232. * @param mixed $value The array or string to be encoded.
  2233. * @return mixed $value The encoded value.
  2234. */
  2235. function rawurlencode_deep( $value ) {
  2236. return map_deep( $value, 'rawurlencode' );
  2237. }
  2238. /**
  2239. * Navigates through an array, object, or scalar, and decodes URL-encoded values
  2240. *
  2241. * @since 4.4.0
  2242. *
  2243. * @param mixed $value The array or string to be decoded.
  2244. * @return mixed $value The decoded value.
  2245. */
  2246. function urldecode_deep( $value ) {
  2247. return map_deep( $value, 'urldecode' );
  2248. }
  2249. /**
  2250. * Converts email addresses characters to HTML entities to block spam bots.
  2251. *
  2252. * @since 0.71
  2253. *
  2254. * @param string $email_address Email address.
  2255. * @param int $hex_encoding Optional. Set to 1 to enable hex encoding.
  2256. * @return string Converted email address.
  2257. */
  2258. function antispambot( $email_address, $hex_encoding = 0 ) {
  2259. $email_no_spam_address = '';
  2260. for ( $i = 0, $len = strlen( $email_address ); $i < $len; $i++ ) {
  2261. $j = rand( 0, 1 + $hex_encoding );
  2262. if ( $j == 0 ) {
  2263. $email_no_spam_address .= '&#' . ord( $email_address[$i] ) . ';';
  2264. } elseif ( $j == 1 ) {
  2265. $email_no_spam_address .= $email_address[$i];
  2266. } elseif ( $j == 2 ) {
  2267. $email_no_spam_address .= '%' . zeroise( dechex( ord( $email_address[$i] ) ), 2 );
  2268. }
  2269. }
  2270. return str_replace( '@', '&#64;', $email_no_spam_address );
  2271. }
  2272. /**
  2273. * Callback to convert URI match to HTML A element.
  2274. *
  2275. * This function was backported from 2.5.0 to 2.3.2. Regex callback for make_clickable().
  2276. *
  2277. * @since 2.3.2
  2278. * @access private
  2279. *
  2280. * @param array $matches Single Regex Match.
  2281. * @return string HTML A element with URI address.
  2282. */
  2283. function _make_url_clickable_cb( $matches ) {
  2284. $url = $matches[2];
  2285. if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
  2286. // If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL.
  2287. // Then we can let the parenthesis balancer do its thing below.
  2288. $url .= $matches[3];
  2289. $suffix = '';
  2290. } else {
  2291. $suffix = $matches[3];
  2292. }
  2293. // Include parentheses in the URL only if paired
  2294. while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
  2295. $suffix = strrchr( $url, ')' ) . $suffix;
  2296. $url = substr( $url, 0, strrpos( $url, ')' ) );
  2297. }
  2298. $url = esc_url($url);
  2299. if ( empty($url) )
  2300. return $matches[0];
  2301. return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
  2302. }
  2303. /**
  2304. * Callback to convert URL match to HTML A element.
  2305. *
  2306. * This function was backported from 2.5.0 to 2.3.2. Regex callback for make_clickable().
  2307. *
  2308. * @since 2.3.2
  2309. * @access private
  2310. *
  2311. * @param array $matches Single Regex Match.
  2312. * @return string HTML A element with URL address.
  2313. */
  2314. function _make_web_ftp_clickable_cb( $matches ) {
  2315. $ret = '';
  2316. $dest = $matches[2];
  2317. $dest = 'http://' . $dest;
  2318. // removed trailing [.,;:)] from URL
  2319. if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
  2320. $ret = substr($dest, -1);
  2321. $dest = substr($dest, 0, strlen($dest)-1);
  2322. }
  2323. $dest = esc_url($dest);
  2324. if ( empty($dest) )
  2325. return $matches[0];
  2326. return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
  2327. }
  2328. /**
  2329. * Callback to convert email address match to HTML A element.
  2330. *
  2331. * This function was backported from 2.5.0 to 2.3.2. Regex callback for make_clickable().
  2332. *
  2333. * @since 2.3.2
  2334. * @access private
  2335. *
  2336. * @param array $matches Single Regex Match.
  2337. * @return string HTML A element with email address.
  2338. */
  2339. function _make_email_clickable_cb( $matches ) {
  2340. $email = $matches[2] . '@' . $matches[3];
  2341. return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
  2342. }
  2343. /**
  2344. * Convert plaintext URI to HTML links.
  2345. *
  2346. * Converts URI, www and ftp, and email addresses. Finishes by fixing links
  2347. * within links.
  2348. *
  2349. * @since 0.71
  2350. *
  2351. * @param string $text Content to convert URIs.
  2352. * @return string Content with converted URIs.
  2353. */
  2354. function make_clickable( $text ) {
  2355. $r = '';
  2356. $textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // split out HTML tags
  2357. $nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>
  2358. foreach ( $textarr as $piece ) {
  2359. 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 ) )
  2360. $nested_code_pre++;
  2361. elseif ( $nested_code_pre && ( '</code>' === strtolower( $piece ) || '</pre>' === strtolower( $piece ) || '</script>' === strtolower( $piece ) || '</style>' === strtolower( $piece ) ) )
  2362. $nested_code_pre--;
  2363. if ( $nested_code_pre || empty( $piece ) || ( $piece[0] === '<' && ! preg_match( '|^<\s*[\w]{1,20}+://|', $piece ) ) ) {
  2364. $r .= $piece;
  2365. continue;
  2366. }
  2367. // Long strings might contain expensive edge cases ...
  2368. if ( 10000 < strlen( $piece ) ) {
  2369. // ... break it up
  2370. foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses
  2371. if ( 2101 < strlen( $chunk ) ) {
  2372. $r .= $chunk; // Too big, no whitespace: bail.
  2373. } else {
  2374. $r .= make_clickable( $chunk );
  2375. }
  2376. }
  2377. } else {
  2378. $ret = " $piece "; // Pad with whitespace to simplify the regexes
  2379. $url_clickable = '~
  2380. ([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation
  2381. ( # 2: URL
  2382. [\\w]{1,20}+:// # Scheme and hier-part prefix
  2383. (?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long
  2384. [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character
  2385. (?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
  2386. [\'.,;:!?)] # Punctuation URL character
  2387. [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
  2388. )*
  2389. )
  2390. (\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing)
  2391. ~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character.
  2392. // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
  2393. $ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret );
  2394. $ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
  2395. $ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
  2396. $ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
  2397. $r .= $ret;
  2398. }
  2399. }
  2400. // Cleanup of accidental links within links
  2401. return preg_replace( '#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r );
  2402. }
  2403. /**
  2404. * Breaks a string into chunks by splitting at whitespace characters.
  2405. * The length of each returned chunk is as close to the specified length goal as possible,
  2406. * with the caveat that each chunk includes its trailing delimiter.
  2407. * Chunks longer than the goal are guaranteed to not have any inner whitespace.
  2408. *
  2409. * Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
  2410. *
  2411. * Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
  2412. *
  2413. * _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) ==
  2414. * array (
  2415. * 0 => '1234 67890 ', // 11 characters: Perfect split
  2416. * 1 => '1234 ', // 5 characters: '1234 67890a' was too long
  2417. * 2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long
  2418. * 3 => '1234 890 ', // 11 characters: Perfect split
  2419. * 4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long
  2420. * 5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split
  2421. * 6 => ' 45678 ', // 11 characters: Perfect split
  2422. * 7 => '1 3 5 7 90 ', // 11 characters: End of $string
  2423. * );
  2424. *
  2425. * @since 3.4.0
  2426. * @access private
  2427. *
  2428. * @param string $string The string to split.
  2429. * @param int $goal The desired chunk length.
  2430. * @return array Numeric array of chunks.
  2431. */
  2432. function _split_str_by_whitespace( $string, $goal ) {
  2433. $chunks = array();
  2434. $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
  2435. while ( $goal < strlen( $string_nullspace ) ) {
  2436. $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
  2437. if ( false === $pos ) {
  2438. $pos = strpos( $string_nullspace, "\000", $goal + 1 );
  2439. if ( false === $pos ) {
  2440. break;
  2441. }
  2442. }
  2443. $chunks[] = substr( $string, 0, $pos + 1 );
  2444. $string = substr( $string, $pos + 1 );
  2445. $string_nullspace = substr( $string_nullspace, $pos + 1 );
  2446. }
  2447. if ( $string ) {
  2448. $chunks[] = $string;
  2449. }
  2450. return $chunks;
  2451. }
  2452. /**
  2453. * Adds rel nofollow string to all HTML A elements in content.
  2454. *
  2455. * @since 1.5.0
  2456. *
  2457. * @param string $text Content that may contain HTML A elements.
  2458. * @return string Converted content.
  2459. */
  2460. function wp_rel_nofollow( $text ) {
  2461. // This is a pre save filter, so text is already escaped.
  2462. $text = stripslashes($text);
  2463. $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
  2464. return wp_slash( $text );
  2465. }
  2466. /**
  2467. * Callback to add rel=nofollow string to HTML A element.
  2468. *
  2469. * Will remove already existing rel="nofollow" and rel='nofollow' from the
  2470. * string to prevent from invalidating (X)HTML.
  2471. *
  2472. * @since 2.3.0
  2473. *
  2474. * @param array $matches Single Match
  2475. * @return string HTML A Element with rel nofollow.
  2476. */
  2477. function wp_rel_nofollow_callback( $matches ) {
  2478. $text = $matches[1];
  2479. $atts = shortcode_parse_atts( $matches[1] );
  2480. $rel = 'nofollow';
  2481. if ( preg_match( '%href=["\'](' . preg_quote( set_url_scheme( home_url(), 'http' ) ) . ')%i', $text ) ||
  2482. preg_match( '%href=["\'](' . preg_quote( set_url_scheme( home_url(), 'https' ) ) . ')%i', $text )
  2483. ) {
  2484. return "<a $text>";
  2485. }
  2486. if ( ! empty( $atts['rel'] ) ) {
  2487. $parts = array_map( 'trim', explode( ' ', $atts['rel'] ) );
  2488. if ( false === array_search( 'nofollow', $parts ) ) {
  2489. $parts[] = 'nofollow';
  2490. }
  2491. $rel = implode( ' ', $parts );
  2492. unset( $atts['rel'] );
  2493. $html = '';
  2494. foreach ( $atts as $name => $value ) {
  2495. $html .= "{$name}=\"$value\" ";
  2496. }
  2497. $text = trim( $html );
  2498. }
  2499. return "<a $text rel=\"$rel\">";
  2500. }
  2501. /**
  2502. * Convert one smiley code to the icon graphic file equivalent.
  2503. *
  2504. * Callback handler for convert_smilies().
  2505. *
  2506. * Looks up one smiley code in the $wpsmiliestrans global array and returns an
  2507. * `<img>` string for that smiley.
  2508. *
  2509. * @since 2.8.0
  2510. *
  2511. * @global array $wpsmiliestrans
  2512. *
  2513. * @param array $matches Single match. Smiley code to convert to image.
  2514. * @return string Image string for smiley.
  2515. */
  2516. function translate_smiley( $matches ) {
  2517. global $wpsmiliestrans;
  2518. if ( count( $matches ) == 0 )
  2519. return '';
  2520. $smiley = trim( reset( $matches ) );
  2521. $img = $wpsmiliestrans[ $smiley ];
  2522. $matches = array();
  2523. $ext = preg_match( '/\.([^.]+)$/', $img, $matches ) ? strtolower( $matches[1] ) : false;
  2524. $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
  2525. // Don't convert smilies that aren't images - they're probably emoji.
  2526. if ( ! in_array( $ext, $image_exts ) ) {
  2527. return $img;
  2528. }
  2529. /**
  2530. * Filters the Smiley image URL before it's used in the image element.
  2531. *
  2532. * @since 2.9.0
  2533. *
  2534. * @param string $smiley_url URL for the smiley image.
  2535. * @param string $img Filename for the smiley image.
  2536. * @param string $site_url Site URL, as returned by site_url().
  2537. */
  2538. $src_url = apply_filters( 'smilies_src', includes_url( "images/smilies/$img" ), $img, site_url() );
  2539. return sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', esc_url( $src_url ), esc_attr( $smiley ) );
  2540. }
  2541. /**
  2542. * Convert text equivalent of smilies to images.
  2543. *
  2544. * Will only convert smilies if the option 'use_smilies' is true and the global
  2545. * used in the function isn't empty.
  2546. *
  2547. * @since 0.71
  2548. *
  2549. * @global string|array $wp_smiliessearch
  2550. *
  2551. * @param string $text Content to convert smilies from text.
  2552. * @return string Converted content with text smilies replaced with images.
  2553. */
  2554. function convert_smilies( $text ) {
  2555. global $wp_smiliessearch;
  2556. $output = '';
  2557. if ( get_option( 'use_smilies' ) && ! empty( $wp_smiliessearch ) ) {
  2558. // HTML loop taken from texturize function, could possible be consolidated
  2559. $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // capture the tags as well as in between
  2560. $stop = count( $textarr );// loop stuff
  2561. // Ignore proessing of specific tags
  2562. $tags_to_ignore = 'code|pre|style|script|textarea';
  2563. $ignore_block_element = '';
  2564. for ( $i = 0; $i < $stop; $i++ ) {
  2565. $content = $textarr[$i];
  2566. // If we're in an ignore block, wait until we find its closing tag
  2567. if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
  2568. $ignore_block_element = $matches[1];
  2569. }
  2570. // If it's not a tag and not in ignore block
  2571. if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
  2572. $content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content );
  2573. }
  2574. // did we exit ignore block
  2575. if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
  2576. $ignore_block_element = '';
  2577. }
  2578. $output .= $content;
  2579. }
  2580. } else {
  2581. // return default text.
  2582. $output = $text;
  2583. }
  2584. return $output;
  2585. }
  2586. /**
  2587. * Verifies that an email is valid.
  2588. *
  2589. * Does not grok i18n domains. Not RFC compliant.
  2590. *
  2591. * @since 0.71
  2592. *
  2593. * @param string $email Email address to verify.
  2594. * @param bool $deprecated Deprecated.
  2595. * @return string|bool Either false or the valid email address.
  2596. */
  2597. function is_email( $email, $deprecated = false ) {
  2598. if ( ! empty( $deprecated ) )
  2599. _deprecated_argument( __FUNCTION__, '3.0.0' );
  2600. // Test for the minimum length the email can be
  2601. if ( strlen( $email ) < 6 ) {
  2602. /**
  2603. * Filters whether an email address is valid.
  2604. *
  2605. * This filter is evaluated under several different contexts, such as 'email_too_short',
  2606. * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
  2607. * 'domain_no_periods', 'sub_hyphen_limits', 'sub_invalid_chars', or no specific context.
  2608. *
  2609. * @since 2.8.0
  2610. *
  2611. * @param bool $is_email Whether the email address has passed the is_email() checks. Default false.
  2612. * @param string $email The email address being checked.
  2613. * @param string $context Context under which the email was tested.
  2614. */
  2615. return apply_filters( 'is_email', false, $email, 'email_too_short' );
  2616. }
  2617. // Test for an @ character after the first position
  2618. if ( strpos( $email, '@', 1 ) === false ) {
  2619. /** This filter is documented in wp-includes/formatting.php */
  2620. return apply_filters( 'is_email', false, $email, 'email_no_at' );
  2621. }
  2622. // Split out the local and domain parts
  2623. list( $local, $domain ) = explode( '@', $email, 2 );
  2624. // LOCAL PART
  2625. // Test for invalid characters
  2626. if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
  2627. /** This filter is documented in wp-includes/formatting.php */
  2628. return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
  2629. }
  2630. // DOMAIN PART
  2631. // Test for sequences of periods
  2632. if ( preg_match( '/\.{2,}/', $domain ) ) {
  2633. /** This filter is documented in wp-includes/formatting.php */
  2634. return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
  2635. }
  2636. // Test for leading and trailing periods and whitespace
  2637. if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
  2638. /** This filter is documented in wp-includes/formatting.php */
  2639. return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
  2640. }
  2641. // Split the domain into subs
  2642. $subs = explode( '.', $domain );
  2643. // Assume the domain will have at least two subs
  2644. if ( 2 > count( $subs ) ) {
  2645. /** This filter is documented in wp-includes/formatting.php */
  2646. return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
  2647. }
  2648. // Loop through each sub
  2649. foreach ( $subs as $sub ) {
  2650. // Test for leading and trailing hyphens and whitespace
  2651. if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
  2652. /** This filter is documented in wp-includes/formatting.php */
  2653. return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
  2654. }
  2655. // Test for invalid characters
  2656. if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
  2657. /** This filter is documented in wp-includes/formatting.php */
  2658. return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
  2659. }
  2660. }
  2661. // Congratulations your email made it!
  2662. /** This filter is documented in wp-includes/formatting.php */
  2663. return apply_filters( 'is_email', $email, $email, null );
  2664. }
  2665. /**
  2666. * Convert to ASCII from email subjects.
  2667. *
  2668. * @since 1.2.0
  2669. *
  2670. * @param string $string Subject line
  2671. * @return string Converted string to ASCII
  2672. */
  2673. function wp_iso_descrambler( $string ) {
  2674. /* this may only work with iso-8859-1, I'm afraid */
  2675. if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
  2676. return $string;
  2677. } else {
  2678. $subject = str_replace('_', ' ', $matches[2]);
  2679. return preg_replace_callback( '#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject );
  2680. }
  2681. }
  2682. /**
  2683. * Helper function to convert hex encoded chars to ASCII
  2684. *
  2685. * @since 3.1.0
  2686. * @access private
  2687. *
  2688. * @param array $match The preg_replace_callback matches array
  2689. * @return string Converted chars
  2690. */
  2691. function _wp_iso_convert( $match ) {
  2692. return chr( hexdec( strtolower( $match[1] ) ) );
  2693. }
  2694. /**
  2695. * Returns a date in the GMT equivalent.
  2696. *
  2697. * Requires and returns a date in the Y-m-d H:i:s format. If there is a
  2698. * timezone_string available, the date is assumed to be in that timezone,
  2699. * otherwise it simply subtracts the value of the 'gmt_offset' option. Return
  2700. * format can be overridden using the $format parameter.
  2701. *
  2702. * @since 1.2.0
  2703. *
  2704. * @param string $string The date to be converted.
  2705. * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
  2706. * @return string GMT version of the date provided.
  2707. */
  2708. function get_gmt_from_date( $string, $format = 'Y-m-d H:i:s' ) {
  2709. $tz = get_option( 'timezone_string' );
  2710. if ( $tz ) {
  2711. $datetime = date_create( $string, new DateTimeZone( $tz ) );
  2712. if ( ! $datetime ) {
  2713. return gmdate( $format, 0 );
  2714. }
  2715. $datetime->setTimezone( new DateTimeZone( 'UTC' ) );
  2716. $string_gmt = $datetime->format( $format );
  2717. } else {
  2718. 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 ) ) {
  2719. $datetime = strtotime( $string );
  2720. if ( false === $datetime ) {
  2721. return gmdate( $format, 0 );
  2722. }
  2723. return gmdate( $format, $datetime );
  2724. }
  2725. $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
  2726. $string_gmt = gmdate( $format, $string_time - get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
  2727. }
  2728. return $string_gmt;
  2729. }
  2730. /**
  2731. * Converts a GMT date into the correct format for the blog.
  2732. *
  2733. * Requires and returns a date in the Y-m-d H:i:s format. If there is a
  2734. * timezone_string available, the returned date is in that timezone, otherwise
  2735. * it simply adds the value of gmt_offset. Return format can be overridden
  2736. * using the $format parameter
  2737. *
  2738. * @since 1.2.0
  2739. *
  2740. * @param string $string The date to be converted.
  2741. * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
  2742. * @return string Formatted date relative to the timezone / GMT offset.
  2743. */
  2744. function get_date_from_gmt( $string, $format = 'Y-m-d H:i:s' ) {
  2745. $tz = get_option( 'timezone_string' );
  2746. if ( $tz ) {
  2747. $datetime = date_create( $string, new DateTimeZone( 'UTC' ) );
  2748. if ( ! $datetime )
  2749. return date( $format, 0 );
  2750. $datetime->setTimezone( new DateTimeZone( $tz ) );
  2751. $string_localtime = $datetime->format( $format );
  2752. } else {
  2753. 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) )
  2754. return date( $format, 0 );
  2755. $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
  2756. $string_localtime = gmdate( $format, $string_time + get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
  2757. }
  2758. return $string_localtime;
  2759. }
  2760. /**
  2761. * Computes an offset in seconds from an iso8601 timezone.
  2762. *
  2763. * @since 1.5.0
  2764. *
  2765. * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
  2766. * @return int|float The offset in seconds.
  2767. */
  2768. function iso8601_timezone_to_offset( $timezone ) {
  2769. // $timezone is either 'Z' or '[+|-]hhmm'
  2770. if ($timezone == 'Z') {
  2771. $offset = 0;
  2772. } else {
  2773. $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
  2774. $hours = intval(substr($timezone, 1, 2));
  2775. $minutes = intval(substr($timezone, 3, 4)) / 60;
  2776. $offset = $sign * HOUR_IN_SECONDS * ($hours + $minutes);
  2777. }
  2778. return $offset;
  2779. }
  2780. /**
  2781. * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
  2782. *
  2783. * @since 1.5.0
  2784. *
  2785. * @param string $date_string Date and time in ISO 8601 format {@link https://en.wikipedia.org/wiki/ISO_8601}.
  2786. * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
  2787. * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
  2788. */
  2789. function iso8601_to_datetime( $date_string, $timezone = 'user' ) {
  2790. $timezone = strtolower($timezone);
  2791. if ($timezone == 'gmt') {
  2792. 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);
  2793. if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
  2794. $offset = iso8601_timezone_to_offset($date_bits[7]);
  2795. } else { // we don't have a timezone, so we assume user local timezone (not server's!)
  2796. $offset = HOUR_IN_SECONDS * get_option('gmt_offset');
  2797. }
  2798. $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
  2799. $timestamp -= $offset;
  2800. return gmdate('Y-m-d H:i:s', $timestamp);
  2801. } elseif ($timezone == 'user') {
  2802. 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);
  2803. }
  2804. }
  2805. /**
  2806. * Strips out all characters that are not allowable in an email.
  2807. *
  2808. * @since 1.5.0
  2809. *
  2810. * @param string $email Email address to filter.
  2811. * @return string Filtered email address.
  2812. */
  2813. function sanitize_email( $email ) {
  2814. // Test for the minimum length the email can be
  2815. if ( strlen( $email ) < 6 ) {
  2816. /**
  2817. * Filters a sanitized email address.
  2818. *
  2819. * This filter is evaluated under several contexts, including 'email_too_short',
  2820. * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
  2821. * 'domain_no_periods', 'domain_no_valid_subs', or no context.
  2822. *
  2823. * @since 2.8.0
  2824. *
  2825. * @param string $email The sanitized email address.
  2826. * @param string $email The email address, as provided to sanitize_email().
  2827. * @param string $message A message to pass to the user.
  2828. */
  2829. return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
  2830. }
  2831. // Test for an @ character after the first position
  2832. if ( strpos( $email, '@', 1 ) === false ) {
  2833. /** This filter is documented in wp-includes/formatting.php */
  2834. return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
  2835. }
  2836. // Split out the local and domain parts
  2837. list( $local, $domain ) = explode( '@', $email, 2 );
  2838. // LOCAL PART
  2839. // Test for invalid characters
  2840. $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
  2841. if ( '' === $local ) {
  2842. /** This filter is documented in wp-includes/formatting.php */
  2843. return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
  2844. }
  2845. // DOMAIN PART
  2846. // Test for sequences of periods
  2847. $domain = preg_replace( '/\.{2,}/', '', $domain );
  2848. if ( '' === $domain ) {
  2849. /** This filter is documented in wp-includes/formatting.php */
  2850. return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
  2851. }
  2852. // Test for leading and trailing periods and whitespace
  2853. $domain = trim( $domain, " \t\n\r\0\x0B." );
  2854. if ( '' === $domain ) {
  2855. /** This filter is documented in wp-includes/formatting.php */
  2856. return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
  2857. }
  2858. // Split the domain into subs
  2859. $subs = explode( '.', $domain );
  2860. // Assume the domain will have at least two subs
  2861. if ( 2 > count( $subs ) ) {
  2862. /** This filter is documented in wp-includes/formatting.php */
  2863. return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
  2864. }
  2865. // Create an array that will contain valid subs
  2866. $new_subs = array();
  2867. // Loop through each sub
  2868. foreach ( $subs as $sub ) {
  2869. // Test for leading and trailing hyphens
  2870. $sub = trim( $sub, " \t\n\r\0\x0B-" );
  2871. // Test for invalid characters
  2872. $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
  2873. // If there's anything left, add it to the valid subs
  2874. if ( '' !== $sub ) {
  2875. $new_subs[] = $sub;
  2876. }
  2877. }
  2878. // If there aren't 2 or more valid subs
  2879. if ( 2 > count( $new_subs ) ) {
  2880. /** This filter is documented in wp-includes/formatting.php */
  2881. return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
  2882. }
  2883. // Join valid subs into the new domain
  2884. $domain = join( '.', $new_subs );
  2885. // Put the email back together
  2886. $email = $local . '@' . $domain;
  2887. // Congratulations your email made it!
  2888. /** This filter is documented in wp-includes/formatting.php */
  2889. return apply_filters( 'sanitize_email', $email, $email, null );
  2890. }
  2891. /**
  2892. * Determines the difference between two timestamps.
  2893. *
  2894. * The difference is returned in a human readable format such as "1 hour",
  2895. * "5 mins", "2 days".
  2896. *
  2897. * @since 1.5.0
  2898. *
  2899. * @param int $from Unix timestamp from which the difference begins.
  2900. * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
  2901. * @return string Human readable time difference.
  2902. */
  2903. function human_time_diff( $from, $to = '' ) {
  2904. if ( empty( $to ) ) {
  2905. $to = time();
  2906. }
  2907. $diff = (int) abs( $to - $from );
  2908. if ( $diff < HOUR_IN_SECONDS ) {
  2909. $mins = round( $diff / MINUTE_IN_SECONDS );
  2910. if ( $mins <= 1 )
  2911. $mins = 1;
  2912. /* translators: Time difference between two dates, in minutes (min=minute). 1: Number of minutes */
  2913. $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
  2914. } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
  2915. $hours = round( $diff / HOUR_IN_SECONDS );
  2916. if ( $hours <= 1 )
  2917. $hours = 1;
  2918. /* translators: Time difference between two dates, in hours. 1: Number of hours */
  2919. $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
  2920. } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
  2921. $days = round( $diff / DAY_IN_SECONDS );
  2922. if ( $days <= 1 )
  2923. $days = 1;
  2924. /* translators: Time difference between two dates, in days. 1: Number of days */
  2925. $since = sprintf( _n( '%s day', '%s days', $days ), $days );
  2926. } elseif ( $diff < MONTH_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
  2927. $weeks = round( $diff / WEEK_IN_SECONDS );
  2928. if ( $weeks <= 1 )
  2929. $weeks = 1;
  2930. /* translators: Time difference between two dates, in weeks. 1: Number of weeks */
  2931. $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
  2932. } elseif ( $diff < YEAR_IN_SECONDS && $diff >= MONTH_IN_SECONDS ) {
  2933. $months = round( $diff / MONTH_IN_SECONDS );
  2934. if ( $months <= 1 )
  2935. $months = 1;
  2936. /* translators: Time difference between two dates, in months. 1: Number of months */
  2937. $since = sprintf( _n( '%s month', '%s months', $months ), $months );
  2938. } elseif ( $diff >= YEAR_IN_SECONDS ) {
  2939. $years = round( $diff / YEAR_IN_SECONDS );
  2940. if ( $years <= 1 )
  2941. $years = 1;
  2942. /* translators: Time difference between two dates, in years. 1: Number of years */
  2943. $since = sprintf( _n( '%s year', '%s years', $years ), $years );
  2944. }
  2945. /**
  2946. * Filters the human readable difference between two timestamps.
  2947. *
  2948. * @since 4.0.0
  2949. *
  2950. * @param string $since The difference in human readable text.
  2951. * @param int $diff The difference in seconds.
  2952. * @param int $from Unix timestamp from which the difference begins.
  2953. * @param int $to Unix timestamp to end the time difference.
  2954. */
  2955. return apply_filters( 'human_time_diff', $since, $diff, $from, $to );
  2956. }
  2957. /**
  2958. * Generates an excerpt from the content, if needed.
  2959. *
  2960. * The excerpt word amount will be 55 words and if the amount is greater than
  2961. * that, then the string ' [&hellip;]' will be appended to the excerpt. If the string
  2962. * is less than 55 words, then the content will be returned as is.
  2963. *
  2964. * The 55 word limit can be modified by plugins/themes using the {@see 'excerpt_length'} filter
  2965. * The ' [&hellip;]' string can be modified by plugins/themes using the {@see 'excerpt_more'} filter
  2966. *
  2967. * @since 1.5.0
  2968. *
  2969. * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
  2970. * @return string The excerpt.
  2971. */
  2972. function wp_trim_excerpt( $text = '' ) {
  2973. $raw_excerpt = $text;
  2974. if ( '' == $text ) {
  2975. $text = get_the_content('');
  2976. $text = strip_shortcodes( $text );
  2977. /** This filter is documented in wp-includes/post-template.php */
  2978. $text = apply_filters( 'the_content', $text );
  2979. $text = str_replace(']]>', ']]&gt;', $text);
  2980. /**
  2981. * Filters the number of words in an excerpt.
  2982. *
  2983. * @since 2.7.0
  2984. *
  2985. * @param int $number The number of words. Default 55.
  2986. */
  2987. $excerpt_length = apply_filters( 'excerpt_length', 55 );
  2988. /**
  2989. * Filters the string in the "more" link displayed after a trimmed excerpt.
  2990. *
  2991. * @since 2.9.0
  2992. *
  2993. * @param string $more_string The string shown within the more link.
  2994. */
  2995. $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[&hellip;]' );
  2996. $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
  2997. }
  2998. /**
  2999. * Filters the trimmed excerpt string.
  3000. *
  3001. * @since 2.8.0
  3002. *
  3003. * @param string $text The trimmed text.
  3004. * @param string $raw_excerpt The text prior to trimming.
  3005. */
  3006. return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
  3007. }
  3008. /**
  3009. * Trims text to a certain number of words.
  3010. *
  3011. * This function is localized. For languages that count 'words' by the individual
  3012. * character (such as East Asian languages), the $num_words argument will apply
  3013. * to the number of individual characters.
  3014. *
  3015. * @since 3.3.0
  3016. *
  3017. * @param string $text Text to trim.
  3018. * @param int $num_words Number of words. Default 55.
  3019. * @param string $more Optional. What to append if $text needs to be trimmed. Default '&hellip;'.
  3020. * @return string Trimmed text.
  3021. */
  3022. function wp_trim_words( $text, $num_words = 55, $more = null ) {
  3023. if ( null === $more ) {
  3024. $more = __( '&hellip;' );
  3025. }
  3026. $original_text = $text;
  3027. $text = wp_strip_all_tags( $text );
  3028. /*
  3029. * translators: If your word count is based on single characters (e.g. East Asian characters),
  3030. * enter 'characters_excluding_spaces' or 'characters_including_spaces'. Otherwise, enter 'words'.
  3031. * Do not translate into your own language.
  3032. */
  3033. if ( strpos( _x( 'words', 'Word count type. Do not translate!' ), 'characters' ) === 0 && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
  3034. $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
  3035. preg_match_all( '/./u', $text, $words_array );
  3036. $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
  3037. $sep = '';
  3038. } else {
  3039. $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
  3040. $sep = ' ';
  3041. }
  3042. if ( count( $words_array ) > $num_words ) {
  3043. array_pop( $words_array );
  3044. $text = implode( $sep, $words_array );
  3045. $text = $text . $more;
  3046. } else {
  3047. $text = implode( $sep, $words_array );
  3048. }
  3049. /**
  3050. * Filters the text content after words have been trimmed.
  3051. *
  3052. * @since 3.3.0
  3053. *
  3054. * @param string $text The trimmed text.
  3055. * @param int $num_words The number of words to trim the text to. Default 55.
  3056. * @param string $more An optional string to append to the end of the trimmed text, e.g. &hellip;.
  3057. * @param string $original_text The text before it was trimmed.
  3058. */
  3059. return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
  3060. }
  3061. /**
  3062. * Converts named entities into numbered entities.
  3063. *
  3064. * @since 1.5.1
  3065. *
  3066. * @param string $text The text within which entities will be converted.
  3067. * @return string Text with converted entities.
  3068. */
  3069. function ent2ncr( $text ) {
  3070. /**
  3071. * Filters text before named entities are converted into numbered entities.
  3072. *
  3073. * A non-null string must be returned for the filter to be evaluated.
  3074. *
  3075. * @since 3.3.0
  3076. *
  3077. * @param null $converted_text The text to be converted. Default null.
  3078. * @param string $text The text prior to entity conversion.
  3079. */
  3080. $filtered = apply_filters( 'pre_ent2ncr', null, $text );
  3081. if ( null !== $filtered )
  3082. return $filtered;
  3083. $to_ncr = array(
  3084. '&quot;' => '&#34;',
  3085. '&amp;' => '&#38;',
  3086. '&lt;' => '&#60;',
  3087. '&gt;' => '&#62;',
  3088. '|' => '&#124;',
  3089. '&nbsp;' => '&#160;',
  3090. '&iexcl;' => '&#161;',
  3091. '&cent;' => '&#162;',
  3092. '&pound;' => '&#163;',
  3093. '&curren;' => '&#164;',
  3094. '&yen;' => '&#165;',
  3095. '&brvbar;' => '&#166;',
  3096. '&brkbar;' => '&#166;',
  3097. '&sect;' => '&#167;',
  3098. '&uml;' => '&#168;',
  3099. '&die;' => '&#168;',
  3100. '&copy;' => '&#169;',
  3101. '&ordf;' => '&#170;',
  3102. '&laquo;' => '&#171;',
  3103. '&not;' => '&#172;',
  3104. '&shy;' => '&#173;',
  3105. '&reg;' => '&#174;',
  3106. '&macr;' => '&#175;',
  3107. '&hibar;' => '&#175;',
  3108. '&deg;' => '&#176;',
  3109. '&plusmn;' => '&#177;',
  3110. '&sup2;' => '&#178;',
  3111. '&sup3;' => '&#179;',
  3112. '&acute;' => '&#180;',
  3113. '&micro;' => '&#181;',
  3114. '&para;' => '&#182;',
  3115. '&middot;' => '&#183;',
  3116. '&cedil;' => '&#184;',
  3117. '&sup1;' => '&#185;',
  3118. '&ordm;' => '&#186;',
  3119. '&raquo;' => '&#187;',
  3120. '&frac14;' => '&#188;',
  3121. '&frac12;' => '&#189;',
  3122. '&frac34;' => '&#190;',
  3123. '&iquest;' => '&#191;',
  3124. '&Agrave;' => '&#192;',
  3125. '&Aacute;' => '&#193;',
  3126. '&Acirc;' => '&#194;',
  3127. '&Atilde;' => '&#195;',
  3128. '&Auml;' => '&#196;',
  3129. '&Aring;' => '&#197;',
  3130. '&AElig;' => '&#198;',
  3131. '&Ccedil;' => '&#199;',
  3132. '&Egrave;' => '&#200;',
  3133. '&Eacute;' => '&#201;',
  3134. '&Ecirc;' => '&#202;',
  3135. '&Euml;' => '&#203;',
  3136. '&Igrave;' => '&#204;',
  3137. '&Iacute;' => '&#205;',
  3138. '&Icirc;' => '&#206;',
  3139. '&Iuml;' => '&#207;',
  3140. '&ETH;' => '&#208;',
  3141. '&Ntilde;' => '&#209;',
  3142. '&Ograve;' => '&#210;',
  3143. '&Oacute;' => '&#211;',
  3144. '&Ocirc;' => '&#212;',
  3145. '&Otilde;' => '&#213;',
  3146. '&Ouml;' => '&#214;',
  3147. '&times;' => '&#215;',
  3148. '&Oslash;' => '&#216;',
  3149. '&Ugrave;' => '&#217;',
  3150. '&Uacute;' => '&#218;',
  3151. '&Ucirc;' => '&#219;',
  3152. '&Uuml;' => '&#220;',
  3153. '&Yacute;' => '&#221;',
  3154. '&THORN;' => '&#222;',
  3155. '&szlig;' => '&#223;',
  3156. '&agrave;' => '&#224;',
  3157. '&aacute;' => '&#225;',
  3158. '&acirc;' => '&#226;',
  3159. '&atilde;' => '&#227;',
  3160. '&auml;' => '&#228;',
  3161. '&aring;' => '&#229;',
  3162. '&aelig;' => '&#230;',
  3163. '&ccedil;' => '&#231;',
  3164. '&egrave;' => '&#232;',
  3165. '&eacute;' => '&#233;',
  3166. '&ecirc;' => '&#234;',
  3167. '&euml;' => '&#235;',
  3168. '&igrave;' => '&#236;',
  3169. '&iacute;' => '&#237;',
  3170. '&icirc;' => '&#238;',
  3171. '&iuml;' => '&#239;',
  3172. '&eth;' => '&#240;',
  3173. '&ntilde;' => '&#241;',
  3174. '&ograve;' => '&#242;',
  3175. '&oacute;' => '&#243;',
  3176. '&ocirc;' => '&#244;',
  3177. '&otilde;' => '&#245;',
  3178. '&ouml;' => '&#246;',
  3179. '&divide;' => '&#247;',
  3180. '&oslash;' => '&#248;',
  3181. '&ugrave;' => '&#249;',
  3182. '&uacute;' => '&#250;',
  3183. '&ucirc;' => '&#251;',
  3184. '&uuml;' => '&#252;',
  3185. '&yacute;' => '&#253;',
  3186. '&thorn;' => '&#254;',
  3187. '&yuml;' => '&#255;',
  3188. '&OElig;' => '&#338;',
  3189. '&oelig;' => '&#339;',
  3190. '&Scaron;' => '&#352;',
  3191. '&scaron;' => '&#353;',
  3192. '&Yuml;' => '&#376;',
  3193. '&fnof;' => '&#402;',
  3194. '&circ;' => '&#710;',
  3195. '&tilde;' => '&#732;',
  3196. '&Alpha;' => '&#913;',
  3197. '&Beta;' => '&#914;',
  3198. '&Gamma;' => '&#915;',
  3199. '&Delta;' => '&#916;',
  3200. '&Epsilon;' => '&#917;',
  3201. '&Zeta;' => '&#918;',
  3202. '&Eta;' => '&#919;',
  3203. '&Theta;' => '&#920;',
  3204. '&Iota;' => '&#921;',
  3205. '&Kappa;' => '&#922;',
  3206. '&Lambda;' => '&#923;',
  3207. '&Mu;' => '&#924;',
  3208. '&Nu;' => '&#925;',
  3209. '&Xi;' => '&#926;',
  3210. '&Omicron;' => '&#927;',
  3211. '&Pi;' => '&#928;',
  3212. '&Rho;' => '&#929;',
  3213. '&Sigma;' => '&#931;',
  3214. '&Tau;' => '&#932;',
  3215. '&Upsilon;' => '&#933;',
  3216. '&Phi;' => '&#934;',
  3217. '&Chi;' => '&#935;',
  3218. '&Psi;' => '&#936;',
  3219. '&Omega;' => '&#937;',
  3220. '&alpha;' => '&#945;',
  3221. '&beta;' => '&#946;',
  3222. '&gamma;' => '&#947;',
  3223. '&delta;' => '&#948;',
  3224. '&epsilon;' => '&#949;',
  3225. '&zeta;' => '&#950;',
  3226. '&eta;' => '&#951;',
  3227. '&theta;' => '&#952;',
  3228. '&iota;' => '&#953;',
  3229. '&kappa;' => '&#954;',
  3230. '&lambda;' => '&#955;',
  3231. '&mu;' => '&#956;',
  3232. '&nu;' => '&#957;',
  3233. '&xi;' => '&#958;',
  3234. '&omicron;' => '&#959;',
  3235. '&pi;' => '&#960;',
  3236. '&rho;' => '&#961;',
  3237. '&sigmaf;' => '&#962;',
  3238. '&sigma;' => '&#963;',
  3239. '&tau;' => '&#964;',
  3240. '&upsilon;' => '&#965;',
  3241. '&phi;' => '&#966;',
  3242. '&chi;' => '&#967;',
  3243. '&psi;' => '&#968;',
  3244. '&omega;' => '&#969;',
  3245. '&thetasym;' => '&#977;',
  3246. '&upsih;' => '&#978;',
  3247. '&piv;' => '&#982;',
  3248. '&ensp;' => '&#8194;',
  3249. '&emsp;' => '&#8195;',
  3250. '&thinsp;' => '&#8201;',
  3251. '&zwnj;' => '&#8204;',
  3252. '&zwj;' => '&#8205;',
  3253. '&lrm;' => '&#8206;',
  3254. '&rlm;' => '&#8207;',
  3255. '&ndash;' => '&#8211;',
  3256. '&mdash;' => '&#8212;',
  3257. '&lsquo;' => '&#8216;',
  3258. '&rsquo;' => '&#8217;',
  3259. '&sbquo;' => '&#8218;',
  3260. '&ldquo;' => '&#8220;',
  3261. '&rdquo;' => '&#8221;',
  3262. '&bdquo;' => '&#8222;',
  3263. '&dagger;' => '&#8224;',
  3264. '&Dagger;' => '&#8225;',
  3265. '&bull;' => '&#8226;',
  3266. '&hellip;' => '&#8230;',
  3267. '&permil;' => '&#8240;',
  3268. '&prime;' => '&#8242;',
  3269. '&Prime;' => '&#8243;',
  3270. '&lsaquo;' => '&#8249;',
  3271. '&rsaquo;' => '&#8250;',
  3272. '&oline;' => '&#8254;',
  3273. '&frasl;' => '&#8260;',
  3274. '&euro;' => '&#8364;',
  3275. '&image;' => '&#8465;',
  3276. '&weierp;' => '&#8472;',
  3277. '&real;' => '&#8476;',
  3278. '&trade;' => '&#8482;',
  3279. '&alefsym;' => '&#8501;',
  3280. '&crarr;' => '&#8629;',
  3281. '&lArr;' => '&#8656;',
  3282. '&uArr;' => '&#8657;',
  3283. '&rArr;' => '&#8658;',
  3284. '&dArr;' => '&#8659;',
  3285. '&hArr;' => '&#8660;',
  3286. '&forall;' => '&#8704;',
  3287. '&part;' => '&#8706;',
  3288. '&exist;' => '&#8707;',
  3289. '&empty;' => '&#8709;',
  3290. '&nabla;' => '&#8711;',
  3291. '&isin;' => '&#8712;',
  3292. '&notin;' => '&#8713;',
  3293. '&ni;' => '&#8715;',
  3294. '&prod;' => '&#8719;',
  3295. '&sum;' => '&#8721;',
  3296. '&minus;' => '&#8722;',
  3297. '&lowast;' => '&#8727;',
  3298. '&radic;' => '&#8730;',
  3299. '&prop;' => '&#8733;',
  3300. '&infin;' => '&#8734;',
  3301. '&ang;' => '&#8736;',
  3302. '&and;' => '&#8743;',
  3303. '&or;' => '&#8744;',
  3304. '&cap;' => '&#8745;',
  3305. '&cup;' => '&#8746;',
  3306. '&int;' => '&#8747;',
  3307. '&there4;' => '&#8756;',
  3308. '&sim;' => '&#8764;',
  3309. '&cong;' => '&#8773;',
  3310. '&asymp;' => '&#8776;',
  3311. '&ne;' => '&#8800;',
  3312. '&equiv;' => '&#8801;',
  3313. '&le;' => '&#8804;',
  3314. '&ge;' => '&#8805;',
  3315. '&sub;' => '&#8834;',
  3316. '&sup;' => '&#8835;',
  3317. '&nsub;' => '&#8836;',
  3318. '&sube;' => '&#8838;',
  3319. '&supe;' => '&#8839;',
  3320. '&oplus;' => '&#8853;',
  3321. '&otimes;' => '&#8855;',
  3322. '&perp;' => '&#8869;',
  3323. '&sdot;' => '&#8901;',
  3324. '&lceil;' => '&#8968;',
  3325. '&rceil;' => '&#8969;',
  3326. '&lfloor;' => '&#8970;',
  3327. '&rfloor;' => '&#8971;',
  3328. '&lang;' => '&#9001;',
  3329. '&rang;' => '&#9002;',
  3330. '&larr;' => '&#8592;',
  3331. '&uarr;' => '&#8593;',
  3332. '&rarr;' => '&#8594;',
  3333. '&darr;' => '&#8595;',
  3334. '&harr;' => '&#8596;',
  3335. '&loz;' => '&#9674;',
  3336. '&spades;' => '&#9824;',
  3337. '&clubs;' => '&#9827;',
  3338. '&hearts;' => '&#9829;',
  3339. '&diams;' => '&#9830;'
  3340. );
  3341. return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
  3342. }
  3343. /**
  3344. * Formats text for the editor.
  3345. *
  3346. * Generally the browsers treat everything inside a textarea as text, but
  3347. * it is still a good idea to HTML entity encode `<`, `>` and `&` in the content.
  3348. *
  3349. * The filter {@see 'format_for_editor'} is applied here. If `$text` is empty the
  3350. * filter will be applied to an empty string.
  3351. *
  3352. * @since 4.3.0
  3353. *
  3354. * @see _WP_Editors::editor()
  3355. *
  3356. * @param string $text The text to be formatted.
  3357. * @param string $default_editor The default editor for the current user.
  3358. * It is usually either 'html' or 'tinymce'.
  3359. * @return string The formatted text after filter is applied.
  3360. */
  3361. function format_for_editor( $text, $default_editor = null ) {
  3362. if ( $text ) {
  3363. $text = htmlspecialchars( $text, ENT_NOQUOTES, get_option( 'blog_charset' ) );
  3364. }
  3365. /**
  3366. * Filters the text after it is formatted for the editor.
  3367. *
  3368. * @since 4.3.0
  3369. *
  3370. * @param string $text The formatted text.
  3371. * @param string $default_editor The default editor for the current user.
  3372. * It is usually either 'html' or 'tinymce'.
  3373. */
  3374. return apply_filters( 'format_for_editor', $text, $default_editor );
  3375. }
  3376. /**
  3377. * Perform a deep string replace operation to ensure the values in $search are no longer present
  3378. *
  3379. * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
  3380. * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
  3381. * str_replace would return
  3382. *
  3383. * @since 2.8.1
  3384. * @access private
  3385. *
  3386. * @param string|array $search The value being searched for, otherwise known as the needle.
  3387. * An array may be used to designate multiple needles.
  3388. * @param string $subject The string being searched and replaced on, otherwise known as the haystack.
  3389. * @return string The string with the replaced svalues.
  3390. */
  3391. function _deep_replace( $search, $subject ) {
  3392. $subject = (string) $subject;
  3393. $count = 1;
  3394. while ( $count ) {
  3395. $subject = str_replace( $search, '', $subject, $count );
  3396. }
  3397. return $subject;
  3398. }
  3399. /**
  3400. * Escapes data for use in a MySQL query.
  3401. *
  3402. * Usually you should prepare queries using wpdb::prepare().
  3403. * Sometimes, spot-escaping is required or useful. One example
  3404. * is preparing an array for use in an IN clause.
  3405. *
  3406. * @since 2.8.0
  3407. *
  3408. * @global wpdb $wpdb WordPress database abstraction object.
  3409. *
  3410. * @param string|array $data Unescaped data
  3411. * @return string|array Escaped data
  3412. */
  3413. function esc_sql( $data ) {
  3414. global $wpdb;
  3415. return $wpdb->_escape( $data );
  3416. }
  3417. /**
  3418. * Checks and cleans a URL.
  3419. *
  3420. * A number of characters are removed from the URL. If the URL is for displaying
  3421. * (the default behaviour) ampersands are also replaced. The {@see 'clean_url'} filter
  3422. * is applied to the returned cleaned URL.
  3423. *
  3424. * @since 2.8.0
  3425. *
  3426. * @param string $url The URL to be cleaned.
  3427. * @param array $protocols Optional. An array of acceptable protocols.
  3428. * Defaults to return value of wp_allowed_protocols()
  3429. * @param string $_context Private. Use esc_url_raw() for database usage.
  3430. * @return string The cleaned $url after the {@see 'clean_url'} filter is applied.
  3431. */
  3432. function esc_url( $url, $protocols = null, $_context = 'display' ) {
  3433. $original_url = $url;
  3434. if ( '' == $url )
  3435. return $url;
  3436. $url = str_replace( ' ', '%20', $url );
  3437. $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\[\]\\x80-\\xff]|i', '', $url);
  3438. if ( '' === $url ) {
  3439. return $url;
  3440. }
  3441. if ( 0 !== stripos( $url, 'mailto:' ) ) {
  3442. $strip = array('%0d', '%0a', '%0D', '%0A');
  3443. $url = _deep_replace($strip, $url);
  3444. }
  3445. $url = str_replace(';//', '://', $url);
  3446. /* If the URL doesn't appear to contain a scheme, we
  3447. * presume it needs http:// prepended (unless a relative
  3448. * link starting with /, # or ? or a php file).
  3449. */
  3450. if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
  3451. ! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
  3452. $url = 'http://' . $url;
  3453. // Replace ampersands and single quotes only when displaying.
  3454. if ( 'display' == $_context ) {
  3455. $url = wp_kses_normalize_entities( $url );
  3456. $url = str_replace( '&amp;', '&#038;', $url );
  3457. $url = str_replace( "'", '&#039;', $url );
  3458. }
  3459. if ( ( false !== strpos( $url, '[' ) ) || ( false !== strpos( $url, ']' ) ) ) {
  3460. $parsed = wp_parse_url( $url );
  3461. $front = '';
  3462. if ( isset( $parsed['scheme'] ) ) {
  3463. $front .= $parsed['scheme'] . '://';
  3464. } elseif ( '/' === $url[0] ) {
  3465. $front .= '//';
  3466. }
  3467. if ( isset( $parsed['user'] ) ) {
  3468. $front .= $parsed['user'];
  3469. }
  3470. if ( isset( $parsed['pass'] ) ) {
  3471. $front .= ':' . $parsed['pass'];
  3472. }
  3473. if ( isset( $parsed['user'] ) || isset( $parsed['pass'] ) ) {
  3474. $front .= '@';
  3475. }
  3476. if ( isset( $parsed['host'] ) ) {
  3477. $front .= $parsed['host'];
  3478. }
  3479. if ( isset( $parsed['port'] ) ) {
  3480. $front .= ':' . $parsed['port'];
  3481. }
  3482. $end_dirty = str_replace( $front, '', $url );
  3483. $end_clean = str_replace( array( '[', ']' ), array( '%5B', '%5D' ), $end_dirty );
  3484. $url = str_replace( $end_dirty, $end_clean, $url );
  3485. }
  3486. if ( '/' === $url[0] ) {
  3487. $good_protocol_url = $url;
  3488. } else {
  3489. if ( ! is_array( $protocols ) )
  3490. $protocols = wp_allowed_protocols();
  3491. $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
  3492. if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
  3493. return '';
  3494. }
  3495. /**
  3496. * Filters a string cleaned and escaped for output as a URL.
  3497. *
  3498. * @since 2.3.0
  3499. *
  3500. * @param string $good_protocol_url The cleaned URL to be returned.
  3501. * @param string $original_url The URL prior to cleaning.
  3502. * @param string $_context If 'display', replace ampersands and single quotes only.
  3503. */
  3504. return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
  3505. }
  3506. /**
  3507. * Performs esc_url() for database usage.
  3508. *
  3509. * @since 2.8.0
  3510. *
  3511. * @param string $url The URL to be cleaned.
  3512. * @param array $protocols An array of acceptable protocols.
  3513. * @return string The cleaned URL.
  3514. */
  3515. function esc_url_raw( $url, $protocols = null ) {
  3516. return esc_url( $url, $protocols, 'db' );
  3517. }
  3518. /**
  3519. * Convert entities, while preserving already-encoded entities.
  3520. *
  3521. * @link https://secure.php.net/htmlentities Borrowed from the PHP Manual user notes.
  3522. *
  3523. * @since 1.2.2
  3524. *
  3525. * @param string $myHTML The text to be converted.
  3526. * @return string Converted text.
  3527. */
  3528. function htmlentities2( $myHTML ) {
  3529. $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
  3530. $translation_table[chr(38)] = '&';
  3531. return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&amp;", strtr($myHTML, $translation_table) );
  3532. }
  3533. /**
  3534. * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
  3535. *
  3536. * Escapes text strings for echoing in JS. It is intended to be used for inline JS
  3537. * (in a tag attribute, for example onclick="..."). Note that the strings have to
  3538. * be in single quotes. The {@see 'js_escape'} filter is also applied here.
  3539. *
  3540. * @since 2.8.0
  3541. *
  3542. * @param string $text The text to be escaped.
  3543. * @return string Escaped text.
  3544. */
  3545. function esc_js( $text ) {
  3546. $safe_text = wp_check_invalid_utf8( $text );
  3547. $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
  3548. $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
  3549. $safe_text = str_replace( "\r", '', $safe_text );
  3550. $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
  3551. /**
  3552. * Filters a string cleaned and escaped for output in JavaScript.
  3553. *
  3554. * Text passed to esc_js() is stripped of invalid or special characters,
  3555. * and properly slashed for output.
  3556. *
  3557. * @since 2.0.6
  3558. *
  3559. * @param string $safe_text The text after it has been escaped.
  3560. * @param string $text The text prior to being escaped.
  3561. */
  3562. return apply_filters( 'js_escape', $safe_text, $text );
  3563. }
  3564. /**
  3565. * Escaping for HTML blocks.
  3566. *
  3567. * @since 2.8.0
  3568. *
  3569. * @param string $text
  3570. * @return string
  3571. */
  3572. function esc_html( $text ) {
  3573. $safe_text = wp_check_invalid_utf8( $text );
  3574. $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
  3575. /**
  3576. * Filters a string cleaned and escaped for output in HTML.
  3577. *
  3578. * Text passed to esc_html() is stripped of invalid or special characters
  3579. * before output.
  3580. *
  3581. * @since 2.8.0
  3582. *
  3583. * @param string $safe_text The text after it has been escaped.
  3584. * @param string $text The text prior to being escaped.
  3585. */
  3586. return apply_filters( 'esc_html', $safe_text, $text );
  3587. }
  3588. /**
  3589. * Escaping for HTML attributes.
  3590. *
  3591. * @since 2.8.0
  3592. *
  3593. * @param string $text
  3594. * @return string
  3595. */
  3596. function esc_attr( $text ) {
  3597. $safe_text = wp_check_invalid_utf8( $text );
  3598. $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
  3599. /**
  3600. * Filters a string cleaned and escaped for output in an HTML attribute.
  3601. *
  3602. * Text passed to esc_attr() is stripped of invalid or special characters
  3603. * before output.
  3604. *
  3605. * @since 2.0.6
  3606. *
  3607. * @param string $safe_text The text after it has been escaped.
  3608. * @param string $text The text prior to being escaped.
  3609. */
  3610. return apply_filters( 'attribute_escape', $safe_text, $text );
  3611. }
  3612. /**
  3613. * Escaping for textarea values.
  3614. *
  3615. * @since 3.1.0
  3616. *
  3617. * @param string $text
  3618. * @return string
  3619. */
  3620. function esc_textarea( $text ) {
  3621. $safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
  3622. /**
  3623. * Filters a string cleaned and escaped for output in a textarea element.
  3624. *
  3625. * @since 3.1.0
  3626. *
  3627. * @param string $safe_text The text after it has been escaped.
  3628. * @param string $text The text prior to being escaped.
  3629. */
  3630. return apply_filters( 'esc_textarea', $safe_text, $text );
  3631. }
  3632. /**
  3633. * Escape an HTML tag name.
  3634. *
  3635. * @since 2.5.0
  3636. *
  3637. * @param string $tag_name
  3638. * @return string
  3639. */
  3640. function tag_escape( $tag_name ) {
  3641. $safe_tag = strtolower( preg_replace('/[^a-zA-Z0-9_:]/', '', $tag_name) );
  3642. /**
  3643. * Filters a string cleaned and escaped for output as an HTML tag.
  3644. *
  3645. * @since 2.8.0
  3646. *
  3647. * @param string $safe_tag The tag name after it has been escaped.
  3648. * @param string $tag_name The text before it was escaped.
  3649. */
  3650. return apply_filters( 'tag_escape', $safe_tag, $tag_name );
  3651. }
  3652. /**
  3653. * Convert full URL paths to absolute paths.
  3654. *
  3655. * Removes the http or https protocols and the domain. Keeps the path '/' at the
  3656. * beginning, so it isn't a true relative link, but from the web root base.
  3657. *
  3658. * @since 2.1.0
  3659. * @since 4.1.0 Support was added for relative URLs.
  3660. *
  3661. * @param string $link Full URL path.
  3662. * @return string Absolute path.
  3663. */
  3664. function wp_make_link_relative( $link ) {
  3665. return preg_replace( '|^(https?:)?//[^/]+(/?.*)|i', '$2', $link );
  3666. }
  3667. /**
  3668. * Sanitises various option values based on the nature of the option.
  3669. *
  3670. * This is basically a switch statement which will pass $value through a number
  3671. * of functions depending on the $option.
  3672. *
  3673. * @since 2.0.5
  3674. *
  3675. * @global wpdb $wpdb WordPress database abstraction object.
  3676. *
  3677. * @param string $option The name of the option.
  3678. * @param string $value The unsanitised value.
  3679. * @return string Sanitized value.
  3680. */
  3681. function sanitize_option( $option, $value ) {
  3682. global $wpdb;
  3683. $original_value = $value;
  3684. $error = '';
  3685. switch ( $option ) {
  3686. case 'admin_email' :
  3687. case 'new_admin_email' :
  3688. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
  3689. if ( is_wp_error( $value ) ) {
  3690. $error = $value->get_error_message();
  3691. } else {
  3692. $value = sanitize_email( $value );
  3693. if ( ! is_email( $value ) ) {
  3694. $error = __( 'The email address entered did not appear to be a valid email address. Please enter a valid email address.' );
  3695. }
  3696. }
  3697. break;
  3698. case 'thumbnail_size_w':
  3699. case 'thumbnail_size_h':
  3700. case 'medium_size_w':
  3701. case 'medium_size_h':
  3702. case 'medium_large_size_w':
  3703. case 'medium_large_size_h':
  3704. case 'large_size_w':
  3705. case 'large_size_h':
  3706. case 'mailserver_port':
  3707. case 'comment_max_links':
  3708. case 'page_on_front':
  3709. case 'page_for_posts':
  3710. case 'rss_excerpt_length':
  3711. case 'default_category':
  3712. case 'default_email_category':
  3713. case 'default_link_category':
  3714. case 'close_comments_days_old':
  3715. case 'comments_per_page':
  3716. case 'thread_comments_depth':
  3717. case 'users_can_register':
  3718. case 'start_of_week':
  3719. case 'site_icon':
  3720. $value = absint( $value );
  3721. break;
  3722. case 'posts_per_page':
  3723. case 'posts_per_rss':
  3724. $value = (int) $value;
  3725. if ( empty($value) )
  3726. $value = 1;
  3727. if ( $value < -1 )
  3728. $value = abs($value);
  3729. break;
  3730. case 'default_ping_status':
  3731. case 'default_comment_status':
  3732. // Options that if not there have 0 value but need to be something like "closed"
  3733. if ( $value == '0' || $value == '')
  3734. $value = 'closed';
  3735. break;
  3736. case 'blogdescription':
  3737. case 'blogname':
  3738. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
  3739. if ( $value !== $original_value ) {
  3740. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', wp_encode_emoji( $original_value ) );
  3741. }
  3742. if ( is_wp_error( $value ) ) {
  3743. $error = $value->get_error_message();
  3744. } else {
  3745. $value = esc_html( $value );
  3746. }
  3747. break;
  3748. case 'blog_charset':
  3749. $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
  3750. break;
  3751. case 'blog_public':
  3752. // This is the value if the settings checkbox is not checked on POST. Don't rely on this.
  3753. if ( null === $value )
  3754. $value = 1;
  3755. else
  3756. $value = intval( $value );
  3757. break;
  3758. case 'date_format':
  3759. case 'time_format':
  3760. case 'mailserver_url':
  3761. case 'mailserver_login':
  3762. case 'mailserver_pass':
  3763. case 'upload_path':
  3764. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
  3765. if ( is_wp_error( $value ) ) {
  3766. $error = $value->get_error_message();
  3767. } else {
  3768. $value = strip_tags( $value );
  3769. $value = wp_kses_data( $value );
  3770. }
  3771. break;
  3772. case 'ping_sites':
  3773. $value = explode( "\n", $value );
  3774. $value = array_filter( array_map( 'trim', $value ) );
  3775. $value = array_filter( array_map( 'esc_url_raw', $value ) );
  3776. $value = implode( "\n", $value );
  3777. break;
  3778. case 'gmt_offset':
  3779. $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
  3780. break;
  3781. case 'siteurl':
  3782. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
  3783. if ( is_wp_error( $value ) ) {
  3784. $error = $value->get_error_message();
  3785. } else {
  3786. if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
  3787. $value = esc_url_raw( $value );
  3788. } else {
  3789. $error = __( 'The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.' );
  3790. }
  3791. }
  3792. break;
  3793. case 'home':
  3794. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
  3795. if ( is_wp_error( $value ) ) {
  3796. $error = $value->get_error_message();
  3797. } else {
  3798. if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
  3799. $value = esc_url_raw( $value );
  3800. } else {
  3801. $error = __( 'The Site address you entered did not appear to be a valid URL. Please enter a valid URL.' );
  3802. }
  3803. }
  3804. break;
  3805. case 'WPLANG':
  3806. $allowed = get_available_languages();
  3807. if ( ! is_multisite() && defined( 'WPLANG' ) && '' !== WPLANG && 'en_US' !== WPLANG ) {
  3808. $allowed[] = WPLANG;
  3809. }
  3810. if ( ! in_array( $value, $allowed ) && ! empty( $value ) ) {
  3811. $value = get_option( $option );
  3812. }
  3813. break;
  3814. case 'illegal_names':
  3815. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
  3816. if ( is_wp_error( $value ) ) {
  3817. $error = $value->get_error_message();
  3818. } else {
  3819. if ( ! is_array( $value ) )
  3820. $value = explode( ' ', $value );
  3821. $value = array_values( array_filter( array_map( 'trim', $value ) ) );
  3822. if ( ! $value )
  3823. $value = '';
  3824. }
  3825. break;
  3826. case 'limited_email_domains':
  3827. case 'banned_email_domains':
  3828. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
  3829. if ( is_wp_error( $value ) ) {
  3830. $error = $value->get_error_message();
  3831. } else {
  3832. if ( ! is_array( $value ) )
  3833. $value = explode( "\n", $value );
  3834. $domains = array_values( array_filter( array_map( 'trim', $value ) ) );
  3835. $value = array();
  3836. foreach ( $domains as $domain ) {
  3837. if ( ! preg_match( '/(--|\.\.)/', $domain ) && preg_match( '|^([a-zA-Z0-9-\.])+$|', $domain ) ) {
  3838. $value[] = $domain;
  3839. }
  3840. }
  3841. if ( ! $value )
  3842. $value = '';
  3843. }
  3844. break;
  3845. case 'timezone_string':
  3846. $allowed_zones = timezone_identifiers_list();
  3847. if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
  3848. $error = __( 'The timezone you have entered is not valid. Please select a valid timezone.' );
  3849. }
  3850. break;
  3851. case 'permalink_structure':
  3852. case 'category_base':
  3853. case 'tag_base':
  3854. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
  3855. if ( is_wp_error( $value ) ) {
  3856. $error = $value->get_error_message();
  3857. } else {
  3858. $value = esc_url_raw( $value );
  3859. $value = str_replace( 'http://', '', $value );
  3860. }
  3861. if ( 'permalink_structure' === $option && '' !== $value && ! preg_match( '/%[^\/%]+%/', $value ) ) {
  3862. $error = sprintf(
  3863. /* translators: %s: Codex URL */
  3864. __( 'A structure tag is required when using custom permalinks. <a href="%s">Learn more</a>' ),
  3865. __( 'https://codex.wordpress.org/Using_Permalinks#Choosing_your_permalink_structure' )
  3866. );
  3867. }
  3868. break;
  3869. case 'default_role' :
  3870. if ( ! get_role( $value ) && get_role( 'subscriber' ) )
  3871. $value = 'subscriber';
  3872. break;
  3873. case 'moderation_keys':
  3874. case 'blacklist_keys':
  3875. $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
  3876. if ( is_wp_error( $value ) ) {
  3877. $error = $value->get_error_message();
  3878. } else {
  3879. $value = explode( "\n", $value );
  3880. $value = array_filter( array_map( 'trim', $value ) );
  3881. $value = array_unique( $value );
  3882. $value = implode( "\n", $value );
  3883. }
  3884. break;
  3885. }
  3886. if ( ! empty( $error ) ) {
  3887. $value = get_option( $option );
  3888. if ( function_exists( 'add_settings_error' ) ) {
  3889. add_settings_error( $option, "invalid_{$option}", $error );
  3890. }
  3891. }
  3892. /**
  3893. * Filters an option value following sanitization.
  3894. *
  3895. * @since 2.3.0
  3896. * @since 4.3.0 Added the `$original_value` parameter.
  3897. *
  3898. * @param string $value The sanitized option value.
  3899. * @param string $option The option name.
  3900. * @param string $original_value The original value passed to the function.
  3901. */
  3902. return apply_filters( "sanitize_option_{$option}", $value, $option, $original_value );
  3903. }
  3904. /**
  3905. * Maps a function to all non-iterable elements of an array or an object.
  3906. *
  3907. * This is similar to `array_walk_recursive()` but acts upon objects too.
  3908. *
  3909. * @since 4.4.0
  3910. *
  3911. * @param mixed $value The array, object, or scalar.
  3912. * @param callable $callback The function to map onto $value.
  3913. * @return mixed The value with the callback applied to all non-arrays and non-objects inside it.
  3914. */
  3915. function map_deep( $value, $callback ) {
  3916. if ( is_array( $value ) ) {
  3917. foreach ( $value as $index => $item ) {
  3918. $value[ $index ] = map_deep( $item, $callback );
  3919. }
  3920. } elseif ( is_object( $value ) ) {
  3921. $object_vars = get_object_vars( $value );
  3922. foreach ( $object_vars as $property_name => $property_value ) {
  3923. $value->$property_name = map_deep( $property_value, $callback );
  3924. }
  3925. } else {
  3926. $value = call_user_func( $callback, $value );
  3927. }
  3928. return $value;
  3929. }
  3930. /**
  3931. * Parses a string into variables to be stored in an array.
  3932. *
  3933. * Uses {@link https://secure.php.net/parse_str parse_str()} and stripslashes if
  3934. * {@link https://secure.php.net/magic_quotes magic_quotes_gpc} is on.
  3935. *
  3936. * @since 2.2.1
  3937. *
  3938. * @param string $string The string to be parsed.
  3939. * @param array $array Variables will be stored in this array.
  3940. */
  3941. function wp_parse_str( $string, &$array ) {
  3942. parse_str( $string, $array );
  3943. if ( get_magic_quotes_gpc() )
  3944. $array = stripslashes_deep( $array );
  3945. /**
  3946. * Filters the array of variables derived from a parsed string.
  3947. *
  3948. * @since 2.3.0
  3949. *
  3950. * @param array $array The array populated with variables.
  3951. */
  3952. $array = apply_filters( 'wp_parse_str', $array );
  3953. }
  3954. /**
  3955. * Convert lone less than signs.
  3956. *
  3957. * KSES already converts lone greater than signs.
  3958. *
  3959. * @since 2.3.0
  3960. *
  3961. * @param string $text Text to be converted.
  3962. * @return string Converted text.
  3963. */
  3964. function wp_pre_kses_less_than( $text ) {
  3965. return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
  3966. }
  3967. /**
  3968. * Callback function used by preg_replace.
  3969. *
  3970. * @since 2.3.0
  3971. *
  3972. * @param array $matches Populated by matches to preg_replace.
  3973. * @return string The text returned after esc_html if needed.
  3974. */
  3975. function wp_pre_kses_less_than_callback( $matches ) {
  3976. if ( false === strpos($matches[0], '>') )
  3977. return esc_html($matches[0]);
  3978. return $matches[0];
  3979. }
  3980. /**
  3981. * WordPress implementation of PHP sprintf() with filters.
  3982. *
  3983. * @since 2.5.0
  3984. * @link https://secure.php.net/sprintf
  3985. *
  3986. * @param string $pattern The string which formatted args are inserted.
  3987. * @param mixed $args ,... Arguments to be formatted into the $pattern string.
  3988. * @return string The formatted string.
  3989. */
  3990. function wp_sprintf( $pattern ) {
  3991. $args = func_get_args();
  3992. $len = strlen($pattern);
  3993. $start = 0;
  3994. $result = '';
  3995. $arg_index = 0;
  3996. while ( $len > $start ) {
  3997. // Last character: append and break
  3998. if ( strlen($pattern) - 1 == $start ) {
  3999. $result .= substr($pattern, -1);
  4000. break;
  4001. }
  4002. // Literal %: append and continue
  4003. if ( substr($pattern, $start, 2) == '%%' ) {
  4004. $start += 2;
  4005. $result .= '%';
  4006. continue;
  4007. }
  4008. // Get fragment before next %
  4009. $end = strpos($pattern, '%', $start + 1);
  4010. if ( false === $end )
  4011. $end = $len;
  4012. $fragment = substr($pattern, $start, $end - $start);
  4013. // Fragment has a specifier
  4014. if ( $pattern[$start] == '%' ) {
  4015. // Find numbered arguments or take the next one in order
  4016. if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
  4017. $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
  4018. $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
  4019. } else {
  4020. ++$arg_index;
  4021. $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
  4022. }
  4023. /**
  4024. * Filters a fragment from the pattern passed to wp_sprintf().
  4025. *
  4026. * If the fragment is unchanged, then sprintf() will be run on the fragment.
  4027. *
  4028. * @since 2.5.0
  4029. *
  4030. * @param string $fragment A fragment from the pattern.
  4031. * @param string $arg The argument.
  4032. */
  4033. $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
  4034. if ( $_fragment != $fragment )
  4035. $fragment = $_fragment;
  4036. else
  4037. $fragment = sprintf($fragment, strval($arg) );
  4038. }
  4039. // Append to result and move to next fragment
  4040. $result .= $fragment;
  4041. $start = $end;
  4042. }
  4043. return $result;
  4044. }
  4045. /**
  4046. * Localize list items before the rest of the content.
  4047. *
  4048. * The '%l' must be at the first characters can then contain the rest of the
  4049. * content. The list items will have ', ', ', and', and ' and ' added depending
  4050. * on the amount of list items in the $args parameter.
  4051. *
  4052. * @since 2.5.0
  4053. *
  4054. * @param string $pattern Content containing '%l' at the beginning.
  4055. * @param array $args List items to prepend to the content and replace '%l'.
  4056. * @return string Localized list items and rest of the content.
  4057. */
  4058. function wp_sprintf_l( $pattern, $args ) {
  4059. // Not a match
  4060. if ( substr($pattern, 0, 2) != '%l' )
  4061. return $pattern;
  4062. // Nothing to work with
  4063. if ( empty($args) )
  4064. return '';
  4065. /**
  4066. * Filters the translated delimiters used by wp_sprintf_l().
  4067. * Placeholders (%s) are included to assist translators and then
  4068. * removed before the array of strings reaches the filter.
  4069. *
  4070. * Please note: Ampersands and entities should be avoided here.
  4071. *
  4072. * @since 2.5.0
  4073. *
  4074. * @param array $delimiters An array of translated delimiters.
  4075. */
  4076. $l = apply_filters( 'wp_sprintf_l', array(
  4077. /* translators: used to join items in a list with more than 2 items */
  4078. 'between' => sprintf( __('%s, %s'), '', '' ),
  4079. /* translators: used to join last two items in a list with more than 2 times */
  4080. 'between_last_two' => sprintf( __('%s, and %s'), '', '' ),
  4081. /* translators: used to join items in a list with only 2 items */
  4082. 'between_only_two' => sprintf( __('%s and %s'), '', '' ),
  4083. ) );
  4084. $args = (array) $args;
  4085. $result = array_shift($args);
  4086. if ( count($args) == 1 )
  4087. $result .= $l['between_only_two'] . array_shift($args);
  4088. // Loop when more than two args
  4089. $i = count($args);
  4090. while ( $i ) {
  4091. $arg = array_shift($args);
  4092. $i--;
  4093. if ( 0 == $i )
  4094. $result .= $l['between_last_two'] . $arg;
  4095. else
  4096. $result .= $l['between'] . $arg;
  4097. }
  4098. return $result . substr($pattern, 2);
  4099. }
  4100. /**
  4101. * Safely extracts not more than the first $count characters from html string.
  4102. *
  4103. * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
  4104. * be counted as one character. For example &amp; will be counted as 4, &lt; as
  4105. * 3, etc.
  4106. *
  4107. * @since 2.5.0
  4108. *
  4109. * @param string $str String to get the excerpt from.
  4110. * @param int $count Maximum number of characters to take.
  4111. * @param string $more Optional. What to append if $str needs to be trimmed. Defaults to empty string.
  4112. * @return string The excerpt.
  4113. */
  4114. function wp_html_excerpt( $str, $count, $more = null ) {
  4115. if ( null === $more )
  4116. $more = '';
  4117. $str = wp_strip_all_tags( $str, true );
  4118. $excerpt = mb_substr( $str, 0, $count );
  4119. // remove part of an entity at the end
  4120. $excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );
  4121. if ( $str != $excerpt )
  4122. $excerpt = trim( $excerpt ) . $more;
  4123. return $excerpt;
  4124. }
  4125. /**
  4126. * Add a Base url to relative links in passed content.
  4127. *
  4128. * By default it supports the 'src' and 'href' attributes. However this can be
  4129. * changed via the 3rd param.
  4130. *
  4131. * @since 2.7.0
  4132. *
  4133. * @global string $_links_add_base
  4134. *
  4135. * @param string $content String to search for links in.
  4136. * @param string $base The base URL to prefix to links.
  4137. * @param array $attrs The attributes which should be processed.
  4138. * @return string The processed content.
  4139. */
  4140. function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
  4141. global $_links_add_base;
  4142. $_links_add_base = $base;
  4143. $attrs = implode('|', (array)$attrs);
  4144. return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
  4145. }
  4146. /**
  4147. * Callback to add a base url to relative links in passed content.
  4148. *
  4149. * @since 2.7.0
  4150. * @access private
  4151. *
  4152. * @global string $_links_add_base
  4153. *
  4154. * @param string $m The matched link.
  4155. * @return string The processed link.
  4156. */
  4157. function _links_add_base( $m ) {
  4158. global $_links_add_base;
  4159. //1 = attribute name 2 = quotation mark 3 = URL
  4160. return $m[1] . '=' . $m[2] .
  4161. ( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ?
  4162. $m[3] :
  4163. WP_Http::make_absolute_url( $m[3], $_links_add_base )
  4164. )
  4165. . $m[2];
  4166. }
  4167. /**
  4168. * Adds a Target attribute to all links in passed content.
  4169. *
  4170. * This function by default only applies to `<a>` tags, however this can be
  4171. * modified by the 3rd param.
  4172. *
  4173. * *NOTE:* Any current target attributed will be stripped and replaced.
  4174. *
  4175. * @since 2.7.0
  4176. *
  4177. * @global string $_links_add_target
  4178. *
  4179. * @param string $content String to search for links in.
  4180. * @param string $target The Target to add to the links.
  4181. * @param array $tags An array of tags to apply to.
  4182. * @return string The processed content.
  4183. */
  4184. function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
  4185. global $_links_add_target;
  4186. $_links_add_target = $target;
  4187. $tags = implode('|', (array)$tags);
  4188. return preg_replace_callback( "!<($tags)([^>]*)>!i", '_links_add_target', $content );
  4189. }
  4190. /**
  4191. * Callback to add a target attribute to all links in passed content.
  4192. *
  4193. * @since 2.7.0
  4194. * @access private
  4195. *
  4196. * @global string $_links_add_target
  4197. *
  4198. * @param string $m The matched link.
  4199. * @return string The processed link.
  4200. */
  4201. function _links_add_target( $m ) {
  4202. global $_links_add_target;
  4203. $tag = $m[1];
  4204. $link = preg_replace('|( target=([\'"])(.*?)\2)|i', '', $m[2]);
  4205. return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
  4206. }
  4207. /**
  4208. * Normalize EOL characters and strip duplicate whitespace.
  4209. *
  4210. * @since 2.7.0
  4211. *
  4212. * @param string $str The string to normalize.
  4213. * @return string The normalized string.
  4214. */
  4215. function normalize_whitespace( $str ) {
  4216. $str = trim( $str );
  4217. $str = str_replace( "\r", "\n", $str );
  4218. $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
  4219. return $str;
  4220. }
  4221. /**
  4222. * Properly strip all HTML tags including script and style
  4223. *
  4224. * This differs from strip_tags() because it removes the contents of
  4225. * the `<script>` and `<style>` tags. E.g. `strip_tags( '<script>something</script>' )`
  4226. * will return 'something'. wp_strip_all_tags will return ''
  4227. *
  4228. * @since 2.9.0
  4229. *
  4230. * @param string $string String containing HTML tags
  4231. * @param bool $remove_breaks Optional. Whether to remove left over line breaks and white space chars
  4232. * @return string The processed string.
  4233. */
  4234. function wp_strip_all_tags($string, $remove_breaks = false) {
  4235. $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
  4236. $string = strip_tags($string);
  4237. if ( $remove_breaks )
  4238. $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
  4239. return trim( $string );
  4240. }
  4241. /**
  4242. * Sanitizes a string from user input or from the database.
  4243. *
  4244. * - Checks for invalid UTF-8,
  4245. * - Converts single `<` characters to entities
  4246. * - Strips all tags
  4247. * - Removes line breaks, tabs, and extra whitespace
  4248. * - Strips octets
  4249. *
  4250. * @since 2.9.0
  4251. *
  4252. * @see sanitize_textarea_field()
  4253. * @see wp_check_invalid_utf8()
  4254. * @see wp_strip_all_tags()
  4255. *
  4256. * @param string $str String to sanitize.
  4257. * @return string Sanitized string.
  4258. */
  4259. function sanitize_text_field( $str ) {
  4260. $filtered = _sanitize_text_fields( $str, false );
  4261. /**
  4262. * Filters a sanitized text field string.
  4263. *
  4264. * @since 2.9.0
  4265. *
  4266. * @param string $filtered The sanitized string.
  4267. * @param string $str The string prior to being sanitized.
  4268. */
  4269. return apply_filters( 'sanitize_text_field', $filtered, $str );
  4270. }
  4271. /**
  4272. * Sanitizes a multiline string from user input or from the database.
  4273. *
  4274. * The function is like sanitize_text_field(), but preserves
  4275. * new lines (\n) and other whitespace, which are legitimate
  4276. * input in textarea elements.
  4277. *
  4278. * @see sanitize_text_field()
  4279. *
  4280. * @since 4.7.0
  4281. *
  4282. * @param string $str String to sanitize.
  4283. * @return string Sanitized string.
  4284. */
  4285. function sanitize_textarea_field( $str ) {
  4286. $filtered = _sanitize_text_fields( $str, true );
  4287. /**
  4288. * Filters a sanitized textarea field string.
  4289. *
  4290. * @since 4.7.0
  4291. *
  4292. * @param string $filtered The sanitized string.
  4293. * @param string $str The string prior to being sanitized.
  4294. */
  4295. return apply_filters( 'sanitize_textarea_field', $filtered, $str );
  4296. }
  4297. /**
  4298. * Internal helper function to sanitize a string from user input or from the db
  4299. *
  4300. * @since 4.7.0
  4301. * @access private
  4302. *
  4303. * @param string $str String to sanitize.
  4304. * @param bool $keep_newlines optional Whether to keep newlines. Default: false.
  4305. * @return string Sanitized string.
  4306. */
  4307. function _sanitize_text_fields( $str, $keep_newlines = false ) {
  4308. $filtered = wp_check_invalid_utf8( $str );
  4309. if ( strpos($filtered, '<') !== false ) {
  4310. $filtered = wp_pre_kses_less_than( $filtered );
  4311. // This will strip extra whitespace for us.
  4312. $filtered = wp_strip_all_tags( $filtered, false );
  4313. // Use html entities in a special case to make sure no later
  4314. // newline stripping stage could lead to a functional tag
  4315. $filtered = str_replace("<\n", "&lt;\n", $filtered);
  4316. }
  4317. if ( ! $keep_newlines ) {
  4318. $filtered = preg_replace( '/[\r\n\t ]+/', ' ', $filtered );
  4319. }
  4320. $filtered = trim( $filtered );
  4321. $found = false;
  4322. while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
  4323. $filtered = str_replace($match[0], '', $filtered);
  4324. $found = true;
  4325. }
  4326. if ( $found ) {
  4327. // Strip out the whitespace that may now exist after removing the octets.
  4328. $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
  4329. }
  4330. return $filtered;
  4331. }
  4332. /**
  4333. * i18n friendly version of basename()
  4334. *
  4335. * @since 3.1.0
  4336. *
  4337. * @param string $path A path.
  4338. * @param string $suffix If the filename ends in suffix this will also be cut off.
  4339. * @return string
  4340. */
  4341. function wp_basename( $path, $suffix = '' ) {
  4342. return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) );
  4343. }
  4344. /**
  4345. * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
  4346. *
  4347. * Violating our coding standards for a good function name.
  4348. *
  4349. * @since 3.0.0
  4350. *
  4351. * @staticvar string|false $dblq
  4352. *
  4353. * @param string $text The text to be modified.
  4354. * @return string The modified text.
  4355. */
  4356. function capital_P_dangit( $text ) {
  4357. // Simple replacement for titles
  4358. $current_filter = current_filter();
  4359. if ( 'the_title' === $current_filter || 'wp_title' === $current_filter )
  4360. return str_replace( 'Wordpress', 'WordPress', $text );
  4361. // Still here? Use the more judicious replacement
  4362. static $dblq = false;
  4363. if ( false === $dblq ) {
  4364. $dblq = _x( '&#8220;', 'opening curly double quote' );
  4365. }
  4366. return str_replace(
  4367. array( ' Wordpress', '&#8216;Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
  4368. array( ' WordPress', '&#8216;WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
  4369. $text );
  4370. }
  4371. /**
  4372. * Sanitize a mime type
  4373. *
  4374. * @since 3.1.3
  4375. *
  4376. * @param string $mime_type Mime type
  4377. * @return string Sanitized mime type
  4378. */
  4379. function sanitize_mime_type( $mime_type ) {
  4380. $sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type );
  4381. /**
  4382. * Filters a mime type following sanitization.
  4383. *
  4384. * @since 3.1.3
  4385. *
  4386. * @param string $sani_mime_type The sanitized mime type.
  4387. * @param string $mime_type The mime type prior to sanitization.
  4388. */
  4389. return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );
  4390. }
  4391. /**
  4392. * Sanitize space or carriage return separated URLs that are used to send trackbacks.
  4393. *
  4394. * @since 3.4.0
  4395. *
  4396. * @param string $to_ping Space or carriage return separated URLs
  4397. * @return string URLs starting with the http or https protocol, separated by a carriage return.
  4398. */
  4399. function sanitize_trackback_urls( $to_ping ) {
  4400. $urls_to_ping = preg_split( '/[\r\n\t ]/', trim( $to_ping ), -1, PREG_SPLIT_NO_EMPTY );
  4401. foreach ( $urls_to_ping as $k => $url ) {
  4402. if ( !preg_match( '#^https?://.#i', $url ) )
  4403. unset( $urls_to_ping[$k] );
  4404. }
  4405. $urls_to_ping = array_map( 'esc_url_raw', $urls_to_ping );
  4406. $urls_to_ping = implode( "\n", $urls_to_ping );
  4407. /**
  4408. * Filters a list of trackback URLs following sanitization.
  4409. *
  4410. * The string returned here consists of a space or carriage return-delimited list
  4411. * of trackback URLs.
  4412. *
  4413. * @since 3.4.0
  4414. *
  4415. * @param string $urls_to_ping Sanitized space or carriage return separated URLs.
  4416. * @param string $to_ping Space or carriage return separated URLs before sanitization.
  4417. */
  4418. return apply_filters( 'sanitize_trackback_urls', $urls_to_ping, $to_ping );
  4419. }
  4420. /**
  4421. * Add slashes to a string or array of strings.
  4422. *
  4423. * This should be used when preparing data for core API that expects slashed data.
  4424. * This should not be used to escape data going directly into an SQL query.
  4425. *
  4426. * @since 3.6.0
  4427. *
  4428. * @param string|array $value String or array of strings to slash.
  4429. * @return string|array Slashed $value
  4430. */
  4431. function wp_slash( $value ) {
  4432. if ( is_array( $value ) ) {
  4433. foreach ( $value as $k => $v ) {
  4434. if ( is_array( $v ) ) {
  4435. $value[$k] = wp_slash( $v );
  4436. } else {
  4437. $value[$k] = addslashes( $v );
  4438. }
  4439. }
  4440. } else {
  4441. $value = addslashes( $value );
  4442. }
  4443. return $value;
  4444. }
  4445. /**
  4446. * Remove slashes from a string or array of strings.
  4447. *
  4448. * This should be used to remove slashes from data passed to core API that
  4449. * expects data to be unslashed.
  4450. *
  4451. * @since 3.6.0
  4452. *
  4453. * @param string|array $value String or array of strings to unslash.
  4454. * @return string|array Unslashed $value
  4455. */
  4456. function wp_unslash( $value ) {
  4457. return stripslashes_deep( $value );
  4458. }
  4459. /**
  4460. * Extract and return the first URL from passed content.
  4461. *
  4462. * @since 3.6.0
  4463. *
  4464. * @param string $content A string which might contain a URL.
  4465. * @return string|false The found URL.
  4466. */
  4467. function get_url_in_content( $content ) {
  4468. if ( empty( $content ) ) {
  4469. return false;
  4470. }
  4471. if ( preg_match( '/<a\s[^>]*?href=([\'"])(.+?)\1/is', $content, $matches ) ) {
  4472. return esc_url_raw( $matches[2] );
  4473. }
  4474. return false;
  4475. }
  4476. /**
  4477. * Returns the regexp for common whitespace characters.
  4478. *
  4479. * By default, spaces include new lines, tabs, nbsp entities, and the UTF-8 nbsp.
  4480. * This is designed to replace the PCRE \s sequence. In ticket #22692, that
  4481. * sequence was found to be unreliable due to random inclusion of the A0 byte.
  4482. *
  4483. * @since 4.0.0
  4484. *
  4485. * @staticvar string $spaces
  4486. *
  4487. * @return string The spaces regexp.
  4488. */
  4489. function wp_spaces_regexp() {
  4490. static $spaces = '';
  4491. if ( empty( $spaces ) ) {
  4492. /**
  4493. * Filters the regexp for common whitespace characters.
  4494. *
  4495. * This string is substituted for the \s sequence as needed in regular
  4496. * expressions. For websites not written in English, different characters
  4497. * may represent whitespace. For websites not encoded in UTF-8, the 0xC2 0xA0
  4498. * sequence may not be in use.
  4499. *
  4500. * @since 4.0.0
  4501. *
  4502. * @param string $spaces Regexp pattern for matching common whitespace characters.
  4503. */
  4504. $spaces = apply_filters( 'wp_spaces_regexp', '[\r\n\t ]|\xC2\xA0|&nbsp;' );
  4505. }
  4506. return $spaces;
  4507. }
  4508. /**
  4509. * Print the important emoji-related styles.
  4510. *
  4511. * @since 4.2.0
  4512. *
  4513. * @staticvar bool $printed
  4514. */
  4515. function print_emoji_styles() {
  4516. static $printed = false;
  4517. if ( $printed ) {
  4518. return;
  4519. }
  4520. $printed = true;
  4521. ?>
  4522. <style type="text/css">
  4523. img.wp-smiley,
  4524. img.emoji {
  4525. display: inline !important;
  4526. border: none !important;
  4527. box-shadow: none !important;
  4528. height: 1em !important;
  4529. width: 1em !important;
  4530. margin: 0 .07em !important;
  4531. vertical-align: -0.1em !important;
  4532. background: none !important;
  4533. padding: 0 !important;
  4534. }
  4535. </style>
  4536. <?php
  4537. }
  4538. /**
  4539. * Print the inline Emoji detection script if it is not already printed.
  4540. *
  4541. * @since 4.2.0
  4542. * @staticvar bool $printed
  4543. */
  4544. function print_emoji_detection_script() {
  4545. static $printed = false;
  4546. if ( $printed ) {
  4547. return;
  4548. }
  4549. $printed = true;
  4550. _print_emoji_detection_script();
  4551. }
  4552. /**
  4553. * Prints inline Emoji dection script
  4554. *
  4555. * @ignore
  4556. * @since 4.6.0
  4557. * @access private
  4558. */
  4559. function _print_emoji_detection_script() {
  4560. $settings = array(
  4561. /**
  4562. * Filters the URL where emoji png images are hosted.
  4563. *
  4564. * @since 4.2.0
  4565. *
  4566. * @param string The emoji base URL for png images.
  4567. */
  4568. 'baseUrl' => apply_filters( 'emoji_url', 'https://s.w.org/images/core/emoji/2.3/72x72/' ),
  4569. /**
  4570. * Filters the extension of the emoji png files.
  4571. *
  4572. * @since 4.2.0
  4573. *
  4574. * @param string The emoji extension for png files. Default .png.
  4575. */
  4576. 'ext' => apply_filters( 'emoji_ext', '.png' ),
  4577. /**
  4578. * Filters the URL where emoji SVG images are hosted.
  4579. *
  4580. * @since 4.6.0
  4581. *
  4582. * @param string The emoji base URL for svg images.
  4583. */
  4584. 'svgUrl' => apply_filters( 'emoji_svg_url', 'https://s.w.org/images/core/emoji/2.3/svg/' ),
  4585. /**
  4586. * Filters the extension of the emoji SVG files.
  4587. *
  4588. * @since 4.6.0
  4589. *
  4590. * @param string The emoji extension for svg files. Default .svg.
  4591. */
  4592. 'svgExt' => apply_filters( 'emoji_svg_ext', '.svg' ),
  4593. );
  4594. $version = 'ver=' . get_bloginfo( 'version' );
  4595. if ( SCRIPT_DEBUG ) {
  4596. $settings['source'] = array(
  4597. /** This filter is documented in wp-includes/class.wp-scripts.php */
  4598. 'wpemoji' => apply_filters( 'script_loader_src', includes_url( "js/wp-emoji.js?$version" ), 'wpemoji' ),
  4599. /** This filter is documented in wp-includes/class.wp-scripts.php */
  4600. 'twemoji' => apply_filters( 'script_loader_src', includes_url( "js/twemoji.js?$version" ), 'twemoji' ),
  4601. );
  4602. ?>
  4603. <script type="text/javascript">
  4604. window._wpemojiSettings = <?php echo wp_json_encode( $settings ); ?>;
  4605. <?php readfile( ABSPATH . WPINC . "/js/wp-emoji-loader.js" ); ?>
  4606. </script>
  4607. <?php
  4608. } else {
  4609. $settings['source'] = array(
  4610. /** This filter is documented in wp-includes/class.wp-scripts.php */
  4611. 'concatemoji' => apply_filters( 'script_loader_src', includes_url( "js/wp-emoji-release.min.js?$version" ), 'concatemoji' ),
  4612. );
  4613. /*
  4614. * If you're looking at a src version of this file, you'll see an "include"
  4615. * statement below. This is used by the `grunt build` process to directly
  4616. * include a minified version of wp-emoji-loader.js, instead of using the
  4617. * readfile() method from above.
  4618. *
  4619. * If you're looking at a build version of this file, you'll see a string of
  4620. * minified JavaScript. If you need to debug it, please turn on SCRIPT_DEBUG
  4621. * and edit wp-emoji-loader.js directly.
  4622. */
  4623. ?>
  4624. <script type="text/javascript">
  4625. window._wpemojiSettings = <?php echo wp_json_encode( $settings ); ?>;
  4626. !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),b=j.toDataURL(),k.clearRect(0,0,j.width,j.height),k.fillText(f(55356,56826,8203,55356,56819),0,0),c=j.toDataURL(),b===c&&(k.clearRect(0,0,j.width,j.height),k.fillText(f(55356,57332,56128,56423,56128,56418,56128,56421,56128,56430,56128,56423,56128,56447),0,0),b=j.toDataURL(),k.clearRect(0,0,j.width,j.height),k.fillText(f(55356,57332,8203,56128,56423,8203,56128,56418,8203,56128,56421,8203,56128,56430,8203,56128,56423,8203,56128,56447),0,0),c=j.toDataURL(),b!==c);case"emoji4":return k.fillText(f(55358,56794,8205,9794,65039),0,0),d=j.toDataURL(),k.clearRect(0,0,j.width,j.height),k.fillText(f(55358,56794,8203,9794,65039),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);
  4627. </script>
  4628. <?php
  4629. }
  4630. }
  4631. /**
  4632. * Convert any 4 byte emoji in a string to their equivalent HTML entity.
  4633. *
  4634. * Currently, only Unicode 7 emoji are supported. Skin tone modifiers are allowed,
  4635. * all other Unicode 8 emoji will be added when the spec is finalised.
  4636. *
  4637. * This allows us to store emoji in a DB using the utf8 character set.
  4638. *
  4639. * @since 4.2.0
  4640. *
  4641. * @param string $content The content to encode.
  4642. * @return string The encoded content.
  4643. */
  4644. function wp_encode_emoji( $content ) {
  4645. if ( function_exists( 'mb_convert_encoding' ) ) {
  4646. $regex = '/(
  4647. \x23\xE2\x83\xA3 # Digits
  4648. [\x30-\x39]\xE2\x83\xA3
  4649. | \xF0\x9F[\x85-\x88][\xA6-\xBF] # Enclosed characters
  4650. | \xF0\x9F[\x8C-\x97][\x80-\xBF] # Misc
  4651. | \xF0\x9F\x98[\x80-\xBF] # Smilies
  4652. | \xF0\x9F\x99[\x80-\x8F]
  4653. | \xF0\x9F\x9A[\x80-\xBF] # Transport and map symbols
  4654. )/x';
  4655. $matches = array();
  4656. if ( preg_match_all( $regex, $content, $matches ) ) {
  4657. if ( ! empty( $matches[1] ) ) {
  4658. foreach ( $matches[1] as $emoji ) {
  4659. /*
  4660. * UTF-32's hex encoding is the same as HTML's hex encoding.
  4661. * So, by converting the emoji from UTF-8 to UTF-32, we magically
  4662. * get the correct hex encoding.
  4663. */
  4664. $unpacked = unpack( 'H*', mb_convert_encoding( $emoji, 'UTF-32', 'UTF-8' ) );
  4665. if ( isset( $unpacked[1] ) ) {
  4666. $entity = '&#x' . ltrim( $unpacked[1], '0' ) . ';';
  4667. $content = str_replace( $emoji, $entity, $content );
  4668. }
  4669. }
  4670. }
  4671. }
  4672. }
  4673. return $content;
  4674. }
  4675. /**
  4676. * Convert emoji to a static img element.
  4677. *
  4678. * @since 4.2.0
  4679. *
  4680. * @param string $text The content to encode.
  4681. * @return string The encoded content.
  4682. */
  4683. function wp_staticize_emoji( $text ) {
  4684. $text = wp_encode_emoji( $text );
  4685. /** This filter is documented in wp-includes/formatting.php */
  4686. $cdn_url = apply_filters( 'emoji_url', 'https://s.w.org/images/core/emoji/2.3/72x72/' );
  4687. /** This filter is documented in wp-includes/formatting.php */
  4688. $ext = apply_filters( 'emoji_ext', '.png' );
  4689. $output = '';
  4690. /*
  4691. * HTML loop taken from smiley function, which was taken from texturize function.
  4692. * It'll never be consolidated.
  4693. *
  4694. * First, capture the tags as well as in between.
  4695. */
  4696. $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
  4697. $stop = count( $textarr );
  4698. // Ignore processing of specific tags.
  4699. $tags_to_ignore = 'code|pre|style|script|textarea';
  4700. $ignore_block_element = '';
  4701. for ( $i = 0; $i < $stop; $i++ ) {
  4702. $content = $textarr[$i];
  4703. // If we're in an ignore block, wait until we find its closing tag.
  4704. if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
  4705. $ignore_block_element = $matches[1];
  4706. }
  4707. // If it's not a tag and not in ignore block.
  4708. if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
  4709. $matches = array();
  4710. if ( preg_match_all( '/(&#x1f1(e[6-9a-f]|f[0-9a-f]);){2}/', $content, $matches ) ) {
  4711. if ( ! empty( $matches[0] ) ) {
  4712. foreach ( $matches[0] as $flag ) {
  4713. $chars = str_replace( array( '&#x', ';'), '', $flag );
  4714. list( $char1, $char2 ) = str_split( $chars, 5 );
  4715. $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 ) );
  4716. $content = str_replace( $flag, $entity, $content );
  4717. }
  4718. }
  4719. }
  4720. // Loosely match the Emoji Unicode range.
  4721. $regex = '/(&#x[2-3][0-9a-f]{3};|&#x1f[1-6][0-9a-f]{2};)/';
  4722. $matches = array();
  4723. if ( preg_match_all( $regex, $content, $matches ) ) {
  4724. if ( ! empty( $matches[1] ) ) {
  4725. foreach ( $matches[1] as $emoji ) {
  4726. $char = str_replace( array( '&#x', ';'), '', $emoji );
  4727. $entity = sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', $cdn_url . $char . $ext, html_entity_decode( $emoji ) );
  4728. $content = str_replace( $emoji, $entity, $content );
  4729. }
  4730. }
  4731. }
  4732. }
  4733. // Did we exit ignore block.
  4734. if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
  4735. $ignore_block_element = '';
  4736. }
  4737. $output .= $content;
  4738. }
  4739. return $output;
  4740. }
  4741. /**
  4742. * Convert emoji in emails into static images.
  4743. *
  4744. * @since 4.2.0
  4745. *
  4746. * @param array $mail The email data array.
  4747. * @return array The email data array, with emoji in the message staticized.
  4748. */
  4749. function wp_staticize_emoji_for_email( $mail ) {
  4750. if ( ! isset( $mail['message'] ) ) {
  4751. return $mail;
  4752. }
  4753. /*
  4754. * We can only transform the emoji into images if it's a text/html email.
  4755. * To do that, here's a cut down version of the same process that happens
  4756. * in wp_mail() - get the Content-Type from the headers, if there is one,
  4757. * then pass it through the wp_mail_content_type filter, in case a plugin
  4758. * is handling changing the Content-Type.
  4759. */
  4760. $headers = array();
  4761. if ( isset( $mail['headers'] ) ) {
  4762. if ( is_array( $mail['headers'] ) ) {
  4763. $headers = $mail['headers'];
  4764. } else {
  4765. $headers = explode( "\n", str_replace( "\r\n", "\n", $mail['headers'] ) );
  4766. }
  4767. }
  4768. foreach ( $headers as $header ) {
  4769. if ( strpos($header, ':') === false ) {
  4770. continue;
  4771. }
  4772. // Explode them out.
  4773. list( $name, $content ) = explode( ':', trim( $header ), 2 );
  4774. // Cleanup crew.
  4775. $name = trim( $name );
  4776. $content = trim( $content );
  4777. if ( 'content-type' === strtolower( $name ) ) {
  4778. if ( strpos( $content, ';' ) !== false ) {
  4779. list( $type, $charset ) = explode( ';', $content );
  4780. $content_type = trim( $type );
  4781. } else {
  4782. $content_type = trim( $content );
  4783. }
  4784. break;
  4785. }
  4786. }
  4787. // Set Content-Type if we don't have a content-type from the input headers.
  4788. if ( ! isset( $content_type ) ) {
  4789. $content_type = 'text/plain';
  4790. }
  4791. /** This filter is documented in wp-includes/pluggable.php */
  4792. $content_type = apply_filters( 'wp_mail_content_type', $content_type );
  4793. if ( 'text/html' === $content_type ) {
  4794. $mail['message'] = wp_staticize_emoji( $mail['message'] );
  4795. }
  4796. return $mail;
  4797. }
  4798. /**
  4799. * Shorten a URL, to be used as link text.
  4800. *
  4801. * @since 1.2.0
  4802. * @since 4.4.0 Moved to wp-includes/formatting.php from wp-admin/includes/misc.php and added $length param.
  4803. *
  4804. * @param string $url URL to shorten.
  4805. * @param int $length Optional. Maximum length of the shortened URL. Default 35 characters.
  4806. * @return string Shortened URL.
  4807. */
  4808. function url_shorten( $url, $length = 35 ) {
  4809. $stripped = str_replace( array( 'https://', 'http://', 'www.' ), '', $url );
  4810. $short_url = untrailingslashit( $stripped );
  4811. if ( strlen( $short_url ) > $length ) {
  4812. $short_url = substr( $short_url, 0, $length - 3 ) . '&hellip;';
  4813. }
  4814. return $short_url;
  4815. }
  4816. /**
  4817. * Sanitizes a hex color.
  4818. *
  4819. * Returns either '', a 3 or 6 digit hex color (with #), or nothing.
  4820. * For sanitizing values without a #, see sanitize_hex_color_no_hash().
  4821. *
  4822. * @since 3.4.0
  4823. *
  4824. * @param string $color
  4825. * @return string|void
  4826. */
  4827. function sanitize_hex_color( $color ) {
  4828. if ( '' === $color ) {
  4829. return '';
  4830. }
  4831. // 3 or 6 hex digits, or the empty string.
  4832. if ( preg_match('|^#([A-Fa-f0-9]{3}){1,2}$|', $color ) ) {
  4833. return $color;
  4834. }
  4835. }
  4836. /**
  4837. * Sanitizes a hex color without a hash. Use sanitize_hex_color() when possible.
  4838. *
  4839. * Saving hex colors without a hash puts the burden of adding the hash on the
  4840. * UI, which makes it difficult to use or upgrade to other color types such as
  4841. * rgba, hsl, rgb, and html color names.
  4842. *
  4843. * Returns either '', a 3 or 6 digit hex color (without a #), or null.
  4844. *
  4845. * @since 3.4.0
  4846. *
  4847. * @param string $color
  4848. * @return string|null
  4849. */
  4850. function sanitize_hex_color_no_hash( $color ) {
  4851. $color = ltrim( $color, '#' );
  4852. if ( '' === $color ) {
  4853. return '';
  4854. }
  4855. return sanitize_hex_color( '#' . $color ) ? $color : null;
  4856. }
  4857. /**
  4858. * Ensures that any hex color is properly hashed.
  4859. * Otherwise, returns value untouched.
  4860. *
  4861. * This method should only be necessary if using sanitize_hex_color_no_hash().
  4862. *
  4863. * @since 3.4.0
  4864. *
  4865. * @param string $color
  4866. * @return string
  4867. */
  4868. function maybe_hash_hex_color( $color ) {
  4869. if ( $unhashed = sanitize_hex_color_no_hash( $color ) ) {
  4870. return '#' . $unhashed;
  4871. }
  4872. return $color;
  4873. }