lib_phpQuery.php 163 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711
  1. <?php
  2. /**
  3. * phpQuery is a server-side, chainable, CSS3 selector driven
  4. * Document Object Model (DOM) API based on jQuery JavaScript Library.
  5. *
  6. * @version 0.9.5
  7. * @link http://code.google.com/p/phpquery/
  8. * @link http://phpquery-library.blogspot.com/
  9. * @link http://jquery.com/
  10. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  11. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  12. * @package phpQuery
  13. */
  14. // class names for instanceof
  15. // TODO move them as class constants into phpQuery
  16. define('DOMDOCUMENT', 'DOMDocument');
  17. define('DOMELEMENT', 'DOMElement');
  18. define('DOMNODELIST', 'DOMNodeList');
  19. define('DOMNODE', 'DOMNode');
  20. /**
  21. * DOMEvent class.
  22. *
  23. * Based on
  24. * @link http://developer.mozilla.org/En/DOM:event
  25. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  26. * @package phpQuery
  27. * @todo implement ArrayAccess ?
  28. */
  29. class DOMEvent {
  30. /**
  31. * Returns a boolean indicating whether the event bubbles up through the DOM or not.
  32. *
  33. * @var unknown_type
  34. */
  35. public $bubbles = true;
  36. /**
  37. * Returns a boolean indicating whether the event is cancelable.
  38. *
  39. * @var unknown_type
  40. */
  41. public $cancelable = true;
  42. /**
  43. * Returns a reference to the currently registered target for the event.
  44. *
  45. * @var unknown_type
  46. */
  47. public $currentTarget;
  48. /**
  49. * Returns detail about the event, depending on the type of event.
  50. *
  51. * @var unknown_type
  52. * @link http://developer.mozilla.org/en/DOM/event.detail
  53. */
  54. public $detail; // ???
  55. /**
  56. * Used to indicate which phase of the event flow is currently being evaluated.
  57. *
  58. * NOT IMPLEMENTED
  59. *
  60. * @var unknown_type
  61. * @link http://developer.mozilla.org/en/DOM/event.eventPhase
  62. */
  63. public $eventPhase; // ???
  64. /**
  65. * The explicit original target of the event (Mozilla-specific).
  66. *
  67. * NOT IMPLEMENTED
  68. *
  69. * @var unknown_type
  70. */
  71. public $explicitOriginalTarget; // moz only
  72. /**
  73. * The original target of the event, before any retargetings (Mozilla-specific).
  74. *
  75. * NOT IMPLEMENTED
  76. *
  77. * @var unknown_type
  78. */
  79. public $originalTarget; // moz only
  80. /**
  81. * Identifies a secondary target for the event.
  82. *
  83. * @var unknown_type
  84. */
  85. public $relatedTarget;
  86. /**
  87. * Returns a reference to the target to which the event was originally dispatched.
  88. *
  89. * @var unknown_type
  90. */
  91. public $target;
  92. /**
  93. * Returns the time that the event was created.
  94. *
  95. * @var unknown_type
  96. */
  97. public $timeStamp;
  98. /**
  99. * Returns the name of the event (case-insensitive).
  100. */
  101. public $type;
  102. public $runDefault = true;
  103. public $data = null;
  104. public function __construct($data) {
  105. foreach($data as $k => $v) {
  106. $this->$k = $v;
  107. }
  108. if (! $this->timeStamp)
  109. $this->timeStamp = time();
  110. }
  111. /**
  112. * Cancels the event (if it is cancelable).
  113. *
  114. */
  115. public function preventDefault() {
  116. $this->runDefault = false;
  117. }
  118. /**
  119. * Stops the propagation of events further along in the DOM.
  120. *
  121. */
  122. public function stopPropagation() {
  123. $this->bubbles = false;
  124. }
  125. }
  126. /**
  127. * DOMDocumentWrapper class simplifies work with DOMDocument.
  128. *
  129. * Know bug:
  130. * - in XHTML fragments, <br /> changes to <br clear="none" />
  131. *
  132. * @todo check XML catalogs compatibility
  133. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  134. * @package phpQuery
  135. */
  136. class DOMDocumentWrapper {
  137. /**
  138. * @var DOMDocument
  139. */
  140. public $document;
  141. public $id;
  142. /**
  143. * @todo Rewrite as method and quess if null.
  144. * @var string
  145. */
  146. public $contentType = '';
  147. public $xpath;
  148. public $uuid = 0;
  149. public $data = array();
  150. public $dataNodes = array();
  151. public $events = array();
  152. public $eventsNodes = array();
  153. public $eventsGlobal = array();
  154. /**
  155. * @TODO iframes support http://code.google.com/p/phpquery/issues/detail?id=28
  156. */
  157. public $frames = array();
  158. /**
  159. * Document root, by default equals to document itself.
  160. * Used by documentFragments.
  161. *
  162. * @var DOMNode
  163. */
  164. public $root;
  165. public $isDocumentFragment;
  166. public $isXML = false;
  167. public $isXHTML = false;
  168. public $isHTML = false;
  169. public $charset;
  170. public function __construct($markup = null, $contentType = null, $newDocumentID = null) {
  171. if (isset($markup))
  172. $this->load($markup, $contentType, $newDocumentID);
  173. $this->id = $newDocumentID
  174. ? $newDocumentID
  175. : md5(microtime());
  176. }
  177. public function load($markup, $contentType = null, $newDocumentID = null) {
  178. // phpQuery::$documents[$id] = $this;
  179. $this->contentType = strtolower($contentType);
  180. if ($markup instanceof DOMDOCUMENT) {
  181. $this->document = $markup;
  182. $this->root = $this->document;
  183. $this->charset = $this->document->encoding;
  184. // TODO isDocumentFragment
  185. } else {
  186. $loaded = $this->loadMarkup($markup);
  187. }
  188. if ($loaded) {
  189. // $this->document->formatOutput = true;
  190. $this->document->preserveWhiteSpace = true;
  191. $this->xpath = new DOMXPath($this->document);
  192. $this->afterMarkupLoad();
  193. return true;
  194. // remember last loaded document
  195. // return phpQuery::selectDocument($id);
  196. }
  197. return false;
  198. }
  199. protected function afterMarkupLoad() {
  200. if ($this->isXHTML) {
  201. $this->xpath->registerNamespace("html", "http://www.w3.org/1999/xhtml");
  202. }
  203. }
  204. protected function loadMarkup($markup) {
  205. $loaded = false;
  206. if ($this->contentType) {
  207. self::debug("Load markup for content type {$this->contentType}");
  208. // content determined by contentType
  209. list($contentType, $charset) = $this->contentTypeToArray($this->contentType);
  210. switch($contentType) {
  211. case 'text/html':
  212. phpQuery::debug("Loading HTML, content type '{$this->contentType}'");
  213. $loaded = $this->loadMarkupHTML($markup, $charset);
  214. break;
  215. case 'text/xml':
  216. case 'application/xhtml+xml':
  217. phpQuery::debug("Loading XML, content type '{$this->contentType}'");
  218. $loaded = $this->loadMarkupXML($markup, $charset);
  219. break;
  220. default:
  221. // for feeds or anything that sometimes doesn't use text/xml
  222. if (strpos('xml', $this->contentType) !== false) {
  223. phpQuery::debug("Loading XML, content type '{$this->contentType}'");
  224. $loaded = $this->loadMarkupXML($markup, $charset);
  225. } else
  226. phpQuery::debug("Could not determine document type from content type '{$this->contentType}'");
  227. }
  228. } else {
  229. // content type autodetection
  230. if ($this->isXML($markup)) {
  231. phpQuery::debug("Loading XML, isXML() == true");
  232. $loaded = $this->loadMarkupXML($markup);
  233. if (! $loaded && $this->isXHTML) {
  234. phpQuery::debug('Loading as XML failed, trying to load as HTML, isXHTML == true');
  235. $loaded = $this->loadMarkupHTML($markup);
  236. }
  237. } else {
  238. phpQuery::debug("Loading HTML, isXML() == false");
  239. $loaded = $this->loadMarkupHTML($markup);
  240. }
  241. }
  242. return $loaded;
  243. }
  244. protected function loadMarkupReset() {
  245. $this->isXML = $this->isXHTML = $this->isHTML = false;
  246. }
  247. protected function documentCreate($charset, $version = '1.0') {
  248. if (! $version)
  249. $version = '1.0';
  250. $this->document = new DOMDocument($version, $charset);
  251. $this->charset = $this->document->encoding;
  252. // $this->document->encoding = $charset;
  253. $this->document->formatOutput = true;
  254. $this->document->preserveWhiteSpace = true;
  255. }
  256. protected function loadMarkupHTML($markup, $requestedCharset = null) {
  257. if (phpQuery::$debug)
  258. phpQuery::debug('Full markup load (HTML): '.substr($markup, 0, 250));
  259. $this->loadMarkupReset();
  260. $this->isHTML = true;
  261. if (!isset($this->isDocumentFragment))
  262. $this->isDocumentFragment = self::isDocumentFragmentHTML($markup);
  263. $charset = null;
  264. $documentCharset = $this->charsetFromHTML($markup);
  265. $addDocumentCharset = false;
  266. if ($documentCharset) {
  267. $charset = $documentCharset;
  268. $markup = $this->charsetFixHTML($markup);
  269. } else if ($requestedCharset) {
  270. $charset = $requestedCharset;
  271. }
  272. if (! $charset)
  273. $charset = phpQuery::$defaultCharset;
  274. // HTTP 1.1 says that the default charset is ISO-8859-1
  275. // @see http://www.w3.org/International/O-HTTP-charset
  276. if (! $documentCharset) {
  277. $documentCharset = 'ISO-8859-1';
  278. $addDocumentCharset = true;
  279. }
  280. // Should be careful here, still need 'magic encoding detection' since lots of pages have other 'default encoding'
  281. // Worse, some pages can have mixed encodings... we'll try not to worry about that
  282. $requestedCharset = strtoupper($requestedCharset);
  283. $documentCharset = strtoupper($documentCharset);
  284. phpQuery::debug("DOC: $documentCharset REQ: $requestedCharset");
  285. if ($requestedCharset && $documentCharset && $requestedCharset !== $documentCharset) {
  286. phpQuery::debug("CHARSET CONVERT");
  287. // Document Encoding Conversion
  288. // http://code.google.com/p/phpquery/issues/detail?id=86
  289. if (function_exists('mb_detect_encoding')) {
  290. $possibleCharsets = array($documentCharset, $requestedCharset, 'AUTO');
  291. $docEncoding = mb_detect_encoding($markup, implode(', ', $possibleCharsets));
  292. if (! $docEncoding)
  293. $docEncoding = $documentCharset; // ok trust the document
  294. phpQuery::debug("DETECTED '$docEncoding'");
  295. // Detected does not match what document says...
  296. if ($docEncoding !== $documentCharset) {
  297. // Tricky..
  298. }
  299. if ($docEncoding !== $requestedCharset) {
  300. phpQuery::debug("CONVERT $docEncoding => $requestedCharset");
  301. $markup = mb_convert_encoding($markup, $requestedCharset, $docEncoding);
  302. $markup = $this->charsetAppendToHTML($markup, $requestedCharset);
  303. $charset = $requestedCharset;
  304. }
  305. } else {
  306. phpQuery::debug("TODO: charset conversion without mbstring...");
  307. }
  308. }
  309. $return = false;
  310. if ($this->isDocumentFragment) {
  311. phpQuery::debug("Full markup load (HTML), DocumentFragment detected, using charset '$charset'");
  312. $return = $this->documentFragmentLoadMarkup($this, $charset, $markup);
  313. } else {
  314. if ($addDocumentCharset) {
  315. phpQuery::debug("Full markup load (HTML), appending charset: '$charset'");
  316. $markup = $this->charsetAppendToHTML($markup, $charset);
  317. }
  318. phpQuery::debug("Full markup load (HTML), documentCreate('$charset')");
  319. $this->documentCreate($charset);
  320. $return = phpQuery::$debug === 2
  321. ? $this->document->loadHTML($markup)
  322. : @$this->document->loadHTML($markup);
  323. if ($return)
  324. $this->root = $this->document;
  325. }
  326. if ($return && ! $this->contentType)
  327. $this->contentType = 'text/html';
  328. return $return;
  329. }
  330. protected function loadMarkupXML($markup, $requestedCharset = null) {
  331. if (phpQuery::$debug)
  332. phpQuery::debug('Full markup load (XML): '.substr($markup, 0, 250));
  333. $this->loadMarkupReset();
  334. $this->isXML = true;
  335. // check against XHTML in contentType or markup
  336. $isContentTypeXHTML = $this->isXHTML();
  337. $isMarkupXHTML = $this->isXHTML($markup);
  338. if ($isContentTypeXHTML || $isMarkupXHTML) {
  339. self::debug('Full markup load (XML), XHTML detected');
  340. $this->isXHTML = true;
  341. }
  342. // determine document fragment
  343. if (! isset($this->isDocumentFragment))
  344. $this->isDocumentFragment = $this->isXHTML
  345. ? self::isDocumentFragmentXHTML($markup)
  346. : self::isDocumentFragmentXML($markup);
  347. // this charset will be used
  348. $charset = null;
  349. // charset from XML declaration @var string
  350. $documentCharset = $this->charsetFromXML($markup);
  351. if (! $documentCharset) {
  352. if ($this->isXHTML) {
  353. // this is XHTML, try to get charset from content-type meta header
  354. $documentCharset = $this->charsetFromHTML($markup);
  355. if ($documentCharset) {
  356. phpQuery::debug("Full markup load (XML), appending XHTML charset '$documentCharset'");
  357. $this->charsetAppendToXML($markup, $documentCharset);
  358. $charset = $documentCharset;
  359. }
  360. }
  361. if (! $documentCharset) {
  362. // if still no document charset...
  363. $charset = $requestedCharset;
  364. }
  365. } else if ($requestedCharset) {
  366. $charset = $requestedCharset;
  367. }
  368. if (! $charset) {
  369. $charset = phpQuery::$defaultCharset;
  370. }
  371. if ($requestedCharset && $documentCharset && $requestedCharset != $documentCharset) {
  372. // TODO place for charset conversion
  373. // $charset = $requestedCharset;
  374. }
  375. $return = false;
  376. if ($this->isDocumentFragment) {
  377. phpQuery::debug("Full markup load (XML), DocumentFragment detected, using charset '$charset'");
  378. $return = $this->documentFragmentLoadMarkup($this, $charset, $markup);
  379. } else {
  380. // FIXME ???
  381. if ($isContentTypeXHTML && ! $isMarkupXHTML)
  382. if (! $documentCharset) {
  383. phpQuery::debug("Full markup load (XML), appending charset '$charset'");
  384. $markup = $this->charsetAppendToXML($markup, $charset);
  385. }
  386. // see http://pl2.php.net/manual/en/book.dom.php#78929
  387. // LIBXML_DTDLOAD (>= PHP 5.1)
  388. // does XML ctalogues works with LIBXML_NONET
  389. // $this->document->resolveExternals = true;
  390. // TODO test LIBXML_COMPACT for performance improvement
  391. // create document
  392. $this->documentCreate($charset);
  393. if (phpversion() < 5.1) {
  394. $this->document->resolveExternals = true;
  395. $return = phpQuery::$debug === 2
  396. ? $this->document->loadXML($markup)
  397. : @$this->document->loadXML($markup);
  398. } else {
  399. /** @link http://pl2.php.net/manual/en/libxml.constants.php */
  400. $libxmlStatic = phpQuery::$debug === 2
  401. ? LIBXML_DTDLOAD|LIBXML_DTDATTR|LIBXML_NONET
  402. : LIBXML_DTDLOAD|LIBXML_DTDATTR|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOERROR;
  403. $return = $this->document->loadXML($markup, $libxmlStatic);
  404. // if (! $return)
  405. // $return = $this->document->loadHTML($markup);
  406. }
  407. if ($return)
  408. $this->root = $this->document;
  409. }
  410. if ($return) {
  411. if (! $this->contentType) {
  412. if ($this->isXHTML)
  413. $this->contentType = 'application/xhtml+xml';
  414. else
  415. $this->contentType = 'text/xml';
  416. }
  417. return $return;
  418. } else {
  419. throw new Exception("Error loading XML markup");
  420. }
  421. }
  422. protected function isXHTML($markup = null) {
  423. if (! isset($markup)) {
  424. return strpos($this->contentType, 'xhtml') !== false;
  425. }
  426. // XXX ok ?
  427. return strpos($markup, "<!DOCTYPE html") !== false;
  428. // return stripos($doctype, 'xhtml') !== false;
  429. // $doctype = isset($dom->doctype) && is_object($dom->doctype)
  430. // ? $dom->doctype->publicId
  431. // : self::$defaultDoctype;
  432. }
  433. protected function isXML($markup) {
  434. // return strpos($markup, '<?xml') !== false && stripos($markup, 'xhtml') === false;
  435. $head = substr($markup, 0, 100);
  436. return strpos($head, '<'.'?xml') !== false && stripos($head, '<html ') === false;
  437. }
  438. protected function contentTypeToArray($contentType) {
  439. $matches = explode(';', trim(strtolower($contentType)));
  440. if (isset($matches[1])) {
  441. $matches[1] = explode('=', $matches[1]);
  442. // strip 'charset='
  443. $matches[1] = isset($matches[1][1]) && trim($matches[1][1])
  444. ? $matches[1][1]
  445. : $matches[1][0];
  446. } else
  447. $matches[1] = null;
  448. return $matches;
  449. }
  450. /**
  451. *
  452. * @param $markup
  453. * @return array contentType, charset
  454. */
  455. protected function contentTypeFromHTML($markup) {
  456. $matches = array();
  457. // find meta tag
  458. preg_match('@<meta[^>]+http-equiv\\s*=\\s*(["|\'])Content-Type\\1([^>]+?)>@i',
  459. $markup, $matches
  460. );
  461. if (! isset($matches[0]))
  462. return array(null, null);
  463. // get attr 'content'
  464. preg_match('@content\\s*=\\s*(["|\'])(.+?)\\1@', $matches[0], $matches);
  465. if (! isset($matches[0]))
  466. return array(null, null);
  467. return $this->contentTypeToArray($matches[2]);
  468. }
  469. protected function charsetFromHTML($markup) {
  470. $contentType = $this->contentTypeFromHTML($markup);
  471. return $contentType[1];
  472. }
  473. protected function charsetFromXML($markup) {
  474. $matches = array();
  475. // find declaration
  476. preg_match('@<'.'?xml[^>]+encoding\\s*=\\s*(["|\'])(.*?)\\1@i',
  477. $markup, $matches
  478. );
  479. return isset($matches[2])
  480. ? strtolower($matches[2])
  481. : null;
  482. }
  483. /**
  484. * Repositions meta[type=charset] at the start of head. Bypasses DOMDocument bug.
  485. *
  486. * @link http://code.google.com/p/phpquery/issues/detail?id=80
  487. * @param $html
  488. */
  489. protected function charsetFixHTML($markup) {
  490. $matches = array();
  491. // find meta tag
  492. preg_match('@\s*<meta[^>]+http-equiv\\s*=\\s*(["|\'])Content-Type\\1([^>]+?)>@i',
  493. $markup, $matches, PREG_OFFSET_CAPTURE
  494. );
  495. if (! isset($matches[0]))
  496. return;
  497. $metaContentType = $matches[0][0];
  498. $markup = substr($markup, 0, $matches[0][1])
  499. .substr($markup, $matches[0][1]+strlen($metaContentType));
  500. $headStart = stripos($markup, '<head');
  501. $headStop = stripos($markup, '>', $headStart);
  502. $markup = substr($markup, 0, $headStop+1).$metaContentType
  503. .substr($markup, $headStop+1);
  504. return $markup;
  505. }
  506. protected function charsetAppendToHTML($html, $charset, $xhtml = false) {
  507. // remove existing meta[type=content-type]
  508. $html = preg_replace('@\s*<meta[^>]+http-equiv\\s*=\\s*(["|\'])Content-Type\\1([^>]+?)>@i', '', $html);
  509. $meta = '<meta http-equiv="Content-Type" content="text/html;charset='
  510. .$charset.'" '
  511. .($xhtml ? '/' : '')
  512. .'>';
  513. if (strpos($html, '<head') === false) {
  514. if (strpos($html, '<html') === false) {
  515. return $meta.$html;
  516. } else {
  517. return preg_replace(
  518. '@<html(.*?)(?(?<!\?)>)@s',
  519. "<html\\1><head>{$meta}</head>",
  520. $html
  521. );
  522. }
  523. } else {
  524. return preg_replace(
  525. '@<head(.*?)(?(?<!\?)>)@s',
  526. '<head\\1>'.$meta,
  527. $html
  528. );
  529. }
  530. }
  531. protected function charsetAppendToXML($markup, $charset) {
  532. $declaration = '<'.'?xml version="1.0" encoding="'.$charset.'"?'.'>';
  533. return $declaration.$markup;
  534. }
  535. public static function isDocumentFragmentHTML($markup) {
  536. return stripos($markup, '<html') === false && stripos($markup, '<!doctype') === false;
  537. }
  538. public static function isDocumentFragmentXML($markup) {
  539. return stripos($markup, '<'.'?xml') === false;
  540. }
  541. public static function isDocumentFragmentXHTML($markup) {
  542. return self::isDocumentFragmentHTML($markup);
  543. }
  544. public function importAttr($value) {
  545. // TODO
  546. }
  547. /**
  548. *
  549. * @param $source
  550. * @param $target
  551. * @param $sourceCharset
  552. * @return array Array of imported nodes.
  553. */
  554. public function import($source, $sourceCharset = null) {
  555. // TODO charset conversions
  556. $return = array();
  557. if ($source instanceof DOMNODE && !($source instanceof DOMNODELIST))
  558. $source = array($source);
  559. // if (is_array($source)) {
  560. // foreach($source as $node) {
  561. // if (is_string($node)) {
  562. // // string markup
  563. // $fake = $this->documentFragmentCreate($node, $sourceCharset);
  564. // if ($fake === false)
  565. // throw new Exception("Error loading documentFragment markup");
  566. // else
  567. // $return = array_merge($return,
  568. // $this->import($fake->root->childNodes)
  569. // );
  570. // } else {
  571. // $return[] = $this->document->importNode($node, true);
  572. // }
  573. // }
  574. // return $return;
  575. // } else {
  576. // // string markup
  577. // $fake = $this->documentFragmentCreate($source, $sourceCharset);
  578. // if ($fake === false)
  579. // throw new Exception("Error loading documentFragment markup");
  580. // else
  581. // return $this->import($fake->root->childNodes);
  582. // }
  583. if (is_array($source) || $source instanceof DOMNODELIST) {
  584. // dom nodes
  585. self::debug('Importing nodes to document');
  586. foreach($source as $node)
  587. $return[] = $this->document->importNode($node, true);
  588. } else {
  589. // string markup
  590. $fake = $this->documentFragmentCreate($source, $sourceCharset);
  591. if ($fake === false)
  592. throw new Exception("Error loading documentFragment markup");
  593. else
  594. return $this->import($fake->root->childNodes);
  595. }
  596. return $return;
  597. }
  598. /**
  599. * Creates new document fragment.
  600. *
  601. * @param $source
  602. * @return DOMDocumentWrapper
  603. */
  604. protected function documentFragmentCreate($source, $charset = null) {
  605. $fake = new DOMDocumentWrapper();
  606. $fake->contentType = $this->contentType;
  607. $fake->isXML = $this->isXML;
  608. $fake->isHTML = $this->isHTML;
  609. $fake->isXHTML = $this->isXHTML;
  610. $fake->root = $fake->document;
  611. if (! $charset)
  612. $charset = $this->charset;
  613. // $fake->documentCreate($this->charset);
  614. if ($source instanceof DOMNODE && !($source instanceof DOMNODELIST))
  615. $source = array($source);
  616. if (is_array($source) || $source instanceof DOMNODELIST) {
  617. // dom nodes
  618. // load fake document
  619. if (! $this->documentFragmentLoadMarkup($fake, $charset))
  620. return false;
  621. $nodes = $fake->import($source);
  622. foreach($nodes as $node)
  623. $fake->root->appendChild($node);
  624. } else {
  625. // string markup
  626. $this->documentFragmentLoadMarkup($fake, $charset, $source);
  627. }
  628. return $fake;
  629. }
  630. /**
  631. *
  632. * @param $document DOMDocumentWrapper
  633. * @param $markup
  634. * @return $document
  635. */
  636. private function documentFragmentLoadMarkup($fragment, $charset, $markup = null) {
  637. // TODO error handling
  638. // TODO copy doctype
  639. // tempolary turn off
  640. $fragment->isDocumentFragment = false;
  641. if ($fragment->isXML) {
  642. if ($fragment->isXHTML) {
  643. // add FAKE element to set default namespace
  644. $fragment->loadMarkupXML('<?xml version="1.0" encoding="'.$charset.'"?>'
  645. .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" '
  646. .'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
  647. .'<fake xmlns="http://www.w3.org/1999/xhtml">'.$markup.'</fake>');
  648. $fragment->root = $fragment->document->firstChild->nextSibling;
  649. } else {
  650. $fragment->loadMarkupXML('<?xml version="1.0" encoding="'.$charset.'"?><fake>'.$markup.'</fake>');
  651. $fragment->root = $fragment->document->firstChild;
  652. }
  653. } else {
  654. $markup2 = phpQuery::$defaultDoctype.'<html><head><meta http-equiv="Content-Type" content="text/html;charset='
  655. .$charset.'"></head>';
  656. $noBody = strpos($markup, '<body') === false;
  657. if ($noBody)
  658. $markup2 .= '<body>';
  659. $markup2 .= $markup;
  660. if ($noBody)
  661. $markup2 .= '</body>';
  662. $markup2 .= '</html>';
  663. $fragment->loadMarkupHTML($markup2);
  664. // TODO resolv body tag merging issue
  665. $fragment->root = $noBody
  666. ? $fragment->document->firstChild->nextSibling->firstChild->nextSibling
  667. : $fragment->document->firstChild->nextSibling->firstChild->nextSibling;
  668. }
  669. if (! $fragment->root)
  670. return false;
  671. $fragment->isDocumentFragment = true;
  672. return true;
  673. }
  674. protected function documentFragmentToMarkup($fragment) {
  675. phpQuery::debug('documentFragmentToMarkup');
  676. $tmp = $fragment->isDocumentFragment;
  677. $fragment->isDocumentFragment = false;
  678. $markup = $fragment->markup();
  679. if ($fragment->isXML) {
  680. $markup = substr($markup, 0, strrpos($markup, '</fake>'));
  681. if ($fragment->isXHTML) {
  682. $markup = substr($markup, strpos($markup, '<fake')+43);
  683. } else {
  684. $markup = substr($markup, strpos($markup, '<fake>')+6);
  685. }
  686. } else {
  687. $markup = substr($markup, strpos($markup, '<body>')+6);
  688. $markup = substr($markup, 0, strrpos($markup, '</body>'));
  689. }
  690. $fragment->isDocumentFragment = $tmp;
  691. if (phpQuery::$debug)
  692. phpQuery::debug('documentFragmentToMarkup: '.substr($markup, 0, 150));
  693. return $markup;
  694. }
  695. /**
  696. * Return document markup, starting with optional $nodes as root.
  697. *
  698. * @param $nodes DOMNode|DOMNodeList
  699. * @return string
  700. */
  701. public function markup($nodes = null, $innerMarkup = false) {
  702. if (isset($nodes) && count($nodes) == 1 && $nodes[0] instanceof DOMDOCUMENT)
  703. $nodes = null;
  704. if (isset($nodes)) {
  705. $markup = '';
  706. if (!is_array($nodes) && !($nodes instanceof DOMNODELIST) )
  707. $nodes = array($nodes);
  708. if ($this->isDocumentFragment && ! $innerMarkup)
  709. foreach($nodes as $i => $node)
  710. if ($node->isSameNode($this->root)) {
  711. // var_dump($node);
  712. $nodes = array_slice($nodes, 0, $i)
  713. + phpQuery::DOMNodeListToArray($node->childNodes)
  714. + array_slice($nodes, $i+1);
  715. }
  716. if ($this->isXML && ! $innerMarkup) {
  717. self::debug("Getting outerXML with charset '{$this->charset}'");
  718. // we need outerXML, so we can benefit from
  719. // $node param support in saveXML()
  720. foreach($nodes as $node)
  721. $markup .= $this->document->saveXML($node);
  722. } else {
  723. $loop = array();
  724. if ($innerMarkup)
  725. foreach($nodes as $node) {
  726. if ($node->childNodes)
  727. foreach($node->childNodes as $child)
  728. $loop[] = $child;
  729. else
  730. $loop[] = $node;
  731. }
  732. else
  733. $loop = $nodes;
  734. self::debug("Getting markup, moving selected nodes (".count($loop).") to new DocumentFragment");
  735. $fake = $this->documentFragmentCreate($loop);
  736. $markup = $this->documentFragmentToMarkup($fake);
  737. }
  738. if ($this->isXHTML) {
  739. self::debug("Fixing XHTML");
  740. $markup = self::markupFixXHTML($markup);
  741. }
  742. self::debug("Markup: ".substr($markup, 0, 250));
  743. return $markup;
  744. } else {
  745. if ($this->isDocumentFragment) {
  746. // documentFragment, html only...
  747. self::debug("Getting markup, DocumentFragment detected");
  748. // return $this->markup(
  749. //// $this->document->getElementsByTagName('body')->item(0)
  750. // $this->document->root, true
  751. // );
  752. $markup = $this->documentFragmentToMarkup($this);
  753. // no need for markupFixXHTML, as it's done thought markup($nodes) method
  754. return $markup;
  755. } else {
  756. self::debug("Getting markup (".($this->isXML?'XML':'HTML')."), final with charset '{$this->charset}'");
  757. $markup = $this->isXML
  758. ? $this->document->saveXML()
  759. : $this->document->saveHTML();
  760. if ($this->isXHTML) {
  761. self::debug("Fixing XHTML");
  762. $markup = self::markupFixXHTML($markup);
  763. }
  764. self::debug("Markup: ".substr($markup, 0, 250));
  765. return $markup;
  766. }
  767. }
  768. }
  769. protected static function markupFixXHTML($markup) {
  770. $markup = self::expandEmptyTag('script', $markup);
  771. $markup = self::expandEmptyTag('select', $markup);
  772. $markup = self::expandEmptyTag('textarea', $markup);
  773. return $markup;
  774. }
  775. public static function debug($text) {
  776. phpQuery::debug($text);
  777. }
  778. /**
  779. * expandEmptyTag
  780. *
  781. * @param $tag
  782. * @param $xml
  783. * @return unknown_type
  784. * @author mjaque at ilkebenson dot com
  785. * @link http://php.net/manual/en/domdocument.savehtml.php#81256
  786. */
  787. public static function expandEmptyTag($tag, $xml){
  788. $indice = 0;
  789. while ($indice< strlen($xml)){
  790. $pos = strpos($xml, "<$tag ", $indice);
  791. if ($pos){
  792. $posCierre = strpos($xml, ">", $pos);
  793. if ($xml[$posCierre-1] == "/"){
  794. $xml = substr_replace($xml, "></$tag>", $posCierre-1, 2);
  795. }
  796. $indice = $posCierre;
  797. }
  798. else break;
  799. }
  800. return $xml;
  801. }
  802. }
  803. /**
  804. * Event handling class.
  805. *
  806. * @author Tobiasz Cudnik
  807. * @package phpQuery
  808. * @static
  809. */
  810. abstract class phpQueryEvents {
  811. /**
  812. * Trigger a type of event on every matched element.
  813. *
  814. * @param DOMNode|phpQueryObject|string $document
  815. * @param string $type
  816. * @param array<DOMEvent> $data
  817. *
  818. * @TODO exclusive events (with !)
  819. * @TODO global events (test)
  820. * @TODO support more than event in $type (space-separated)
  821. */
  822. public static function trigger($document, $type, $data = array(), $node = null) {
  823. // trigger: function(type, data, elem, donative, extra) {
  824. $documentID = phpQuery::getDocumentID($document);
  825. $namespace = null;
  826. if (strpos($type, '.') !== false)
  827. list($name, $namespace) = explode('.', $type);
  828. else
  829. $name = $type;
  830. if (! $node) {
  831. if (self::issetGlobal($documentID, $type)) {
  832. $pq = phpQuery::getDocument($documentID);
  833. // TODO check add($pq->document)
  834. $pq->find('*')->add($pq->document)
  835. ->trigger($type, $data);
  836. }
  837. } else {
  838. if (isset($data[0]) && $data[0] instanceof DOMEvent) {
  839. $event = $data[0];
  840. $event->relatedTarget = $event->target;
  841. $event->target = $node;
  842. $data = array_slice($data, 1);
  843. } else {
  844. $event = new DOMEvent(array(
  845. 'type' => $type,
  846. 'target' => $node,
  847. 'timeStamp' => time(),
  848. ));
  849. }
  850. $i = 0;
  851. while($node) {
  852. // TODO whois
  853. phpQuery::debug("Triggering ".($i?"bubbled ":'')."event '{$type}' on "
  854. ."node \n");//.phpQueryObject::whois($node)."\n");
  855. $event->currentTarget = $node;
  856. $eventNode = self::getNode($documentID, $node);
  857. if (isset($eventNode->eventHandlers)) {
  858. foreach($eventNode->eventHandlers as $eventType => $handlers) {
  859. $eventNamespace = null;
  860. if (strpos($type, '.') !== false)
  861. list($eventName, $eventNamespace) = explode('.', $eventType);
  862. else
  863. $eventName = $eventType;
  864. if ($name != $eventName)
  865. continue;
  866. if ($namespace && $eventNamespace && $namespace != $eventNamespace)
  867. continue;
  868. foreach($handlers as $handler) {
  869. phpQuery::debug("Calling event handler\n");
  870. $event->data = $handler['data']
  871. ? $handler['data']
  872. : null;
  873. $params = array_merge(array($event), $data);
  874. $return = phpQuery::callbackRun($handler['callback'], $params);
  875. if ($return === false) {
  876. $event->bubbles = false;
  877. }
  878. }
  879. }
  880. }
  881. // to bubble or not to bubble...
  882. if (! $event->bubbles)
  883. break;
  884. $node = $node->parentNode;
  885. $i++;
  886. }
  887. }
  888. }
  889. /**
  890. * Binds a handler to one or more events (like click) for each matched element.
  891. * Can also bind custom events.
  892. *
  893. * @param DOMNode|phpQueryObject|string $document
  894. * @param unknown_type $type
  895. * @param unknown_type $data Optional
  896. * @param unknown_type $callback
  897. *
  898. * @TODO support '!' (exclusive) events
  899. * @TODO support more than event in $type (space-separated)
  900. * @TODO support binding to global events
  901. */
  902. public static function add($document, $node, $type, $data, $callback = null) {
  903. phpQuery::debug("Binding '$type' event");
  904. $documentID = phpQuery::getDocumentID($document);
  905. // if (is_null($callback) && is_callable($data)) {
  906. // $callback = $data;
  907. // $data = null;
  908. // }
  909. $eventNode = self::getNode($documentID, $node);
  910. if (! $eventNode)
  911. $eventNode = self::setNode($documentID, $node);
  912. if (!isset($eventNode->eventHandlers[$type]))
  913. $eventNode->eventHandlers[$type] = array();
  914. $eventNode->eventHandlers[$type][] = array(
  915. 'callback' => $callback,
  916. 'data' => $data,
  917. );
  918. }
  919. /**
  920. * Enter description here...
  921. *
  922. * @param DOMNode|phpQueryObject|string $document
  923. * @param unknown_type $type
  924. * @param unknown_type $callback
  925. *
  926. * @TODO namespace events
  927. * @TODO support more than event in $type (space-separated)
  928. */
  929. public static function remove($document, $node, $type = null, $callback = null) {
  930. $documentID = phpQuery::getDocumentID($document);
  931. $eventNode = self::getNode($documentID, $node);
  932. if (is_object($eventNode) && isset($eventNode->eventHandlers[$type])) {
  933. if ($callback) {
  934. foreach($eventNode->eventHandlers[$type] as $k => $handler)
  935. if ($handler['callback'] == $callback)
  936. unset($eventNode->eventHandlers[$type][$k]);
  937. } else {
  938. unset($eventNode->eventHandlers[$type]);
  939. }
  940. }
  941. }
  942. protected static function getNode($documentID, $node) {
  943. foreach(phpQuery::$documents[$documentID]->eventsNodes as $eventNode) {
  944. if ($node->isSameNode($eventNode))
  945. return $eventNode;
  946. }
  947. }
  948. protected static function setNode($documentID, $node) {
  949. phpQuery::$documents[$documentID]->eventsNodes[] = $node;
  950. return phpQuery::$documents[$documentID]->eventsNodes[
  951. count(phpQuery::$documents[$documentID]->eventsNodes)-1
  952. ];
  953. }
  954. protected static function issetGlobal($documentID, $type) {
  955. return isset(phpQuery::$documents[$documentID])
  956. ? in_array($type, phpQuery::$documents[$documentID]->eventsGlobal)
  957. : false;
  958. }
  959. }
  960. interface ICallbackNamed {
  961. function hasName();
  962. function getName();
  963. }
  964. /**
  965. * Callback class introduces currying-like pattern.
  966. *
  967. * Example:
  968. * function foo($param1, $param2, $param3) {
  969. * var_dump($param1, $param2, $param3);
  970. * }
  971. * $fooCurried = new Callback('foo',
  972. * 'param1 is now statically set',
  973. * new CallbackParam, new CallbackParam
  974. * );
  975. * phpQuery::callbackRun($fooCurried,
  976. * array('param2 value', 'param3 value'
  977. * );
  978. *
  979. * Callback class is supported in all phpQuery methods which accepts callbacks.
  980. *
  981. * @link http://code.google.com/p/phpquery/wiki/Callbacks#Param_Structures
  982. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  983. *
  984. * @TODO??? return fake forwarding function created via create_function
  985. * @TODO honor paramStructure
  986. */
  987. class Callback
  988. implements ICallbackNamed {
  989. public $callback = null;
  990. public $params = null;
  991. protected $name;
  992. public function __construct($callback, $param1 = null, $param2 = null,
  993. $param3 = null) {
  994. $params = func_get_args();
  995. $params = array_slice($params, 1);
  996. if ($callback instanceof Callback) {
  997. // TODO implement recurention
  998. } else {
  999. $this->callback = $callback;
  1000. $this->params = $params;
  1001. }
  1002. }
  1003. public function getName() {
  1004. return 'Callback: '.$this->name;
  1005. }
  1006. public function hasName() {
  1007. return isset($this->name) && $this->name;
  1008. }
  1009. public function setName($name) {
  1010. $this->name = $name;
  1011. return $this;
  1012. }
  1013. // TODO test me
  1014. // public function addParams() {
  1015. // $params = func_get_args();
  1016. // return new Callback($this->callback, $this->params+$params);
  1017. // }
  1018. }
  1019. /**
  1020. * Shorthand for new Callback(create_function(...), ...);
  1021. *
  1022. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  1023. */
  1024. class CallbackBody extends Callback {
  1025. public function __construct($paramList, $code, $param1 = null, $param2 = null,
  1026. $param3 = null) {
  1027. $params = func_get_args();
  1028. $params = array_slice($params, 2);
  1029. $this->callback = function (&...$args) use ($paramList, $code) {
  1030. $paramListArray = explode(',', $paramList);
  1031. for ($i = 0; $i < count($paramListArray); $i++) {
  1032. $param = trim($paramListArray[$i]);
  1033. if ($param[0] === '&') {
  1034. $paramName = ltrim($param, '&$');
  1035. ${$paramName} = &$args[$i];
  1036. } else {
  1037. $paramName = ltrim($param, '$');
  1038. ${$paramName} = $args[$i];
  1039. }
  1040. }
  1041. return eval($code);
  1042. };
  1043. $this->params = $params;
  1044. }
  1045. }
  1046. /**
  1047. * Callback type which on execution returns reference passed during creation.
  1048. *
  1049. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  1050. */
  1051. class CallbackReturnReference extends Callback
  1052. implements ICallbackNamed {
  1053. protected $reference;
  1054. public function __construct(&$reference, $name = null){
  1055. $this->reference =& $reference;
  1056. $this->callback = array($this, 'callback');
  1057. }
  1058. public function callback() {
  1059. return $this->reference;
  1060. }
  1061. public function getName() {
  1062. return 'Callback: '.$this->name;
  1063. }
  1064. public function hasName() {
  1065. return isset($this->name) && $this->name;
  1066. }
  1067. }
  1068. /**
  1069. * Callback type which on execution returns value passed during creation.
  1070. *
  1071. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  1072. */
  1073. class CallbackReturnValue extends Callback
  1074. implements ICallbackNamed {
  1075. protected $value;
  1076. protected $name;
  1077. public function __construct($value, $name = null){
  1078. $this->value =& $value;
  1079. $this->name = $name;
  1080. $this->callback = array($this, 'callback');
  1081. }
  1082. public function callback() {
  1083. return $this->value;
  1084. }
  1085. public function __toString() {
  1086. return $this->getName();
  1087. }
  1088. public function getName() {
  1089. return 'Callback: '.$this->name;
  1090. }
  1091. public function hasName() {
  1092. return isset($this->name) && $this->name;
  1093. }
  1094. }
  1095. /**
  1096. * CallbackParameterToReference can be used when we don't really want a callback,
  1097. * only parameter passed to it. CallbackParameterToReference takes first
  1098. * parameter's value and passes it to reference.
  1099. *
  1100. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  1101. */
  1102. class CallbackParameterToReference extends Callback {
  1103. /**
  1104. * @param $reference
  1105. * @TODO implement $paramIndex;
  1106. * param index choose which callback param will be passed to reference
  1107. */
  1108. public function __construct(&$reference){
  1109. $this->callback =& $reference;
  1110. }
  1111. }
  1112. //class CallbackReference extends Callback {
  1113. // /**
  1114. // *
  1115. // * @param $reference
  1116. // * @param $paramIndex
  1117. // * @todo implement $paramIndex; param index choose which callback param will be passed to reference
  1118. // */
  1119. // public function __construct(&$reference, $name = null){
  1120. // $this->callback =& $reference;
  1121. // }
  1122. //}
  1123. class CallbackParam {}
  1124. /**
  1125. * Class representing phpQuery objects.
  1126. *
  1127. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  1128. * @package phpQuery
  1129. * @method phpQueryObject clone() clone()
  1130. * @method phpQueryObject empty() empty()
  1131. * @method phpQueryObject next() next($selector = null)
  1132. * @method phpQueryObject prev() prev($selector = null)
  1133. * @property Int $length
  1134. */
  1135. class phpQueryObject
  1136. implements Iterator, Countable, ArrayAccess {
  1137. public $documentID = null;
  1138. /**
  1139. * DOMDocument class.
  1140. *
  1141. * @var DOMDocument
  1142. */
  1143. public $document = null;
  1144. public $charset = null;
  1145. /**
  1146. *
  1147. * @var DOMDocumentWrapper
  1148. */
  1149. public $documentWrapper = null;
  1150. /**
  1151. * XPath interface.
  1152. *
  1153. * @var DOMXPath
  1154. */
  1155. public $xpath = null;
  1156. /**
  1157. * Stack of selected elements.
  1158. * @TODO refactor to ->nodes
  1159. * @var array
  1160. */
  1161. public $elements = array();
  1162. /**
  1163. * @access private
  1164. */
  1165. protected $elementsBackup = array();
  1166. /**
  1167. * @access private
  1168. */
  1169. protected $previous = null;
  1170. /**
  1171. * @access private
  1172. * @TODO deprecate
  1173. */
  1174. protected $root = array();
  1175. /**
  1176. * Indicated if doument is just a fragment (no <html> tag).
  1177. *
  1178. * Every document is really a full document, so even documentFragments can
  1179. * be queried against <html>, but getDocument(id)->htmlOuter() will return
  1180. * only contents of <body>.
  1181. *
  1182. * @var bool
  1183. */
  1184. public $documentFragment = true;
  1185. /**
  1186. * Iterator interface helper
  1187. * @access private
  1188. */
  1189. protected $elementsIterator = array();
  1190. /**
  1191. * Iterator interface helper
  1192. * @var bool
  1193. * @access private
  1194. */
  1195. protected $valid = false;
  1196. /**
  1197. * Iterator interface helper
  1198. * @access private
  1199. */
  1200. protected $current = null;
  1201. /**
  1202. * Enter description here...
  1203. *
  1204. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1205. */
  1206. public function __construct($documentID) {
  1207. // if ($documentID instanceof self)
  1208. // var_dump($documentID->getDocumentID());
  1209. $id = $documentID instanceof self
  1210. ? $documentID->getDocumentID()
  1211. : $documentID;
  1212. // var_dump($id);
  1213. if (! isset(phpQuery::$documents[$id] )) {
  1214. // var_dump(phpQuery::$documents);
  1215. throw new Exception("Document with ID '{$id}' isn't loaded. Use phpQuery::newDocument(\$html) or phpQuery::newDocumentFile(\$file) first.");
  1216. }
  1217. $this->documentID = $id;
  1218. $this->documentWrapper =& phpQuery::$documents[$id];
  1219. $this->document =& $this->documentWrapper->document;
  1220. $this->xpath =& $this->documentWrapper->xpath;
  1221. $this->charset =& $this->documentWrapper->charset;
  1222. $this->documentFragment =& $this->documentWrapper->isDocumentFragment;
  1223. // TODO check $this->DOM->documentElement;
  1224. // $this->root = $this->document->documentElement;
  1225. $this->root =& $this->documentWrapper->root;
  1226. // $this->toRoot();
  1227. $this->elements = array($this->root);
  1228. }
  1229. /**
  1230. *
  1231. * @access private
  1232. * @param $attr
  1233. * @return unknown_type
  1234. */
  1235. public function __get($attr) {
  1236. switch($attr) {
  1237. // FIXME doesnt work at all ?
  1238. case 'length':
  1239. return $this->size();
  1240. break;
  1241. default:
  1242. return $this->$attr;
  1243. }
  1244. }
  1245. /**
  1246. * Saves actual object to $var by reference.
  1247. * Useful when need to break chain.
  1248. * @param phpQueryObject $var
  1249. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1250. */
  1251. public function toReference(&$var) {
  1252. return $var = $this;
  1253. }
  1254. public function documentFragment($state = null) {
  1255. if ($state) {
  1256. phpQuery::$documents[$this->getDocumentID()]['documentFragment'] = $state;
  1257. return $this;
  1258. }
  1259. return $this->documentFragment;
  1260. }
  1261. /**
  1262. * @access private
  1263. * @TODO documentWrapper
  1264. */
  1265. protected function isRoot( $node) {
  1266. // return $node instanceof DOMDOCUMENT || $node->tagName == 'html';
  1267. return $node instanceof DOMDOCUMENT
  1268. || ($node instanceof DOMELEMENT && $node->tagName == 'html')
  1269. || $this->root->isSameNode($node);
  1270. }
  1271. /**
  1272. * @access private
  1273. */
  1274. protected function stackIsRoot() {
  1275. return $this->size() == 1 && $this->isRoot($this->elements[0]);
  1276. }
  1277. /**
  1278. * Enter description here...
  1279. * NON JQUERY METHOD
  1280. *
  1281. * Watch out, it doesn't creates new instance, can be reverted with end().
  1282. *
  1283. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1284. */
  1285. public function toRoot() {
  1286. $this->elements = array($this->root);
  1287. return $this;
  1288. // return $this->newInstance(array($this->root));
  1289. }
  1290. /**
  1291. * Saves object's DocumentID to $var by reference.
  1292. * <code>
  1293. * $myDocumentId;
  1294. * phpQuery::newDocument('<div/>')
  1295. * ->getDocumentIDRef($myDocumentId)
  1296. * ->find('div')->...
  1297. * </code>
  1298. *
  1299. * @param unknown_type $domId
  1300. * @see phpQuery::newDocument
  1301. * @see phpQuery::newDocumentFile
  1302. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1303. */
  1304. public function getDocumentIDRef(&$documentID) {
  1305. $documentID = $this->getDocumentID();
  1306. return $this;
  1307. }
  1308. /**
  1309. * Returns object with stack set to document root.
  1310. *
  1311. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1312. */
  1313. public function getDocument() {
  1314. return phpQuery::getDocument($this->getDocumentID());
  1315. }
  1316. /**
  1317. *
  1318. * @return DOMDocument
  1319. */
  1320. public function getDOMDocument() {
  1321. return $this->document;
  1322. }
  1323. /**
  1324. * Get object's Document ID.
  1325. *
  1326. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1327. */
  1328. public function getDocumentID() {
  1329. return $this->documentID;
  1330. }
  1331. /**
  1332. * Unloads whole document from memory.
  1333. * CAUTION! None further operations will be possible on this document.
  1334. * All objects referring to it will be useless.
  1335. *
  1336. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1337. */
  1338. public function unloadDocument() {
  1339. phpQuery::unloadDocuments($this->getDocumentID());
  1340. }
  1341. public function isHTML() {
  1342. return $this->documentWrapper->isHTML;
  1343. }
  1344. public function isXHTML() {
  1345. return $this->documentWrapper->isXHTML;
  1346. }
  1347. public function isXML() {
  1348. return $this->documentWrapper->isXML;
  1349. }
  1350. /**
  1351. * Enter description here...
  1352. *
  1353. * @link http://docs.jquery.com/Ajax/serialize
  1354. * @return string
  1355. */
  1356. public function serialize() {
  1357. return phpQuery::param($this->serializeArray());
  1358. }
  1359. /**
  1360. * Enter description here...
  1361. *
  1362. * @link http://docs.jquery.com/Ajax/serializeArray
  1363. * @return array
  1364. */
  1365. public function serializeArray($submit = null) {
  1366. $source = $this->filter('form, input, select, textarea')
  1367. ->find('input, select, textarea')
  1368. ->andSelf()
  1369. ->not('form');
  1370. $return = array();
  1371. // $source->dumpDie();
  1372. foreach($source as $input) {
  1373. $input = phpQuery::pq($input);
  1374. if ($input->is('[disabled]'))
  1375. continue;
  1376. if (!$input->is('[name]'))
  1377. continue;
  1378. if ($input->is('[type=checkbox]') && !$input->is('[checked]'))
  1379. continue;
  1380. // jquery diff
  1381. if ($submit && $input->is('[type=submit]')) {
  1382. if ($submit instanceof DOMELEMENT && ! $input->elements[0]->isSameNode($submit))
  1383. continue;
  1384. else if (is_string($submit) && $input->attr('name') != $submit)
  1385. continue;
  1386. }
  1387. $return[] = array(
  1388. 'name' => $input->attr('name'),
  1389. 'value' => $input->val(),
  1390. );
  1391. }
  1392. return $return;
  1393. }
  1394. /**
  1395. * @access private
  1396. */
  1397. protected function debug($in) {
  1398. if (! phpQuery::$debug )
  1399. return;
  1400. print('<pre>');
  1401. print_r($in);
  1402. // file debug
  1403. // file_put_contents(dirname(__FILE__).'/phpQuery.log', print_r($in, true)."\n", FILE_APPEND);
  1404. // quite handy debug trace
  1405. // if ( is_array($in))
  1406. // print_r(array_slice(debug_backtrace(), 3));
  1407. print("</pre>\n");
  1408. }
  1409. /**
  1410. * @access private
  1411. */
  1412. protected function isRegexp($pattern) {
  1413. return in_array(
  1414. $pattern[ mb_strlen($pattern)-1 ],
  1415. array('^','*','$')
  1416. );
  1417. }
  1418. /**
  1419. * Determines if $char is really a char.
  1420. *
  1421. * @param string $char
  1422. * @return bool
  1423. * @todo rewrite me to charcode range ! ;)
  1424. * @access private
  1425. */
  1426. protected function isChar($char) {
  1427. return extension_loaded('mbstring') && phpQuery::$mbstringSupport
  1428. ? mb_eregi('\w', $char)
  1429. : preg_match('@\w@', $char);
  1430. }
  1431. /**
  1432. * @access private
  1433. */
  1434. protected function parseSelector($query) {
  1435. // clean spaces
  1436. // TODO include this inside parsing ?
  1437. $query = trim(
  1438. preg_replace('@\s+@', ' ',
  1439. preg_replace('@\s*(>|\\+|~)\s*@', '\\1', $query)
  1440. )
  1441. );
  1442. $queries = array(array());
  1443. if (! $query)
  1444. return $queries;
  1445. $return =& $queries[0];
  1446. $specialChars = array('>',' ');
  1447. // $specialCharsMapping = array('/' => '>');
  1448. $specialCharsMapping = array();
  1449. $strlen = mb_strlen($query);
  1450. $classChars = array('.', '-');
  1451. $pseudoChars = array('-');
  1452. $tagChars = array('*', '|', '-');
  1453. // split multibyte string
  1454. // http://code.google.com/p/phpquery/issues/detail?id=76
  1455. $_query = array();
  1456. for ($i=0; $i<$strlen; $i++)
  1457. $_query[] = mb_substr($query, $i, 1);
  1458. $query = $_query;
  1459. // it works, but i dont like it...
  1460. $i = 0;
  1461. while( $i < $strlen) {
  1462. $c = $query[$i];
  1463. $tmp = '';
  1464. // TAG
  1465. if ($this->isChar($c) || in_array($c, $tagChars)) {
  1466. while(isset($query[$i])
  1467. && ($this->isChar($query[$i]) || in_array($query[$i], $tagChars))) {
  1468. $tmp .= $query[$i];
  1469. $i++;
  1470. }
  1471. $return[] = $tmp;
  1472. // IDs
  1473. } else if ( $c == '#') {
  1474. $i++;
  1475. while( isset($query[$i]) && ($this->isChar($query[$i]) || $query[$i] == '-')) {
  1476. $tmp .= $query[$i];
  1477. $i++;
  1478. }
  1479. $return[] = '#'.$tmp;
  1480. // SPECIAL CHARS
  1481. } else if (in_array($c, $specialChars)) {
  1482. $return[] = $c;
  1483. $i++;
  1484. // MAPPED SPECIAL MULTICHARS
  1485. // } else if ( $c.$query[$i+1] == '//') {
  1486. // $return[] = ' ';
  1487. // $i = $i+2;
  1488. // MAPPED SPECIAL CHARS
  1489. } else if ( isset($specialCharsMapping[$c])) {
  1490. $return[] = $specialCharsMapping[$c];
  1491. $i++;
  1492. // COMMA
  1493. } else if ( $c == ',') {
  1494. $queries[] = array();
  1495. $return =& $queries[ count($queries)-1 ];
  1496. $i++;
  1497. while( isset($query[$i]) && $query[$i] == ' ')
  1498. $i++;
  1499. // CLASSES
  1500. } else if ($c == '.') {
  1501. while( isset($query[$i]) && ($this->isChar($query[$i]) || in_array($query[$i], $classChars))) {
  1502. $tmp .= $query[$i];
  1503. $i++;
  1504. }
  1505. $return[] = $tmp;
  1506. // ~ General Sibling Selector
  1507. } else if ($c == '~') {
  1508. $spaceAllowed = true;
  1509. $tmp .= $query[$i++];
  1510. while( isset($query[$i])
  1511. && ($this->isChar($query[$i])
  1512. || in_array($query[$i], $classChars)
  1513. || $query[$i] == '*'
  1514. || ($query[$i] == ' ' && $spaceAllowed)
  1515. )) {
  1516. if ($query[$i] != ' ')
  1517. $spaceAllowed = false;
  1518. $tmp .= $query[$i];
  1519. $i++;
  1520. }
  1521. $return[] = $tmp;
  1522. // + Adjacent sibling selectors
  1523. } else if ($c == '+') {
  1524. $spaceAllowed = true;
  1525. $tmp .= $query[$i++];
  1526. while( isset($query[$i])
  1527. && ($this->isChar($query[$i])
  1528. || in_array($query[$i], $classChars)
  1529. || $query[$i] == '*'
  1530. || ($spaceAllowed && $query[$i] == ' ')
  1531. )) {
  1532. if ($query[$i] != ' ')
  1533. $spaceAllowed = false;
  1534. $tmp .= $query[$i];
  1535. $i++;
  1536. }
  1537. $return[] = $tmp;
  1538. // ATTRS
  1539. } else if ($c == '[') {
  1540. $stack = 1;
  1541. $tmp .= $c;
  1542. while( isset($query[++$i])) {
  1543. $tmp .= $query[$i];
  1544. if ( $query[$i] == '[') {
  1545. $stack++;
  1546. } else if ( $query[$i] == ']') {
  1547. $stack--;
  1548. if (! $stack )
  1549. break;
  1550. }
  1551. }
  1552. $return[] = $tmp;
  1553. $i++;
  1554. // PSEUDO CLASSES
  1555. } else if ($c == ':') {
  1556. $stack = 1;
  1557. $tmp .= $query[$i++];
  1558. while( isset($query[$i]) && ($this->isChar($query[$i]) || in_array($query[$i], $pseudoChars))) {
  1559. $tmp .= $query[$i];
  1560. $i++;
  1561. }
  1562. // with arguments ?
  1563. if ( isset($query[$i]) && $query[$i] == '(') {
  1564. $tmp .= $query[$i];
  1565. $stack = 1;
  1566. while( isset($query[++$i])) {
  1567. $tmp .= $query[$i];
  1568. if ( $query[$i] == '(') {
  1569. $stack++;
  1570. } else if ( $query[$i] == ')') {
  1571. $stack--;
  1572. if (! $stack )
  1573. break;
  1574. }
  1575. }
  1576. $return[] = $tmp;
  1577. $i++;
  1578. } else {
  1579. $return[] = $tmp;
  1580. }
  1581. } else {
  1582. $i++;
  1583. }
  1584. }
  1585. foreach($queries as $k => $q) {
  1586. if (isset($q[0])) {
  1587. if (isset($q[0][0]) && $q[0][0] == ':')
  1588. array_unshift($queries[$k], '*');
  1589. if ($q[0] != '>')
  1590. array_unshift($queries[$k], ' ');
  1591. }
  1592. }
  1593. return $queries;
  1594. }
  1595. /**
  1596. * Return matched DOM nodes.
  1597. *
  1598. * @param int $index
  1599. * @return array|DOMElement Single DOMElement or array of DOMElement.
  1600. */
  1601. public function get($index = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  1602. $return = isset($index)
  1603. ? (isset($this->elements[$index]) ? $this->elements[$index] : null)
  1604. : $this->elements;
  1605. // pass thou callbacks
  1606. $args = func_get_args();
  1607. $args = array_slice($args, 1);
  1608. foreach($args as $callback) {
  1609. if (is_array($return))
  1610. foreach($return as $k => $v)
  1611. $return[$k] = phpQuery::callbackRun($callback, array($v));
  1612. else
  1613. $return = phpQuery::callbackRun($callback, array($return));
  1614. }
  1615. return $return;
  1616. }
  1617. /**
  1618. * Return matched DOM nodes.
  1619. * jQuery difference.
  1620. *
  1621. * @param int $index
  1622. * @return array|string Returns string if $index != null
  1623. * @todo implement callbacks
  1624. * @todo return only arrays ?
  1625. * @todo maybe other name...
  1626. */
  1627. public function getString($index = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  1628. if ($index)
  1629. $return = $this->eq($index)->text();
  1630. else {
  1631. $return = array();
  1632. for($i = 0; $i < $this->size(); $i++) {
  1633. $return[] = $this->eq($i)->text();
  1634. }
  1635. }
  1636. // pass thou callbacks
  1637. $args = func_get_args();
  1638. $args = array_slice($args, 1);
  1639. foreach($args as $callback) {
  1640. $return = phpQuery::callbackRun($callback, array($return));
  1641. }
  1642. return $return;
  1643. }
  1644. /**
  1645. * Return matched DOM nodes.
  1646. * jQuery difference.
  1647. *
  1648. * @param int $index
  1649. * @return array|string Returns string if $index != null
  1650. * @todo implement callbacks
  1651. * @todo return only arrays ?
  1652. * @todo maybe other name...
  1653. */
  1654. public function getStrings($index = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  1655. if ($index)
  1656. $return = $this->eq($index)->text();
  1657. else {
  1658. $return = array();
  1659. for($i = 0; $i < $this->size(); $i++) {
  1660. $return[] = $this->eq($i)->text();
  1661. }
  1662. // pass thou callbacks
  1663. $args = func_get_args();
  1664. $args = array_slice($args, 1);
  1665. }
  1666. foreach($args as $callback) {
  1667. if (is_array($return))
  1668. foreach($return as $k => $v)
  1669. $return[$k] = phpQuery::callbackRun($callback, array($v));
  1670. else
  1671. $return = phpQuery::callbackRun($callback, array($return));
  1672. }
  1673. return $return;
  1674. }
  1675. /**
  1676. * Returns new instance of actual class.
  1677. *
  1678. * @param array $newStack Optional. Will replace old stack with new and move old one to history.c
  1679. */
  1680. public function newInstance($newStack = null) {
  1681. $class = get_class($this);
  1682. // support inheritance by passing old object to overloaded constructor
  1683. $new = $class != 'phpQuery'
  1684. ? new $class($this, $this->getDocumentID())
  1685. : new phpQueryObject($this->getDocumentID());
  1686. $new->previous = $this;
  1687. if (is_null($newStack)) {
  1688. $new->elements = $this->elements;
  1689. if ($this->elementsBackup)
  1690. $this->elements = $this->elementsBackup;
  1691. } else if (is_string($newStack)) {
  1692. $new->elements = phpQuery::pq($newStack, $this->getDocumentID())->stack();
  1693. } else {
  1694. $new->elements = $newStack;
  1695. }
  1696. return $new;
  1697. }
  1698. /**
  1699. * Enter description here...
  1700. *
  1701. * In the future, when PHP will support XLS 2.0, then we would do that this way:
  1702. * contains(tokenize(@class, '\s'), "something")
  1703. * @param string $class
  1704. * @param DOMElement $node
  1705. * @access private
  1706. */
  1707. protected function matchClasses(string $class, object $node): bool {
  1708. // multi-class
  1709. if ( mb_strpos($class, '.', 1)) {
  1710. $classes = explode('.', substr($class, 1));
  1711. $classesCount = count( $classes );
  1712. $nodeClasses = explode(' ', $node->getAttribute('class') );
  1713. $nodeClassesCount = count( $nodeClasses );
  1714. if ( $classesCount > $nodeClassesCount )
  1715. return false;
  1716. $diff = count(
  1717. array_diff(
  1718. $classes,
  1719. $nodeClasses
  1720. )
  1721. );
  1722. if (! $diff )
  1723. return true;
  1724. // single-class
  1725. } else {
  1726. return in_array(
  1727. // strip leading dot from class name
  1728. substr($class, 1),
  1729. // get classes for element as array
  1730. explode(' ', $node->getAttribute('class') )
  1731. );
  1732. }
  1733. }
  1734. /**
  1735. * @access private
  1736. */
  1737. protected function runQuery($XQuery, $selector = null, $compare = null) {
  1738. if ($compare && ! method_exists($this, $compare))
  1739. return false;
  1740. $stack = array();
  1741. if (! $this->elements)
  1742. $this->debug('Stack empty, skipping...');
  1743. // var_dump($this->elements[0]->nodeType);
  1744. // element, document
  1745. foreach($this->stack(array(1, 9, 13)) as $k => $stackNode) {
  1746. $detachAfter = false;
  1747. // to work on detached nodes we need temporary place them somewhere
  1748. // thats because context xpath queries sucks ;]
  1749. $testNode = $stackNode;
  1750. while ($testNode) {
  1751. if (! $testNode->parentNode && ! $this->isRoot($testNode)) {
  1752. $this->root->appendChild($testNode);
  1753. $detachAfter = $testNode;
  1754. break;
  1755. }
  1756. $testNode = isset($testNode->parentNode)
  1757. ? $testNode->parentNode
  1758. : null;
  1759. }
  1760. // XXX tmp ?
  1761. $xpath = $this->documentWrapper->isXHTML
  1762. ? $this->getNodeXpath($stackNode, 'html')
  1763. : $this->getNodeXpath($stackNode);
  1764. // FIXME pseudoclasses-only query, support XML
  1765. $query = $XQuery == '//' && $xpath == '/html[1]'
  1766. ? '//*'
  1767. : $xpath.$XQuery;
  1768. $this->debug("XPATH: {$query}");
  1769. // run query, get elements
  1770. $nodes = $this->xpath->query($query);
  1771. $this->debug("QUERY FETCHED");
  1772. if (! $nodes->length )
  1773. $this->debug('Nothing found');
  1774. $debug = array();
  1775. foreach($nodes as $node) {
  1776. $matched = false;
  1777. if ( $compare) {
  1778. phpQuery::$debug ?
  1779. $this->debug("Found: ".$this->whois( $node ).", comparing with {$compare}()")
  1780. : null;
  1781. $phpQueryDebug = phpQuery::$debug;
  1782. phpQuery::$debug = false;
  1783. // TODO ??? use phpQuery::callbackRun()
  1784. if (call_user_func_array(array($this, $compare), array($selector, $node)))
  1785. $matched = true;
  1786. phpQuery::$debug = $phpQueryDebug;
  1787. } else {
  1788. $matched = true;
  1789. }
  1790. if ( $matched) {
  1791. if (phpQuery::$debug)
  1792. $debug[] = $this->whois( $node );
  1793. $stack[] = $node;
  1794. }
  1795. }
  1796. if (phpQuery::$debug) {
  1797. $this->debug("Matched ".count($debug).": ".implode(', ', $debug));
  1798. }
  1799. if ($detachAfter)
  1800. $this->root->removeChild($detachAfter);
  1801. }
  1802. $this->elements = $stack;
  1803. }
  1804. /**
  1805. * used for ordering results in find()
  1806. */
  1807. private function cmpByLineNo($a , $b) {
  1808. return $a->getLineNo() <= $b->getLineNo() ? -1 : 1;
  1809. }
  1810. /**
  1811. * Enter description here...
  1812. *
  1813. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1814. */
  1815. public function find($selectors, $context = null, $noHistory = false) {
  1816. if (!$noHistory)
  1817. // backup last stack /for end()/
  1818. $this->elementsBackup = $this->elements;
  1819. // allow to define context
  1820. // TODO combine code below with phpQuery::pq() context guessing code
  1821. // as generic function
  1822. if ($context) {
  1823. if (! is_array($context) && $context instanceof DOMELEMENT)
  1824. $this->elements = array($context);
  1825. else if (is_array($context)) {
  1826. $this->elements = array();
  1827. foreach ($context as $c)
  1828. if ($c instanceof DOMELEMENT)
  1829. $this->elements[] = $c;
  1830. } else if ( $context instanceof self )
  1831. $this->elements = $context->elements;
  1832. }
  1833. $queries = $this->parseSelector($selectors);
  1834. $this->debug(array('FIND', $selectors, $queries));
  1835. $XQuery = '';
  1836. // remember stack state because of multi-queries
  1837. $oldStack = $this->elements;
  1838. // here we will be keeping found elements
  1839. $stack = array();
  1840. foreach($queries as $selector) {
  1841. $this->elements = $oldStack;
  1842. $delimiterBefore = false;
  1843. foreach($selector as $s) {
  1844. // TAG
  1845. $isTag = extension_loaded('mbstring') && phpQuery::$mbstringSupport
  1846. ? mb_ereg_match('^[\w|\||-]+$', $s) || $s == '*'
  1847. : preg_match('@^[\w|\||-]+$@', $s) || $s == '*';
  1848. if ($isTag) {
  1849. if ($this->isXML()) {
  1850. // namespace support
  1851. if (mb_strpos($s, '|') !== false) {
  1852. $ns = $tag = null;
  1853. list($ns, $tag) = explode('|', $s);
  1854. $XQuery .= "$ns:$tag";
  1855. } else if ($s == '*') {
  1856. $XQuery .= "*";
  1857. } else {
  1858. $XQuery .= "*[local-name()='$s']";
  1859. }
  1860. } else {
  1861. $XQuery .= $s;
  1862. }
  1863. // ID
  1864. } else if ($s[0] == '#') {
  1865. if ($delimiterBefore)
  1866. $XQuery .= '*';
  1867. $XQuery .= "[@id='".substr($s, 1)."']";
  1868. // ATTRIBUTES
  1869. } else if ($s[0] == '[') {
  1870. if ($delimiterBefore)
  1871. $XQuery .= '*';
  1872. // strip side brackets
  1873. $attr = trim($s, '][');
  1874. $execute = false;
  1875. // attr with specified value
  1876. if (mb_strpos($s, '=')) {
  1877. $value = null;
  1878. list($attr, $value) = explode('=', $attr);
  1879. $value = trim($value, "'\"");
  1880. if ($this->isRegexp($attr)) {
  1881. // cut regexp character
  1882. $attr = substr($attr, 0, -1);
  1883. $execute = true;
  1884. $XQuery .= "[@{$attr}]";
  1885. } else {
  1886. $XQuery .= "[@{$attr}='{$value}']";
  1887. }
  1888. // attr without specified value
  1889. } else {
  1890. $XQuery .= "[@{$attr}]";
  1891. }
  1892. if ($execute) {
  1893. $this->runQuery($XQuery, $s, 'is');
  1894. $XQuery = '';
  1895. if (!$this->size())
  1896. break;
  1897. }
  1898. // CLASSES
  1899. } else if ($s[0] == '.') {
  1900. // TODO use return $this->find("./self::*[contains(concat(\" \",@class,\" \"), \" $class \")]");
  1901. // thx wizDom ;)
  1902. if ($delimiterBefore)
  1903. $XQuery .= '*';
  1904. $XQuery .= '[@class]';
  1905. $this->runQuery($XQuery, $s, 'matchClasses');
  1906. $XQuery = '';
  1907. if (!$this->size() )
  1908. break;
  1909. // ~ General Sibling Selector
  1910. } else if ($s[0] == '~') {
  1911. $this->runQuery($XQuery);
  1912. $XQuery = '';
  1913. $this->elements = $this
  1914. ->siblings(
  1915. substr($s, 1)
  1916. )->elements;
  1917. if (!$this->size() )
  1918. break;
  1919. // + Adjacent sibling selectors
  1920. } else if ($s[0] == '+') {
  1921. // TODO /following-sibling::
  1922. $this->runQuery($XQuery);
  1923. $XQuery = '';
  1924. $subSelector = substr($s, 1);
  1925. $subElements = $this->elements;
  1926. $this->elements = array();
  1927. foreach($subElements as $node) {
  1928. // search first DOMElement sibling
  1929. $test = $node->nextSibling;
  1930. while($test && ! ($test instanceof DOMELEMENT))
  1931. $test = $test->nextSibling;
  1932. if ($test && $this->is($subSelector, $test))
  1933. $this->elements[] = $test;
  1934. }
  1935. if (!$this->size() )
  1936. break;
  1937. // PSEUDO CLASSES
  1938. } else if ($s[0] == ':') {
  1939. // TODO optimization for :first :last
  1940. if ($XQuery) {
  1941. $this->runQuery($XQuery);
  1942. $XQuery = '';
  1943. }
  1944. if (!$this->size())
  1945. break;
  1946. $this->pseudoClasses($s);
  1947. if (!$this->size())
  1948. break;
  1949. // DIRECT DESCENDANDS
  1950. } else if ($s == '>') {
  1951. $XQuery .= '/';
  1952. $delimiterBefore = 2;
  1953. // ALL DESCENDANDS
  1954. } else if ($s == ' ') {
  1955. $XQuery .= '//';
  1956. $delimiterBefore = 2;
  1957. // ERRORS
  1958. } else {
  1959. phpQuery::debug("Unrecognized token '$s'");
  1960. }
  1961. $delimiterBefore = $delimiterBefore === 2;
  1962. }
  1963. // run query if any
  1964. if ($XQuery && $XQuery != '//') {
  1965. $this->runQuery($XQuery);
  1966. $XQuery = '';
  1967. }
  1968. foreach($this->elements as $node)
  1969. if (! $this->elementsContainsNode($node, $stack))
  1970. $stack[] = $node;
  1971. }
  1972. usort($stack, array('phpQueryObject', 'cmpByLineNo'));
  1973. $this->elements = $stack;
  1974. return $this->newInstance();
  1975. }
  1976. /**
  1977. * @todo create API for classes with pseudoselectors
  1978. * @access private
  1979. */
  1980. protected function pseudoClasses($class) {
  1981. // TODO clean args parsing ?
  1982. $class = ltrim($class, ':');
  1983. $haveArgs = mb_strpos($class, '(');
  1984. if ($haveArgs !== false) {
  1985. $args = substr($class, $haveArgs+1, -1);
  1986. $class = substr($class, 0, $haveArgs);
  1987. }
  1988. switch($class) {
  1989. case 'even':
  1990. case 'odd':
  1991. $stack = array();
  1992. foreach($this->elements as $i => $node) {
  1993. if ($class == 'even' && ($i%2) == 0)
  1994. $stack[] = $node;
  1995. else if ( $class == 'odd' && $i % 2 )
  1996. $stack[] = $node;
  1997. }
  1998. $this->elements = $stack;
  1999. break;
  2000. case 'eq':
  2001. $k = intval($args);
  2002. $this->elements = isset( $this->elements[$k] )
  2003. ? array( $this->elements[$k] )
  2004. : array();
  2005. break;
  2006. case 'gt':
  2007. $this->elements = array_slice($this->elements, $args+1);
  2008. break;
  2009. case 'lt':
  2010. $this->elements = array_slice($this->elements, 0, $args+1);
  2011. break;
  2012. case 'first':
  2013. if (isset($this->elements[0]))
  2014. $this->elements = array($this->elements[0]);
  2015. break;
  2016. case 'last':
  2017. if ($this->elements)
  2018. $this->elements = array($this->elements[count($this->elements)-1]);
  2019. break;
  2020. /*case 'parent':
  2021. $stack = array();
  2022. foreach($this->elements as $node) {
  2023. if ( $node->childNodes->length )
  2024. $stack[] = $node;
  2025. }
  2026. $this->elements = $stack;
  2027. break;*/
  2028. case 'contains':
  2029. $text = trim($args, "\"'");
  2030. $stack = array();
  2031. foreach($this->elements as $node) {
  2032. if (mb_stripos($node->textContent, $text) === false)
  2033. continue;
  2034. $stack[] = $node;
  2035. }
  2036. $this->elements = $stack;
  2037. break;
  2038. case 'not':
  2039. $selector = self::unQuote($args);
  2040. $this->elements = $this->not($selector)->stack();
  2041. break;
  2042. case 'slice':
  2043. // TODO jQuery difference ?
  2044. $args = explode(',',
  2045. str_replace(', ', ',', trim($args, "\"'"))
  2046. );
  2047. $start = $args[0];
  2048. $end = isset($args[1])
  2049. ? $args[1]
  2050. : null;
  2051. if ($end > 0)
  2052. $end = $end-$start;
  2053. $this->elements = array_slice($this->elements, $start, $end);
  2054. break;
  2055. case 'has':
  2056. $selector = trim($args, "\"'");
  2057. $stack = array();
  2058. foreach($this->stack(1) as $el) {
  2059. if ($this->find($selector, $el, true)->length)
  2060. $stack[] = $el;
  2061. }
  2062. $this->elements = $stack;
  2063. break;
  2064. case 'submit':
  2065. case 'reset':
  2066. $this->elements = phpQuery::merge(
  2067. $this->map(array($this, 'is'),
  2068. "input[type=$class]", new CallbackParam()
  2069. ),
  2070. $this->map(array($this, 'is'),
  2071. "button[type=$class]", new CallbackParam()
  2072. )
  2073. );
  2074. break;
  2075. // $stack = array();
  2076. // foreach($this->elements as $node)
  2077. // if ($node->is('input[type=submit]') || $node->is('button[type=submit]'))
  2078. // $stack[] = $el;
  2079. // $this->elements = $stack;
  2080. case 'input':
  2081. $this->elements = $this->map(
  2082. array($this, 'is'),
  2083. 'input', new CallbackParam()
  2084. )->elements;
  2085. break;
  2086. case 'password':
  2087. case 'checkbox':
  2088. case 'radio':
  2089. case 'hidden':
  2090. case 'image':
  2091. case 'file':
  2092. $this->elements = $this->map(
  2093. array($this, 'is'),
  2094. "input[type=$class]", new CallbackParam()
  2095. )->elements;
  2096. break;
  2097. case 'parent':
  2098. $this->elements = $this->map(
  2099. function ($node) {
  2100. return $node instanceof DOMELEMENT && $node->childNodes->length
  2101. ? $node : null;
  2102. }
  2103. )->elements;
  2104. break;
  2105. case 'empty':
  2106. $this->elements = $this->map(
  2107. function ($node) {
  2108. return $node instanceof DOMELEMENT && $node->childNodes->length
  2109. ? null : $node;
  2110. }
  2111. )->elements;
  2112. break;
  2113. case 'disabled':
  2114. case 'selected':
  2115. case 'checked':
  2116. $this->elements = $this->map(
  2117. array($this, 'is'),
  2118. "[$class]", new CallbackParam()
  2119. )->elements;
  2120. break;
  2121. case 'enabled':
  2122. $this->elements = $this->map(
  2123. function ($node) {
  2124. return pq($node)->not(":disabled") ? $node : null;
  2125. }
  2126. )->elements;
  2127. break;
  2128. case 'header':
  2129. $this->elements = $this->map(
  2130. function ($node) {
  2131. $isHeader = isset($node->tagName) && in_array($node->tagName, array(
  2132. "h1", "h2", "h3", "h4", "h5", "h6", "h7"
  2133. ));
  2134. return $isHeader
  2135. ? $node
  2136. : null;
  2137. }
  2138. )->elements;
  2139. break;
  2140. case 'only-child':
  2141. $this->elements = $this->map(
  2142. function ($node) {
  2143. return pq($node)->siblings()->size() == 0 ? $node : null;
  2144. }
  2145. )->elements;
  2146. break;
  2147. case 'first-child':
  2148. $this->elements = $this->map(
  2149. function ($node) { return pq($node)->prevAll()->size() == 0 ? $node : null; }
  2150. )->elements;
  2151. break;
  2152. case 'last-child':
  2153. $this->elements = $this->map(
  2154. function ($node) { return pq($node)->nextAll()->size() == 0 ? $node : null; }
  2155. )->elements;
  2156. break;
  2157. case 'nth-child':
  2158. $param = trim($args, "\"'");
  2159. if (! $param)
  2160. break;
  2161. // nth-child(n+b) to nth-child(1n+b)
  2162. if ($param[0] == 'n')
  2163. $param = '1'.$param;
  2164. // :nth-child(index/even/odd/equation)
  2165. if ($param == 'even' || $param == 'odd')
  2166. $mapped = $this->map(
  2167. function ($node, $param) {
  2168. $index = pq($node)->prevAll()->size()+1;
  2169. if ($param == "even" && ($index%2) == 0)
  2170. return $node;
  2171. else if ($param == "odd" && $index%2 == 1)
  2172. return $node;
  2173. else
  2174. return null;
  2175. },
  2176. new CallbackParam(), $param
  2177. );
  2178. else if (mb_strlen($param) > 1 && $param[1] == 'n')
  2179. // an+b
  2180. $mapped = $this->map(
  2181. function ($node, $param) {
  2182. $prevs = pq($node)->prevAll()->size();
  2183. $index = 1+$prevs;
  2184. $b = mb_strlen($param) > 3
  2185. ? $param[3]
  2186. : 0;
  2187. $a = $param[0];
  2188. if ($b && $param[2] == "-")
  2189. $b = -$b;
  2190. if ($a > 0) {
  2191. return ($index-$b)%$a == 0
  2192. ? $node
  2193. : null;
  2194. phpQuery::debug($a."*".floor($index/$a)."+$b-1 == ".($a*floor($index/$a)+$b-1)." ?= $prevs");
  2195. return $a*floor($index/$a)+$b-1 == $prevs
  2196. ? $node
  2197. : null;
  2198. } else if ($a == 0)
  2199. return $index == $b
  2200. ? $node
  2201. : null;
  2202. else
  2203. // negative value
  2204. return $index <= $b
  2205. ? $node
  2206. : null;
  2207. // if (! $b)
  2208. // return $index%$a == 0
  2209. // ? $node
  2210. // : null;
  2211. // else
  2212. // return ($index-$b)%$a == 0
  2213. // ? $node
  2214. // : null;
  2215. },
  2216. new CallbackParam(), $param
  2217. );
  2218. else
  2219. // index
  2220. $mapped = $this->map(
  2221. function ($node, $index) {
  2222. $prevs = pq($node)->prevAll()->size();
  2223. if ($prevs && $prevs == $index-1)
  2224. return $node;
  2225. else if (! $prevs && $index == 1)
  2226. return $node;
  2227. else
  2228. return null;
  2229. },
  2230. new CallbackParam(), $param
  2231. );
  2232. $this->elements = $mapped->elements;
  2233. break;
  2234. default:
  2235. $this->debug("Unknown pseudoclass '{$class}', skipping...");
  2236. }
  2237. }
  2238. /**
  2239. * @access private
  2240. */
  2241. protected function __pseudoClassParam($paramsString) {
  2242. // TODO;
  2243. }
  2244. /**
  2245. * Enter description here...
  2246. *
  2247. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2248. */
  2249. public function is($selector, $nodes = null) {
  2250. phpQuery::debug(array("Is:", $selector));
  2251. if (! $selector)
  2252. return false;
  2253. $oldStack = $this->elements;
  2254. $returnArray = false;
  2255. if ($nodes && is_array($nodes)) {
  2256. $this->elements = $nodes;
  2257. } else if ($nodes)
  2258. $this->elements = array($nodes);
  2259. $this->filter($selector, true);
  2260. $stack = $this->elements;
  2261. $this->elements = $oldStack;
  2262. if ($nodes)
  2263. return $stack ? $stack : null;
  2264. return (bool)count($stack);
  2265. }
  2266. /**
  2267. * Enter description here...
  2268. * jQuery difference.
  2269. *
  2270. * Callback:
  2271. * - $index int
  2272. * - $node DOMNode
  2273. *
  2274. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2275. * @link http://docs.jquery.com/Traversing/filter
  2276. */
  2277. public function filterCallback($callback, $_skipHistory = false) {
  2278. if (! $_skipHistory) {
  2279. $this->elementsBackup = $this->elements;
  2280. $this->debug("Filtering by callback");
  2281. }
  2282. $newStack = array();
  2283. foreach($this->elements as $index => $node) {
  2284. $result = phpQuery::callbackRun($callback, array($index, $node));
  2285. if (is_null($result) || (! is_null($result) && $result))
  2286. $newStack[] = $node;
  2287. }
  2288. $this->elements = $newStack;
  2289. return $_skipHistory
  2290. ? $this
  2291. : $this->newInstance();
  2292. }
  2293. /**
  2294. * Enter description here...
  2295. *
  2296. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2297. * @link http://docs.jquery.com/Traversing/filter
  2298. */
  2299. public function filter($selectors, $_skipHistory = false) {
  2300. if ($selectors instanceof Callback OR $selectors instanceof Closure)
  2301. return $this->filterCallback($selectors, $_skipHistory);
  2302. if (! $_skipHistory)
  2303. $this->elementsBackup = $this->elements;
  2304. $notSimpleSelector = array(' ', '>', '~', '+', '/');
  2305. if (! is_array($selectors))
  2306. $selectors = $this->parseSelector($selectors);
  2307. if (! $_skipHistory)
  2308. $this->debug(array("Filtering:", $selectors));
  2309. $finalStack = array();
  2310. foreach($selectors as $selector) {
  2311. $stack = array();
  2312. if (! $selector)
  2313. break;
  2314. // avoid first space or /
  2315. if (in_array($selector[0], $notSimpleSelector))
  2316. $selector = array_slice($selector, 1);
  2317. // PER NODE selector chunks
  2318. foreach($this->stack() as $node) {
  2319. $break = false;
  2320. foreach($selector as $s) {
  2321. if (!($node instanceof DOMELEMENT)) {
  2322. // all besides DOMElement
  2323. if ( $s[0] == '[') {
  2324. $attr = trim($s, '[]');
  2325. if ( mb_strpos($attr, '=')) {
  2326. list( $attr, $val ) = explode('=', $attr);
  2327. if ($attr == 'nodeType' && $node->nodeType != $val)
  2328. $break = true;
  2329. }
  2330. } else
  2331. $break = true;
  2332. } else {
  2333. // DOMElement only
  2334. // ID
  2335. if ( $s[0] == '#') {
  2336. if ( $node->getAttribute('id') != substr($s, 1) )
  2337. $break = true;
  2338. // CLASSES
  2339. } else if ( $s[0] == '.') {
  2340. if (! $this->matchClasses( $s, $node ) )
  2341. $break = true;
  2342. // ATTRS
  2343. } else if ( $s[0] == '[') {
  2344. // strip side brackets
  2345. $attr = trim($s, '[]');
  2346. if (mb_strpos($attr, '=')) {
  2347. list($attr, $val) = explode('=', $attr);
  2348. $val = self::unQuote($val);
  2349. if ($attr == 'nodeType') {
  2350. if ($val != $node->nodeType)
  2351. $break = true;
  2352. } else if ($this->isRegexp($attr)) {
  2353. $val = extension_loaded('mbstring') && phpQuery::$mbstringSupport
  2354. ? quotemeta(trim($val, '"\''))
  2355. : preg_quote(trim($val, '"\''), '@');
  2356. // switch last character
  2357. switch( substr($attr, -1)) {
  2358. // quotemeta used insted of preg_quote
  2359. // http://code.google.com/p/phpquery/issues/detail?id=76
  2360. case '^':
  2361. $pattern = '^'.$val;
  2362. break;
  2363. case '*':
  2364. $pattern = '.*'.$val.'.*';
  2365. break;
  2366. case '$':
  2367. $pattern = '.*'.$val.'$';
  2368. break;
  2369. }
  2370. // cut last character
  2371. $attr = substr($attr, 0, -1);
  2372. $isMatch = extension_loaded('mbstring') && phpQuery::$mbstringSupport
  2373. ? mb_ereg_match($pattern, $node->getAttribute($attr))
  2374. : preg_match("@{$pattern}@", $node->getAttribute($attr));
  2375. if (! $isMatch)
  2376. $break = true;
  2377. } else if ($node->getAttribute($attr) != $val)
  2378. $break = true;
  2379. } else if (! $node->hasAttribute($attr))
  2380. $break = true;
  2381. // PSEUDO CLASSES
  2382. } else if ( $s[0] == ':') {
  2383. // skip
  2384. // TAG
  2385. } else if (trim($s)) {
  2386. if ($s != '*') {
  2387. // TODO namespaces
  2388. if (isset($node->tagName)) {
  2389. if ($node->tagName != $s)
  2390. $break = true;
  2391. } else if ($s == 'html' && ! $this->isRoot($node))
  2392. $break = true;
  2393. }
  2394. // AVOID NON-SIMPLE SELECTORS
  2395. } else if (in_array($s, $notSimpleSelector)) {
  2396. $break = true;
  2397. $this->debug(array('Skipping non simple selector', $selector));
  2398. }
  2399. }
  2400. if ($break)
  2401. break;
  2402. }
  2403. // if element passed all chunks of selector - add it to new stack
  2404. if (! $break )
  2405. $stack[] = $node;
  2406. }
  2407. $tmpStack = $this->elements;
  2408. $this->elements = $stack;
  2409. // PER ALL NODES selector chunks
  2410. foreach($selector as $s)
  2411. // PSEUDO CLASSES
  2412. if ($s[0] == ':')
  2413. $this->pseudoClasses($s);
  2414. foreach($this->elements as $node)
  2415. // XXX it should be merged without duplicates
  2416. // but jQuery doesnt do that
  2417. $finalStack[] = $node;
  2418. $this->elements = $tmpStack;
  2419. }
  2420. $this->elements = $finalStack;
  2421. if ($_skipHistory) {
  2422. return $this;
  2423. } else {
  2424. $this->debug("Stack length after filter(): ".count($finalStack));
  2425. return $this->newInstance();
  2426. }
  2427. }
  2428. /**
  2429. * @TODO implement in all methods using passed parameters
  2430. */
  2431. protected static function unQuote(string $value): string {
  2432. return $value[0] == '\'' || $value[0] == '"'
  2433. ? substr($value, 1, -1)
  2434. : $value;
  2435. }
  2436. /**
  2437. * Enter description here...
  2438. *
  2439. * @link http://docs.jquery.com/Ajax/load
  2440. * @return phpQuery|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2441. * @todo Support $selector
  2442. */
  2443. public function load($url, $data = null, $callback = null) {
  2444. if ($data && ! is_array($data)) {
  2445. $callback = $data;
  2446. $data = null;
  2447. }
  2448. if (mb_strpos($url, ' ') !== false) {
  2449. $matches = null;
  2450. if (extension_loaded('mbstring') && phpQuery::$mbstringSupport)
  2451. mb_ereg('^([^ ]+) (.*)$', $url, $matches);
  2452. else
  2453. preg_match('^([^ ]+) (.*)$', $url, $matches);
  2454. $url = $matches[1];
  2455. $selector = $matches[2];
  2456. // FIXME this sucks, pass as callback param
  2457. $this->_loadSelector = $selector;
  2458. }
  2459. $ajax = array(
  2460. 'url' => $url,
  2461. 'type' => $data ? 'POST' : 'GET',
  2462. 'data' => $data,
  2463. 'complete' => $callback,
  2464. 'success' => array($this, '__loadSuccess')
  2465. );
  2466. phpQuery::ajax($ajax);
  2467. return $this;
  2468. }
  2469. /**
  2470. * @access private
  2471. * @param $html
  2472. * @return unknown_type
  2473. */
  2474. public function __loadSuccess($html) {
  2475. if ($this->_loadSelector) {
  2476. $html = phpQuery::newDocument($html)->find($this->_loadSelector);
  2477. unset($this->_loadSelector);
  2478. }
  2479. foreach($this->stack(1) as $node) {
  2480. phpQuery::pq($node, $this->getDocumentID())
  2481. ->markup($html);
  2482. }
  2483. }
  2484. /**
  2485. * Enter description here...
  2486. *
  2487. * @return phpQuery|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2488. * @todo
  2489. */
  2490. public function css() {
  2491. // TODO
  2492. return $this;
  2493. }
  2494. /**
  2495. * @todo
  2496. *
  2497. */
  2498. public function show(){
  2499. // TODO
  2500. return $this;
  2501. }
  2502. /**
  2503. * @todo
  2504. *
  2505. */
  2506. public function hide(){
  2507. // TODO
  2508. return $this;
  2509. }
  2510. /**
  2511. * Trigger a type of event on every matched element.
  2512. *
  2513. * @param unknown_type $type
  2514. * @param unknown_type $data
  2515. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2516. * @TODO support more than event in $type (space-separated)
  2517. */
  2518. public function trigger($type, $data = array()) {
  2519. foreach($this->elements as $node)
  2520. phpQueryEvents::trigger($this->getDocumentID(), $type, $data, $node);
  2521. return $this;
  2522. }
  2523. /**
  2524. * This particular method triggers all bound event handlers on an element (for a specific event type) WITHOUT executing the browsers default actions.
  2525. *
  2526. * @param unknown_type $type
  2527. * @param unknown_type $data
  2528. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2529. * @TODO
  2530. */
  2531. public function triggerHandler($type, $data = array()) {
  2532. // TODO;
  2533. }
  2534. /**
  2535. * Binds a handler to one or more events (like click) for each matched element.
  2536. * Can also bind custom events.
  2537. *
  2538. * @param unknown_type $type
  2539. * @param unknown_type $data Optional
  2540. * @param unknown_type $callback
  2541. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2542. * @TODO support '!' (exclusive) events
  2543. * @TODO support more than event in $type (space-separated)
  2544. */
  2545. public function bind($type, $data, $callback = null) {
  2546. // TODO check if $data is callable, not using is_callable
  2547. if (! isset($callback)) {
  2548. $callback = $data;
  2549. $data = null;
  2550. }
  2551. foreach($this->elements as $node)
  2552. phpQueryEvents::add($this->getDocumentID(), $node, $type, $data, $callback);
  2553. return $this;
  2554. }
  2555. /**
  2556. * Enter description here...
  2557. *
  2558. * @param unknown_type $type
  2559. * @param unknown_type $callback
  2560. * @return unknown
  2561. * @TODO namespace events
  2562. * @TODO support more than event in $type (space-separated)
  2563. */
  2564. public function unbind($type = null, $callback = null) {
  2565. foreach($this->elements as $node)
  2566. phpQueryEvents::remove($this->getDocumentID(), $node, $type, $callback);
  2567. return $this;
  2568. }
  2569. /**
  2570. * Enter description here...
  2571. *
  2572. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2573. */
  2574. public function change($callback = null) {
  2575. if ($callback)
  2576. return $this->bind('change', $callback);
  2577. return $this->trigger('change');
  2578. }
  2579. /**
  2580. * Enter description here...
  2581. *
  2582. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2583. */
  2584. public function submit($callback = null) {
  2585. if ($callback)
  2586. return $this->bind('submit', $callback);
  2587. return $this->trigger('submit');
  2588. }
  2589. /**
  2590. * Enter description here...
  2591. *
  2592. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2593. */
  2594. public function click($callback = null) {
  2595. if ($callback)
  2596. return $this->bind('click', $callback);
  2597. return $this->trigger('click');
  2598. }
  2599. /**
  2600. * Enter description here...
  2601. *
  2602. * @param String|phpQuery
  2603. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2604. */
  2605. public function wrapAllOld($wrapper) {
  2606. $wrapper = pq($wrapper)->_clone();
  2607. if (!$wrapper->size() || !$this->size() )
  2608. return $this;
  2609. $wrapper->insertBefore($this->elements[0]);
  2610. $deepest = $wrapper->elements[0];
  2611. while($deepest->firstChild && $deepest->firstChild instanceof DOMELEMENT)
  2612. $deepest = $deepest->firstChild;
  2613. pq($deepest)->append($this);
  2614. return $this;
  2615. }
  2616. /**
  2617. * Enter description here...
  2618. *
  2619. * TODO testme...
  2620. * @param String|phpQuery
  2621. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2622. */
  2623. public function wrapAll($wrapper) {
  2624. if (!$this->size())
  2625. return $this;
  2626. return phpQuery::pq($wrapper, $this->getDocumentID())
  2627. ->clone()
  2628. ->insertBefore($this->get(0))
  2629. ->map(array($this, '___wrapAllCallback'))
  2630. ->append($this);
  2631. }
  2632. /**
  2633. *
  2634. * @param $node
  2635. * @return unknown_type
  2636. * @access private
  2637. */
  2638. public function ___wrapAllCallback($node) {
  2639. $deepest = $node;
  2640. while($deepest->firstChild && $deepest->firstChild instanceof DOMELEMENT)
  2641. $deepest = $deepest->firstChild;
  2642. return $deepest;
  2643. }
  2644. /**
  2645. * Enter description here...
  2646. * NON JQUERY METHOD
  2647. *
  2648. * @param String|phpQuery
  2649. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2650. */
  2651. public function wrapAllPHP($codeBefore, $codeAfter) {
  2652. return $this
  2653. ->slice(0, 1)
  2654. ->beforePHP($codeBefore)
  2655. ->end()
  2656. ->slice(-1)
  2657. ->afterPHP($codeAfter)
  2658. ->end();
  2659. }
  2660. /**
  2661. * Enter description here...
  2662. *
  2663. * @param String|phpQuery
  2664. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2665. */
  2666. public function wrap($wrapper) {
  2667. foreach($this->stack() as $node)
  2668. phpQuery::pq($node, $this->getDocumentID())->wrapAll($wrapper);
  2669. return $this;
  2670. }
  2671. /**
  2672. * Enter description here...
  2673. *
  2674. * @param String|phpQuery
  2675. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2676. */
  2677. public function wrapPHP($codeBefore, $codeAfter) {
  2678. foreach($this->stack() as $node)
  2679. phpQuery::pq($node, $this->getDocumentID())->wrapAllPHP($codeBefore, $codeAfter);
  2680. return $this;
  2681. }
  2682. /**
  2683. * Enter description here...
  2684. *
  2685. * @param String|phpQuery
  2686. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2687. */
  2688. public function wrapInner($wrapper) {
  2689. foreach($this->stack() as $node)
  2690. phpQuery::pq($node, $this->getDocumentID())->contents()->wrapAll($wrapper);
  2691. return $this;
  2692. }
  2693. /**
  2694. * Enter description here...
  2695. *
  2696. * @param String|phpQuery
  2697. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2698. */
  2699. public function wrapInnerPHP($codeBefore, $codeAfter) {
  2700. foreach($this->stack(1) as $node)
  2701. phpQuery::pq($node, $this->getDocumentID())->contents()
  2702. ->wrapAllPHP($codeBefore, $codeAfter);
  2703. return $this;
  2704. }
  2705. /**
  2706. * Enter description here...
  2707. *
  2708. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2709. * @testme Support for text nodes
  2710. */
  2711. public function contents() {
  2712. $stack = array();
  2713. foreach($this->stack(1) as $el) {
  2714. // FIXME (fixed) http://code.google.com/p/phpquery/issues/detail?id=56
  2715. // if (! isset($el->childNodes))
  2716. // continue;
  2717. foreach($el->childNodes as $node) {
  2718. $stack[] = $node;
  2719. }
  2720. }
  2721. return $this->newInstance($stack);
  2722. }
  2723. /**
  2724. * Enter description here...
  2725. *
  2726. * jQuery difference.
  2727. *
  2728. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2729. */
  2730. public function contentsUnwrap() {
  2731. foreach($this->stack(1) as $node) {
  2732. if (! $node->parentNode )
  2733. continue;
  2734. $childNodes = array();
  2735. // any modification in DOM tree breaks childNodes iteration, so cache them first
  2736. foreach($node->childNodes as $chNode )
  2737. $childNodes[] = $chNode;
  2738. foreach($childNodes as $chNode )
  2739. // $node->parentNode->appendChild($chNode);
  2740. $node->parentNode->insertBefore($chNode, $node);
  2741. $node->parentNode->removeChild($node);
  2742. }
  2743. return $this;
  2744. }
  2745. /**
  2746. * Enter description here...
  2747. *
  2748. * jQuery difference.
  2749. */
  2750. public function switchWith($markup) {
  2751. $markup = pq($markup, $this->getDocumentID());
  2752. $content = null;
  2753. foreach($this->stack(1) as $node) {
  2754. pq($node)
  2755. ->contents()->toReference($content)->end()
  2756. ->replaceWith($markup->clone()->append($content));
  2757. }
  2758. return $this;
  2759. }
  2760. /**
  2761. * Enter description here...
  2762. *
  2763. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2764. */
  2765. public function eq($num) {
  2766. $oldStack = $this->elements;
  2767. $this->elementsBackup = $this->elements;
  2768. $this->elements = array();
  2769. if ( isset($oldStack[$num]) )
  2770. $this->elements[] = $oldStack[$num];
  2771. return $this->newInstance();
  2772. }
  2773. public function size(): int {
  2774. return count($this->elements);
  2775. }
  2776. /**
  2777. * Enter description here...
  2778. *
  2779. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2780. * @deprecated Use length as attribute
  2781. */
  2782. public function length() {
  2783. return $this->size();
  2784. }
  2785. public function count(): int {
  2786. return $this->size();
  2787. }
  2788. /**
  2789. * Enter description here...
  2790. *
  2791. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2792. * @todo $level
  2793. */
  2794. public function end($level = 1) {
  2795. // $this->elements = array_pop( $this->history );
  2796. // return $this;
  2797. // $this->previous->DOM = $this->DOM;
  2798. // $this->previous->XPath = $this->XPath;
  2799. return $this->previous
  2800. ? $this->previous
  2801. : $this;
  2802. }
  2803. /**
  2804. * Enter description here...
  2805. * Normal use ->clone() .
  2806. *
  2807. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2808. * @access private
  2809. */
  2810. public function _clone() {
  2811. $newStack = array();
  2812. //pr(array('copy... ', $this->whois()));
  2813. //$this->dumpHistory('copy');
  2814. $this->elementsBackup = $this->elements;
  2815. foreach($this->elements as $node) {
  2816. $newStack[] = $node->cloneNode(true);
  2817. }
  2818. $this->elements = $newStack;
  2819. return $this->newInstance();
  2820. }
  2821. /**
  2822. * Enter description here...
  2823. *
  2824. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2825. */
  2826. public function replaceWithPHP($code) {
  2827. return $this->replaceWith(phpQuery::php($code));
  2828. }
  2829. /**
  2830. * Enter description here...
  2831. *
  2832. * @param String|phpQuery $content
  2833. * @link http://docs.jquery.com/Manipulation/replaceWith#content
  2834. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2835. */
  2836. public function replaceWith($content) {
  2837. return $this->after($content)->remove();
  2838. }
  2839. /**
  2840. * Enter description here...
  2841. *
  2842. * @param String $selector
  2843. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2844. * @todo this works ?
  2845. */
  2846. public function replaceAll($selector) {
  2847. foreach(phpQuery::pq($selector, $this->getDocumentID()) as $node)
  2848. phpQuery::pq($node, $this->getDocumentID())
  2849. ->after($this->_clone())
  2850. ->remove();
  2851. return $this;
  2852. }
  2853. /**
  2854. * Enter description here...
  2855. *
  2856. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2857. */
  2858. public function remove($selector = null) {
  2859. $loop = $selector
  2860. ? $this->filter($selector)->elements
  2861. : $this->elements;
  2862. foreach($loop as $node) {
  2863. if (! $node->parentNode )
  2864. continue;
  2865. if (isset($node->tagName))
  2866. $this->debug("Removing '{$node->tagName}'");
  2867. $node->parentNode->removeChild($node);
  2868. // Mutation event
  2869. $event = new DOMEvent(array(
  2870. 'target' => $node,
  2871. 'type' => 'DOMNodeRemoved'
  2872. ));
  2873. phpQueryEvents::trigger($this->getDocumentID(),
  2874. $event->type, array($event), $node
  2875. );
  2876. }
  2877. return $this;
  2878. }
  2879. protected function markupEvents($newMarkup, $oldMarkup, $node) {
  2880. if ($node->tagName == 'textarea' && $newMarkup != $oldMarkup) {
  2881. $event = new DOMEvent(array(
  2882. 'target' => $node,
  2883. 'type' => 'change'
  2884. ));
  2885. phpQueryEvents::trigger($this->getDocumentID(),
  2886. $event->type, array($event), $node
  2887. );
  2888. }
  2889. }
  2890. /**
  2891. * jQuey difference
  2892. *
  2893. * @param $markup
  2894. * @return unknown_type
  2895. * @TODO trigger change event for textarea
  2896. */
  2897. public function markup($markup = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  2898. $args = func_get_args();
  2899. if ($this->documentWrapper->isXML)
  2900. return call_user_func_array(array($this, 'xml'), $args);
  2901. else
  2902. return call_user_func_array(array($this, 'html'), $args);
  2903. }
  2904. /**
  2905. * jQuey difference
  2906. *
  2907. * @param $markup
  2908. * @return unknown_type
  2909. */
  2910. public function markupOuter($callback1 = null, $callback2 = null, $callback3 = null) {
  2911. $args = func_get_args();
  2912. if ($this->documentWrapper->isXML)
  2913. return call_user_func_array(array($this, 'xmlOuter'), $args);
  2914. else
  2915. return call_user_func_array(array($this, 'htmlOuter'), $args);
  2916. }
  2917. /**
  2918. * Enter description here...
  2919. *
  2920. * @param unknown_type $html
  2921. * @return string|phpQuery|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2922. * @TODO force html result
  2923. */
  2924. public function html($html = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  2925. if (isset($html)) {
  2926. // INSERT
  2927. $nodes = $this->documentWrapper->import($html);
  2928. $this->empty();
  2929. foreach($this->stack(1) as $alreadyAdded => $node) {
  2930. // for now, limit events for textarea
  2931. if (($this->isXHTML() || $this->isHTML()) && $node->tagName == 'textarea')
  2932. $oldHtml = pq($node, $this->getDocumentID())->markup();
  2933. foreach($nodes as $newNode) {
  2934. $node->appendChild($alreadyAdded
  2935. ? $newNode->cloneNode(true)
  2936. : $newNode
  2937. );
  2938. }
  2939. // for now, limit events for textarea
  2940. if (($this->isXHTML() || $this->isHTML()) && $node->tagName == 'textarea')
  2941. $this->markupEvents($html, $oldHtml, $node);
  2942. }
  2943. return $this;
  2944. } else {
  2945. // FETCH
  2946. $return = $this->documentWrapper->markup($this->elements, true);
  2947. $args = func_get_args();
  2948. foreach(array_slice($args, 1) as $callback) {
  2949. $return = phpQuery::callbackRun($callback, array($return));
  2950. }
  2951. return $return;
  2952. }
  2953. }
  2954. /**
  2955. * @TODO force xml result
  2956. */
  2957. public function xml($xml = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  2958. $args = func_get_args();
  2959. return call_user_func_array(array($this, 'html'), $args);
  2960. }
  2961. /**
  2962. * Enter description here...
  2963. * @TODO force html result
  2964. *
  2965. * @return String
  2966. */
  2967. public function htmlOuter($callback1 = null, $callback2 = null, $callback3 = null) {
  2968. $markup = $this->documentWrapper->markup($this->elements);
  2969. // pass thou callbacks
  2970. $args = func_get_args();
  2971. foreach($args as $callback) {
  2972. $markup = phpQuery::callbackRun($callback, array($markup));
  2973. }
  2974. return $markup;
  2975. }
  2976. /**
  2977. * @TODO force xml result
  2978. */
  2979. public function xmlOuter($callback1 = null, $callback2 = null, $callback3 = null) {
  2980. $args = func_get_args();
  2981. return call_user_func_array(array($this, 'htmlOuter'), $args);
  2982. }
  2983. public function __toString() {
  2984. return $this->markupOuter();
  2985. }
  2986. /**
  2987. * Just like html(), but returns markup with VALID (dangerous) PHP tags.
  2988. *
  2989. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2990. * @todo support returning markup with PHP tags when called without param
  2991. */
  2992. public function php($code = null) {
  2993. return $this->markupPHP($code);
  2994. }
  2995. /**
  2996. * Enter description here...
  2997. *
  2998. * @param $code
  2999. * @return unknown_type
  3000. */
  3001. public function markupPHP($code = null) {
  3002. return isset($code)
  3003. ? $this->markup(phpQuery::php($code))
  3004. : phpQuery::markupToPHP($this->markup());
  3005. }
  3006. /**
  3007. * Enter description here...
  3008. *
  3009. * @param $code
  3010. * @return unknown_type
  3011. */
  3012. public function markupOuterPHP() {
  3013. return phpQuery::markupToPHP($this->markupOuter());
  3014. }
  3015. /**
  3016. * Enter description here...
  3017. *
  3018. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3019. */
  3020. public function children($selector = null) {
  3021. $stack = array();
  3022. foreach($this->stack(1) as $node) {
  3023. // foreach($node->getElementsByTagName('*') as $newNode) {
  3024. foreach($node->childNodes as $newNode) {
  3025. if ($newNode->nodeType != 1)
  3026. continue;
  3027. if ($selector && ! $this->is($selector, $newNode))
  3028. continue;
  3029. if ($this->elementsContainsNode($newNode, $stack))
  3030. continue;
  3031. $stack[] = $newNode;
  3032. }
  3033. }
  3034. $this->elementsBackup = $this->elements;
  3035. $this->elements = $stack;
  3036. return $this->newInstance();
  3037. }
  3038. /**
  3039. * Enter description here...
  3040. *
  3041. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3042. */
  3043. public function ancestors($selector = null) {
  3044. return $this->children( $selector );
  3045. }
  3046. /**
  3047. * Enter description here...
  3048. *
  3049. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3050. */
  3051. public function append( $content) {
  3052. return $this->insert($content, __FUNCTION__);
  3053. }
  3054. /**
  3055. * Enter description here...
  3056. *
  3057. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3058. */
  3059. public function appendPHP( $content) {
  3060. return $this->insert("<php><!-- {$content} --></php>", 'append');
  3061. }
  3062. /**
  3063. * Enter description here...
  3064. *
  3065. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3066. */
  3067. public function appendTo( $seletor) {
  3068. return $this->insert($seletor, __FUNCTION__);
  3069. }
  3070. /**
  3071. * Enter description here...
  3072. *
  3073. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3074. */
  3075. public function prepend( $content) {
  3076. return $this->insert($content, __FUNCTION__);
  3077. }
  3078. /**
  3079. * Enter description here...
  3080. *
  3081. * @todo accept many arguments, which are joined, arrays maybe also
  3082. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3083. */
  3084. public function prependPHP( $content) {
  3085. return $this->insert("<php><!-- {$content} --></php>", 'prepend');
  3086. }
  3087. /**
  3088. * Enter description here...
  3089. *
  3090. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3091. */
  3092. public function prependTo( $seletor) {
  3093. return $this->insert($seletor, __FUNCTION__);
  3094. }
  3095. /**
  3096. * Enter description here...
  3097. *
  3098. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3099. */
  3100. public function before($content) {
  3101. return $this->insert($content, __FUNCTION__);
  3102. }
  3103. /**
  3104. * Enter description here...
  3105. *
  3106. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3107. */
  3108. public function beforePHP( $content) {
  3109. return $this->insert("<php><!-- {$content} --></php>", 'before');
  3110. }
  3111. /**
  3112. * Enter description here...
  3113. *
  3114. * @param String|phpQuery
  3115. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3116. */
  3117. public function insertBefore( $seletor) {
  3118. return $this->insert($seletor, __FUNCTION__);
  3119. }
  3120. /**
  3121. * Enter description here...
  3122. *
  3123. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3124. */
  3125. public function after( $content) {
  3126. return $this->insert($content, __FUNCTION__);
  3127. }
  3128. /**
  3129. * Enter description here...
  3130. *
  3131. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3132. */
  3133. public function afterPHP( $content) {
  3134. return $this->insert("<php><!-- {$content} --></php>", 'after');
  3135. }
  3136. /**
  3137. * Enter description here...
  3138. *
  3139. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3140. */
  3141. public function insertAfter( $seletor) {
  3142. return $this->insert($seletor, __FUNCTION__);
  3143. }
  3144. /**
  3145. * Internal insert method. Don't use it.
  3146. *
  3147. * @param unknown_type $target
  3148. * @param unknown_type $type
  3149. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3150. * @access private
  3151. */
  3152. public function insert($target, $type) {
  3153. $this->debug("Inserting data with '{$type}'");
  3154. $to = false;
  3155. switch( $type) {
  3156. case 'appendTo':
  3157. case 'prependTo':
  3158. case 'insertBefore':
  3159. case 'insertAfter':
  3160. $to = true;
  3161. }
  3162. switch(gettype($target)) {
  3163. case 'string':
  3164. $insertFrom = $insertTo = array();
  3165. if ($to) {
  3166. // INSERT TO
  3167. $insertFrom = $this->elements;
  3168. if (phpQuery::isMarkup($target)) {
  3169. // $target is new markup, import it
  3170. $insertTo = $this->documentWrapper->import($target);
  3171. // insert into selected element
  3172. } else {
  3173. // $tagret is a selector
  3174. $thisStack = $this->elements;
  3175. $this->toRoot();
  3176. $insertTo = $this->find($target)->elements;
  3177. $this->elements = $thisStack;
  3178. }
  3179. } else {
  3180. // INSERT FROM
  3181. $insertTo = $this->elements;
  3182. $insertFrom = $this->documentWrapper->import($target);
  3183. }
  3184. break;
  3185. case 'object':
  3186. $insertFrom = $insertTo = array();
  3187. // phpQuery
  3188. if ($target instanceof self) {
  3189. if ($to) {
  3190. $insertTo = $target->elements;
  3191. if ($this->documentFragment && $this->stackIsRoot())
  3192. // get all body children
  3193. // $loop = $this->find('body > *')->elements;
  3194. // TODO test it, test it hard...
  3195. // $loop = $this->newInstance($this->root)->find('> *')->elements;
  3196. $loop = $this->root->childNodes;
  3197. else
  3198. $loop = $this->elements;
  3199. // import nodes if needed
  3200. $insertFrom = $this->getDocumentID() == $target->getDocumentID()
  3201. ? $loop
  3202. : $target->documentWrapper->import($loop);
  3203. } else {
  3204. $insertTo = $this->elements;
  3205. if ( $target->documentFragment && $target->stackIsRoot() )
  3206. // get all body children
  3207. // $loop = $target->find('body > *')->elements;
  3208. $loop = $target->root->childNodes;
  3209. else
  3210. $loop = $target->elements;
  3211. // import nodes if needed
  3212. $insertFrom = $this->getDocumentID() == $target->getDocumentID()
  3213. ? $loop
  3214. : $this->documentWrapper->import($loop);
  3215. }
  3216. // DOMNODE
  3217. } elseif ($target instanceof DOMNODE) {
  3218. // import node if needed
  3219. // if ( $target->ownerDocument != $this->DOM )
  3220. // $target = $this->DOM->importNode($target, true);
  3221. if ( $to) {
  3222. $insertTo = array($target);
  3223. if ($this->documentFragment && $this->stackIsRoot())
  3224. // get all body children
  3225. $loop = $this->root->childNodes;
  3226. // $loop = $this->find('body > *')->elements;
  3227. else
  3228. $loop = $this->elements;
  3229. foreach($loop as $fromNode)
  3230. // import nodes if needed
  3231. $insertFrom[] = ! $fromNode->ownerDocument->isSameNode($target->ownerDocument)
  3232. ? $target->ownerDocument->importNode($fromNode, true)
  3233. : $fromNode;
  3234. } else {
  3235. // import node if needed
  3236. if (! $target->ownerDocument->isSameNode($this->document))
  3237. $target = $this->document->importNode($target, true);
  3238. $insertTo = $this->elements;
  3239. $insertFrom[] = $target;
  3240. }
  3241. }
  3242. break;
  3243. }
  3244. phpQuery::debug("From ".count($insertFrom)."; To ".count($insertTo)." nodes");
  3245. foreach($insertTo as $insertNumber => $toNode) {
  3246. // we need static relative elements in some cases
  3247. switch( $type) {
  3248. case 'prependTo':
  3249. case 'prepend':
  3250. $firstChild = $toNode->firstChild;
  3251. break;
  3252. case 'insertAfter':
  3253. case 'after':
  3254. $nextSibling = $toNode->nextSibling;
  3255. break;
  3256. }
  3257. foreach($insertFrom as $fromNode) {
  3258. // clone if inserted already before
  3259. $insert = $insertNumber
  3260. ? $fromNode->cloneNode(true)
  3261. : $fromNode;
  3262. switch($type) {
  3263. case 'appendTo':
  3264. case 'append':
  3265. // $toNode->insertBefore(
  3266. // $fromNode,
  3267. // $toNode->lastChild->nextSibling
  3268. // );
  3269. $toNode->appendChild($insert);
  3270. $eventTarget = $insert;
  3271. break;
  3272. case 'prependTo':
  3273. case 'prepend':
  3274. $toNode->insertBefore(
  3275. $insert,
  3276. $firstChild
  3277. );
  3278. break;
  3279. case 'insertBefore':
  3280. case 'before':
  3281. if (! $toNode->parentNode)
  3282. throw new Exception("No parentNode, can't do {$type}()");
  3283. else
  3284. $toNode->parentNode->insertBefore(
  3285. $insert,
  3286. $toNode
  3287. );
  3288. break;
  3289. case 'insertAfter':
  3290. case 'after':
  3291. if (! $toNode->parentNode)
  3292. throw new Exception("No parentNode, can't do {$type}()");
  3293. else
  3294. $toNode->parentNode->insertBefore(
  3295. $insert,
  3296. $nextSibling
  3297. );
  3298. break;
  3299. }
  3300. // Mutation event
  3301. $event = new DOMEvent(array(
  3302. 'target' => $insert,
  3303. 'type' => 'DOMNodeInserted'
  3304. ));
  3305. phpQueryEvents::trigger($this->getDocumentID(),
  3306. $event->type, array($event), $insert
  3307. );
  3308. }
  3309. }
  3310. return $this;
  3311. }
  3312. /**
  3313. * Enter description here...
  3314. *
  3315. * @return Int
  3316. */
  3317. public function index($subject) {
  3318. $index = -1;
  3319. $subject = $subject instanceof phpQueryObject
  3320. ? $subject->elements[0]
  3321. : $subject;
  3322. foreach($this->newInstance() as $k => $node) {
  3323. if ($node->isSameNode($subject))
  3324. $index = $k;
  3325. }
  3326. return $index;
  3327. }
  3328. /**
  3329. * @return phpQueryObject
  3330. * @testme
  3331. */
  3332. public function slice(int $start, $end = null): object {
  3333. // $last = count($this->elements)-1;
  3334. // $end = $end
  3335. // ? min($end, $last)
  3336. // : $last;
  3337. // if ($start < 0)
  3338. // $start = $last+$start;
  3339. // if ($start > $last)
  3340. // return array();
  3341. if ($end > 0)
  3342. $end = $end-$start;
  3343. return $this->newInstance(
  3344. array_slice($this->elements, $start, $end)
  3345. );
  3346. }
  3347. /**
  3348. * @return phpQueryObject
  3349. */
  3350. public function reverse(): object {
  3351. $this->elementsBackup = $this->elements;
  3352. $this->elements = array_reverse($this->elements);
  3353. return $this->newInstance();
  3354. }
  3355. /**
  3356. * Return joined text content.
  3357. * @return String
  3358. */
  3359. public function text($text = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  3360. if (isset($text))
  3361. return $this->html(htmlspecialchars($text), ENT_NOQUOTES, 'UTF-8');
  3362. $args = func_get_args();
  3363. $args = array_slice($args, 1);
  3364. $return = '';
  3365. foreach($this->elements as $node) {
  3366. $text = $node->textContent;
  3367. if (count($this->elements) > 1 && $text)
  3368. $text .= "\n";
  3369. foreach($args as $callback) {
  3370. $text = phpQuery::callbackRun($callback, array($text));
  3371. }
  3372. $return .= $text;
  3373. }
  3374. return $return;
  3375. }
  3376. /**
  3377. * Enter description here...
  3378. *
  3379. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3380. */
  3381. public function plugin($class, $file = null) {
  3382. phpQuery::plugin($class, $file);
  3383. return $this;
  3384. }
  3385. /**
  3386. * Deprecated, use $pq->plugin() instead.
  3387. *
  3388. * @deprecated
  3389. * @param $class
  3390. * @param $file
  3391. * @return unknown_type
  3392. */
  3393. public static function extend($class, $file = null) {
  3394. return phpQuery::plugin($class, $file);
  3395. }
  3396. /**
  3397. *
  3398. * @access private
  3399. * @param $method
  3400. * @param $args
  3401. * @return unknown_type
  3402. */
  3403. public function __call($method, $args) {
  3404. $aliasMethods = array('clone', 'empty');
  3405. if (isset(phpQuery::$extendMethods[$method])) {
  3406. array_unshift($args, $this);
  3407. return phpQuery::callbackRun(
  3408. phpQuery::$extendMethods[$method], $args
  3409. );
  3410. } else if (isset(phpQuery::$pluginsMethods[$method])) {
  3411. array_unshift($args, $this);
  3412. $class = phpQuery::$pluginsMethods[$method];
  3413. $realClass = "phpQueryObjectPlugin_$class";
  3414. $return = call_user_func_array(
  3415. array($realClass, $method),
  3416. $args
  3417. );
  3418. // XXX deprecate ?
  3419. return is_null($return)
  3420. ? $this
  3421. : $return;
  3422. } else if (in_array($method, $aliasMethods)) {
  3423. return call_user_func_array(array($this, '_'.$method), $args);
  3424. } else
  3425. throw new Exception("Method '{$method}' doesnt exist");
  3426. }
  3427. /**
  3428. * Safe rename of next().
  3429. *
  3430. * Use it ONLY when need to call next() on an iterated object (in same time).
  3431. * Normaly there is no need to do such thing ;)
  3432. *
  3433. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3434. * @access private
  3435. */
  3436. public function _next($selector = null) {
  3437. return $this->newInstance(
  3438. $this->getElementSiblings('nextSibling', $selector, true)
  3439. );
  3440. }
  3441. /**
  3442. * Use prev() and next().
  3443. *
  3444. * @deprecated
  3445. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3446. * @access private
  3447. */
  3448. public function _prev($selector = null) {
  3449. return $this->prev($selector);
  3450. }
  3451. /**
  3452. * Enter description here...
  3453. *
  3454. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3455. */
  3456. public function prev($selector = null) {
  3457. return $this->newInstance(
  3458. $this->getElementSiblings('previousSibling', $selector, true)
  3459. );
  3460. }
  3461. /**
  3462. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3463. * @todo
  3464. */
  3465. public function prevAll($selector = null) {
  3466. return $this->newInstance(
  3467. $this->getElementSiblings('previousSibling', $selector)
  3468. );
  3469. }
  3470. /**
  3471. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3472. * @todo FIXME: returns source elements insted of next siblings
  3473. */
  3474. public function nextAll($selector = null) {
  3475. return $this->newInstance(
  3476. $this->getElementSiblings('nextSibling', $selector)
  3477. );
  3478. }
  3479. /**
  3480. * @access private
  3481. */
  3482. protected function getElementSiblings($direction, $selector = null, $limitToOne = false) {
  3483. $stack = array();
  3484. $count = 0;
  3485. foreach($this->stack() as $node) {
  3486. $test = $node;
  3487. while( isset($test->{$direction}) && $test->{$direction}) {
  3488. $test = $test->{$direction};
  3489. if (! $test instanceof DOMELEMENT)
  3490. continue;
  3491. $stack[] = $test;
  3492. if ($limitToOne)
  3493. break;
  3494. }
  3495. }
  3496. if ($selector) {
  3497. $stackOld = $this->elements;
  3498. $this->elements = $stack;
  3499. $stack = $this->filter($selector, true)->stack();
  3500. $this->elements = $stackOld;
  3501. }
  3502. return $stack;
  3503. }
  3504. /**
  3505. * Enter description here...
  3506. *
  3507. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3508. */
  3509. public function siblings($selector = null) {
  3510. $stack = array();
  3511. $siblings = array_merge(
  3512. $this->getElementSiblings('previousSibling', $selector),
  3513. $this->getElementSiblings('nextSibling', $selector)
  3514. );
  3515. foreach($siblings as $node) {
  3516. if (! $this->elementsContainsNode($node, $stack))
  3517. $stack[] = $node;
  3518. }
  3519. return $this->newInstance($stack);
  3520. }
  3521. /**
  3522. * Enter description here...
  3523. *
  3524. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3525. */
  3526. public function not($selector = null) {
  3527. if (is_string($selector))
  3528. phpQuery::debug(array('not', $selector));
  3529. else
  3530. phpQuery::debug('not');
  3531. $stack = array();
  3532. if ($selector instanceof self || $selector instanceof DOMNODE) {
  3533. foreach($this->stack() as $node) {
  3534. if ($selector instanceof self) {
  3535. $matchFound = false;
  3536. foreach($selector->stack() as $notNode) {
  3537. if ($notNode->isSameNode($node))
  3538. $matchFound = true;
  3539. }
  3540. if (! $matchFound)
  3541. $stack[] = $node;
  3542. } else if ($selector instanceof DOMNODE) {
  3543. if (! $selector->isSameNode($node))
  3544. $stack[] = $node;
  3545. } else {
  3546. if (! $this->is($selector))
  3547. $stack[] = $node;
  3548. }
  3549. }
  3550. } else {
  3551. $orgStack = $this->stack();
  3552. $matched = $this->filter($selector, true)->stack();
  3553. // $matched = array();
  3554. // // simulate OR in filter() instead of AND 5y
  3555. // foreach($this->parseSelector($selector) as $s) {
  3556. // $matched = array_merge($matched,
  3557. // $this->filter(array($s))->stack()
  3558. // );
  3559. // }
  3560. foreach($orgStack as $node)
  3561. if (! $this->elementsContainsNode($node, $matched))
  3562. $stack[] = $node;
  3563. }
  3564. return $this->newInstance($stack);
  3565. }
  3566. /**
  3567. * Enter description here...
  3568. *
  3569. * @param string|phpQueryObject
  3570. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3571. */
  3572. public function add($selector = null) {
  3573. if (! $selector)
  3574. return $this;
  3575. $stack = array();
  3576. $this->elementsBackup = $this->elements;
  3577. $found = phpQuery::pq($selector, $this->getDocumentID());
  3578. $this->merge($found->elements);
  3579. return $this->newInstance();
  3580. }
  3581. /**
  3582. * @access private
  3583. */
  3584. protected function merge() {
  3585. foreach(func_get_args() as $nodes)
  3586. foreach($nodes as $newNode )
  3587. if (! $this->elementsContainsNode($newNode) )
  3588. $this->elements[] = $newNode;
  3589. }
  3590. /**
  3591. * @access private
  3592. * TODO refactor to stackContainsNode
  3593. */
  3594. protected function elementsContainsNode($nodeToCheck, $elementsStack = null) {
  3595. $loop = ! is_null($elementsStack)
  3596. ? $elementsStack
  3597. : $this->elements;
  3598. foreach($loop as $node) {
  3599. if ( $node->isSameNode( $nodeToCheck ) )
  3600. return true;
  3601. }
  3602. return false;
  3603. }
  3604. /**
  3605. * Enter description here...
  3606. *
  3607. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3608. */
  3609. public function parent($selector = null) {
  3610. $stack = array();
  3611. foreach($this->elements as $node )
  3612. if ( $node->parentNode && ! $this->elementsContainsNode($node->parentNode, $stack) )
  3613. $stack[] = $node->parentNode;
  3614. $this->elementsBackup = $this->elements;
  3615. $this->elements = $stack;
  3616. if ( $selector )
  3617. $this->filter($selector, true);
  3618. return $this->newInstance();
  3619. }
  3620. /**
  3621. * Enter description here...
  3622. *
  3623. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3624. */
  3625. public function parents($selector = null) {
  3626. $stack = array();
  3627. if (! $this->elements )
  3628. $this->debug('parents() - stack empty');
  3629. foreach($this->elements as $node) {
  3630. $test = $node;
  3631. while( $test->parentNode) {
  3632. $test = $test->parentNode;
  3633. if ($this->isRoot($test))
  3634. break;
  3635. if (! $this->elementsContainsNode($test, $stack)) {
  3636. $stack[] = $test;
  3637. continue;
  3638. }
  3639. }
  3640. }
  3641. $this->elementsBackup = $this->elements;
  3642. $this->elements = $stack;
  3643. if ( $selector )
  3644. $this->filter($selector, true);
  3645. return $this->newInstance();
  3646. }
  3647. /**
  3648. * Internal stack iterator.
  3649. *
  3650. * @access private
  3651. */
  3652. public function stack($nodeTypes = null) {
  3653. if (!isset($nodeTypes))
  3654. return $this->elements;
  3655. if (!is_array($nodeTypes))
  3656. $nodeTypes = array($nodeTypes);
  3657. $return = array();
  3658. foreach($this->elements as $node) {
  3659. if (in_array($node->nodeType, $nodeTypes))
  3660. $return[] = $node;
  3661. }
  3662. return $return;
  3663. }
  3664. // TODO phpdoc; $oldAttr is result of hasAttribute, before any changes
  3665. protected function attrEvents($attr, $oldAttr, $oldValue, $node) {
  3666. // skip events for XML documents
  3667. if (! $this->isXHTML() && ! $this->isHTML())
  3668. return;
  3669. $event = null;
  3670. // identify
  3671. $isInputValue = $node->tagName == 'input'
  3672. && (
  3673. in_array($node->getAttribute('type'),
  3674. array('text', 'password', 'hidden'))
  3675. || !$node->getAttribute('type')
  3676. );
  3677. $isRadio = $node->tagName == 'input'
  3678. && $node->getAttribute('type') == 'radio';
  3679. $isCheckbox = $node->tagName == 'input'
  3680. && $node->getAttribute('type') == 'checkbox';
  3681. $isOption = $node->tagName == 'option';
  3682. if ($isInputValue && $attr == 'value' && $oldValue != $node->getAttribute($attr)) {
  3683. $event = new DOMEvent(array(
  3684. 'target' => $node,
  3685. 'type' => 'change'
  3686. ));
  3687. } else if (($isRadio || $isCheckbox) && $attr == 'checked' && (
  3688. // check
  3689. (! $oldAttr && $node->hasAttribute($attr))
  3690. // un-check
  3691. || (! $node->hasAttribute($attr) && $oldAttr)
  3692. )) {
  3693. $event = new DOMEvent(array(
  3694. 'target' => $node,
  3695. 'type' => 'change'
  3696. ));
  3697. } else if ($isOption && $node->parentNode && $attr == 'selected' && (
  3698. // select
  3699. (! $oldAttr && $node->hasAttribute($attr))
  3700. // un-select
  3701. || (! $node->hasAttribute($attr) && $oldAttr)
  3702. )) {
  3703. $event = new DOMEvent(array(
  3704. 'target' => $node->parentNode,
  3705. 'type' => 'change'
  3706. ));
  3707. }
  3708. if ($event) {
  3709. phpQueryEvents::trigger($this->getDocumentID(),
  3710. $event->type, array($event), $node
  3711. );
  3712. }
  3713. }
  3714. public function attr($attr = null, $value = null) {
  3715. foreach($this->stack(1) as $node) {
  3716. if (! is_null($value)) {
  3717. $loop = $attr == '*'
  3718. ? $this->getNodeAttrs($node)
  3719. : array($attr);
  3720. foreach($loop as $a) {
  3721. $oldValue = $node->getAttribute($a);
  3722. $oldAttr = $node->hasAttribute($a);
  3723. // TODO raises an error when charset other than UTF-8
  3724. // while document's charset is also not UTF-8
  3725. @$node->setAttribute($a, $value);
  3726. $this->attrEvents($a, $oldAttr, $oldValue, $node);
  3727. }
  3728. } else if ($attr == '*') {
  3729. // jQuery difference
  3730. $return = array();
  3731. foreach($node->attributes as $n => $v)
  3732. $return[$n] = $v->value;
  3733. return $return;
  3734. } else
  3735. return $node->hasAttribute($attr)
  3736. ? $node->getAttribute($attr)
  3737. : null;
  3738. }
  3739. return is_null($value)
  3740. ? '' : $this;
  3741. }
  3742. /**
  3743. * @access private
  3744. */
  3745. protected function getNodeAttrs($node) {
  3746. $return = array();
  3747. foreach($node->attributes as $n => $o)
  3748. $return[] = $n;
  3749. return $return;
  3750. }
  3751. /**
  3752. * Enter description here...
  3753. *
  3754. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3755. * @todo check CDATA ???
  3756. */
  3757. public function attrPHP($attr, $code) {
  3758. if (! is_null($code)) {
  3759. $value = '<'.'?php '.$code.' ?'.'>';
  3760. // TODO tempolary solution
  3761. // http://code.google.com/p/phpquery/issues/detail?id=17
  3762. // if (function_exists('mb_detect_encoding') && mb_detect_encoding($value) == 'ASCII')
  3763. // $value = mb_convert_encoding($value, 'UTF-8', 'HTML-ENTITIES');
  3764. }
  3765. foreach($this->stack(1) as $node) {
  3766. if (! is_null($code)) {
  3767. // $attrNode = $this->DOM->createAttribute($attr);
  3768. $node->setAttribute($attr, $value);
  3769. // $attrNode->value = $value;
  3770. // $node->appendChild($attrNode);
  3771. } else if ( $attr == '*') {
  3772. // jQuery diff
  3773. $return = array();
  3774. foreach($node->attributes as $n => $v)
  3775. $return[$n] = $v->value;
  3776. return $return;
  3777. } else
  3778. return $node->getAttribute($attr);
  3779. }
  3780. return $this;
  3781. }
  3782. /**
  3783. * Enter description here...
  3784. *
  3785. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3786. */
  3787. public function removeAttr($attr) {
  3788. foreach($this->stack(1) as $node) {
  3789. $loop = $attr == '*'
  3790. ? $this->getNodeAttrs($node)
  3791. : array($attr);
  3792. foreach($loop as $a) {
  3793. $oldValue = $node->getAttribute($a);
  3794. $node->removeAttribute($a);
  3795. $this->attrEvents($a, $oldValue, null, $node);
  3796. }
  3797. }
  3798. return $this;
  3799. }
  3800. /**
  3801. * Return form element value.
  3802. *
  3803. * @return String Fields value.
  3804. */
  3805. public function val($val = null) {
  3806. if (! isset($val)) {
  3807. if ($this->eq(0)->is('select')) {
  3808. $selected = $this->eq(0)->find('option[selected=selected]');
  3809. if ($selected->is('[value]'))
  3810. return $selected->attr('value');
  3811. else
  3812. return $selected->text();
  3813. } else if ($this->eq(0)->is('textarea'))
  3814. return $this->eq(0)->markup();
  3815. else
  3816. return $this->eq(0)->attr('value');
  3817. } else {
  3818. $_val = null;
  3819. foreach($this->stack(1) as $node) {
  3820. $node = pq($node, $this->getDocumentID());
  3821. if (is_array($val) && in_array($node->attr('type'), array('checkbox', 'radio'))) {
  3822. $isChecked = in_array($node->attr('value'), $val)
  3823. || in_array($node->attr('name'), $val);
  3824. if ($isChecked)
  3825. $node->attr('checked', 'checked');
  3826. else
  3827. $node->removeAttr('checked');
  3828. } else if ($node->get(0)->tagName == 'select') {
  3829. if (! isset($_val)) {
  3830. $_val = array();
  3831. if (! is_array($val))
  3832. $_val = array((string)$val);
  3833. else
  3834. foreach($val as $v)
  3835. $_val[] = $v;
  3836. }
  3837. foreach($node['option']->stack(1) as $option) {
  3838. $option = pq($option, $this->getDocumentID());
  3839. $selected = false;
  3840. // XXX: workaround for string comparsion, see issue #96
  3841. // http://code.google.com/p/phpquery/issues/detail?id=96
  3842. $selected = is_null($option->attr('value'))
  3843. ? in_array($option->markup(), $_val)
  3844. : in_array($option->attr('value'), $_val);
  3845. // $optionValue = $option->attr('value');
  3846. // $optionText = $option->text();
  3847. // $optionTextLenght = mb_strlen($optionText);
  3848. // foreach($_val as $v)
  3849. // if ($optionValue == $v)
  3850. // $selected = true;
  3851. // else if ($optionText == $v && $optionTextLenght == mb_strlen($v))
  3852. // $selected = true;
  3853. if ($selected)
  3854. $option->attr('selected', 'selected');
  3855. else
  3856. $option->removeAttr('selected');
  3857. }
  3858. } else if ($node->get(0)->tagName == 'textarea')
  3859. $node->markup($val);
  3860. else
  3861. $node->attr('value', $val);
  3862. }
  3863. }
  3864. return $this;
  3865. }
  3866. /**
  3867. * Enter description here...
  3868. *
  3869. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3870. */
  3871. public function andSelf() {
  3872. if ( $this->previous )
  3873. $this->elements = array_merge($this->elements, $this->previous->elements);
  3874. return $this;
  3875. }
  3876. /**
  3877. * Enter description here...
  3878. *
  3879. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3880. */
  3881. public function addClass( $className) {
  3882. if (! $className)
  3883. return $this;
  3884. foreach($this->stack(1) as $node) {
  3885. if (! $this->is(".$className", $node))
  3886. $node->setAttribute(
  3887. 'class',
  3888. trim($node->getAttribute('class').' '.$className)
  3889. );
  3890. }
  3891. return $this;
  3892. }
  3893. /**
  3894. * Enter description here...
  3895. *
  3896. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3897. */
  3898. public function addClassPHP( $className) {
  3899. foreach($this->stack(1) as $node) {
  3900. $classes = $node->getAttribute('class');
  3901. $newValue = $classes
  3902. ? $classes.' <'.'?php '.$className.' ?'.'>'
  3903. : '<'.'?php '.$className.' ?'.'>';
  3904. $node->setAttribute('class', $newValue);
  3905. }
  3906. return $this;
  3907. }
  3908. /**
  3909. * Enter description here...
  3910. *
  3911. * @param string $className
  3912. * @return bool
  3913. */
  3914. public function hasClass($className) {
  3915. foreach($this->stack(1) as $node) {
  3916. if ( $this->is(".$className", $node))
  3917. return true;
  3918. }
  3919. return false;
  3920. }
  3921. /**
  3922. * Enter description here...
  3923. *
  3924. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3925. */
  3926. public function removeClass($className) {
  3927. foreach($this->stack(1) as $node) {
  3928. $classes = explode( ' ', $node->getAttribute('class'));
  3929. if ( in_array($className, $classes)) {
  3930. $classes = array_diff($classes, array($className));
  3931. if ( $classes )
  3932. $node->setAttribute('class', implode(' ', $classes));
  3933. else
  3934. $node->removeAttribute('class');
  3935. }
  3936. }
  3937. return $this;
  3938. }
  3939. /**
  3940. * Enter description here...
  3941. *
  3942. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3943. */
  3944. public function toggleClass($className) {
  3945. foreach($this->stack(1) as $node) {
  3946. if ( $this->is( $node, '.'.$className ))
  3947. $this->removeClass($className);
  3948. else
  3949. $this->addClass($className);
  3950. }
  3951. return $this;
  3952. }
  3953. /**
  3954. * Proper name without underscore (just ->empty()) also works.
  3955. *
  3956. * Removes all child nodes from the set of matched elements.
  3957. *
  3958. * Example:
  3959. * pq("p")._empty()
  3960. *
  3961. * HTML:
  3962. * <p>Hello, <span>Person</span> <a href="#">and person</a></p>
  3963. *
  3964. * Result:
  3965. * [ <p></p> ]
  3966. *
  3967. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3968. * @access private
  3969. */
  3970. public function _empty() {
  3971. foreach($this->stack(1) as $node) {
  3972. // thx to 'dave at dgx dot cz'
  3973. $node->nodeValue = '';
  3974. }
  3975. return $this;
  3976. }
  3977. /**
  3978. * Enter description here...
  3979. *
  3980. * @param array|string $callback Expects $node as first param, $index as second
  3981. * @param array $scope External variables passed to callback. Use compact('varName1', 'varName2'...) and extract($scope)
  3982. * @param array $arg1 Will ba passed as third and futher args to callback.
  3983. * @param array $arg2 Will ba passed as fourth and futher args to callback, and so on...
  3984. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3985. */
  3986. public function each($callback, $param1 = null, $param2 = null, $param3 = null) {
  3987. $paramStructure = null;
  3988. if (func_num_args() > 1) {
  3989. $paramStructure = func_get_args();
  3990. $paramStructure = array_slice($paramStructure, 1);
  3991. }
  3992. foreach($this->elements as $v)
  3993. phpQuery::callbackRun($callback, array($v), $paramStructure);
  3994. return $this;
  3995. }
  3996. /**
  3997. * Run callback on actual object.
  3998. *
  3999. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4000. */
  4001. public function callback($callback, $param1 = null, $param2 = null, $param3 = null) {
  4002. $params = func_get_args();
  4003. $params[0] = $this;
  4004. phpQuery::callbackRun($callback, $params);
  4005. return $this;
  4006. }
  4007. /**
  4008. * Enter description here...
  4009. *
  4010. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4011. * @todo add $scope and $args as in each() ???
  4012. */
  4013. public function map($callback, $param1 = null, $param2 = null, $param3 = null) {
  4014. // $stack = array();
  4015. //// foreach($this->newInstance() as $node) {
  4016. // foreach($this->newInstance() as $node) {
  4017. // $result = call_user_func($callback, $node);
  4018. // if ($result)
  4019. // $stack[] = $result;
  4020. // }
  4021. $params = func_get_args();
  4022. array_unshift($params, $this->elements);
  4023. return $this->newInstance(
  4024. call_user_func_array(array('phpQuery', 'map'), $params)
  4025. // phpQuery::map($this->elements, $callback)
  4026. );
  4027. }
  4028. /**
  4029. * Enter description here...
  4030. *
  4031. * @param <type> $key
  4032. * @param <type> $value
  4033. */
  4034. public function data($key, $value = null) {
  4035. if (! isset($value)) {
  4036. // TODO? implement specific jQuery behavior od returning parent values
  4037. // is child which we look up doesn't exist
  4038. return phpQuery::data($this->get(0), $key, $value, $this->getDocumentID());
  4039. } else {
  4040. foreach($this as $node)
  4041. phpQuery::data($node, $key, $value, $this->getDocumentID());
  4042. return $this;
  4043. }
  4044. }
  4045. /**
  4046. * Enter description here...
  4047. *
  4048. * @param <type> $key
  4049. */
  4050. public function removeData($key) {
  4051. foreach($this as $node)
  4052. phpQuery::removeData($node, $key, $this->getDocumentID());
  4053. return $this;
  4054. }
  4055. // INTERFACE IMPLEMENTATIONS
  4056. // ITERATOR INTERFACE
  4057. /**
  4058. * @return void
  4059. * @access private
  4060. */
  4061. #[\ReturnTypeWillChange]
  4062. public function rewind() {
  4063. $this->debug('iterating foreach');
  4064. // phpQuery::selectDocument($this->getDocumentID());
  4065. $this->elementsBackup = $this->elements;
  4066. $this->elementsIterator = $this->elements;
  4067. $this->valid = isset( $this->elements[0] )
  4068. ? 1 : 0;
  4069. // $this->elements = $this->valid
  4070. // ? array($this->elements[0])
  4071. // : array();
  4072. $this->current = 0;
  4073. }
  4074. /**
  4075. * @return DOMElement
  4076. * @access private
  4077. */
  4078. #[\ReturnTypeWillChange]
  4079. public function current() {
  4080. return $this->elementsIterator[ $this->current ];
  4081. }
  4082. /**
  4083. * @return mixed
  4084. * @access private
  4085. */
  4086. #[\ReturnTypeWillChange]
  4087. public function key() {
  4088. return $this->current;
  4089. }
  4090. /**
  4091. * Double-function method.
  4092. *
  4093. * First: main iterator interface method.
  4094. * Second: Returning next sibling, alias for _next().
  4095. *
  4096. * Proper functionality is choosed automagicaly.
  4097. *
  4098. * @see phpQueryObject::_next()
  4099. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4100. */
  4101. #[\ReturnTypeWillChange]
  4102. public function next($cssSelector = null){
  4103. // if ($cssSelector || $this->valid)
  4104. // return $this->_next($cssSelector);
  4105. $this->valid = isset( $this->elementsIterator[ $this->current+1 ] )
  4106. ? true
  4107. : false;
  4108. if (! $this->valid && $this->elementsIterator) {
  4109. $this->elementsIterator = null;
  4110. } else if ($this->valid) {
  4111. $this->current++;
  4112. } else {
  4113. return $this->_next($cssSelector);
  4114. }
  4115. }
  4116. /**
  4117. * @access private
  4118. */
  4119. public function valid(): bool {
  4120. return $this->valid;
  4121. }
  4122. // ITERATOR INTERFACE END
  4123. // ARRAYACCESS INTERFACE
  4124. /**
  4125. * @access private
  4126. */
  4127. public function offsetExists($offset): bool {
  4128. return $this->find($offset)->size() > 0;
  4129. }
  4130. /**
  4131. * @access private
  4132. * @param mixed $offset
  4133. * @return mixed
  4134. */
  4135. #[\ReturnTypeWillChange]
  4136. public function offsetGet($offset) {
  4137. return $this->find($offset);
  4138. }
  4139. /**
  4140. * @return void
  4141. * @access private
  4142. */
  4143. #[\ReturnTypeWillChange]
  4144. public function offsetSet($offset, $value) {
  4145. // $this->find($offset)->replaceWith($value);
  4146. $this->find($offset)->html($value);
  4147. }
  4148. /**
  4149. * @return void
  4150. * @access private
  4151. */
  4152. #[\ReturnTypeWillChange]
  4153. public function offsetUnset($offset) {
  4154. // empty
  4155. throw new Exception("Can't do unset, use array interface only for calling queries and replacing HTML.");
  4156. }
  4157. // ARRAYACCESS INTERFACE END
  4158. /**
  4159. * Returns node's XPath.
  4160. *
  4161. * @param unknown_type $oneNode
  4162. * @return string
  4163. * @TODO use native getNodePath is avaible
  4164. * @access private
  4165. */
  4166. protected function getNodeXpath($oneNode = null, $namespace = null) {
  4167. $return = array();
  4168. $loop = $oneNode
  4169. ? array($oneNode)
  4170. : $this->elements;
  4171. // if ($namespace)
  4172. // $namespace .= ':';
  4173. foreach($loop as $node) {
  4174. if ($node instanceof DOMDOCUMENT) {
  4175. $return[] = '';
  4176. continue;
  4177. }
  4178. $xpath = array();
  4179. while(! ($node instanceof DOMDOCUMENT)) {
  4180. $i = 1;
  4181. $sibling = $node;
  4182. while($sibling->previousSibling) {
  4183. $sibling = $sibling->previousSibling;
  4184. $isElement = $sibling instanceof DOMELEMENT;
  4185. if ($isElement && $sibling->tagName == $node->tagName)
  4186. $i++;
  4187. }
  4188. $xpath[] = $this->isXML()
  4189. ? "*[local-name()='{$node->tagName}'][{$i}]"
  4190. : "{$node->tagName}[{$i}]";
  4191. $node = $node->parentNode;
  4192. }
  4193. $xpath = join('/', array_reverse($xpath));
  4194. $return[] = '/'.$xpath;
  4195. }
  4196. return $oneNode
  4197. ? $return[0]
  4198. : $return;
  4199. }
  4200. // HELPERS
  4201. public function whois($oneNode = null) {
  4202. $return = array();
  4203. $loop = $oneNode
  4204. ? array( $oneNode )
  4205. : $this->elements;
  4206. foreach($loop as $node) {
  4207. if (isset($node->tagName)) {
  4208. $tag = in_array($node->tagName, array('php', 'js'))
  4209. ? strtoupper($node->tagName)
  4210. : $node->tagName;
  4211. $return[] = $tag
  4212. .($node->getAttribute('id')
  4213. ? '#'.$node->getAttribute('id'):'')
  4214. .($node->getAttribute('class')
  4215. ? '.'.join('.', explode(' ', $node->getAttribute('class'))):'')
  4216. .($node->getAttribute('name')
  4217. ? '[name="'.$node->getAttribute('name').'"]':'')
  4218. .($node->getAttribute('value') && strpos($node->getAttribute('value'), '<'.'?php') === false
  4219. ? '[value="'.substr(str_replace("\n", '', $node->getAttribute('value')), 0, 15).'"]':'')
  4220. .($node->getAttribute('value') && strpos($node->getAttribute('value'), '<'.'?php') !== false
  4221. ? '[value=PHP]':'')
  4222. .($node->getAttribute('selected')
  4223. ? '[selected]':'')
  4224. .($node->getAttribute('checked')
  4225. ? '[checked]':'')
  4226. ;
  4227. } else if ($node instanceof DOMTEXT) {
  4228. if (trim($node->textContent))
  4229. $return[] = 'Text:'.substr(str_replace("\n", ' ', $node->textContent), 0, 15);
  4230. } else {
  4231. }
  4232. }
  4233. return $oneNode && isset($return[0])
  4234. ? $return[0]
  4235. : $return;
  4236. }
  4237. /**
  4238. * Dump htmlOuter and preserve chain. Usefull for debugging.
  4239. *
  4240. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4241. *
  4242. */
  4243. public function dump() {
  4244. print 'DUMP #'.(phpQuery::$dumpCount++).' ';
  4245. $debug = phpQuery::$debug;
  4246. phpQuery::$debug = false;
  4247. // print __FILE__.':'.__LINE__."\n";
  4248. var_dump($this->htmlOuter());
  4249. return $this;
  4250. }
  4251. public function dumpWhois() {
  4252. print 'DUMP #'.(phpQuery::$dumpCount++).' ';
  4253. $debug = phpQuery::$debug;
  4254. phpQuery::$debug = false;
  4255. // print __FILE__.':'.__LINE__."\n";
  4256. var_dump('whois', $this->whois());
  4257. phpQuery::$debug = $debug;
  4258. return $this;
  4259. }
  4260. public function dumpLength() {
  4261. print 'DUMP #'.(phpQuery::$dumpCount++).' ';
  4262. $debug = phpQuery::$debug;
  4263. phpQuery::$debug = false;
  4264. // print __FILE__.':'.__LINE__."\n";
  4265. var_dump('length', $this->size());
  4266. phpQuery::$debug = $debug;
  4267. return $this;
  4268. }
  4269. public function dumpTree($html = true, $title = true) {
  4270. $output = $title
  4271. ? 'DUMP #'.(phpQuery::$dumpCount++)." \n" : '';
  4272. $debug = phpQuery::$debug;
  4273. phpQuery::$debug = false;
  4274. foreach($this->stack() as $node)
  4275. $output .= $this->__dumpTree($node);
  4276. phpQuery::$debug = $debug;
  4277. print $html
  4278. ? nl2br(str_replace(' ', '&nbsp;', $output))
  4279. : $output;
  4280. return $this;
  4281. }
  4282. private function __dumpTree($node, $intend = 0) {
  4283. $whois = $this->whois($node);
  4284. $return = '';
  4285. if ($whois)
  4286. $return .= str_repeat(' - ', $intend).$whois."\n";
  4287. if (isset($node->childNodes))
  4288. foreach($node->childNodes as $chNode)
  4289. $return .= $this->__dumpTree($chNode, $intend+1);
  4290. return $return;
  4291. }
  4292. /**
  4293. * Dump htmlOuter and stop script execution. Usefull for debugging.
  4294. *
  4295. */
  4296. public function dumpDie() {
  4297. print __FILE__.':'.__LINE__;
  4298. var_dump($this->htmlOuter());
  4299. die();
  4300. }
  4301. }
  4302. // -- Multibyte Compatibility functions ---------------------------------------
  4303. // http://svn.iphonewebdev.com/lace/lib/mb_compat.php
  4304. /**
  4305. * mb_internal_encoding()
  4306. *
  4307. * Included for mbstring pseudo-compatability.
  4308. */
  4309. if (!function_exists('mb_internal_encoding'))
  4310. {
  4311. function mb_internal_encoding($enc) {return true; }
  4312. }
  4313. /**
  4314. * mb_regex_encoding()
  4315. *
  4316. * Included for mbstring pseudo-compatability.
  4317. */
  4318. if (!function_exists('mb_regex_encoding'))
  4319. {
  4320. function mb_regex_encoding($enc) {return true; }
  4321. }
  4322. /**
  4323. * mb_strlen()
  4324. *
  4325. * Included for mbstring pseudo-compatability.
  4326. */
  4327. if (!function_exists('mb_strlen'))
  4328. {
  4329. function mb_strlen($str)
  4330. {
  4331. return strlen($str);
  4332. }
  4333. }
  4334. /**
  4335. * mb_strpos()
  4336. *
  4337. * Included for mbstring pseudo-compatability.
  4338. */
  4339. if (!function_exists('mb_strpos'))
  4340. {
  4341. function mb_strpos($haystack, $needle, $offset=0)
  4342. {
  4343. return strpos($haystack, $needle, $offset);
  4344. }
  4345. }
  4346. /**
  4347. * mb_stripos()
  4348. *
  4349. * Included for mbstring pseudo-compatability.
  4350. */
  4351. if (!function_exists('mb_stripos'))
  4352. {
  4353. function mb_stripos($haystack, $needle, $offset=0)
  4354. {
  4355. return stripos($haystack, $needle, $offset);
  4356. }
  4357. }
  4358. /**
  4359. * mb_substr()
  4360. *
  4361. * Included for mbstring pseudo-compatability.
  4362. */
  4363. if (!function_exists('mb_substr'))
  4364. {
  4365. function mb_substr($str, $start, $length=0)
  4366. {
  4367. return substr($str, $start, $length);
  4368. }
  4369. }
  4370. /**
  4371. * mb_substr_count()
  4372. *
  4373. * Included for mbstring pseudo-compatability.
  4374. */
  4375. if (!function_exists('mb_substr_count'))
  4376. {
  4377. function mb_substr_count($haystack, $needle)
  4378. {
  4379. return substr_count($haystack, $needle);
  4380. }
  4381. }
  4382. /**
  4383. * Static namespace for phpQuery functions.
  4384. *
  4385. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  4386. * @package phpQuery
  4387. */
  4388. abstract class phpQuery {
  4389. /**
  4390. * XXX: Workaround for mbstring problems
  4391. *
  4392. * @var bool
  4393. */
  4394. public static $mbstringSupport = true;
  4395. public static $debug = false;
  4396. public static $documents = array();
  4397. public static $defaultDocumentID = null;
  4398. // public static $defaultDoctype = 'html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"';
  4399. /**
  4400. * Applies only to HTML.
  4401. *
  4402. * @var unknown_type
  4403. */
  4404. public static $defaultDoctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  4405. "http://www.w3.org/TR/html4/loose.dtd">';
  4406. public static $defaultCharset = 'UTF-8';
  4407. /**
  4408. * Static namespace for plugins.
  4409. *
  4410. * @var object
  4411. */
  4412. public static $plugins = array();
  4413. /**
  4414. * List of loaded plugins.
  4415. */
  4416. public static $pluginsLoaded = array();
  4417. public static $pluginsMethods = array();
  4418. public static $pluginsStaticMethods = array();
  4419. public static $extendMethods = array();
  4420. /**
  4421. * @TODO implement
  4422. */
  4423. public static $extendStaticMethods = array();
  4424. /**
  4425. * Hosts allowed for AJAX connections.
  4426. * Dot '.' means $_SERVER['HTTP_HOST'] (if any).
  4427. *
  4428. * @var array
  4429. */
  4430. public static $ajaxAllowedHosts = array(
  4431. '.'
  4432. );
  4433. /**
  4434. * AJAX settings.
  4435. *
  4436. * @var array
  4437. * XXX should it be static or not ?
  4438. */
  4439. public static $ajaxSettings = array(
  4440. 'url' => '',//TODO
  4441. 'global' => true,
  4442. 'type' => "GET",
  4443. 'timeout' => null,
  4444. 'contentType' => "application/x-www-form-urlencoded",
  4445. 'processData' => true,
  4446. // 'async' => true,
  4447. 'data' => null,
  4448. 'username' => null,
  4449. 'password' => null,
  4450. 'accepts' => array(
  4451. 'xml' => "application/xml, text/xml",
  4452. 'html' => "text/html",
  4453. 'script' => "text/javascript, application/javascript",
  4454. 'json' => "application/json, text/javascript",
  4455. 'text' => "text/plain",
  4456. '_default' => "*/*"
  4457. )
  4458. );
  4459. public static $lastModified = null;
  4460. public static $active = 0;
  4461. public static $dumpCount = 0;
  4462. /**
  4463. * Multi-purpose function.
  4464. * Use pq() as shortcut.
  4465. *
  4466. * In below examples, $pq is any result of pq(); function.
  4467. *
  4468. * 1. Import markup into existing document (without any attaching):
  4469. * - Import into selected document:
  4470. * pq('<div/>') // DOESNT accept text nodes at beginning of input string !
  4471. * - Import into document with ID from $pq->getDocumentID():
  4472. * pq('<div/>', $pq->getDocumentID())
  4473. * - Import into same document as DOMNode belongs to:
  4474. * pq('<div/>', DOMNode)
  4475. * - Import into document from phpQuery object:
  4476. * pq('<div/>', $pq)
  4477. *
  4478. * 2. Run query:
  4479. * - Run query on last selected document:
  4480. * pq('div.myClass')
  4481. * - Run query on document with ID from $pq->getDocumentID():
  4482. * pq('div.myClass', $pq->getDocumentID())
  4483. * - Run query on same document as DOMNode belongs to and use node(s)as root for query:
  4484. * pq('div.myClass', DOMNode)
  4485. * - Run query on document from phpQuery object
  4486. * and use object's stack as root node(s) for query:
  4487. * pq('div.myClass', $pq)
  4488. *
  4489. * @param string|DOMNode|DOMNodeList|array $arg1 HTML markup, CSS Selector, DOMNode or array of DOMNodes
  4490. * @param string|phpQueryObject|DOMNode $context DOM ID from $pq->getDocumentID(), phpQuery object (determines also query root) or DOMNode (determines also query root)
  4491. *
  4492. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery|QueryTemplatesPhpQuery|false
  4493. * phpQuery object or false in case of error.
  4494. */
  4495. public static function pq($arg1, $context = null) {
  4496. if ($arg1 instanceof DOMNODE && ! isset($context)) {
  4497. foreach(phpQuery::$documents as $documentWrapper) {
  4498. $compare = $arg1 instanceof DOMDocument
  4499. ? $arg1 : $arg1->ownerDocument;
  4500. if ($documentWrapper->document->isSameNode($compare))
  4501. $context = $documentWrapper->id;
  4502. }
  4503. }
  4504. if (! $context) {
  4505. $domId = self::$defaultDocumentID;
  4506. if (! $domId)
  4507. throw new Exception("Can't use last created DOM, because there isn't any. Use phpQuery::newDocument() first.");
  4508. // } else if (is_object($context) && ($context instanceof PHPQUERY || is_subclass_of($context, 'phpQueryObject')))
  4509. } else if (is_object($context) && $context instanceof phpQueryObject)
  4510. $domId = $context->getDocumentID();
  4511. else if ($context instanceof DOMDOCUMENT) {
  4512. $domId = self::getDocumentID($context);
  4513. if (! $domId) {
  4514. //throw new Exception('Orphaned DOMDocument');
  4515. $domId = self::newDocument($context)->getDocumentID();
  4516. }
  4517. } else if ($context instanceof DOMNODE) {
  4518. $domId = self::getDocumentID($context);
  4519. if (! $domId) {
  4520. throw new Exception('Orphaned DOMNode');
  4521. // $domId = self::newDocument($context->ownerDocument);
  4522. }
  4523. } else
  4524. $domId = $context;
  4525. if ($arg1 instanceof phpQueryObject) {
  4526. // if (is_object($arg1) && (get_class($arg1) == 'phpQueryObject' || $arg1 instanceof PHPQUERY || is_subclass_of($arg1, 'phpQueryObject'))) {
  4527. /**
  4528. * Return $arg1 or import $arg1 stack if document differs:
  4529. * pq(pq('<div/>'))
  4530. */
  4531. if ($arg1->getDocumentID() == $domId)
  4532. return $arg1;
  4533. $class = get_class($arg1);
  4534. // support inheritance by passing old object to overloaded constructor
  4535. $phpQuery = $class != 'phpQuery'
  4536. ? new $class($arg1, $domId)
  4537. : new phpQueryObject($domId);
  4538. $phpQuery->elements = array();
  4539. foreach($arg1->elements as $node)
  4540. $phpQuery->elements[] = $phpQuery->document->importNode($node, true);
  4541. return $phpQuery;
  4542. } else if ($arg1 instanceof DOMNODE || (is_array($arg1) && isset($arg1[0]) && $arg1[0] instanceof DOMNODE)) {
  4543. /*
  4544. * Wrap DOM nodes with phpQuery object, import into document when needed:
  4545. * pq(array($domNode1, $domNode2))
  4546. */
  4547. $phpQuery = new phpQueryObject($domId);
  4548. if (!($arg1 instanceof DOMNODELIST) && ! is_array($arg1))
  4549. $arg1 = array($arg1);
  4550. $phpQuery->elements = array();
  4551. foreach($arg1 as $node) {
  4552. $sameDocument = $node->ownerDocument instanceof DOMDOCUMENT
  4553. && ! $node->ownerDocument->isSameNode($phpQuery->document);
  4554. $phpQuery->elements[] = $sameDocument
  4555. ? $phpQuery->document->importNode($node, true)
  4556. : $node;
  4557. }
  4558. return $phpQuery;
  4559. } else if (self::isMarkup($arg1)) {
  4560. /**
  4561. * Import HTML:
  4562. * pq('<div/>')
  4563. */
  4564. $phpQuery = new phpQueryObject($domId);
  4565. return $phpQuery->newInstance(
  4566. $phpQuery->documentWrapper->import($arg1)
  4567. );
  4568. } else {
  4569. /**
  4570. * Run CSS query:
  4571. * pq('div.myClass')
  4572. */
  4573. $phpQuery = new phpQueryObject($domId);
  4574. // if ($context && ($context instanceof PHPQUERY || is_subclass_of($context, 'phpQueryObject')))
  4575. if ($context && $context instanceof phpQueryObject)
  4576. $phpQuery->elements = $context->elements;
  4577. else if ($context && $context instanceof DOMNODELIST) {
  4578. $phpQuery->elements = array();
  4579. foreach($context as $node)
  4580. $phpQuery->elements[] = $node;
  4581. } else if ($context && $context instanceof DOMNODE)
  4582. $phpQuery->elements = array($context);
  4583. return $phpQuery->find($arg1);
  4584. }
  4585. }
  4586. /**
  4587. * Sets default document to $id. Document has to be loaded prior
  4588. * to using this method.
  4589. * $id can be retrived via getDocumentID() or getDocumentIDRef().
  4590. *
  4591. * @param unknown_type $id
  4592. */
  4593. public static function selectDocument($id) {
  4594. $id = self::getDocumentID($id);
  4595. self::debug("Selecting document '$id' as default one");
  4596. self::$defaultDocumentID = self::getDocumentID($id);
  4597. }
  4598. /**
  4599. * Returns document with id $id or last used as phpQueryObject.
  4600. * $id can be retrived via getDocumentID() or getDocumentIDRef().
  4601. * Chainable.
  4602. *
  4603. * @see phpQuery::selectDocument()
  4604. * @param unknown_type $id
  4605. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4606. */
  4607. public static function getDocument($id = null) {
  4608. if ($id)
  4609. phpQuery::selectDocument($id);
  4610. else
  4611. $id = phpQuery::$defaultDocumentID;
  4612. return new phpQueryObject($id);
  4613. }
  4614. /**
  4615. * Creates new document from markup.
  4616. * Chainable.
  4617. *
  4618. * @param string $markup
  4619. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4620. */
  4621. public static function newDocument($markup = null, $contentType = null) {
  4622. if (! $markup)
  4623. $markup = '';
  4624. $documentID = phpQuery::createDocumentWrapper($markup, $contentType);
  4625. return new phpQueryObject($documentID);
  4626. }
  4627. /**
  4628. * Creates new document from markup.
  4629. * Chainable.
  4630. *
  4631. * @param string $markup
  4632. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4633. */
  4634. public static function newDocumentHTML($markup = null, $charset = null) {
  4635. $contentType = $charset
  4636. ? ";charset=$charset"
  4637. : '';
  4638. return self::newDocument($markup, "text/html{$contentType}");
  4639. }
  4640. /**
  4641. * Creates new document from markup.
  4642. * Chainable.
  4643. *
  4644. * @param string $markup
  4645. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4646. */
  4647. public static function newDocumentXML($markup = null, $charset = null) {
  4648. $contentType = $charset
  4649. ? ";charset=$charset"
  4650. : '';
  4651. return self::newDocument($markup, "text/xml{$contentType}");
  4652. }
  4653. /**
  4654. * Creates new document from markup.
  4655. * Chainable.
  4656. *
  4657. * @param string $markup
  4658. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4659. */
  4660. public static function newDocumentXHTML($markup = null, $charset = null) {
  4661. $contentType = $charset
  4662. ? ";charset=$charset"
  4663. : '';
  4664. return self::newDocument($markup, "application/xhtml+xml{$contentType}");
  4665. }
  4666. /**
  4667. * Creates new document from markup.
  4668. * Chainable.
  4669. *
  4670. * @param string $markup
  4671. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4672. */
  4673. public static function newDocumentPHP($markup = null, $contentType = "text/html") {
  4674. // TODO pass charset to phpToMarkup if possible (use DOMDocumentWrapper function)
  4675. $markup = phpQuery::phpToMarkup($markup, self::$defaultCharset);
  4676. return self::newDocument($markup, $contentType);
  4677. }
  4678. public static function phpToMarkup($php, $charset = 'utf-8') {
  4679. $regexes = array(
  4680. '@(<(?!\\?)(?:[^>]|\\?>)+\\w+\\s*=\\s*)(\')([^\']*)<'.'?php?(.*?)(?:\\?>)([^\']*)\'@s',
  4681. '@(<(?!\\?)(?:[^>]|\\?>)+\\w+\\s*=\\s*)(")([^"]*)<'.'?php?(.*?)(?:\\?>)([^"]*)"@s',
  4682. );
  4683. foreach($regexes as $regex)
  4684. while (preg_match($regex, $php, $matches)) {
  4685. $php = preg_replace_callback(
  4686. $regex,
  4687. array('phpQuery', '_phpToMarkupCallback'),
  4688. $php
  4689. );
  4690. }
  4691. $regex = '@(^|>[^<]*)+?(<\?php(.*?)(\?>))@s';
  4692. //preg_match_all($regex, $php, $matches);
  4693. //var_dump($matches);
  4694. $php = preg_replace($regex, '\\1<php><!-- \\3 --></php>', $php);
  4695. return $php;
  4696. }
  4697. public static function _phpToMarkupCallback($m, $charset = 'utf-8') {
  4698. return $m[1].$m[2]
  4699. .htmlspecialchars("<"."?php".$m[4]."?".">", ENT_QUOTES|ENT_NOQUOTES, $charset)
  4700. .$m[5].$m[2];
  4701. }
  4702. public static function _markupToPHPCallback($m) {
  4703. return "<"."?php ".htmlspecialchars_decode($m[1])." ?".">";
  4704. }
  4705. /**
  4706. * Converts document markup containing PHP code generated by phpQuery::php()
  4707. * into valid (executable) PHP code syntax.
  4708. *
  4709. * @param string|phpQueryObject $content
  4710. * @return string PHP code.
  4711. */
  4712. public static function markupToPHP($content) {
  4713. if ($content instanceof phpQueryObject)
  4714. $content = $content->markupOuter();
  4715. /* <php>...</php> to <?php...? > */
  4716. $content = preg_replace_callback(
  4717. '@<php>\s*<!--(.*?)-->\s*</php>@s',
  4718. array('phpQuery', '_markupToPHPCallback'),
  4719. $content
  4720. );
  4721. /* <node attr='< ?php ? >'> extra space added to save highlighters */
  4722. $regexes = array(
  4723. '@(<(?!\\?)(?:[^>]|\\?>)+\\w+\\s*=\\s*)(\')([^\']*)(?:&lt;|%3C)\\?(?:php)?(.*?)(?:\\?(?:&gt;|%3E))([^\']*)\'@s',
  4724. '@(<(?!\\?)(?:[^>]|\\?>)+\\w+\\s*=\\s*)(")([^"]*)(?:&lt;|%3C)\\?(?:php)?(.*?)(?:\\?(?:&gt;|%3E))([^"]*)"@s',
  4725. );
  4726. foreach($regexes as $regex)
  4727. while (preg_match($regex, $content))
  4728. $content = preg_replace_callback(
  4729. $regex,
  4730. function ($m) {
  4731. return $m[1].$m[2].$m[3]."<?php "
  4732. .str_replace(
  4733. array("%20", "%3E", "%09", "&#10;", "&#9;", "%7B", "%24", "%7D", "%22", "%5B", "%5D"),
  4734. array(" ", ">", " ", "\n", " ", "{", "$", "}", '"', "[", "]"),
  4735. htmlspecialchars_decode($m[4])
  4736. )
  4737. ." ?>".$m[5].$m[2];
  4738. },
  4739. $content
  4740. );
  4741. return $content;
  4742. }
  4743. /**
  4744. * Creates new document from file $file.
  4745. * Chainable.
  4746. *
  4747. * @param string $file URLs allowed. See File wrapper page at php.net for more supported sources.
  4748. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4749. */
  4750. public static function newDocumentFile($file, $contentType = null) {
  4751. $documentID = self::createDocumentWrapper(
  4752. file_get_contents($file), $contentType
  4753. );
  4754. return new phpQueryObject($documentID);
  4755. }
  4756. /**
  4757. * Creates new document from markup.
  4758. * Chainable.
  4759. *
  4760. * @param string $markup
  4761. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4762. */
  4763. public static function newDocumentFileHTML($file, $charset = null) {
  4764. $contentType = $charset
  4765. ? ";charset=$charset"
  4766. : '';
  4767. return self::newDocumentFile($file, "text/html{$contentType}");
  4768. }
  4769. /**
  4770. * Creates new document from markup.
  4771. * Chainable.
  4772. *
  4773. * @param string $markup
  4774. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4775. */
  4776. public static function newDocumentFileXML($file, $charset = null) {
  4777. $contentType = $charset
  4778. ? ";charset=$charset"
  4779. : '';
  4780. return self::newDocumentFile($file, "text/xml{$contentType}");
  4781. }
  4782. /**
  4783. * Creates new document from markup.
  4784. * Chainable.
  4785. *
  4786. * @param string $markup
  4787. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4788. */
  4789. public static function newDocumentFileXHTML($file, $charset = null) {
  4790. $contentType = $charset
  4791. ? ";charset=$charset"
  4792. : '';
  4793. return self::newDocumentFile($file, "application/xhtml+xml{$contentType}");
  4794. }
  4795. /**
  4796. * Creates new document from markup.
  4797. * Chainable.
  4798. *
  4799. * @param string $markup
  4800. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4801. */
  4802. public static function newDocumentFilePHP($file, $contentType = null) {
  4803. return self::newDocumentPHP(file_get_contents($file), $contentType);
  4804. }
  4805. /**
  4806. * Reuses existing DOMDocument object.
  4807. * Chainable.
  4808. *
  4809. * @param $document DOMDocument
  4810. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4811. * @TODO support DOMDocument
  4812. */
  4813. public static function loadDocument($document) {
  4814. // TODO
  4815. die('TODO loadDocument');
  4816. }
  4817. /**
  4818. * Enter description here...
  4819. *
  4820. * @param unknown_type $html
  4821. * @param unknown_type $domId
  4822. * @return unknown New DOM ID
  4823. * @todo support PHP tags in input
  4824. * @todo support passing DOMDocument object from self::loadDocument
  4825. */
  4826. protected static function createDocumentWrapper($html, $contentType = null, $documentID = null) {
  4827. if (function_exists('domxml_open_mem'))
  4828. throw new Exception("Old PHP4 DOM XML extension detected. phpQuery won't work until this extension is enabled.");
  4829. // $id = $documentID
  4830. // ? $documentID
  4831. // : md5(microtime());
  4832. $document = null;
  4833. if ($html instanceof DOMDOCUMENT) {
  4834. if (self::getDocumentID($html)) {
  4835. // document already exists in phpQuery::$documents, make a copy
  4836. $document = clone $html;
  4837. } else {
  4838. // new document, add it to phpQuery::$documents
  4839. $wrapper = new DOMDocumentWrapper($html, $contentType, $documentID);
  4840. }
  4841. } else {
  4842. $wrapper = new DOMDocumentWrapper($html, $contentType, $documentID);
  4843. }
  4844. // $wrapper->id = $id;
  4845. // bind document
  4846. phpQuery::$documents[$wrapper->id] = $wrapper;
  4847. // remember last loaded document
  4848. phpQuery::selectDocument($wrapper->id);
  4849. return $wrapper->id;
  4850. }
  4851. /**
  4852. * Extend class namespace.
  4853. *
  4854. * @param string|array $target
  4855. * @param array $source
  4856. * @TODO support string $source
  4857. * @return unknown_type
  4858. */
  4859. public static function extend($target, $source) {
  4860. switch($target) {
  4861. case 'phpQueryObject':
  4862. $targetRef = &self::$extendMethods;
  4863. $targetRef2 = &self::$pluginsMethods;
  4864. break;
  4865. case 'phpQuery':
  4866. $targetRef = &self::$extendStaticMethods;
  4867. $targetRef2 = &self::$pluginsStaticMethods;
  4868. break;
  4869. default:
  4870. throw new Exception("Unsupported \$target type");
  4871. }
  4872. if (is_string($source))
  4873. $source = array($source => $source);
  4874. foreach($source as $method => $callback) {
  4875. if (isset($targetRef[$method])) {
  4876. // throw new Exception
  4877. self::debug("Duplicate method '{$method}', can\'t extend '{$target}'");
  4878. continue;
  4879. }
  4880. if (isset($targetRef2[$method])) {
  4881. // throw new Exception
  4882. self::debug("Duplicate method '{$method}' from plugin '{$targetRef2[$method]}',"
  4883. ." can\'t extend '{$target}'");
  4884. continue;
  4885. }
  4886. $targetRef[$method] = $callback;
  4887. }
  4888. return true;
  4889. }
  4890. /**
  4891. * Extend phpQuery with $class from $file.
  4892. *
  4893. * @param string $class Extending class name. Real class name can be prepended phpQuery_.
  4894. * @param string $file Filename to include. Defaults to "{$class}.php".
  4895. */
  4896. public static function plugin($class, $file = null) {
  4897. // TODO $class checked against phpQuery_$class
  4898. // if (strpos($class, 'phpQuery') === 0)
  4899. // $class = substr($class, 8);
  4900. if (in_array($class, self::$pluginsLoaded))
  4901. return true;
  4902. if (! $file)
  4903. $file = $class.'.php';
  4904. $objectClassExists = class_exists('phpQueryObjectPlugin_'.$class);
  4905. $staticClassExists = class_exists('phpQueryPlugin_'.$class);
  4906. if (! $objectClassExists && ! $staticClassExists)
  4907. require_once($file);
  4908. self::$pluginsLoaded[] = $class;
  4909. // static methods
  4910. if (class_exists('phpQueryPlugin_'.$class)) {
  4911. $realClass = 'phpQueryPlugin_'.$class;
  4912. $vars = get_class_vars($realClass);
  4913. $loop = isset($vars['phpQueryMethods'])
  4914. && ! is_null($vars['phpQueryMethods'])
  4915. ? $vars['phpQueryMethods']
  4916. : get_class_methods($realClass);
  4917. foreach($loop as $method) {
  4918. if ($method == '__initialize')
  4919. continue;
  4920. if (! is_callable(array($realClass, $method)))
  4921. continue;
  4922. if (isset(self::$pluginsStaticMethods[$method])) {
  4923. throw new Exception("Duplicate method '{$method}' from plugin '{$c}' conflicts with same method from plugin '".self::$pluginsStaticMethods[$method]."'");
  4924. return;
  4925. }
  4926. self::$pluginsStaticMethods[$method] = $class;
  4927. }
  4928. if (method_exists($realClass, '__initialize'))
  4929. call_user_func_array(array($realClass, '__initialize'), array());
  4930. }
  4931. // object methods
  4932. if (class_exists('phpQueryObjectPlugin_'.$class)) {
  4933. $realClass = 'phpQueryObjectPlugin_'.$class;
  4934. $vars = get_class_vars($realClass);
  4935. $loop = isset($vars['phpQueryMethods'])
  4936. && ! is_null($vars['phpQueryMethods'])
  4937. ? $vars['phpQueryMethods']
  4938. : get_class_methods($realClass);
  4939. foreach($loop as $method) {
  4940. if (! is_callable(array($realClass, $method)))
  4941. continue;
  4942. if (isset(self::$pluginsMethods[$method])) {
  4943. throw new Exception("Duplicate method '{$method}' from plugin '{$c}' conflicts with same method from plugin '".self::$pluginsMethods[$method]."'");
  4944. continue;
  4945. }
  4946. self::$pluginsMethods[$method] = $class;
  4947. }
  4948. }
  4949. return true;
  4950. }
  4951. /**
  4952. * Unloades all or specified document from memory.
  4953. *
  4954. * @param mixed $documentID @see phpQuery::getDocumentID() for supported types.
  4955. */
  4956. public static function unloadDocuments($id = null) {
  4957. if (isset($id)) {
  4958. if ($id = self::getDocumentID($id))
  4959. unset(phpQuery::$documents[$id]);
  4960. } else {
  4961. foreach(phpQuery::$documents as $k => $v) {
  4962. unset(phpQuery::$documents[$k]);
  4963. }
  4964. }
  4965. }
  4966. /**
  4967. * Parses phpQuery object or HTML result against PHP tags and makes them active.
  4968. *
  4969. * @param phpQuery|string $content
  4970. * @deprecated
  4971. * @return string
  4972. */
  4973. public static function unsafePHPTags($content) {
  4974. return self::markupToPHP($content);
  4975. }
  4976. public static function DOMNodeListToArray($DOMNodeList) {
  4977. $array = array();
  4978. if (! $DOMNodeList)
  4979. return $array;
  4980. foreach($DOMNodeList as $node)
  4981. $array[] = $node;
  4982. return $array;
  4983. }
  4984. /**
  4985. * Checks if $input is HTML string, which has to start with '<'.
  4986. *
  4987. * @param String $input
  4988. * @return Bool
  4989. * @todo still used ?
  4990. */
  4991. public static function isMarkup($input) {
  4992. return ! is_array($input) && substr(trim($input), 0, 1) == '<';
  4993. }
  4994. public static function debug($text) {
  4995. if (self::$debug)
  4996. print var_dump($text);
  4997. }
  4998. /**
  4999. * Make an AJAX request.
  5000. *
  5001. * @param array See $options http://docs.jquery.com/Ajax/jQuery.ajax#toptions
  5002. * Additional options are:
  5003. * 'document' - document for global events, @see phpQuery::getDocumentID()
  5004. * 'referer' - implemented
  5005. * 'requested_with' - TODO; not implemented (X-Requested-With)
  5006. * @return Zend_Http_Client
  5007. * @link http://docs.jquery.com/Ajax/jQuery.ajax
  5008. *
  5009. * @TODO $options['cache']
  5010. * @TODO $options['processData']
  5011. * @TODO $options['xhr']
  5012. * @TODO $options['data'] as string
  5013. * @TODO XHR interface
  5014. */
  5015. public static function ajax($options = array(), $xhr = null) {
  5016. $options = array_merge(
  5017. self::$ajaxSettings, $options
  5018. );
  5019. $documentID = isset($options['document'])
  5020. ? self::getDocumentID($options['document'])
  5021. : null;
  5022. if ($xhr) {
  5023. // reuse existing XHR object, but clean it up
  5024. $client = $xhr;
  5025. // $client->setParameterPost(null);
  5026. // $client->setParameterGet(null);
  5027. $client->setAuth(false);
  5028. $client->setHeaders("If-Modified-Since", null);
  5029. $client->setHeaders("Referer", null);
  5030. $client->resetParameters();
  5031. } else {
  5032. // create new XHR object
  5033. require_once('Zend/Http/Client.php');
  5034. $client = new Zend_Http_Client();
  5035. $client->setCookieJar();
  5036. }
  5037. if (isset($options['timeout']))
  5038. $client->setConfig(array(
  5039. 'timeout' => $options['timeout'],
  5040. ));
  5041. // 'maxredirects' => 0,
  5042. foreach(self::$ajaxAllowedHosts as $k => $host)
  5043. if ($host == '.' && isset($_SERVER['HTTP_HOST']))
  5044. self::$ajaxAllowedHosts[$k] = $_SERVER['HTTP_HOST'];
  5045. $host = parse_url($options['url'], PHP_URL_HOST);
  5046. if (! in_array($host, self::$ajaxAllowedHosts)) {
  5047. throw new Exception("Request not permitted, host '$host' not present in "
  5048. ."phpQuery::\$ajaxAllowedHosts");
  5049. }
  5050. // JSONP
  5051. $jsre = "/=\\?(&|$)/";
  5052. if (isset($options['dataType']) && $options['dataType'] == 'jsonp') {
  5053. $jsonpCallbackParam = $options['jsonp']
  5054. ? $options['jsonp'] : 'callback';
  5055. if (strtolower($options['type']) == 'get') {
  5056. if (! preg_match($jsre, $options['url'])) {
  5057. $sep = strpos($options['url'], '?')
  5058. ? '&' : '?';
  5059. $options['url'] .= "$sep$jsonpCallbackParam=?";
  5060. }
  5061. } else if ($options['data']) {
  5062. $jsonp = false;
  5063. foreach($options['data'] as $n => $v) {
  5064. if ($v == '?')
  5065. $jsonp = true;
  5066. }
  5067. if (! $jsonp) {
  5068. $options['data'][$jsonpCallbackParam] = '?';
  5069. }
  5070. }
  5071. $options['dataType'] = 'json';
  5072. }
  5073. if (isset($options['dataType']) && $options['dataType'] == 'json') {
  5074. $jsonpCallback = 'json_'.md5(microtime());
  5075. $jsonpData = $jsonpUrl = false;
  5076. if ($options['data']) {
  5077. foreach($options['data'] as $n => $v) {
  5078. if ($v == '?')
  5079. $jsonpData = $n;
  5080. }
  5081. }
  5082. if (preg_match($jsre, $options['url']))
  5083. $jsonpUrl = true;
  5084. if ($jsonpData !== false || $jsonpUrl) {
  5085. // remember callback name for httpData()
  5086. $options['_jsonp'] = $jsonpCallback;
  5087. if ($jsonpData !== false)
  5088. $options['data'][$jsonpData] = $jsonpCallback;
  5089. if ($jsonpUrl)
  5090. $options['url'] = preg_replace($jsre, "=$jsonpCallback\\1", $options['url']);
  5091. }
  5092. }
  5093. $client->setUri($options['url']);
  5094. $client->setMethod(strtoupper($options['type']));
  5095. if (isset($options['referer']) && $options['referer'])
  5096. $client->setHeaders('Referer', $options['referer']);
  5097. $client->setHeaders(array(
  5098. // 'content-type' => $options['contentType'],
  5099. 'User-Agent' => 'Mozilla/5.0 (X11; U; Linux x86; en-US; rv:1.9.0.5) Gecko'
  5100. .'/2008122010 Firefox/3.0.5',
  5101. // TODO custom charset
  5102. 'Accept-Charset' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  5103. // 'Connection' => 'keep-alive',
  5104. // 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  5105. 'Accept-Language' => 'en-us,en;q=0.5',
  5106. ));
  5107. if ($options['username'])
  5108. $client->setAuth($options['username'], $options['password']);
  5109. if (isset($options['ifModified']) && $options['ifModified'])
  5110. $client->setHeaders("If-Modified-Since",
  5111. self::$lastModified
  5112. ? self::$lastModified
  5113. : "Thu, 01 Jan 1970 00:00:00 GMT"
  5114. );
  5115. $client->setHeaders("Accept",
  5116. isset($options['dataType'])
  5117. && isset(self::$ajaxSettings['accepts'][ $options['dataType'] ])
  5118. ? self::$ajaxSettings['accepts'][ $options['dataType'] ].", */*"
  5119. : self::$ajaxSettings['accepts']['_default']
  5120. );
  5121. // TODO $options['processData']
  5122. if ($options['data'] instanceof phpQueryObject) {
  5123. $serialized = $options['data']->serializeArray($options['data']);
  5124. $options['data'] = array();
  5125. foreach($serialized as $r)
  5126. $options['data'][ $r['name'] ] = $r['value'];
  5127. }
  5128. if (strtolower($options['type']) == 'get') {
  5129. $client->setParameterGet($options['data']);
  5130. } else if (strtolower($options['type']) == 'post') {
  5131. $client->setEncType($options['contentType']);
  5132. $client->setParameterPost($options['data']);
  5133. }
  5134. if (self::$active == 0 && $options['global'])
  5135. phpQueryEvents::trigger($documentID, 'ajaxStart');
  5136. self::$active++;
  5137. // beforeSend callback
  5138. if (isset($options['beforeSend']) && $options['beforeSend'])
  5139. phpQuery::callbackRun($options['beforeSend'], array($client));
  5140. // ajaxSend event
  5141. if ($options['global'])
  5142. phpQueryEvents::trigger($documentID, 'ajaxSend', array($client, $options));
  5143. if (phpQuery::$debug) {
  5144. self::debug("{$options['type']}: {$options['url']}\n");
  5145. self::debug("Options: <pre>".var_export($options, true)."</pre>\n");
  5146. // if ($client->getCookieJar())
  5147. // self::debug("Cookies: <pre>".var_export($client->getCookieJar()->getMatchingCookies($options['url']), true)."</pre>\n");
  5148. }
  5149. // request
  5150. $response = $client->request();
  5151. if (phpQuery::$debug) {
  5152. self::debug('Status: '.$response->getStatus().' / '.$response->getMessage());
  5153. self::debug($client->getLastRequest());
  5154. self::debug($response->getHeaders());
  5155. }
  5156. if ($response->isSuccessful()) {
  5157. // XXX tempolary
  5158. self::$lastModified = $response->getHeader('Last-Modified');
  5159. $data = self::httpData($response->getBody(), $options['dataType'], $options);
  5160. if (isset($options['success']) && $options['success'])
  5161. phpQuery::callbackRun($options['success'], array($data, $response->getStatus(), $options));
  5162. if ($options['global'])
  5163. phpQueryEvents::trigger($documentID, 'ajaxSuccess', array($client, $options));
  5164. } else {
  5165. if (isset($options['error']) && $options['error'])
  5166. phpQuery::callbackRun($options['error'], array($client, $response->getStatus(), $response->getMessage()));
  5167. if ($options['global'])
  5168. phpQueryEvents::trigger($documentID, 'ajaxError', array($client, /*$response->getStatus(),*/$response->getMessage(), $options));
  5169. }
  5170. if (isset($options['complete']) && $options['complete'])
  5171. phpQuery::callbackRun($options['complete'], array($client, $response->getStatus()));
  5172. if ($options['global'])
  5173. phpQueryEvents::trigger($documentID, 'ajaxComplete', array($client, $options));
  5174. if ($options['global'] && ! --self::$active)
  5175. phpQueryEvents::trigger($documentID, 'ajaxStop');
  5176. return $client;
  5177. // if (is_null($domId))
  5178. // $domId = self::$defaultDocumentID ? self::$defaultDocumentID : false;
  5179. // return new phpQueryAjaxResponse($response, $domId);
  5180. }
  5181. protected static function httpData($data, $type, $options) {
  5182. if (isset($options['dataFilter']) && $options['dataFilter'])
  5183. $data = self::callbackRun($options['dataFilter'], array($data, $type));
  5184. if (is_string($data)) {
  5185. if ($type == "json") {
  5186. if (isset($options['_jsonp']) && $options['_jsonp']) {
  5187. $data = preg_replace('/^\s*\w+\((.*)\)\s*$/s', '$1', $data);
  5188. }
  5189. $data = self::parseJSON($data);
  5190. }
  5191. }
  5192. return $data;
  5193. }
  5194. /**
  5195. * Enter description here...
  5196. *
  5197. * @param array|phpQuery $data
  5198. *
  5199. */
  5200. public static function param($data) {
  5201. return http_build_query($data, '', '&');
  5202. }
  5203. public static function get($url, $data = null, $callback = null, $type = null) {
  5204. if (!is_array($data)) {
  5205. $callback = $data;
  5206. $data = null;
  5207. }
  5208. // TODO some array_values on this shit
  5209. return phpQuery::ajax(array(
  5210. 'type' => 'GET',
  5211. 'url' => $url,
  5212. 'data' => $data,
  5213. 'success' => $callback,
  5214. 'dataType' => $type,
  5215. ));
  5216. }
  5217. public static function post($url, $data = null, $callback = null, $type = null) {
  5218. if (!is_array($data)) {
  5219. $callback = $data;
  5220. $data = null;
  5221. }
  5222. return phpQuery::ajax(array(
  5223. 'type' => 'POST',
  5224. 'url' => $url,
  5225. 'data' => $data,
  5226. 'success' => $callback,
  5227. 'dataType' => $type,
  5228. ));
  5229. }
  5230. public static function getJSON($url, $data = null, $callback = null) {
  5231. if (!is_array($data)) {
  5232. $callback = $data;
  5233. $data = null;
  5234. }
  5235. // TODO some array_values on this shit
  5236. return phpQuery::ajax(array(
  5237. 'type' => 'GET',
  5238. 'url' => $url,
  5239. 'data' => $data,
  5240. 'success' => $callback,
  5241. 'dataType' => 'json',
  5242. ));
  5243. }
  5244. public static function ajaxSetup($options) {
  5245. self::$ajaxSettings = array_merge(
  5246. self::$ajaxSettings,
  5247. $options
  5248. );
  5249. }
  5250. public static function ajaxAllowHost($host1, $host2 = null, $host3 = null) {
  5251. $loop = is_array($host1)
  5252. ? $host1
  5253. : func_get_args();
  5254. foreach($loop as $host) {
  5255. if ($host && ! in_array($host, phpQuery::$ajaxAllowedHosts)) {
  5256. phpQuery::$ajaxAllowedHosts[] = $host;
  5257. }
  5258. }
  5259. }
  5260. public static function ajaxAllowURL($url1, $url2 = null, $url3 = null) {
  5261. $loop = is_array($url1)
  5262. ? $url1
  5263. : func_get_args();
  5264. foreach($loop as $url)
  5265. phpQuery::ajaxAllowHost(parse_url($url, PHP_URL_HOST));
  5266. }
  5267. /**
  5268. * Returns JSON representation of $data.
  5269. *
  5270. * @static
  5271. * @param mixed $data
  5272. * @return string
  5273. */
  5274. public static function toJSON($data) {
  5275. if (function_exists('json_encode'))
  5276. return json_encode($data);
  5277. require_once('Zend/Json/Encoder.php');
  5278. return Zend_Json_Encoder::encode($data);
  5279. }
  5280. /**
  5281. * Parses JSON into proper PHP type.
  5282. *
  5283. * @static
  5284. * @param string $json
  5285. * @return mixed
  5286. */
  5287. public static function parseJSON($json) {
  5288. if (function_exists('json_decode')) {
  5289. $return = json_decode(trim($json), true);
  5290. // json_decode and UTF8 issues
  5291. if (isset($return))
  5292. return $return;
  5293. }
  5294. require_once('Zend/Json/Decoder.php');
  5295. return Zend_Json_Decoder::decode($json);
  5296. }
  5297. /**
  5298. * Returns source's document ID.
  5299. *
  5300. * @param $source DOMNode|phpQueryObject
  5301. * @return string
  5302. */
  5303. public static function getDocumentID($source) {
  5304. if ($source instanceof DOMDOCUMENT) {
  5305. foreach(phpQuery::$documents as $id => $document) {
  5306. if ($source->isSameNode($document->document))
  5307. return $id;
  5308. }
  5309. } else if ($source instanceof DOMNODE) {
  5310. foreach(phpQuery::$documents as $id => $document) {
  5311. if ($source->ownerDocument->isSameNode($document->document))
  5312. return $id;
  5313. }
  5314. } else if ($source instanceof phpQueryObject)
  5315. return $source->getDocumentID();
  5316. else if (is_string($source) && isset(phpQuery::$documents[$source]))
  5317. return $source;
  5318. }
  5319. /**
  5320. * Get DOMDocument object related to $source.
  5321. * Returns null if such document doesn't exist.
  5322. *
  5323. * @param $source DOMNode|phpQueryObject|string
  5324. * @return string
  5325. */
  5326. public static function getDOMDocument($source) {
  5327. if ($source instanceof DOMDOCUMENT)
  5328. return $source;
  5329. $id = self::getDocumentID($source);
  5330. return $id
  5331. ? self::$documents[$id]['document']
  5332. : null;
  5333. }
  5334. // UTILITIES
  5335. // http://docs.jquery.com/Utilities
  5336. /**
  5337. *
  5338. * @return unknown_type
  5339. * @link http://docs.jquery.com/Utilities/jQuery.makeArray
  5340. */
  5341. public static function makeArray($object) {
  5342. $array = array();
  5343. if (is_object($object) && $object instanceof DOMNODELIST) {
  5344. foreach($object as $value)
  5345. $array[] = $value;
  5346. } else if (is_object($object) && ! ($object instanceof Iterator)) {
  5347. foreach(get_object_vars($object) as $name => $value)
  5348. $array[0][$name] = $value;
  5349. } else {
  5350. foreach($object as $name => $value)
  5351. $array[0][$name] = $value;
  5352. }
  5353. return $array;
  5354. }
  5355. public static function inArray($value, $array) {
  5356. return in_array($value, $array);
  5357. }
  5358. /**
  5359. *
  5360. * @param $object
  5361. * @param $callback
  5362. * @return unknown_type
  5363. * @link http://docs.jquery.com/Utilities/jQuery.each
  5364. */
  5365. public static function each($object, $callback, $param1 = null, $param2 = null, $param3 = null) {
  5366. $paramStructure = null;
  5367. if (func_num_args() > 2) {
  5368. $paramStructure = func_get_args();
  5369. $paramStructure = array_slice($paramStructure, 2);
  5370. }
  5371. if (is_object($object) && ! ($object instanceof Iterator)) {
  5372. foreach(get_object_vars($object) as $name => $value)
  5373. phpQuery::callbackRun($callback, array($name, $value), $paramStructure);
  5374. } else {
  5375. foreach($object as $name => $value)
  5376. phpQuery::callbackRun($callback, array($name, $value), $paramStructure);
  5377. }
  5378. }
  5379. /**
  5380. *
  5381. * @link http://docs.jquery.com/Utilities/jQuery.map
  5382. */
  5383. public static function map($array, $callback, $param1 = null, $param2 = null, $param3 = null) {
  5384. $result = array();
  5385. $paramStructure = null;
  5386. if (func_num_args() > 2) {
  5387. $paramStructure = func_get_args();
  5388. $paramStructure = array_slice($paramStructure, 2);
  5389. }
  5390. foreach($array as $v) {
  5391. $vv = phpQuery::callbackRun($callback, array($v), $paramStructure);
  5392. // $callbackArgs = $args;
  5393. // foreach($args as $i => $arg) {
  5394. // $callbackArgs[$i] = $arg instanceof CallbackParam
  5395. // ? $v
  5396. // : $arg;
  5397. // }
  5398. // $vv = call_user_func_array($callback, $callbackArgs);
  5399. if (is_array($vv)) {
  5400. foreach($vv as $vvv)
  5401. $result[] = $vvv;
  5402. } else if ($vv !== null) {
  5403. $result[] = $vv;
  5404. }
  5405. }
  5406. return $result;
  5407. }
  5408. /**
  5409. *
  5410. * @param $callback Callback
  5411. * @param $params
  5412. * @param $paramStructure
  5413. * @return unknown_type
  5414. */
  5415. public static function callbackRun($callback, $params = array(), $paramStructure = null) {
  5416. if (! $callback)
  5417. return;
  5418. if ($callback instanceof CallbackParameterToReference) {
  5419. // TODO support ParamStructure to select which $param push to reference
  5420. if (isset($params[0]))
  5421. $callback->callback = $params[0];
  5422. return true;
  5423. }
  5424. if ($callback instanceof Callback) {
  5425. $paramStructure = $callback->params;
  5426. $callback = $callback->callback;
  5427. }
  5428. if (! $paramStructure)
  5429. return call_user_func_array($callback, $params);
  5430. $p = 0;
  5431. foreach($paramStructure as $i => $v) {
  5432. $paramStructure[$i] = $v instanceof CallbackParam
  5433. ? $params[$p++]
  5434. : $v;
  5435. }
  5436. return call_user_func_array($callback, $paramStructure);
  5437. }
  5438. /**
  5439. * Merge 2 phpQuery objects.
  5440. * @param phpQueryObject $one
  5441. * @param phpQueryObject $two
  5442. * @protected
  5443. * @todo node lists, phpQueryObject
  5444. */
  5445. public static function merge(object $one, object $two): array {
  5446. $elements = $one->elements;
  5447. foreach($two->elements as $node) {
  5448. $exists = false;
  5449. foreach($elements as $node2) {
  5450. if ($node2->isSameNode($node))
  5451. $exists = true;
  5452. }
  5453. if (! $exists)
  5454. $elements[] = $node;
  5455. }
  5456. return $elements;
  5457. // $one = $one->newInstance();
  5458. // $one->elements = $elements;
  5459. // return $one;
  5460. }
  5461. /**
  5462. *
  5463. * @param $array
  5464. * @param $callback
  5465. * @param $invert
  5466. * @return unknown_type
  5467. * @link http://docs.jquery.com/Utilities/jQuery.grep
  5468. */
  5469. public static function grep($array, $callback, $invert = false) {
  5470. $result = array();
  5471. foreach($array as $k => $v) {
  5472. $r = call_user_func_array($callback, array($v, $k));
  5473. if ($r === !(bool)$invert)
  5474. $result[] = $v;
  5475. }
  5476. return $result;
  5477. }
  5478. public static function unique($array) {
  5479. return array_unique($array);
  5480. }
  5481. /**
  5482. *
  5483. * @param $function
  5484. * @return unknown_type
  5485. * @TODO there are problems with non-static methods, second parameter pass it
  5486. * but doesnt verify is method is really callable
  5487. */
  5488. public static function isFunction($function) {
  5489. return is_callable($function);
  5490. }
  5491. public static function trim($str) {
  5492. return trim($str);
  5493. }
  5494. /* PLUGINS NAMESPACE */
  5495. /**
  5496. *
  5497. * @param $url
  5498. * @param $callback
  5499. * @param $param1
  5500. * @param $param2
  5501. * @param $param3
  5502. * @return phpQueryObject
  5503. */
  5504. public static function browserGet($url, $callback, $param1 = null, $param2 = null, $param3 = null) {
  5505. if (self::plugin('WebBrowser')) {
  5506. $params = func_get_args();
  5507. return self::callbackRun(array(self::$plugins, 'browserGet'), $params);
  5508. } else {
  5509. self::debug('WebBrowser plugin not available...');
  5510. }
  5511. }
  5512. /**
  5513. *
  5514. * @param $url
  5515. * @param $data
  5516. * @param $callback
  5517. * @param $param1
  5518. * @param $param2
  5519. * @param $param3
  5520. * @return phpQueryObject
  5521. */
  5522. public static function browserPost($url, $data, $callback, $param1 = null, $param2 = null, $param3 = null) {
  5523. if (self::plugin('WebBrowser')) {
  5524. $params = func_get_args();
  5525. return self::callbackRun(array(self::$plugins, 'browserPost'), $params);
  5526. } else {
  5527. self::debug('WebBrowser plugin not available...');
  5528. }
  5529. }
  5530. /**
  5531. *
  5532. * @param $ajaxSettings
  5533. * @param $callback
  5534. * @param $param1
  5535. * @param $param2
  5536. * @param $param3
  5537. * @return phpQueryObject
  5538. */
  5539. public static function browser($ajaxSettings, $callback, $param1 = null, $param2 = null, $param3 = null) {
  5540. if (self::plugin('WebBrowser')) {
  5541. $params = func_get_args();
  5542. return self::callbackRun(array(self::$plugins, 'browser'), $params);
  5543. } else {
  5544. self::debug('WebBrowser plugin not available...');
  5545. }
  5546. }
  5547. /**
  5548. *
  5549. * @param $code
  5550. * @return string
  5551. */
  5552. public static function php($code) {
  5553. return self::code('php', $code);
  5554. }
  5555. /**
  5556. *
  5557. * @param $type
  5558. * @param $code
  5559. * @return string
  5560. */
  5561. public static function code($type, $code) {
  5562. return "<$type><!-- ".trim($code)." --></$type>";
  5563. }
  5564. public static function __callStatic($method, $params) {
  5565. return call_user_func_array(
  5566. array(phpQuery::$plugins, $method),
  5567. $params
  5568. );
  5569. }
  5570. protected static function dataSetupNode($node, $documentID) {
  5571. // search are return if alredy exists
  5572. foreach(phpQuery::$documents[$documentID]->dataNodes as $dataNode) {
  5573. if ($node->isSameNode($dataNode))
  5574. return $dataNode;
  5575. }
  5576. // if doesn't, add it
  5577. phpQuery::$documents[$documentID]->dataNodes[] = $node;
  5578. return $node;
  5579. }
  5580. protected static function dataRemoveNode($node, $documentID) {
  5581. // search are return if alredy exists
  5582. foreach(phpQuery::$documents[$documentID]->dataNodes as $k => $dataNode) {
  5583. if ($node->isSameNode($dataNode)) {
  5584. unset(self::$documents[$documentID]->dataNodes[$k]);
  5585. unset(self::$documents[$documentID]->data[ $dataNode->dataID ]);
  5586. }
  5587. }
  5588. }
  5589. public static function data($node, $name, $data, $documentID = null) {
  5590. if (! $documentID)
  5591. // TODO check if this works
  5592. $documentID = self::getDocumentID($node);
  5593. $document = phpQuery::$documents[$documentID];
  5594. $node = self::dataSetupNode($node, $documentID);
  5595. if (! isset($node->dataID))
  5596. $node->dataID = ++phpQuery::$documents[$documentID]->uuid;
  5597. $id = $node->dataID;
  5598. if (! isset($document->data[$id]))
  5599. $document->data[$id] = array();
  5600. if (! is_null($data))
  5601. $document->data[$id][$name] = $data;
  5602. if ($name) {
  5603. if (isset($document->data[$id][$name]))
  5604. return $document->data[$id][$name];
  5605. } else
  5606. return $id;
  5607. }
  5608. public static function removeData($node, $name, $documentID) {
  5609. if (! $documentID)
  5610. // TODO check if this works
  5611. $documentID = self::getDocumentID($node);
  5612. $document = phpQuery::$documents[$documentID];
  5613. $node = self::dataSetupNode($node, $documentID);
  5614. $id = $node->dataID;
  5615. if ($name) {
  5616. if (isset($document->data[$id][$name]))
  5617. unset($document->data[$id][$name]);
  5618. $name = null;
  5619. foreach($document->data[$id] as $name)
  5620. break;
  5621. if (! $name)
  5622. self::removeData($node, $name, $documentID);
  5623. } else {
  5624. self::dataRemoveNode($node, $documentID);
  5625. }
  5626. }
  5627. }
  5628. /**
  5629. * Plugins static namespace class.
  5630. *
  5631. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  5632. * @package phpQuery
  5633. * @todo move plugin methods here (as statics)
  5634. */
  5635. class phpQueryPlugins {
  5636. public function __call($method, $args) {
  5637. if (isset(phpQuery::$extendStaticMethods[$method])) {
  5638. $return = call_user_func_array(
  5639. phpQuery::$extendStaticMethods[$method],
  5640. $args
  5641. );
  5642. } else if (isset(phpQuery::$pluginsStaticMethods[$method])) {
  5643. $class = phpQuery::$pluginsStaticMethods[$method];
  5644. $realClass = "phpQueryPlugin_$class";
  5645. $return = call_user_func_array(
  5646. array($realClass, $method),
  5647. $args
  5648. );
  5649. return isset($return)
  5650. ? $return
  5651. : $this;
  5652. } else
  5653. throw new Exception("Method '{$method}' doesnt exist");
  5654. }
  5655. }
  5656. /**
  5657. * Shortcut to phpQuery::pq($arg1, $context)
  5658. * Chainable.
  5659. *
  5660. * @see phpQuery::pq()
  5661. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  5662. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  5663. * @package phpQuery
  5664. */
  5665. function pq($arg1, $context = null) {
  5666. $args = func_get_args();
  5667. return call_user_func_array(
  5668. array('phpQuery', 'pq'),
  5669. $args
  5670. );
  5671. }
  5672. // add plugins dir and Zend framework to include path
  5673. set_include_path(
  5674. get_include_path()
  5675. .PATH_SEPARATOR.dirname(__FILE__).'/phpQuery/'
  5676. .PATH_SEPARATOR.dirname(__FILE__).'/phpQuery/plugins/'
  5677. );
  5678. // why ? no __call nor __get for statics in php...
  5679. // XXX __callStatic will be available in PHP 5.3
  5680. phpQuery::$plugins = new phpQueryPlugins();
  5681. // include bootstrap file (personal library config)
  5682. if (file_exists(dirname(__FILE__).'/phpQuery/bootstrap.php'))
  5683. require_once dirname(__FILE__).'/phpQuery/bootstrap.php';