lib_phpQuery.php 164 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712
  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 unknown_type
  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. * @var unknown_type
  157. */
  158. public $frames = array();
  159. /**
  160. * Document root, by default equals to document itself.
  161. * Used by documentFragments.
  162. *
  163. * @var DOMNode
  164. */
  165. public $root;
  166. public $isDocumentFragment;
  167. public $isXML = false;
  168. public $isXHTML = false;
  169. public $isHTML = false;
  170. public $charset;
  171. public function __construct($markup = null, $contentType = null, $newDocumentID = null) {
  172. if (isset($markup))
  173. $this->load($markup, $contentType, $newDocumentID);
  174. $this->id = $newDocumentID
  175. ? $newDocumentID
  176. : md5(microtime());
  177. }
  178. public function load($markup, $contentType = null, $newDocumentID = null) {
  179. // phpQuery::$documents[$id] = $this;
  180. $this->contentType = strtolower($contentType);
  181. if ($markup instanceof DOMDOCUMENT) {
  182. $this->document = $markup;
  183. $this->root = $this->document;
  184. $this->charset = $this->document->encoding;
  185. // TODO isDocumentFragment
  186. } else {
  187. $loaded = $this->loadMarkup($markup);
  188. }
  189. if ($loaded) {
  190. // $this->document->formatOutput = true;
  191. $this->document->preserveWhiteSpace = true;
  192. $this->xpath = new DOMXPath($this->document);
  193. $this->afterMarkupLoad();
  194. return true;
  195. // remember last loaded document
  196. // return phpQuery::selectDocument($id);
  197. }
  198. return false;
  199. }
  200. protected function afterMarkupLoad() {
  201. if ($this->isXHTML) {
  202. $this->xpath->registerNamespace("html", "http://www.w3.org/1999/xhtml");
  203. }
  204. }
  205. protected function loadMarkup($markup) {
  206. $loaded = false;
  207. if ($this->contentType) {
  208. self::debug("Load markup for content type {$this->contentType}");
  209. // content determined by contentType
  210. list($contentType, $charset) = $this->contentTypeToArray($this->contentType);
  211. switch($contentType) {
  212. case 'text/html':
  213. phpQuery::debug("Loading HTML, content type '{$this->contentType}'");
  214. $loaded = $this->loadMarkupHTML($markup, $charset);
  215. break;
  216. case 'text/xml':
  217. case 'application/xhtml+xml':
  218. phpQuery::debug("Loading XML, content type '{$this->contentType}'");
  219. $loaded = $this->loadMarkupXML($markup, $charset);
  220. break;
  221. default:
  222. // for feeds or anything that sometimes doesn't use text/xml
  223. if (strpos('xml', $this->contentType) !== false) {
  224. phpQuery::debug("Loading XML, content type '{$this->contentType}'");
  225. $loaded = $this->loadMarkupXML($markup, $charset);
  226. } else
  227. phpQuery::debug("Could not determine document type from content type '{$this->contentType}'");
  228. }
  229. } else {
  230. // content type autodetection
  231. if ($this->isXML($markup)) {
  232. phpQuery::debug("Loading XML, isXML() == true");
  233. $loaded = $this->loadMarkupXML($markup);
  234. if (! $loaded && $this->isXHTML) {
  235. phpQuery::debug('Loading as XML failed, trying to load as HTML, isXHTML == true');
  236. $loaded = $this->loadMarkupHTML($markup);
  237. }
  238. } else {
  239. phpQuery::debug("Loading HTML, isXML() == false");
  240. $loaded = $this->loadMarkupHTML($markup);
  241. }
  242. }
  243. return $loaded;
  244. }
  245. protected function loadMarkupReset() {
  246. $this->isXML = $this->isXHTML = $this->isHTML = false;
  247. }
  248. protected function documentCreate($charset, $version = '1.0') {
  249. if (! $version)
  250. $version = '1.0';
  251. $this->document = new DOMDocument($version, $charset);
  252. $this->charset = $this->document->encoding;
  253. // $this->document->encoding = $charset;
  254. $this->document->formatOutput = true;
  255. $this->document->preserveWhiteSpace = true;
  256. }
  257. protected function loadMarkupHTML($markup, $requestedCharset = null) {
  258. if (phpQuery::$debug)
  259. phpQuery::debug('Full markup load (HTML): '.substr($markup, 0, 250));
  260. $this->loadMarkupReset();
  261. $this->isHTML = true;
  262. if (!isset($this->isDocumentFragment))
  263. $this->isDocumentFragment = self::isDocumentFragmentHTML($markup);
  264. $charset = null;
  265. $documentCharset = $this->charsetFromHTML($markup);
  266. $addDocumentCharset = false;
  267. if ($documentCharset) {
  268. $charset = $documentCharset;
  269. $markup = $this->charsetFixHTML($markup);
  270. } else if ($requestedCharset) {
  271. $charset = $requestedCharset;
  272. }
  273. if (! $charset)
  274. $charset = phpQuery::$defaultCharset;
  275. // HTTP 1.1 says that the default charset is ISO-8859-1
  276. // @see http://www.w3.org/International/O-HTTP-charset
  277. if (! $documentCharset) {
  278. $documentCharset = 'ISO-8859-1';
  279. $addDocumentCharset = true;
  280. }
  281. // Should be careful here, still need 'magic encoding detection' since lots of pages have other 'default encoding'
  282. // Worse, some pages can have mixed encodings... we'll try not to worry about that
  283. $requestedCharset = strtoupper($requestedCharset);
  284. $documentCharset = strtoupper($documentCharset);
  285. phpQuery::debug("DOC: $documentCharset REQ: $requestedCharset");
  286. if ($requestedCharset && $documentCharset && $requestedCharset !== $documentCharset) {
  287. phpQuery::debug("CHARSET CONVERT");
  288. // Document Encoding Conversion
  289. // http://code.google.com/p/phpquery/issues/detail?id=86
  290. if (function_exists('mb_detect_encoding')) {
  291. $possibleCharsets = array($documentCharset, $requestedCharset, 'AUTO');
  292. $docEncoding = mb_detect_encoding($markup, implode(', ', $possibleCharsets));
  293. if (! $docEncoding)
  294. $docEncoding = $documentCharset; // ok trust the document
  295. phpQuery::debug("DETECTED '$docEncoding'");
  296. // Detected does not match what document says...
  297. if ($docEncoding !== $documentCharset) {
  298. // Tricky..
  299. }
  300. if ($docEncoding !== $requestedCharset) {
  301. phpQuery::debug("CONVERT $docEncoding => $requestedCharset");
  302. $markup = mb_convert_encoding($markup, $requestedCharset, $docEncoding);
  303. $markup = $this->charsetAppendToHTML($markup, $requestedCharset);
  304. $charset = $requestedCharset;
  305. }
  306. } else {
  307. phpQuery::debug("TODO: charset conversion without mbstring...");
  308. }
  309. }
  310. $return = false;
  311. if ($this->isDocumentFragment) {
  312. phpQuery::debug("Full markup load (HTML), DocumentFragment detected, using charset '$charset'");
  313. $return = $this->documentFragmentLoadMarkup($this, $charset, $markup);
  314. } else {
  315. if ($addDocumentCharset) {
  316. phpQuery::debug("Full markup load (HTML), appending charset: '$charset'");
  317. $markup = $this->charsetAppendToHTML($markup, $charset);
  318. }
  319. phpQuery::debug("Full markup load (HTML), documentCreate('$charset')");
  320. $this->documentCreate($charset);
  321. $return = phpQuery::$debug === 2
  322. ? $this->document->loadHTML($markup)
  323. : @$this->document->loadHTML($markup);
  324. if ($return)
  325. $this->root = $this->document;
  326. }
  327. if ($return && ! $this->contentType)
  328. $this->contentType = 'text/html';
  329. return $return;
  330. }
  331. protected function loadMarkupXML($markup, $requestedCharset = null) {
  332. if (phpQuery::$debug)
  333. phpQuery::debug('Full markup load (XML): '.substr($markup, 0, 250));
  334. $this->loadMarkupReset();
  335. $this->isXML = true;
  336. // check agains XHTML in contentType or markup
  337. $isContentTypeXHTML = $this->isXHTML();
  338. $isMarkupXHTML = $this->isXHTML($markup);
  339. if ($isContentTypeXHTML || $isMarkupXHTML) {
  340. self::debug('Full markup load (XML), XHTML detected');
  341. $this->isXHTML = true;
  342. }
  343. // determine document fragment
  344. if (! isset($this->isDocumentFragment))
  345. $this->isDocumentFragment = $this->isXHTML
  346. ? self::isDocumentFragmentXHTML($markup)
  347. : self::isDocumentFragmentXML($markup);
  348. // this charset will be used
  349. $charset = null;
  350. // charset from XML declaration @var string
  351. $documentCharset = $this->charsetFromXML($markup);
  352. if (! $documentCharset) {
  353. if ($this->isXHTML) {
  354. // this is XHTML, try to get charset from content-type meta header
  355. $documentCharset = $this->charsetFromHTML($markup);
  356. if ($documentCharset) {
  357. phpQuery::debug("Full markup load (XML), appending XHTML charset '$documentCharset'");
  358. $this->charsetAppendToXML($markup, $documentCharset);
  359. $charset = $documentCharset;
  360. }
  361. }
  362. if (! $documentCharset) {
  363. // if still no document charset...
  364. $charset = $requestedCharset;
  365. }
  366. } else if ($requestedCharset) {
  367. $charset = $requestedCharset;
  368. }
  369. if (! $charset) {
  370. $charset = phpQuery::$defaultCharset;
  371. }
  372. if ($requestedCharset && $documentCharset && $requestedCharset != $documentCharset) {
  373. // TODO place for charset conversion
  374. // $charset = $requestedCharset;
  375. }
  376. $return = false;
  377. if ($this->isDocumentFragment) {
  378. phpQuery::debug("Full markup load (XML), DocumentFragment detected, using charset '$charset'");
  379. $return = $this->documentFragmentLoadMarkup($this, $charset, $markup);
  380. } else {
  381. // FIXME ???
  382. if ($isContentTypeXHTML && ! $isMarkupXHTML)
  383. if (! $documentCharset) {
  384. phpQuery::debug("Full markup load (XML), appending charset '$charset'");
  385. $markup = $this->charsetAppendToXML($markup, $charset);
  386. }
  387. // see http://pl2.php.net/manual/en/book.dom.php#78929
  388. // LIBXML_DTDLOAD (>= PHP 5.1)
  389. // does XML ctalogues works with LIBXML_NONET
  390. // $this->document->resolveExternals = true;
  391. // TODO test LIBXML_COMPACT for performance improvement
  392. // create document
  393. $this->documentCreate($charset);
  394. if (phpversion() < 5.1) {
  395. $this->document->resolveExternals = true;
  396. $return = phpQuery::$debug === 2
  397. ? $this->document->loadXML($markup)
  398. : @$this->document->loadXML($markup);
  399. } else {
  400. /** @link http://pl2.php.net/manual/en/libxml.constants.php */
  401. $libxmlStatic = phpQuery::$debug === 2
  402. ? LIBXML_DTDLOAD|LIBXML_DTDATTR|LIBXML_NONET
  403. : LIBXML_DTDLOAD|LIBXML_DTDATTR|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOERROR;
  404. $return = $this->document->loadXML($markup, $libxmlStatic);
  405. // if (! $return)
  406. // $return = $this->document->loadHTML($markup);
  407. }
  408. if ($return)
  409. $this->root = $this->document;
  410. }
  411. if ($return) {
  412. if (! $this->contentType) {
  413. if ($this->isXHTML)
  414. $this->contentType = 'application/xhtml+xml';
  415. else
  416. $this->contentType = 'text/xml';
  417. }
  418. return $return;
  419. } else {
  420. throw new Exception("Error loading XML markup");
  421. }
  422. }
  423. protected function isXHTML($markup = null) {
  424. if (! isset($markup)) {
  425. return strpos($this->contentType, 'xhtml') !== false;
  426. }
  427. // XXX ok ?
  428. return strpos($markup, "<!DOCTYPE html") !== false;
  429. // return stripos($doctype, 'xhtml') !== false;
  430. // $doctype = isset($dom->doctype) && is_object($dom->doctype)
  431. // ? $dom->doctype->publicId
  432. // : self::$defaultDoctype;
  433. }
  434. protected function isXML($markup) {
  435. // return strpos($markup, '<?xml') !== false && stripos($markup, 'xhtml') === false;
  436. return strpos(substr($markup, 0, 100), '<'.'?xml') !== 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;
  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 unknown_type $type
  816. * @param unknown_type $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 = create_function($paramList, $code);
  1030. $this->params = $params;
  1031. }
  1032. }
  1033. /**
  1034. * Callback type which on execution returns reference passed during creation.
  1035. *
  1036. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  1037. */
  1038. class CallbackReturnReference extends Callback
  1039. implements ICallbackNamed {
  1040. protected $reference;
  1041. public function __construct(&$reference, $name = null){
  1042. $this->reference =& $reference;
  1043. $this->callback = array($this, 'callback');
  1044. }
  1045. public function callback() {
  1046. return $this->reference;
  1047. }
  1048. public function getName() {
  1049. return 'Callback: '.$this->name;
  1050. }
  1051. public function hasName() {
  1052. return isset($this->name) && $this->name;
  1053. }
  1054. }
  1055. /**
  1056. * Callback type which on execution returns value passed during creation.
  1057. *
  1058. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  1059. */
  1060. class CallbackReturnValue extends Callback
  1061. implements ICallbackNamed {
  1062. protected $value;
  1063. protected $name;
  1064. public function __construct($value, $name = null){
  1065. $this->value =& $value;
  1066. $this->name = $name;
  1067. $this->callback = array($this, 'callback');
  1068. }
  1069. public function callback() {
  1070. return $this->value;
  1071. }
  1072. public function __toString() {
  1073. return $this->getName();
  1074. }
  1075. public function getName() {
  1076. return 'Callback: '.$this->name;
  1077. }
  1078. public function hasName() {
  1079. return isset($this->name) && $this->name;
  1080. }
  1081. }
  1082. /**
  1083. * CallbackParameterToReference can be used when we don't really want a callback,
  1084. * only parameter passed to it. CallbackParameterToReference takes first
  1085. * parameter's value and passes it to reference.
  1086. *
  1087. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  1088. */
  1089. class CallbackParameterToReference extends Callback {
  1090. /**
  1091. * @param $reference
  1092. * @TODO implement $paramIndex;
  1093. * param index choose which callback param will be passed to reference
  1094. */
  1095. public function __construct(&$reference){
  1096. $this->callback =& $reference;
  1097. }
  1098. }
  1099. //class CallbackReference extends Callback {
  1100. // /**
  1101. // *
  1102. // * @param $reference
  1103. // * @param $paramIndex
  1104. // * @todo implement $paramIndex; param index choose which callback param will be passed to reference
  1105. // */
  1106. // public function __construct(&$reference, $name = null){
  1107. // $this->callback =& $reference;
  1108. // }
  1109. //}
  1110. class CallbackParam {}
  1111. /**
  1112. * Class representing phpQuery objects.
  1113. *
  1114. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  1115. * @package phpQuery
  1116. * @method phpQueryObject clone() clone()
  1117. * @method phpQueryObject empty() empty()
  1118. * @method phpQueryObject next() next($selector = null)
  1119. * @method phpQueryObject prev() prev($selector = null)
  1120. * @property Int $length
  1121. */
  1122. class phpQueryObject
  1123. implements Iterator, Countable, ArrayAccess {
  1124. public $documentID = null;
  1125. /**
  1126. * DOMDocument class.
  1127. *
  1128. * @var DOMDocument
  1129. */
  1130. public $document = null;
  1131. public $charset = null;
  1132. /**
  1133. *
  1134. * @var DOMDocumentWrapper
  1135. */
  1136. public $documentWrapper = null;
  1137. /**
  1138. * XPath interface.
  1139. *
  1140. * @var DOMXPath
  1141. */
  1142. public $xpath = null;
  1143. /**
  1144. * Stack of selected elements.
  1145. * @TODO refactor to ->nodes
  1146. * @var array
  1147. */
  1148. public $elements = array();
  1149. /**
  1150. * @access private
  1151. */
  1152. protected $elementsBackup = array();
  1153. /**
  1154. * @access private
  1155. */
  1156. protected $previous = null;
  1157. /**
  1158. * @access private
  1159. * @TODO deprecate
  1160. */
  1161. protected $root = array();
  1162. /**
  1163. * Indicated if doument is just a fragment (no <html> tag).
  1164. *
  1165. * Every document is realy a full document, so even documentFragments can
  1166. * be queried against <html>, but getDocument(id)->htmlOuter() will return
  1167. * only contents of <body>.
  1168. *
  1169. * @var bool
  1170. */
  1171. public $documentFragment = true;
  1172. /**
  1173. * Iterator interface helper
  1174. * @access private
  1175. */
  1176. protected $elementsInterator = array();
  1177. /**
  1178. * Iterator interface helper
  1179. * @access private
  1180. */
  1181. protected $valid = false;
  1182. /**
  1183. * Iterator interface helper
  1184. * @access private
  1185. */
  1186. protected $current = null;
  1187. /**
  1188. * Enter description here...
  1189. *
  1190. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1191. */
  1192. public function __construct($documentID) {
  1193. // if ($documentID instanceof self)
  1194. // var_dump($documentID->getDocumentID());
  1195. $id = $documentID instanceof self
  1196. ? $documentID->getDocumentID()
  1197. : $documentID;
  1198. // var_dump($id);
  1199. if (! isset(phpQuery::$documents[$id] )) {
  1200. // var_dump(phpQuery::$documents);
  1201. throw new Exception("Document with ID '{$id}' isn't loaded. Use phpQuery::newDocument(\$html) or phpQuery::newDocumentFile(\$file) first.");
  1202. }
  1203. $this->documentID = $id;
  1204. $this->documentWrapper =& phpQuery::$documents[$id];
  1205. $this->document =& $this->documentWrapper->document;
  1206. $this->xpath =& $this->documentWrapper->xpath;
  1207. $this->charset =& $this->documentWrapper->charset;
  1208. $this->documentFragment =& $this->documentWrapper->isDocumentFragment;
  1209. // TODO check $this->DOM->documentElement;
  1210. // $this->root = $this->document->documentElement;
  1211. $this->root =& $this->documentWrapper->root;
  1212. // $this->toRoot();
  1213. $this->elements = array($this->root);
  1214. }
  1215. /**
  1216. *
  1217. * @access private
  1218. * @param $attr
  1219. * @return unknown_type
  1220. */
  1221. public function __get($attr) {
  1222. switch($attr) {
  1223. // FIXME doesnt work at all ?
  1224. case 'length':
  1225. return $this->size();
  1226. break;
  1227. default:
  1228. return $this->$attr;
  1229. }
  1230. }
  1231. /**
  1232. * Saves actual object to $var by reference.
  1233. * Useful when need to break chain.
  1234. * @param phpQueryObject $var
  1235. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1236. */
  1237. public function toReference(&$var) {
  1238. return $var = $this;
  1239. }
  1240. public function documentFragment($state = null) {
  1241. if ($state) {
  1242. phpQuery::$documents[$this->getDocumentID()]['documentFragment'] = $state;
  1243. return $this;
  1244. }
  1245. return $this->documentFragment;
  1246. }
  1247. /**
  1248. * @access private
  1249. * @TODO documentWrapper
  1250. */
  1251. protected function isRoot( $node) {
  1252. // return $node instanceof DOMDOCUMENT || $node->tagName == 'html';
  1253. return $node instanceof DOMDOCUMENT
  1254. || ($node instanceof DOMELEMENT && $node->tagName == 'html')
  1255. || $this->root->isSameNode($node);
  1256. }
  1257. /**
  1258. * @access private
  1259. */
  1260. protected function stackIsRoot() {
  1261. return $this->size() == 1 && $this->isRoot($this->elements[0]);
  1262. }
  1263. /**
  1264. * Enter description here...
  1265. * NON JQUERY METHOD
  1266. *
  1267. * Watch out, it doesn't creates new instance, can be reverted with end().
  1268. *
  1269. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1270. */
  1271. public function toRoot() {
  1272. $this->elements = array($this->root);
  1273. return $this;
  1274. // return $this->newInstance(array($this->root));
  1275. }
  1276. /**
  1277. * Saves object's DocumentID to $var by reference.
  1278. * <code>
  1279. * $myDocumentId;
  1280. * phpQuery::newDocument('<div/>')
  1281. * ->getDocumentIDRef($myDocumentId)
  1282. * ->find('div')->...
  1283. * </code>
  1284. *
  1285. * @param unknown_type $domId
  1286. * @see phpQuery::newDocument
  1287. * @see phpQuery::newDocumentFile
  1288. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1289. */
  1290. public function getDocumentIDRef(&$documentID) {
  1291. $documentID = $this->getDocumentID();
  1292. return $this;
  1293. }
  1294. /**
  1295. * Returns object with stack set to document root.
  1296. *
  1297. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1298. */
  1299. public function getDocument() {
  1300. return phpQuery::getDocument($this->getDocumentID());
  1301. }
  1302. /**
  1303. *
  1304. * @return DOMDocument
  1305. */
  1306. public function getDOMDocument() {
  1307. return $this->document;
  1308. }
  1309. /**
  1310. * Get object's Document ID.
  1311. *
  1312. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1313. */
  1314. public function getDocumentID() {
  1315. return $this->documentID;
  1316. }
  1317. /**
  1318. * Unloads whole document from memory.
  1319. * CAUTION! None further operations will be possible on this document.
  1320. * All objects refering to it will be useless.
  1321. *
  1322. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1323. */
  1324. public function unloadDocument() {
  1325. phpQuery::unloadDocuments($this->getDocumentID());
  1326. }
  1327. public function isHTML() {
  1328. return $this->documentWrapper->isHTML;
  1329. }
  1330. public function isXHTML() {
  1331. return $this->documentWrapper->isXHTML;
  1332. }
  1333. public function isXML() {
  1334. return $this->documentWrapper->isXML;
  1335. }
  1336. /**
  1337. * Enter description here...
  1338. *
  1339. * @link http://docs.jquery.com/Ajax/serialize
  1340. * @return string
  1341. */
  1342. public function serialize() {
  1343. return phpQuery::param($this->serializeArray());
  1344. }
  1345. /**
  1346. * Enter description here...
  1347. *
  1348. * @link http://docs.jquery.com/Ajax/serializeArray
  1349. * @return array
  1350. */
  1351. public function serializeArray($submit = null) {
  1352. $source = $this->filter('form, input, select, textarea')
  1353. ->find('input, select, textarea')
  1354. ->andSelf()
  1355. ->not('form');
  1356. $return = array();
  1357. // $source->dumpDie();
  1358. foreach($source as $input) {
  1359. $input = phpQuery::pq($input);
  1360. if ($input->is('[disabled]'))
  1361. continue;
  1362. if (!$input->is('[name]'))
  1363. continue;
  1364. if ($input->is('[type=checkbox]') && !$input->is('[checked]'))
  1365. continue;
  1366. // jquery diff
  1367. if ($submit && $input->is('[type=submit]')) {
  1368. if ($submit instanceof DOMELEMENT && ! $input->elements[0]->isSameNode($submit))
  1369. continue;
  1370. else if (is_string($submit) && $input->attr('name') != $submit)
  1371. continue;
  1372. }
  1373. $return[] = array(
  1374. 'name' => $input->attr('name'),
  1375. 'value' => $input->val(),
  1376. );
  1377. }
  1378. return $return;
  1379. }
  1380. /**
  1381. * @access private
  1382. */
  1383. protected function debug($in) {
  1384. if (! phpQuery::$debug )
  1385. return;
  1386. print('<pre>');
  1387. print_r($in);
  1388. // file debug
  1389. // file_put_contents(dirname(__FILE__).'/phpQuery.log', print_r($in, true)."\n", FILE_APPEND);
  1390. // quite handy debug trace
  1391. // if ( is_array($in))
  1392. // print_r(array_slice(debug_backtrace(), 3));
  1393. print("</pre>\n");
  1394. }
  1395. /**
  1396. * @access private
  1397. */
  1398. protected function isRegexp($pattern) {
  1399. return in_array(
  1400. $pattern[ mb_strlen($pattern)-1 ],
  1401. array('^','*','$')
  1402. );
  1403. }
  1404. /**
  1405. * Determines if $char is really a char.
  1406. *
  1407. * @param string $char
  1408. * @return bool
  1409. * @todo rewrite me to charcode range ! ;)
  1410. * @access private
  1411. */
  1412. protected function isChar($char) {
  1413. return extension_loaded('mbstring') && phpQuery::$mbstringSupport
  1414. ? mb_eregi('\w', $char)
  1415. : preg_match('@\w@', $char);
  1416. }
  1417. /**
  1418. * @access private
  1419. */
  1420. protected function parseSelector($query) {
  1421. // clean spaces
  1422. // TODO include this inside parsing ?
  1423. $query = trim(
  1424. preg_replace('@\s+@', ' ',
  1425. preg_replace('@\s*(>|\\+|~)\s*@', '\\1', $query)
  1426. )
  1427. );
  1428. $queries = array(array());
  1429. if (! $query)
  1430. return $queries;
  1431. $return =& $queries[0];
  1432. $specialChars = array('>',' ');
  1433. // $specialCharsMapping = array('/' => '>');
  1434. $specialCharsMapping = array();
  1435. $strlen = mb_strlen($query);
  1436. $classChars = array('.', '-');
  1437. $pseudoChars = array('-');
  1438. $tagChars = array('*', '|', '-');
  1439. // split multibyte string
  1440. // http://code.google.com/p/phpquery/issues/detail?id=76
  1441. $_query = array();
  1442. for ($i=0; $i<$strlen; $i++)
  1443. $_query[] = mb_substr($query, $i, 1);
  1444. $query = $_query;
  1445. // it works, but i dont like it...
  1446. $i = 0;
  1447. while( $i < $strlen) {
  1448. $c = $query[$i];
  1449. $tmp = '';
  1450. // TAG
  1451. if ($this->isChar($c) || in_array($c, $tagChars)) {
  1452. while(isset($query[$i])
  1453. && ($this->isChar($query[$i]) || in_array($query[$i], $tagChars))) {
  1454. $tmp .= $query[$i];
  1455. $i++;
  1456. }
  1457. $return[] = $tmp;
  1458. // IDs
  1459. } else if ( $c == '#') {
  1460. $i++;
  1461. while( isset($query[$i]) && ($this->isChar($query[$i]) || $query[$i] == '-')) {
  1462. $tmp .= $query[$i];
  1463. $i++;
  1464. }
  1465. $return[] = '#'.$tmp;
  1466. // SPECIAL CHARS
  1467. } else if (in_array($c, $specialChars)) {
  1468. $return[] = $c;
  1469. $i++;
  1470. // MAPPED SPECIAL MULTICHARS
  1471. // } else if ( $c.$query[$i+1] == '//') {
  1472. // $return[] = ' ';
  1473. // $i = $i+2;
  1474. // MAPPED SPECIAL CHARS
  1475. } else if ( isset($specialCharsMapping[$c])) {
  1476. $return[] = $specialCharsMapping[$c];
  1477. $i++;
  1478. // COMMA
  1479. } else if ( $c == ',') {
  1480. $queries[] = array();
  1481. $return =& $queries[ count($queries)-1 ];
  1482. $i++;
  1483. while( isset($query[$i]) && $query[$i] == ' ')
  1484. $i++;
  1485. // CLASSES
  1486. } else if ($c == '.') {
  1487. while( isset($query[$i]) && ($this->isChar($query[$i]) || in_array($query[$i], $classChars))) {
  1488. $tmp .= $query[$i];
  1489. $i++;
  1490. }
  1491. $return[] = $tmp;
  1492. // ~ General Sibling Selector
  1493. } else if ($c == '~') {
  1494. $spaceAllowed = true;
  1495. $tmp .= $query[$i++];
  1496. while( isset($query[$i])
  1497. && ($this->isChar($query[$i])
  1498. || in_array($query[$i], $classChars)
  1499. || $query[$i] == '*'
  1500. || ($query[$i] == ' ' && $spaceAllowed)
  1501. )) {
  1502. if ($query[$i] != ' ')
  1503. $spaceAllowed = false;
  1504. $tmp .= $query[$i];
  1505. $i++;
  1506. }
  1507. $return[] = $tmp;
  1508. // + Adjacent sibling selectors
  1509. } else if ($c == '+') {
  1510. $spaceAllowed = true;
  1511. $tmp .= $query[$i++];
  1512. while( isset($query[$i])
  1513. && ($this->isChar($query[$i])
  1514. || in_array($query[$i], $classChars)
  1515. || $query[$i] == '*'
  1516. || ($spaceAllowed && $query[$i] == ' ')
  1517. )) {
  1518. if ($query[$i] != ' ')
  1519. $spaceAllowed = false;
  1520. $tmp .= $query[$i];
  1521. $i++;
  1522. }
  1523. $return[] = $tmp;
  1524. // ATTRS
  1525. } else if ($c == '[') {
  1526. $stack = 1;
  1527. $tmp .= $c;
  1528. while( isset($query[++$i])) {
  1529. $tmp .= $query[$i];
  1530. if ( $query[$i] == '[') {
  1531. $stack++;
  1532. } else if ( $query[$i] == ']') {
  1533. $stack--;
  1534. if (! $stack )
  1535. break;
  1536. }
  1537. }
  1538. $return[] = $tmp;
  1539. $i++;
  1540. // PSEUDO CLASSES
  1541. } else if ($c == ':') {
  1542. $stack = 1;
  1543. $tmp .= $query[$i++];
  1544. while( isset($query[$i]) && ($this->isChar($query[$i]) || in_array($query[$i], $pseudoChars))) {
  1545. $tmp .= $query[$i];
  1546. $i++;
  1547. }
  1548. // with arguments ?
  1549. if ( isset($query[$i]) && $query[$i] == '(') {
  1550. $tmp .= $query[$i];
  1551. $stack = 1;
  1552. while( isset($query[++$i])) {
  1553. $tmp .= $query[$i];
  1554. if ( $query[$i] == '(') {
  1555. $stack++;
  1556. } else if ( $query[$i] == ')') {
  1557. $stack--;
  1558. if (! $stack )
  1559. break;
  1560. }
  1561. }
  1562. $return[] = $tmp;
  1563. $i++;
  1564. } else {
  1565. $return[] = $tmp;
  1566. }
  1567. } else {
  1568. $i++;
  1569. }
  1570. }
  1571. foreach($queries as $k => $q) {
  1572. if (isset($q[0])) {
  1573. if (isset($q[0][0]) && $q[0][0] == ':')
  1574. array_unshift($queries[$k], '*');
  1575. if ($q[0] != '>')
  1576. array_unshift($queries[$k], ' ');
  1577. }
  1578. }
  1579. return $queries;
  1580. }
  1581. /**
  1582. * Return matched DOM nodes.
  1583. *
  1584. * @param int $index
  1585. * @return array|DOMElement Single DOMElement or array of DOMElement.
  1586. */
  1587. public function get($index = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  1588. $return = isset($index)
  1589. ? (isset($this->elements[$index]) ? $this->elements[$index] : null)
  1590. : $this->elements;
  1591. // pass thou callbacks
  1592. $args = func_get_args();
  1593. $args = array_slice($args, 1);
  1594. foreach($args as $callback) {
  1595. if (is_array($return))
  1596. foreach($return as $k => $v)
  1597. $return[$k] = phpQuery::callbackRun($callback, array($v));
  1598. else
  1599. $return = phpQuery::callbackRun($callback, array($return));
  1600. }
  1601. return $return;
  1602. }
  1603. /**
  1604. * Return matched DOM nodes.
  1605. * jQuery difference.
  1606. *
  1607. * @param int $index
  1608. * @return array|string Returns string if $index != null
  1609. * @todo implement callbacks
  1610. * @todo return only arrays ?
  1611. * @todo maybe other name...
  1612. */
  1613. public function getString($index = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  1614. if ($index)
  1615. $return = $this->eq($index)->text();
  1616. else {
  1617. $return = array();
  1618. for($i = 0; $i < $this->size(); $i++) {
  1619. $return[] = $this->eq($i)->text();
  1620. }
  1621. }
  1622. // pass thou callbacks
  1623. $args = func_get_args();
  1624. $args = array_slice($args, 1);
  1625. foreach($args as $callback) {
  1626. $return = phpQuery::callbackRun($callback, array($return));
  1627. }
  1628. return $return;
  1629. }
  1630. /**
  1631. * Return matched DOM nodes.
  1632. * jQuery difference.
  1633. *
  1634. * @param int $index
  1635. * @return array|string Returns string if $index != null
  1636. * @todo implement callbacks
  1637. * @todo return only arrays ?
  1638. * @todo maybe other name...
  1639. */
  1640. public function getStrings($index = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  1641. if ($index)
  1642. $return = $this->eq($index)->text();
  1643. else {
  1644. $return = array();
  1645. for($i = 0; $i < $this->size(); $i++) {
  1646. $return[] = $this->eq($i)->text();
  1647. }
  1648. // pass thou callbacks
  1649. $args = func_get_args();
  1650. $args = array_slice($args, 1);
  1651. }
  1652. foreach($args as $callback) {
  1653. if (is_array($return))
  1654. foreach($return as $k => $v)
  1655. $return[$k] = phpQuery::callbackRun($callback, array($v));
  1656. else
  1657. $return = phpQuery::callbackRun($callback, array($return));
  1658. }
  1659. return $return;
  1660. }
  1661. /**
  1662. * Returns new instance of actual class.
  1663. *
  1664. * @param array $newStack Optional. Will replace old stack with new and move old one to history.c
  1665. */
  1666. public function newInstance($newStack = null) {
  1667. $class = get_class($this);
  1668. // support inheritance by passing old object to overloaded constructor
  1669. $new = $class != 'phpQuery'
  1670. ? new $class($this, $this->getDocumentID())
  1671. : new phpQueryObject($this->getDocumentID());
  1672. $new->previous = $this;
  1673. if (is_null($newStack)) {
  1674. $new->elements = $this->elements;
  1675. if ($this->elementsBackup)
  1676. $this->elements = $this->elementsBackup;
  1677. } else if (is_string($newStack)) {
  1678. $new->elements = phpQuery::pq($newStack, $this->getDocumentID())->stack();
  1679. } else {
  1680. $new->elements = $newStack;
  1681. }
  1682. return $new;
  1683. }
  1684. /**
  1685. * Enter description here...
  1686. *
  1687. * In the future, when PHP will support XLS 2.0, then we would do that this way:
  1688. * contains(tokenize(@class, '\s'), "something")
  1689. * @param unknown_type $class
  1690. * @param unknown_type $node
  1691. * @return boolean
  1692. * @access private
  1693. */
  1694. protected function matchClasses($class, $node) {
  1695. // multi-class
  1696. if ( mb_strpos($class, '.', 1)) {
  1697. $classes = explode('.', substr($class, 1));
  1698. $classesCount = count( $classes );
  1699. $nodeClasses = explode(' ', $node->getAttribute('class') );
  1700. $nodeClassesCount = count( $nodeClasses );
  1701. if ( $classesCount > $nodeClassesCount )
  1702. return false;
  1703. $diff = count(
  1704. array_diff(
  1705. $classes,
  1706. $nodeClasses
  1707. )
  1708. );
  1709. if (! $diff )
  1710. return true;
  1711. // single-class
  1712. } else {
  1713. return in_array(
  1714. // strip leading dot from class name
  1715. substr($class, 1),
  1716. // get classes for element as array
  1717. explode(' ', $node->getAttribute('class') )
  1718. );
  1719. }
  1720. }
  1721. /**
  1722. * @access private
  1723. */
  1724. protected function runQuery($XQuery, $selector = null, $compare = null) {
  1725. if ($compare && ! method_exists($this, $compare))
  1726. return false;
  1727. $stack = array();
  1728. if (! $this->elements)
  1729. $this->debug('Stack empty, skipping...');
  1730. // var_dump($this->elements[0]->nodeType);
  1731. // element, document
  1732. foreach($this->stack(array(1, 9, 13)) as $k => $stackNode) {
  1733. $detachAfter = false;
  1734. // to work on detached nodes we need temporary place them somewhere
  1735. // thats because context xpath queries sucks ;]
  1736. $testNode = $stackNode;
  1737. while ($testNode) {
  1738. if (! $testNode->parentNode && ! $this->isRoot($testNode)) {
  1739. $this->root->appendChild($testNode);
  1740. $detachAfter = $testNode;
  1741. break;
  1742. }
  1743. $testNode = isset($testNode->parentNode)
  1744. ? $testNode->parentNode
  1745. : null;
  1746. }
  1747. // XXX tmp ?
  1748. $xpath = $this->documentWrapper->isXHTML
  1749. ? $this->getNodeXpath($stackNode, 'html')
  1750. : $this->getNodeXpath($stackNode);
  1751. // FIXME pseudoclasses-only query, support XML
  1752. $query = $XQuery == '//' && $xpath == '/html[1]'
  1753. ? '//*'
  1754. : $xpath.$XQuery;
  1755. $this->debug("XPATH: {$query}");
  1756. // run query, get elements
  1757. $nodes = $this->xpath->query($query);
  1758. $this->debug("QUERY FETCHED");
  1759. if (! $nodes->length )
  1760. $this->debug('Nothing found');
  1761. $debug = array();
  1762. foreach($nodes as $node) {
  1763. $matched = false;
  1764. if ( $compare) {
  1765. phpQuery::$debug ?
  1766. $this->debug("Found: ".$this->whois( $node ).", comparing with {$compare}()")
  1767. : null;
  1768. $phpQueryDebug = phpQuery::$debug;
  1769. phpQuery::$debug = false;
  1770. // TODO ??? use phpQuery::callbackRun()
  1771. if (call_user_func_array(array($this, $compare), array($selector, $node)))
  1772. $matched = true;
  1773. phpQuery::$debug = $phpQueryDebug;
  1774. } else {
  1775. $matched = true;
  1776. }
  1777. if ( $matched) {
  1778. if (phpQuery::$debug)
  1779. $debug[] = $this->whois( $node );
  1780. $stack[] = $node;
  1781. }
  1782. }
  1783. if (phpQuery::$debug) {
  1784. $this->debug("Matched ".count($debug).": ".implode(', ', $debug));
  1785. }
  1786. if ($detachAfter)
  1787. $this->root->removeChild($detachAfter);
  1788. }
  1789. $this->elements = $stack;
  1790. }
  1791. /**
  1792. * used for ordering results in find()
  1793. */
  1794. private function cmpByLineNo($a , $b) {
  1795. return $a->getLineNo() <= $b->getLineNo() ? -1 : 1;
  1796. }
  1797. /**
  1798. * Enter description here...
  1799. *
  1800. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1801. */
  1802. public function find($selectors, $context = null, $noHistory = false) {
  1803. if (!$noHistory)
  1804. // backup last stack /for end()/
  1805. $this->elementsBackup = $this->elements;
  1806. // allow to define context
  1807. // TODO combine code below with phpQuery::pq() context guessing code
  1808. // as generic function
  1809. if ($context) {
  1810. if (! is_array($context) && $context instanceof DOMELEMENT)
  1811. $this->elements = array($context);
  1812. else if (is_array($context)) {
  1813. $this->elements = array();
  1814. foreach ($context as $c)
  1815. if ($c instanceof DOMELEMENT)
  1816. $this->elements[] = $c;
  1817. } else if ( $context instanceof self )
  1818. $this->elements = $context->elements;
  1819. }
  1820. $queries = $this->parseSelector($selectors);
  1821. $this->debug(array('FIND', $selectors, $queries));
  1822. $XQuery = '';
  1823. // remember stack state because of multi-queries
  1824. $oldStack = $this->elements;
  1825. // here we will be keeping found elements
  1826. $stack = array();
  1827. foreach($queries as $selector) {
  1828. $this->elements = $oldStack;
  1829. $delimiterBefore = false;
  1830. foreach($selector as $s) {
  1831. // TAG
  1832. $isTag = extension_loaded('mbstring') && phpQuery::$mbstringSupport
  1833. ? mb_ereg_match('^[\w|\||-]+$', $s) || $s == '*'
  1834. : preg_match('@^[\w|\||-]+$@', $s) || $s == '*';
  1835. if ($isTag) {
  1836. if ($this->isXML()) {
  1837. // namespace support
  1838. if (mb_strpos($s, '|') !== false) {
  1839. $ns = $tag = null;
  1840. list($ns, $tag) = explode('|', $s);
  1841. $XQuery .= "$ns:$tag";
  1842. } else if ($s == '*') {
  1843. $XQuery .= "*";
  1844. } else {
  1845. $XQuery .= "*[local-name()='$s']";
  1846. }
  1847. } else {
  1848. $XQuery .= $s;
  1849. }
  1850. // ID
  1851. } else if ($s[0] == '#') {
  1852. if ($delimiterBefore)
  1853. $XQuery .= '*';
  1854. $XQuery .= "[@id='".substr($s, 1)."']";
  1855. // ATTRIBUTES
  1856. } else if ($s[0] == '[') {
  1857. if ($delimiterBefore)
  1858. $XQuery .= '*';
  1859. // strip side brackets
  1860. $attr = trim($s, '][');
  1861. $execute = false;
  1862. // attr with specifed value
  1863. if (mb_strpos($s, '=')) {
  1864. $value = null;
  1865. list($attr, $value) = explode('=', $attr);
  1866. $value = trim($value, "'\"");
  1867. if ($this->isRegexp($attr)) {
  1868. // cut regexp character
  1869. $attr = substr($attr, 0, -1);
  1870. $execute = true;
  1871. $XQuery .= "[@{$attr}]";
  1872. } else {
  1873. $XQuery .= "[@{$attr}='{$value}']";
  1874. }
  1875. // attr without specified value
  1876. } else {
  1877. $XQuery .= "[@{$attr}]";
  1878. }
  1879. if ($execute) {
  1880. $this->runQuery($XQuery, $s, 'is');
  1881. $XQuery = '';
  1882. if (! $this->length())
  1883. break;
  1884. }
  1885. // CLASSES
  1886. } else if ($s[0] == '.') {
  1887. // TODO use return $this->find("./self::*[contains(concat(\" \",@class,\" \"), \" $class \")]");
  1888. // thx wizDom ;)
  1889. if ($delimiterBefore)
  1890. $XQuery .= '*';
  1891. $XQuery .= '[@class]';
  1892. $this->runQuery($XQuery, $s, 'matchClasses');
  1893. $XQuery = '';
  1894. if (! $this->length() )
  1895. break;
  1896. // ~ General Sibling Selector
  1897. } else if ($s[0] == '~') {
  1898. $this->runQuery($XQuery);
  1899. $XQuery = '';
  1900. $this->elements = $this
  1901. ->siblings(
  1902. substr($s, 1)
  1903. )->elements;
  1904. if (! $this->length() )
  1905. break;
  1906. // + Adjacent sibling selectors
  1907. } else if ($s[0] == '+') {
  1908. // TODO /following-sibling::
  1909. $this->runQuery($XQuery);
  1910. $XQuery = '';
  1911. $subSelector = substr($s, 1);
  1912. $subElements = $this->elements;
  1913. $this->elements = array();
  1914. foreach($subElements as $node) {
  1915. // search first DOMElement sibling
  1916. $test = $node->nextSibling;
  1917. while($test && ! ($test instanceof DOMELEMENT))
  1918. $test = $test->nextSibling;
  1919. if ($test && $this->is($subSelector, $test))
  1920. $this->elements[] = $test;
  1921. }
  1922. if (! $this->length() )
  1923. break;
  1924. // PSEUDO CLASSES
  1925. } else if ($s[0] == ':') {
  1926. // TODO optimization for :first :last
  1927. if ($XQuery) {
  1928. $this->runQuery($XQuery);
  1929. $XQuery = '';
  1930. }
  1931. if (! $this->length())
  1932. break;
  1933. $this->pseudoClasses($s);
  1934. if (! $this->length())
  1935. break;
  1936. // DIRECT DESCENDANDS
  1937. } else if ($s == '>') {
  1938. $XQuery .= '/';
  1939. $delimiterBefore = 2;
  1940. // ALL DESCENDANDS
  1941. } else if ($s == ' ') {
  1942. $XQuery .= '//';
  1943. $delimiterBefore = 2;
  1944. // ERRORS
  1945. } else {
  1946. phpQuery::debug("Unrecognized token '$s'");
  1947. }
  1948. $delimiterBefore = $delimiterBefore === 2;
  1949. }
  1950. // run query if any
  1951. if ($XQuery && $XQuery != '//') {
  1952. $this->runQuery($XQuery);
  1953. $XQuery = '';
  1954. }
  1955. foreach($this->elements as $node)
  1956. if (! $this->elementsContainsNode($node, $stack))
  1957. $stack[] = $node;
  1958. }
  1959. usort($stack, array('phpQueryObject', 'cmpByLineNo'));
  1960. $this->elements = $stack;
  1961. return $this->newInstance();
  1962. }
  1963. /**
  1964. * @todo create API for classes with pseudoselectors
  1965. * @access private
  1966. */
  1967. protected function pseudoClasses($class) {
  1968. // TODO clean args parsing ?
  1969. $class = ltrim($class, ':');
  1970. $haveArgs = mb_strpos($class, '(');
  1971. if ($haveArgs !== false) {
  1972. $args = substr($class, $haveArgs+1, -1);
  1973. $class = substr($class, 0, $haveArgs);
  1974. }
  1975. switch($class) {
  1976. case 'even':
  1977. case 'odd':
  1978. $stack = array();
  1979. foreach($this->elements as $i => $node) {
  1980. if ($class == 'even' && ($i%2) == 0)
  1981. $stack[] = $node;
  1982. else if ( $class == 'odd' && $i % 2 )
  1983. $stack[] = $node;
  1984. }
  1985. $this->elements = $stack;
  1986. break;
  1987. case 'eq':
  1988. $k = intval($args);
  1989. $this->elements = isset( $this->elements[$k] )
  1990. ? array( $this->elements[$k] )
  1991. : array();
  1992. break;
  1993. case 'gt':
  1994. $this->elements = array_slice($this->elements, $args+1);
  1995. break;
  1996. case 'lt':
  1997. $this->elements = array_slice($this->elements, 0, $args+1);
  1998. break;
  1999. case 'first':
  2000. if (isset($this->elements[0]))
  2001. $this->elements = array($this->elements[0]);
  2002. break;
  2003. case 'last':
  2004. if ($this->elements)
  2005. $this->elements = array($this->elements[count($this->elements)-1]);
  2006. break;
  2007. /*case 'parent':
  2008. $stack = array();
  2009. foreach($this->elements as $node) {
  2010. if ( $node->childNodes->length )
  2011. $stack[] = $node;
  2012. }
  2013. $this->elements = $stack;
  2014. break;*/
  2015. case 'contains':
  2016. $text = trim($args, "\"'");
  2017. $stack = array();
  2018. foreach($this->elements as $node) {
  2019. if (mb_stripos($node->textContent, $text) === false)
  2020. continue;
  2021. $stack[] = $node;
  2022. }
  2023. $this->elements = $stack;
  2024. break;
  2025. case 'not':
  2026. $selector = self::unQuote($args);
  2027. $this->elements = $this->not($selector)->stack();
  2028. break;
  2029. case 'slice':
  2030. // TODO jQuery difference ?
  2031. $args = explode(',',
  2032. str_replace(', ', ',', trim($args, "\"'"))
  2033. );
  2034. $start = $args[0];
  2035. $end = isset($args[1])
  2036. ? $args[1]
  2037. : null;
  2038. if ($end > 0)
  2039. $end = $end-$start;
  2040. $this->elements = array_slice($this->elements, $start, $end);
  2041. break;
  2042. case 'has':
  2043. $selector = trim($args, "\"'");
  2044. $stack = array();
  2045. foreach($this->stack(1) as $el) {
  2046. if ($this->find($selector, $el, true)->length)
  2047. $stack[] = $el;
  2048. }
  2049. $this->elements = $stack;
  2050. break;
  2051. case 'submit':
  2052. case 'reset':
  2053. $this->elements = phpQuery::merge(
  2054. $this->map(array($this, 'is'),
  2055. "input[type=$class]", new CallbackParam()
  2056. ),
  2057. $this->map(array($this, 'is'),
  2058. "button[type=$class]", new CallbackParam()
  2059. )
  2060. );
  2061. break;
  2062. // $stack = array();
  2063. // foreach($this->elements as $node)
  2064. // if ($node->is('input[type=submit]') || $node->is('button[type=submit]'))
  2065. // $stack[] = $el;
  2066. // $this->elements = $stack;
  2067. case 'input':
  2068. $this->elements = $this->map(
  2069. array($this, 'is'),
  2070. 'input', new CallbackParam()
  2071. )->elements;
  2072. break;
  2073. case 'password':
  2074. case 'checkbox':
  2075. case 'radio':
  2076. case 'hidden':
  2077. case 'image':
  2078. case 'file':
  2079. $this->elements = $this->map(
  2080. array($this, 'is'),
  2081. "input[type=$class]", new CallbackParam()
  2082. )->elements;
  2083. break;
  2084. case 'parent':
  2085. $this->elements = $this->map(
  2086. create_function('$node', '
  2087. return $node instanceof DOMELEMENT && $node->childNodes->length
  2088. ? $node : null;')
  2089. )->elements;
  2090. break;
  2091. case 'empty':
  2092. $this->elements = $this->map(
  2093. create_function('$node', '
  2094. return $node instanceof DOMELEMENT && $node->childNodes->length
  2095. ? null : $node;')
  2096. )->elements;
  2097. break;
  2098. case 'disabled':
  2099. case 'selected':
  2100. case 'checked':
  2101. $this->elements = $this->map(
  2102. array($this, 'is'),
  2103. "[$class]", new CallbackParam()
  2104. )->elements;
  2105. break;
  2106. case 'enabled':
  2107. $this->elements = $this->map(
  2108. create_function('$node', '
  2109. return pq($node)->not(":disabled") ? $node : null;')
  2110. )->elements;
  2111. break;
  2112. case 'header':
  2113. $this->elements = $this->map(
  2114. create_function('$node',
  2115. '$isHeader = isset($node->tagName) && in_array($node->tagName, array(
  2116. "h1", "h2", "h3", "h4", "h5", "h6", "h7"
  2117. ));
  2118. return $isHeader
  2119. ? $node
  2120. : null;')
  2121. )->elements;
  2122. // $this->elements = $this->map(
  2123. // create_function('$node', '$node = pq($node);
  2124. // return $node->is("h1")
  2125. // || $node->is("h2")
  2126. // || $node->is("h3")
  2127. // || $node->is("h4")
  2128. // || $node->is("h5")
  2129. // || $node->is("h6")
  2130. // || $node->is("h7")
  2131. // ? $node
  2132. // : null;')
  2133. // )->elements;
  2134. break;
  2135. case 'only-child':
  2136. $this->elements = $this->map(
  2137. create_function('$node',
  2138. 'return pq($node)->siblings()->size() == 0 ? $node : null;')
  2139. )->elements;
  2140. break;
  2141. case 'first-child':
  2142. $this->elements = $this->map(
  2143. create_function('$node', 'return pq($node)->prevAll()->size() == 0 ? $node : null;')
  2144. )->elements;
  2145. break;
  2146. case 'last-child':
  2147. $this->elements = $this->map(
  2148. create_function('$node', 'return pq($node)->nextAll()->size() == 0 ? $node : null;')
  2149. )->elements;
  2150. break;
  2151. case 'nth-child':
  2152. $param = trim($args, "\"'");
  2153. if (! $param)
  2154. break;
  2155. // nth-child(n+b) to nth-child(1n+b)
  2156. if ($param{0} == 'n')
  2157. $param = '1'.$param;
  2158. // :nth-child(index/even/odd/equation)
  2159. if ($param == 'even' || $param == 'odd')
  2160. $mapped = $this->map(
  2161. create_function('$node, $param',
  2162. '$index = pq($node)->prevAll()->size()+1;
  2163. if ($param == "even" && ($index%2) == 0)
  2164. return $node;
  2165. else if ($param == "odd" && $index%2 == 1)
  2166. return $node;
  2167. else
  2168. return null;'),
  2169. new CallbackParam(), $param
  2170. );
  2171. else if (mb_strlen($param) > 1 && $param{1} == 'n')
  2172. // an+b
  2173. $mapped = $this->map(
  2174. create_function('$node, $param',
  2175. '$prevs = pq($node)->prevAll()->size();
  2176. $index = 1+$prevs;
  2177. $b = mb_strlen($param) > 3
  2178. ? $param{3}
  2179. : 0;
  2180. $a = $param{0};
  2181. if ($b && $param{2} == "-")
  2182. $b = -$b;
  2183. if ($a > 0) {
  2184. return ($index-$b)%$a == 0
  2185. ? $node
  2186. : null;
  2187. phpQuery::debug($a."*".floor($index/$a)."+$b-1 == ".($a*floor($index/$a)+$b-1)." ?= $prevs");
  2188. return $a*floor($index/$a)+$b-1 == $prevs
  2189. ? $node
  2190. : null;
  2191. } else if ($a == 0)
  2192. return $index == $b
  2193. ? $node
  2194. : null;
  2195. else
  2196. // negative value
  2197. return $index <= $b
  2198. ? $node
  2199. : null;
  2200. // if (! $b)
  2201. // return $index%$a == 0
  2202. // ? $node
  2203. // : null;
  2204. // else
  2205. // return ($index-$b)%$a == 0
  2206. // ? $node
  2207. // : null;
  2208. '),
  2209. new CallbackParam(), $param
  2210. );
  2211. else
  2212. // index
  2213. $mapped = $this->map(
  2214. create_function('$node, $index',
  2215. '$prevs = pq($node)->prevAll()->size();
  2216. if ($prevs && $prevs == $index-1)
  2217. return $node;
  2218. else if (! $prevs && $index == 1)
  2219. return $node;
  2220. else
  2221. return null;'),
  2222. new CallbackParam(), $param
  2223. );
  2224. $this->elements = $mapped->elements;
  2225. break;
  2226. default:
  2227. $this->debug("Unknown pseudoclass '{$class}', skipping...");
  2228. }
  2229. }
  2230. /**
  2231. * @access private
  2232. */
  2233. protected function __pseudoClassParam($paramsString) {
  2234. // TODO;
  2235. }
  2236. /**
  2237. * Enter description here...
  2238. *
  2239. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2240. */
  2241. public function is($selector, $nodes = null) {
  2242. phpQuery::debug(array("Is:", $selector));
  2243. if (! $selector)
  2244. return false;
  2245. $oldStack = $this->elements;
  2246. $returnArray = false;
  2247. if ($nodes && is_array($nodes)) {
  2248. $this->elements = $nodes;
  2249. } else if ($nodes)
  2250. $this->elements = array($nodes);
  2251. $this->filter($selector, true);
  2252. $stack = $this->elements;
  2253. $this->elements = $oldStack;
  2254. if ($nodes)
  2255. return $stack ? $stack : null;
  2256. return (bool)count($stack);
  2257. }
  2258. /**
  2259. * Enter description here...
  2260. * jQuery difference.
  2261. *
  2262. * Callback:
  2263. * - $index int
  2264. * - $node DOMNode
  2265. *
  2266. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2267. * @link http://docs.jquery.com/Traversing/filter
  2268. */
  2269. public function filterCallback($callback, $_skipHistory = false) {
  2270. if (! $_skipHistory) {
  2271. $this->elementsBackup = $this->elements;
  2272. $this->debug("Filtering by callback");
  2273. }
  2274. $newStack = array();
  2275. foreach($this->elements as $index => $node) {
  2276. $result = phpQuery::callbackRun($callback, array($index, $node));
  2277. if (is_null($result) || (! is_null($result) && $result))
  2278. $newStack[] = $node;
  2279. }
  2280. $this->elements = $newStack;
  2281. return $_skipHistory
  2282. ? $this
  2283. : $this->newInstance();
  2284. }
  2285. /**
  2286. * Enter description here...
  2287. *
  2288. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2289. * @link http://docs.jquery.com/Traversing/filter
  2290. */
  2291. public function filter($selectors, $_skipHistory = false) {
  2292. if ($selectors instanceof Callback OR $selectors instanceof Closure)
  2293. return $this->filterCallback($selectors, $_skipHistory);
  2294. if (! $_skipHistory)
  2295. $this->elementsBackup = $this->elements;
  2296. $notSimpleSelector = array(' ', '>', '~', '+', '/');
  2297. if (! is_array($selectors))
  2298. $selectors = $this->parseSelector($selectors);
  2299. if (! $_skipHistory)
  2300. $this->debug(array("Filtering:", $selectors));
  2301. $finalStack = array();
  2302. foreach($selectors as $selector) {
  2303. $stack = array();
  2304. if (! $selector)
  2305. break;
  2306. // avoid first space or /
  2307. if (in_array($selector[0], $notSimpleSelector))
  2308. $selector = array_slice($selector, 1);
  2309. // PER NODE selector chunks
  2310. foreach($this->stack() as $node) {
  2311. $break = false;
  2312. foreach($selector as $s) {
  2313. if (!($node instanceof DOMELEMENT)) {
  2314. // all besides DOMElement
  2315. if ( $s[0] == '[') {
  2316. $attr = trim($s, '[]');
  2317. if ( mb_strpos($attr, '=')) {
  2318. list( $attr, $val ) = explode('=', $attr);
  2319. if ($attr == 'nodeType' && $node->nodeType != $val)
  2320. $break = true;
  2321. }
  2322. } else
  2323. $break = true;
  2324. } else {
  2325. // DOMElement only
  2326. // ID
  2327. if ( $s[0] == '#') {
  2328. if ( $node->getAttribute('id') != substr($s, 1) )
  2329. $break = true;
  2330. // CLASSES
  2331. } else if ( $s[0] == '.') {
  2332. if (! $this->matchClasses( $s, $node ) )
  2333. $break = true;
  2334. // ATTRS
  2335. } else if ( $s[0] == '[') {
  2336. // strip side brackets
  2337. $attr = trim($s, '[]');
  2338. if (mb_strpos($attr, '=')) {
  2339. list($attr, $val) = explode('=', $attr);
  2340. $val = self::unQuote($val);
  2341. if ($attr == 'nodeType') {
  2342. if ($val != $node->nodeType)
  2343. $break = true;
  2344. } else if ($this->isRegexp($attr)) {
  2345. $val = extension_loaded('mbstring') && phpQuery::$mbstringSupport
  2346. ? quotemeta(trim($val, '"\''))
  2347. : preg_quote(trim($val, '"\''), '@');
  2348. // switch last character
  2349. switch( substr($attr, -1)) {
  2350. // quotemeta used insted of preg_quote
  2351. // http://code.google.com/p/phpquery/issues/detail?id=76
  2352. case '^':
  2353. $pattern = '^'.$val;
  2354. break;
  2355. case '*':
  2356. $pattern = '.*'.$val.'.*';
  2357. break;
  2358. case '$':
  2359. $pattern = '.*'.$val.'$';
  2360. break;
  2361. }
  2362. // cut last character
  2363. $attr = substr($attr, 0, -1);
  2364. $isMatch = extension_loaded('mbstring') && phpQuery::$mbstringSupport
  2365. ? mb_ereg_match($pattern, $node->getAttribute($attr))
  2366. : preg_match("@{$pattern}@", $node->getAttribute($attr));
  2367. if (! $isMatch)
  2368. $break = true;
  2369. } else if ($node->getAttribute($attr) != $val)
  2370. $break = true;
  2371. } else if (! $node->hasAttribute($attr))
  2372. $break = true;
  2373. // PSEUDO CLASSES
  2374. } else if ( $s[0] == ':') {
  2375. // skip
  2376. // TAG
  2377. } else if (trim($s)) {
  2378. if ($s != '*') {
  2379. // TODO namespaces
  2380. if (isset($node->tagName)) {
  2381. if ($node->tagName != $s)
  2382. $break = true;
  2383. } else if ($s == 'html' && ! $this->isRoot($node))
  2384. $break = true;
  2385. }
  2386. // AVOID NON-SIMPLE SELECTORS
  2387. } else if (in_array($s, $notSimpleSelector)) {
  2388. $break = true;
  2389. $this->debug(array('Skipping non simple selector', $selector));
  2390. }
  2391. }
  2392. if ($break)
  2393. break;
  2394. }
  2395. // if element passed all chunks of selector - add it to new stack
  2396. if (! $break )
  2397. $stack[] = $node;
  2398. }
  2399. $tmpStack = $this->elements;
  2400. $this->elements = $stack;
  2401. // PER ALL NODES selector chunks
  2402. foreach($selector as $s)
  2403. // PSEUDO CLASSES
  2404. if ($s[0] == ':')
  2405. $this->pseudoClasses($s);
  2406. foreach($this->elements as $node)
  2407. // XXX it should be merged without duplicates
  2408. // but jQuery doesnt do that
  2409. $finalStack[] = $node;
  2410. $this->elements = $tmpStack;
  2411. }
  2412. $this->elements = $finalStack;
  2413. if ($_skipHistory) {
  2414. return $this;
  2415. } else {
  2416. $this->debug("Stack length after filter(): ".count($finalStack));
  2417. return $this->newInstance();
  2418. }
  2419. }
  2420. /**
  2421. *
  2422. * @param $value
  2423. * @return unknown_type
  2424. * @TODO implement in all methods using passed parameters
  2425. */
  2426. protected static function unQuote($value) {
  2427. return $value[0] == '\'' || $value[0] == '"'
  2428. ? substr($value, 1, -1)
  2429. : $value;
  2430. }
  2431. /**
  2432. * Enter description here...
  2433. *
  2434. * @link http://docs.jquery.com/Ajax/load
  2435. * @return phpQuery|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2436. * @todo Support $selector
  2437. */
  2438. public function load($url, $data = null, $callback = null) {
  2439. if ($data && ! is_array($data)) {
  2440. $callback = $data;
  2441. $data = null;
  2442. }
  2443. if (mb_strpos($url, ' ') !== false) {
  2444. $matches = null;
  2445. if (extension_loaded('mbstring') && phpQuery::$mbstringSupport)
  2446. mb_ereg('^([^ ]+) (.*)$', $url, $matches);
  2447. else
  2448. preg_match('^([^ ]+) (.*)$', $url, $matches);
  2449. $url = $matches[1];
  2450. $selector = $matches[2];
  2451. // FIXME this sucks, pass as callback param
  2452. $this->_loadSelector = $selector;
  2453. }
  2454. $ajax = array(
  2455. 'url' => $url,
  2456. 'type' => $data ? 'POST' : 'GET',
  2457. 'data' => $data,
  2458. 'complete' => $callback,
  2459. 'success' => array($this, '__loadSuccess')
  2460. );
  2461. phpQuery::ajax($ajax);
  2462. return $this;
  2463. }
  2464. /**
  2465. * @access private
  2466. * @param $html
  2467. * @return unknown_type
  2468. */
  2469. public function __loadSuccess($html) {
  2470. if ($this->_loadSelector) {
  2471. $html = phpQuery::newDocument($html)->find($this->_loadSelector);
  2472. unset($this->_loadSelector);
  2473. }
  2474. foreach($this->stack(1) as $node) {
  2475. phpQuery::pq($node, $this->getDocumentID())
  2476. ->markup($html);
  2477. }
  2478. }
  2479. /**
  2480. * Enter description here...
  2481. *
  2482. * @return phpQuery|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2483. * @todo
  2484. */
  2485. public function css() {
  2486. // TODO
  2487. return $this;
  2488. }
  2489. /**
  2490. * @todo
  2491. *
  2492. */
  2493. public function show(){
  2494. // TODO
  2495. return $this;
  2496. }
  2497. /**
  2498. * @todo
  2499. *
  2500. */
  2501. public function hide(){
  2502. // TODO
  2503. return $this;
  2504. }
  2505. /**
  2506. * Trigger a type of event on every matched element.
  2507. *
  2508. * @param unknown_type $type
  2509. * @param unknown_type $data
  2510. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2511. * @TODO support more than event in $type (space-separated)
  2512. */
  2513. public function trigger($type, $data = array()) {
  2514. foreach($this->elements as $node)
  2515. phpQueryEvents::trigger($this->getDocumentID(), $type, $data, $node);
  2516. return $this;
  2517. }
  2518. /**
  2519. * This particular method triggers all bound event handlers on an element (for a specific event type) WITHOUT executing the browsers default actions.
  2520. *
  2521. * @param unknown_type $type
  2522. * @param unknown_type $data
  2523. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2524. * @TODO
  2525. */
  2526. public function triggerHandler($type, $data = array()) {
  2527. // TODO;
  2528. }
  2529. /**
  2530. * Binds a handler to one or more events (like click) for each matched element.
  2531. * Can also bind custom events.
  2532. *
  2533. * @param unknown_type $type
  2534. * @param unknown_type $data Optional
  2535. * @param unknown_type $callback
  2536. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2537. * @TODO support '!' (exclusive) events
  2538. * @TODO support more than event in $type (space-separated)
  2539. */
  2540. public function bind($type, $data, $callback = null) {
  2541. // TODO check if $data is callable, not using is_callable
  2542. if (! isset($callback)) {
  2543. $callback = $data;
  2544. $data = null;
  2545. }
  2546. foreach($this->elements as $node)
  2547. phpQueryEvents::add($this->getDocumentID(), $node, $type, $data, $callback);
  2548. return $this;
  2549. }
  2550. /**
  2551. * Enter description here...
  2552. *
  2553. * @param unknown_type $type
  2554. * @param unknown_type $callback
  2555. * @return unknown
  2556. * @TODO namespace events
  2557. * @TODO support more than event in $type (space-separated)
  2558. */
  2559. public function unbind($type = null, $callback = null) {
  2560. foreach($this->elements as $node)
  2561. phpQueryEvents::remove($this->getDocumentID(), $node, $type, $callback);
  2562. return $this;
  2563. }
  2564. /**
  2565. * Enter description here...
  2566. *
  2567. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2568. */
  2569. public function change($callback = null) {
  2570. if ($callback)
  2571. return $this->bind('change', $callback);
  2572. return $this->trigger('change');
  2573. }
  2574. /**
  2575. * Enter description here...
  2576. *
  2577. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2578. */
  2579. public function submit($callback = null) {
  2580. if ($callback)
  2581. return $this->bind('submit', $callback);
  2582. return $this->trigger('submit');
  2583. }
  2584. /**
  2585. * Enter description here...
  2586. *
  2587. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2588. */
  2589. public function click($callback = null) {
  2590. if ($callback)
  2591. return $this->bind('click', $callback);
  2592. return $this->trigger('click');
  2593. }
  2594. /**
  2595. * Enter description here...
  2596. *
  2597. * @param String|phpQuery
  2598. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2599. */
  2600. public function wrapAllOld($wrapper) {
  2601. $wrapper = pq($wrapper)->_clone();
  2602. if (! $wrapper->length() || ! $this->length() )
  2603. return $this;
  2604. $wrapper->insertBefore($this->elements[0]);
  2605. $deepest = $wrapper->elements[0];
  2606. while($deepest->firstChild && $deepest->firstChild instanceof DOMELEMENT)
  2607. $deepest = $deepest->firstChild;
  2608. pq($deepest)->append($this);
  2609. return $this;
  2610. }
  2611. /**
  2612. * Enter description here...
  2613. *
  2614. * TODO testme...
  2615. * @param String|phpQuery
  2616. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2617. */
  2618. public function wrapAll($wrapper) {
  2619. if (! $this->length())
  2620. return $this;
  2621. return phpQuery::pq($wrapper, $this->getDocumentID())
  2622. ->clone()
  2623. ->insertBefore($this->get(0))
  2624. ->map(array($this, '___wrapAllCallback'))
  2625. ->append($this);
  2626. }
  2627. /**
  2628. *
  2629. * @param $node
  2630. * @return unknown_type
  2631. * @access private
  2632. */
  2633. public function ___wrapAllCallback($node) {
  2634. $deepest = $node;
  2635. while($deepest->firstChild && $deepest->firstChild instanceof DOMELEMENT)
  2636. $deepest = $deepest->firstChild;
  2637. return $deepest;
  2638. }
  2639. /**
  2640. * Enter description here...
  2641. * NON JQUERY METHOD
  2642. *
  2643. * @param String|phpQuery
  2644. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2645. */
  2646. public function wrapAllPHP($codeBefore, $codeAfter) {
  2647. return $this
  2648. ->slice(0, 1)
  2649. ->beforePHP($codeBefore)
  2650. ->end()
  2651. ->slice(-1)
  2652. ->afterPHP($codeAfter)
  2653. ->end();
  2654. }
  2655. /**
  2656. * Enter description here...
  2657. *
  2658. * @param String|phpQuery
  2659. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2660. */
  2661. public function wrap($wrapper) {
  2662. foreach($this->stack() as $node)
  2663. phpQuery::pq($node, $this->getDocumentID())->wrapAll($wrapper);
  2664. return $this;
  2665. }
  2666. /**
  2667. * Enter description here...
  2668. *
  2669. * @param String|phpQuery
  2670. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2671. */
  2672. public function wrapPHP($codeBefore, $codeAfter) {
  2673. foreach($this->stack() as $node)
  2674. phpQuery::pq($node, $this->getDocumentID())->wrapAllPHP($codeBefore, $codeAfter);
  2675. return $this;
  2676. }
  2677. /**
  2678. * Enter description here...
  2679. *
  2680. * @param String|phpQuery
  2681. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2682. */
  2683. public function wrapInner($wrapper) {
  2684. foreach($this->stack() as $node)
  2685. phpQuery::pq($node, $this->getDocumentID())->contents()->wrapAll($wrapper);
  2686. return $this;
  2687. }
  2688. /**
  2689. * Enter description here...
  2690. *
  2691. * @param String|phpQuery
  2692. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2693. */
  2694. public function wrapInnerPHP($codeBefore, $codeAfter) {
  2695. foreach($this->stack(1) as $node)
  2696. phpQuery::pq($node, $this->getDocumentID())->contents()
  2697. ->wrapAllPHP($codeBefore, $codeAfter);
  2698. return $this;
  2699. }
  2700. /**
  2701. * Enter description here...
  2702. *
  2703. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2704. * @testme Support for text nodes
  2705. */
  2706. public function contents() {
  2707. $stack = array();
  2708. foreach($this->stack(1) as $el) {
  2709. // FIXME (fixed) http://code.google.com/p/phpquery/issues/detail?id=56
  2710. // if (! isset($el->childNodes))
  2711. // continue;
  2712. foreach($el->childNodes as $node) {
  2713. $stack[] = $node;
  2714. }
  2715. }
  2716. return $this->newInstance($stack);
  2717. }
  2718. /**
  2719. * Enter description here...
  2720. *
  2721. * jQuery difference.
  2722. *
  2723. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2724. */
  2725. public function contentsUnwrap() {
  2726. foreach($this->stack(1) as $node) {
  2727. if (! $node->parentNode )
  2728. continue;
  2729. $childNodes = array();
  2730. // any modification in DOM tree breaks childNodes iteration, so cache them first
  2731. foreach($node->childNodes as $chNode )
  2732. $childNodes[] = $chNode;
  2733. foreach($childNodes as $chNode )
  2734. // $node->parentNode->appendChild($chNode);
  2735. $node->parentNode->insertBefore($chNode, $node);
  2736. $node->parentNode->removeChild($node);
  2737. }
  2738. return $this;
  2739. }
  2740. /**
  2741. * Enter description here...
  2742. *
  2743. * jQuery difference.
  2744. */
  2745. public function switchWith($markup) {
  2746. $markup = pq($markup, $this->getDocumentID());
  2747. $content = null;
  2748. foreach($this->stack(1) as $node) {
  2749. pq($node)
  2750. ->contents()->toReference($content)->end()
  2751. ->replaceWith($markup->clone()->append($content));
  2752. }
  2753. return $this;
  2754. }
  2755. /**
  2756. * Enter description here...
  2757. *
  2758. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2759. */
  2760. public function eq($num) {
  2761. $oldStack = $this->elements;
  2762. $this->elementsBackup = $this->elements;
  2763. $this->elements = array();
  2764. if ( isset($oldStack[$num]) )
  2765. $this->elements[] = $oldStack[$num];
  2766. return $this->newInstance();
  2767. }
  2768. /**
  2769. * Enter description here...
  2770. *
  2771. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2772. */
  2773. public function size() {
  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() {
  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. * Enter description here...
  3330. *
  3331. * @param unknown_type $start
  3332. * @param unknown_type $end
  3333. *
  3334. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3335. * @testme
  3336. */
  3337. public function slice($start, $end = null) {
  3338. // $last = count($this->elements)-1;
  3339. // $end = $end
  3340. // ? min($end, $last)
  3341. // : $last;
  3342. // if ($start < 0)
  3343. // $start = $last+$start;
  3344. // if ($start > $last)
  3345. // return array();
  3346. if ($end > 0)
  3347. $end = $end-$start;
  3348. return $this->newInstance(
  3349. array_slice($this->elements, $start, $end)
  3350. );
  3351. }
  3352. /**
  3353. * Enter description here...
  3354. *
  3355. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3356. */
  3357. public function reverse() {
  3358. $this->elementsBackup = $this->elements;
  3359. $this->elements = array_reverse($this->elements);
  3360. return $this->newInstance();
  3361. }
  3362. /**
  3363. * Return joined text content.
  3364. * @return String
  3365. */
  3366. public function text($text = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  3367. if (isset($text))
  3368. return $this->html(htmlspecialchars($text), ENT_NOQUOTES, 'UTF-8');
  3369. $args = func_get_args();
  3370. $args = array_slice($args, 1);
  3371. $return = '';
  3372. foreach($this->elements as $node) {
  3373. $text = $node->textContent;
  3374. if (count($this->elements) > 1 && $text)
  3375. $text .= "\n";
  3376. foreach($args as $callback) {
  3377. $text = phpQuery::callbackRun($callback, array($text));
  3378. }
  3379. $return .= $text;
  3380. }
  3381. return $return;
  3382. }
  3383. /**
  3384. * Enter description here...
  3385. *
  3386. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3387. */
  3388. public function plugin($class, $file = null) {
  3389. phpQuery::plugin($class, $file);
  3390. return $this;
  3391. }
  3392. /**
  3393. * Deprecated, use $pq->plugin() instead.
  3394. *
  3395. * @deprecated
  3396. * @param $class
  3397. * @param $file
  3398. * @return unknown_type
  3399. */
  3400. public static function extend($class, $file = null) {
  3401. return $this->plugin($class, $file);
  3402. }
  3403. /**
  3404. *
  3405. * @access private
  3406. * @param $method
  3407. * @param $args
  3408. * @return unknown_type
  3409. */
  3410. public function __call($method, $args) {
  3411. $aliasMethods = array('clone', 'empty');
  3412. if (isset(phpQuery::$extendMethods[$method])) {
  3413. array_unshift($args, $this);
  3414. return phpQuery::callbackRun(
  3415. phpQuery::$extendMethods[$method], $args
  3416. );
  3417. } else if (isset(phpQuery::$pluginsMethods[$method])) {
  3418. array_unshift($args, $this);
  3419. $class = phpQuery::$pluginsMethods[$method];
  3420. $realClass = "phpQueryObjectPlugin_$class";
  3421. $return = call_user_func_array(
  3422. array($realClass, $method),
  3423. $args
  3424. );
  3425. // XXX deprecate ?
  3426. return is_null($return)
  3427. ? $this
  3428. : $return;
  3429. } else if (in_array($method, $aliasMethods)) {
  3430. return call_user_func_array(array($this, '_'.$method), $args);
  3431. } else
  3432. throw new Exception("Method '{$method}' doesnt exist");
  3433. }
  3434. /**
  3435. * Safe rename of next().
  3436. *
  3437. * Use it ONLY when need to call next() on an iterated object (in same time).
  3438. * Normaly there is no need to do such thing ;)
  3439. *
  3440. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3441. * @access private
  3442. */
  3443. public function _next($selector = null) {
  3444. return $this->newInstance(
  3445. $this->getElementSiblings('nextSibling', $selector, true)
  3446. );
  3447. }
  3448. /**
  3449. * Use prev() and next().
  3450. *
  3451. * @deprecated
  3452. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3453. * @access private
  3454. */
  3455. public function _prev($selector = null) {
  3456. return $this->prev($selector);
  3457. }
  3458. /**
  3459. * Enter description here...
  3460. *
  3461. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3462. */
  3463. public function prev($selector = null) {
  3464. return $this->newInstance(
  3465. $this->getElementSiblings('previousSibling', $selector, true)
  3466. );
  3467. }
  3468. /**
  3469. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3470. * @todo
  3471. */
  3472. public function prevAll($selector = null) {
  3473. return $this->newInstance(
  3474. $this->getElementSiblings('previousSibling', $selector)
  3475. );
  3476. }
  3477. /**
  3478. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3479. * @todo FIXME: returns source elements insted of next siblings
  3480. */
  3481. public function nextAll($selector = null) {
  3482. return $this->newInstance(
  3483. $this->getElementSiblings('nextSibling', $selector)
  3484. );
  3485. }
  3486. /**
  3487. * @access private
  3488. */
  3489. protected function getElementSiblings($direction, $selector = null, $limitToOne = false) {
  3490. $stack = array();
  3491. $count = 0;
  3492. foreach($this->stack() as $node) {
  3493. $test = $node;
  3494. while( isset($test->{$direction}) && $test->{$direction}) {
  3495. $test = $test->{$direction};
  3496. if (! $test instanceof DOMELEMENT)
  3497. continue;
  3498. $stack[] = $test;
  3499. if ($limitToOne)
  3500. break;
  3501. }
  3502. }
  3503. if ($selector) {
  3504. $stackOld = $this->elements;
  3505. $this->elements = $stack;
  3506. $stack = $this->filter($selector, true)->stack();
  3507. $this->elements = $stackOld;
  3508. }
  3509. return $stack;
  3510. }
  3511. /**
  3512. * Enter description here...
  3513. *
  3514. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3515. */
  3516. public function siblings($selector = null) {
  3517. $stack = array();
  3518. $siblings = array_merge(
  3519. $this->getElementSiblings('previousSibling', $selector),
  3520. $this->getElementSiblings('nextSibling', $selector)
  3521. );
  3522. foreach($siblings as $node) {
  3523. if (! $this->elementsContainsNode($node, $stack))
  3524. $stack[] = $node;
  3525. }
  3526. return $this->newInstance($stack);
  3527. }
  3528. /**
  3529. * Enter description here...
  3530. *
  3531. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3532. */
  3533. public function not($selector = null) {
  3534. if (is_string($selector))
  3535. phpQuery::debug(array('not', $selector));
  3536. else
  3537. phpQuery::debug('not');
  3538. $stack = array();
  3539. if ($selector instanceof self || $selector instanceof DOMNODE) {
  3540. foreach($this->stack() as $node) {
  3541. if ($selector instanceof self) {
  3542. $matchFound = false;
  3543. foreach($selector->stack() as $notNode) {
  3544. if ($notNode->isSameNode($node))
  3545. $matchFound = true;
  3546. }
  3547. if (! $matchFound)
  3548. $stack[] = $node;
  3549. } else if ($selector instanceof DOMNODE) {
  3550. if (! $selector->isSameNode($node))
  3551. $stack[] = $node;
  3552. } else {
  3553. if (! $this->is($selector))
  3554. $stack[] = $node;
  3555. }
  3556. }
  3557. } else {
  3558. $orgStack = $this->stack();
  3559. $matched = $this->filter($selector, true)->stack();
  3560. // $matched = array();
  3561. // // simulate OR in filter() instead of AND 5y
  3562. // foreach($this->parseSelector($selector) as $s) {
  3563. // $matched = array_merge($matched,
  3564. // $this->filter(array($s))->stack()
  3565. // );
  3566. // }
  3567. foreach($orgStack as $node)
  3568. if (! $this->elementsContainsNode($node, $matched))
  3569. $stack[] = $node;
  3570. }
  3571. return $this->newInstance($stack);
  3572. }
  3573. /**
  3574. * Enter description here...
  3575. *
  3576. * @param string|phpQueryObject
  3577. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3578. */
  3579. public function add($selector = null) {
  3580. if (! $selector)
  3581. return $this;
  3582. $stack = array();
  3583. $this->elementsBackup = $this->elements;
  3584. $found = phpQuery::pq($selector, $this->getDocumentID());
  3585. $this->merge($found->elements);
  3586. return $this->newInstance();
  3587. }
  3588. /**
  3589. * @access private
  3590. */
  3591. protected function merge() {
  3592. foreach(func_get_args() as $nodes)
  3593. foreach($nodes as $newNode )
  3594. if (! $this->elementsContainsNode($newNode) )
  3595. $this->elements[] = $newNode;
  3596. }
  3597. /**
  3598. * @access private
  3599. * TODO refactor to stackContainsNode
  3600. */
  3601. protected function elementsContainsNode($nodeToCheck, $elementsStack = null) {
  3602. $loop = ! is_null($elementsStack)
  3603. ? $elementsStack
  3604. : $this->elements;
  3605. foreach($loop as $node) {
  3606. if ( $node->isSameNode( $nodeToCheck ) )
  3607. return true;
  3608. }
  3609. return false;
  3610. }
  3611. /**
  3612. * Enter description here...
  3613. *
  3614. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3615. */
  3616. public function parent($selector = null) {
  3617. $stack = array();
  3618. foreach($this->elements as $node )
  3619. if ( $node->parentNode && ! $this->elementsContainsNode($node->parentNode, $stack) )
  3620. $stack[] = $node->parentNode;
  3621. $this->elementsBackup = $this->elements;
  3622. $this->elements = $stack;
  3623. if ( $selector )
  3624. $this->filter($selector, true);
  3625. return $this->newInstance();
  3626. }
  3627. /**
  3628. * Enter description here...
  3629. *
  3630. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3631. */
  3632. public function parents($selector = null) {
  3633. $stack = array();
  3634. if (! $this->elements )
  3635. $this->debug('parents() - stack empty');
  3636. foreach($this->elements as $node) {
  3637. $test = $node;
  3638. while( $test->parentNode) {
  3639. $test = $test->parentNode;
  3640. if ($this->isRoot($test))
  3641. break;
  3642. if (! $this->elementsContainsNode($test, $stack)) {
  3643. $stack[] = $test;
  3644. continue;
  3645. }
  3646. }
  3647. }
  3648. $this->elementsBackup = $this->elements;
  3649. $this->elements = $stack;
  3650. if ( $selector )
  3651. $this->filter($selector, true);
  3652. return $this->newInstance();
  3653. }
  3654. /**
  3655. * Internal stack iterator.
  3656. *
  3657. * @access private
  3658. */
  3659. public function stack($nodeTypes = null) {
  3660. if (!isset($nodeTypes))
  3661. return $this->elements;
  3662. if (!is_array($nodeTypes))
  3663. $nodeTypes = array($nodeTypes);
  3664. $return = array();
  3665. foreach($this->elements as $node) {
  3666. if (in_array($node->nodeType, $nodeTypes))
  3667. $return[] = $node;
  3668. }
  3669. return $return;
  3670. }
  3671. // TODO phpdoc; $oldAttr is result of hasAttribute, before any changes
  3672. protected function attrEvents($attr, $oldAttr, $oldValue, $node) {
  3673. // skip events for XML documents
  3674. if (! $this->isXHTML() && ! $this->isHTML())
  3675. return;
  3676. $event = null;
  3677. // identify
  3678. $isInputValue = $node->tagName == 'input'
  3679. && (
  3680. in_array($node->getAttribute('type'),
  3681. array('text', 'password', 'hidden'))
  3682. || !$node->getAttribute('type')
  3683. );
  3684. $isRadio = $node->tagName == 'input'
  3685. && $node->getAttribute('type') == 'radio';
  3686. $isCheckbox = $node->tagName == 'input'
  3687. && $node->getAttribute('type') == 'checkbox';
  3688. $isOption = $node->tagName == 'option';
  3689. if ($isInputValue && $attr == 'value' && $oldValue != $node->getAttribute($attr)) {
  3690. $event = new DOMEvent(array(
  3691. 'target' => $node,
  3692. 'type' => 'change'
  3693. ));
  3694. } else if (($isRadio || $isCheckbox) && $attr == 'checked' && (
  3695. // check
  3696. (! $oldAttr && $node->hasAttribute($attr))
  3697. // un-check
  3698. || (! $node->hasAttribute($attr) && $oldAttr)
  3699. )) {
  3700. $event = new DOMEvent(array(
  3701. 'target' => $node,
  3702. 'type' => 'change'
  3703. ));
  3704. } else if ($isOption && $node->parentNode && $attr == 'selected' && (
  3705. // select
  3706. (! $oldAttr && $node->hasAttribute($attr))
  3707. // un-select
  3708. || (! $node->hasAttribute($attr) && $oldAttr)
  3709. )) {
  3710. $event = new DOMEvent(array(
  3711. 'target' => $node->parentNode,
  3712. 'type' => 'change'
  3713. ));
  3714. }
  3715. if ($event) {
  3716. phpQueryEvents::trigger($this->getDocumentID(),
  3717. $event->type, array($event), $node
  3718. );
  3719. }
  3720. }
  3721. public function attr($attr = null, $value = null) {
  3722. foreach($this->stack(1) as $node) {
  3723. if (! is_null($value)) {
  3724. $loop = $attr == '*'
  3725. ? $this->getNodeAttrs($node)
  3726. : array($attr);
  3727. foreach($loop as $a) {
  3728. $oldValue = $node->getAttribute($a);
  3729. $oldAttr = $node->hasAttribute($a);
  3730. // TODO raises an error when charset other than UTF-8
  3731. // while document's charset is also not UTF-8
  3732. @$node->setAttribute($a, $value);
  3733. $this->attrEvents($a, $oldAttr, $oldValue, $node);
  3734. }
  3735. } else if ($attr == '*') {
  3736. // jQuery difference
  3737. $return = array();
  3738. foreach($node->attributes as $n => $v)
  3739. $return[$n] = $v->value;
  3740. return $return;
  3741. } else
  3742. return $node->hasAttribute($attr)
  3743. ? $node->getAttribute($attr)
  3744. : null;
  3745. }
  3746. return is_null($value)
  3747. ? '' : $this;
  3748. }
  3749. /**
  3750. * @access private
  3751. */
  3752. protected function getNodeAttrs($node) {
  3753. $return = array();
  3754. foreach($node->attributes as $n => $o)
  3755. $return[] = $n;
  3756. return $return;
  3757. }
  3758. /**
  3759. * Enter description here...
  3760. *
  3761. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3762. * @todo check CDATA ???
  3763. */
  3764. public function attrPHP($attr, $code) {
  3765. if (! is_null($code)) {
  3766. $value = '<'.'?php '.$code.' ?'.'>';
  3767. // TODO tempolary solution
  3768. // http://code.google.com/p/phpquery/issues/detail?id=17
  3769. // if (function_exists('mb_detect_encoding') && mb_detect_encoding($value) == 'ASCII')
  3770. // $value = mb_convert_encoding($value, 'UTF-8', 'HTML-ENTITIES');
  3771. }
  3772. foreach($this->stack(1) as $node) {
  3773. if (! is_null($code)) {
  3774. // $attrNode = $this->DOM->createAttribute($attr);
  3775. $node->setAttribute($attr, $value);
  3776. // $attrNode->value = $value;
  3777. // $node->appendChild($attrNode);
  3778. } else if ( $attr == '*') {
  3779. // jQuery diff
  3780. $return = array();
  3781. foreach($node->attributes as $n => $v)
  3782. $return[$n] = $v->value;
  3783. return $return;
  3784. } else
  3785. return $node->getAttribute($attr);
  3786. }
  3787. return $this;
  3788. }
  3789. /**
  3790. * Enter description here...
  3791. *
  3792. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3793. */
  3794. public function removeAttr($attr) {
  3795. foreach($this->stack(1) as $node) {
  3796. $loop = $attr == '*'
  3797. ? $this->getNodeAttrs($node)
  3798. : array($attr);
  3799. foreach($loop as $a) {
  3800. $oldValue = $node->getAttribute($a);
  3801. $node->removeAttribute($a);
  3802. $this->attrEvents($a, $oldValue, null, $node);
  3803. }
  3804. }
  3805. return $this;
  3806. }
  3807. /**
  3808. * Return form element value.
  3809. *
  3810. * @return String Fields value.
  3811. */
  3812. public function val($val = null) {
  3813. if (! isset($val)) {
  3814. if ($this->eq(0)->is('select')) {
  3815. $selected = $this->eq(0)->find('option[selected=selected]');
  3816. if ($selected->is('[value]'))
  3817. return $selected->attr('value');
  3818. else
  3819. return $selected->text();
  3820. } else if ($this->eq(0)->is('textarea'))
  3821. return $this->eq(0)->markup();
  3822. else
  3823. return $this->eq(0)->attr('value');
  3824. } else {
  3825. $_val = null;
  3826. foreach($this->stack(1) as $node) {
  3827. $node = pq($node, $this->getDocumentID());
  3828. if (is_array($val) && in_array($node->attr('type'), array('checkbox', 'radio'))) {
  3829. $isChecked = in_array($node->attr('value'), $val)
  3830. || in_array($node->attr('name'), $val);
  3831. if ($isChecked)
  3832. $node->attr('checked', 'checked');
  3833. else
  3834. $node->removeAttr('checked');
  3835. } else if ($node->get(0)->tagName == 'select') {
  3836. if (! isset($_val)) {
  3837. $_val = array();
  3838. if (! is_array($val))
  3839. $_val = array((string)$val);
  3840. else
  3841. foreach($val as $v)
  3842. $_val[] = $v;
  3843. }
  3844. foreach($node['option']->stack(1) as $option) {
  3845. $option = pq($option, $this->getDocumentID());
  3846. $selected = false;
  3847. // XXX: workaround for string comparsion, see issue #96
  3848. // http://code.google.com/p/phpquery/issues/detail?id=96
  3849. $selected = is_null($option->attr('value'))
  3850. ? in_array($option->markup(), $_val)
  3851. : in_array($option->attr('value'), $_val);
  3852. // $optionValue = $option->attr('value');
  3853. // $optionText = $option->text();
  3854. // $optionTextLenght = mb_strlen($optionText);
  3855. // foreach($_val as $v)
  3856. // if ($optionValue == $v)
  3857. // $selected = true;
  3858. // else if ($optionText == $v && $optionTextLenght == mb_strlen($v))
  3859. // $selected = true;
  3860. if ($selected)
  3861. $option->attr('selected', 'selected');
  3862. else
  3863. $option->removeAttr('selected');
  3864. }
  3865. } else if ($node->get(0)->tagName == 'textarea')
  3866. $node->markup($val);
  3867. else
  3868. $node->attr('value', $val);
  3869. }
  3870. }
  3871. return $this;
  3872. }
  3873. /**
  3874. * Enter description here...
  3875. *
  3876. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3877. */
  3878. public function andSelf() {
  3879. if ( $this->previous )
  3880. $this->elements = array_merge($this->elements, $this->previous->elements);
  3881. return $this;
  3882. }
  3883. /**
  3884. * Enter description here...
  3885. *
  3886. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3887. */
  3888. public function addClass( $className) {
  3889. if (! $className)
  3890. return $this;
  3891. foreach($this->stack(1) as $node) {
  3892. if (! $this->is(".$className", $node))
  3893. $node->setAttribute(
  3894. 'class',
  3895. trim($node->getAttribute('class').' '.$className)
  3896. );
  3897. }
  3898. return $this;
  3899. }
  3900. /**
  3901. * Enter description here...
  3902. *
  3903. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3904. */
  3905. public function addClassPHP( $className) {
  3906. foreach($this->stack(1) as $node) {
  3907. $classes = $node->getAttribute('class');
  3908. $newValue = $classes
  3909. ? $classes.' <'.'?php '.$className.' ?'.'>'
  3910. : '<'.'?php '.$className.' ?'.'>';
  3911. $node->setAttribute('class', $newValue);
  3912. }
  3913. return $this;
  3914. }
  3915. /**
  3916. * Enter description here...
  3917. *
  3918. * @param string $className
  3919. * @return bool
  3920. */
  3921. public function hasClass($className) {
  3922. foreach($this->stack(1) as $node) {
  3923. if ( $this->is(".$className", $node))
  3924. return true;
  3925. }
  3926. return false;
  3927. }
  3928. /**
  3929. * Enter description here...
  3930. *
  3931. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3932. */
  3933. public function removeClass($className) {
  3934. foreach($this->stack(1) as $node) {
  3935. $classes = explode( ' ', $node->getAttribute('class'));
  3936. if ( in_array($className, $classes)) {
  3937. $classes = array_diff($classes, array($className));
  3938. if ( $classes )
  3939. $node->setAttribute('class', implode(' ', $classes));
  3940. else
  3941. $node->removeAttribute('class');
  3942. }
  3943. }
  3944. return $this;
  3945. }
  3946. /**
  3947. * Enter description here...
  3948. *
  3949. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3950. */
  3951. public function toggleClass($className) {
  3952. foreach($this->stack(1) as $node) {
  3953. if ( $this->is( $node, '.'.$className ))
  3954. $this->removeClass($className);
  3955. else
  3956. $this->addClass($className);
  3957. }
  3958. return $this;
  3959. }
  3960. /**
  3961. * Proper name without underscore (just ->empty()) also works.
  3962. *
  3963. * Removes all child nodes from the set of matched elements.
  3964. *
  3965. * Example:
  3966. * pq("p")._empty()
  3967. *
  3968. * HTML:
  3969. * <p>Hello, <span>Person</span> <a href="#">and person</a></p>
  3970. *
  3971. * Result:
  3972. * [ <p></p> ]
  3973. *
  3974. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3975. * @access private
  3976. */
  3977. public function _empty() {
  3978. foreach($this->stack(1) as $node) {
  3979. // thx to 'dave at dgx dot cz'
  3980. $node->nodeValue = '';
  3981. }
  3982. return $this;
  3983. }
  3984. /**
  3985. * Enter description here...
  3986. *
  3987. * @param array|string $callback Expects $node as first param, $index as second
  3988. * @param array $scope External variables passed to callback. Use compact('varName1', 'varName2'...) and extract($scope)
  3989. * @param array $arg1 Will ba passed as third and futher args to callback.
  3990. * @param array $arg2 Will ba passed as fourth and futher args to callback, and so on...
  3991. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3992. */
  3993. public function each($callback, $param1 = null, $param2 = null, $param3 = null) {
  3994. $paramStructure = null;
  3995. if (func_num_args() > 1) {
  3996. $paramStructure = func_get_args();
  3997. $paramStructure = array_slice($paramStructure, 1);
  3998. }
  3999. foreach($this->elements as $v)
  4000. phpQuery::callbackRun($callback, array($v), $paramStructure);
  4001. return $this;
  4002. }
  4003. /**
  4004. * Run callback on actual object.
  4005. *
  4006. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4007. */
  4008. public function callback($callback, $param1 = null, $param2 = null, $param3 = null) {
  4009. $params = func_get_args();
  4010. $params[0] = $this;
  4011. phpQuery::callbackRun($callback, $params);
  4012. return $this;
  4013. }
  4014. /**
  4015. * Enter description here...
  4016. *
  4017. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4018. * @todo add $scope and $args as in each() ???
  4019. */
  4020. public function map($callback, $param1 = null, $param2 = null, $param3 = null) {
  4021. // $stack = array();
  4022. //// foreach($this->newInstance() as $node) {
  4023. // foreach($this->newInstance() as $node) {
  4024. // $result = call_user_func($callback, $node);
  4025. // if ($result)
  4026. // $stack[] = $result;
  4027. // }
  4028. $params = func_get_args();
  4029. array_unshift($params, $this->elements);
  4030. return $this->newInstance(
  4031. call_user_func_array(array('phpQuery', 'map'), $params)
  4032. // phpQuery::map($this->elements, $callback)
  4033. );
  4034. }
  4035. /**
  4036. * Enter description here...
  4037. *
  4038. * @param <type> $key
  4039. * @param <type> $value
  4040. */
  4041. public function data($key, $value = null) {
  4042. if (! isset($value)) {
  4043. // TODO? implement specific jQuery behavior od returning parent values
  4044. // is child which we look up doesn't exist
  4045. return phpQuery::data($this->get(0), $key, $value, $this->getDocumentID());
  4046. } else {
  4047. foreach($this as $node)
  4048. phpQuery::data($node, $key, $value, $this->getDocumentID());
  4049. return $this;
  4050. }
  4051. }
  4052. /**
  4053. * Enter description here...
  4054. *
  4055. * @param <type> $key
  4056. */
  4057. public function removeData($key) {
  4058. foreach($this as $node)
  4059. phpQuery::removeData($node, $key, $this->getDocumentID());
  4060. return $this;
  4061. }
  4062. // INTERFACE IMPLEMENTATIONS
  4063. // ITERATOR INTERFACE
  4064. /**
  4065. * @access private
  4066. */
  4067. public function rewind(){
  4068. $this->debug('iterating foreach');
  4069. // phpQuery::selectDocument($this->getDocumentID());
  4070. $this->elementsBackup = $this->elements;
  4071. $this->elementsInterator = $this->elements;
  4072. $this->valid = isset( $this->elements[0] )
  4073. ? 1 : 0;
  4074. // $this->elements = $this->valid
  4075. // ? array($this->elements[0])
  4076. // : array();
  4077. $this->current = 0;
  4078. }
  4079. /**
  4080. * @access private
  4081. */
  4082. public function current(){
  4083. return $this->elementsInterator[ $this->current ];
  4084. }
  4085. /**
  4086. * @access private
  4087. */
  4088. public function key(){
  4089. return $this->current;
  4090. }
  4091. /**
  4092. * Double-function method.
  4093. *
  4094. * First: main iterator interface method.
  4095. * Second: Returning next sibling, alias for _next().
  4096. *
  4097. * Proper functionality is choosed automagicaly.
  4098. *
  4099. * @see phpQueryObject::_next()
  4100. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4101. */
  4102. public function next($cssSelector = null){
  4103. // if ($cssSelector || $this->valid)
  4104. // return $this->_next($cssSelector);
  4105. $this->valid = isset( $this->elementsInterator[ $this->current+1 ] )
  4106. ? true
  4107. : false;
  4108. if (! $this->valid && $this->elementsInterator) {
  4109. $this->elementsInterator = 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(){
  4120. return $this->valid;
  4121. }
  4122. // ITERATOR INTERFACE END
  4123. // ARRAYACCESS INTERFACE
  4124. /**
  4125. * @access private
  4126. */
  4127. public function offsetExists($offset) {
  4128. return $this->find($offset)->size() > 0;
  4129. }
  4130. /**
  4131. * @access private
  4132. */
  4133. public function offsetGet($offset) {
  4134. return $this->find($offset);
  4135. }
  4136. /**
  4137. * @access private
  4138. */
  4139. public function offsetSet($offset, $value) {
  4140. // $this->find($offset)->replaceWith($value);
  4141. $this->find($offset)->html($value);
  4142. }
  4143. /**
  4144. * @access private
  4145. */
  4146. public function offsetUnset($offset) {
  4147. // empty
  4148. throw new Exception("Can't do unset, use array interface only for calling queries and replacing HTML.");
  4149. }
  4150. // ARRAYACCESS INTERFACE END
  4151. /**
  4152. * Returns node's XPath.
  4153. *
  4154. * @param unknown_type $oneNode
  4155. * @return string
  4156. * @TODO use native getNodePath is avaible
  4157. * @access private
  4158. */
  4159. protected function getNodeXpath($oneNode = null, $namespace = null) {
  4160. $return = array();
  4161. $loop = $oneNode
  4162. ? array($oneNode)
  4163. : $this->elements;
  4164. // if ($namespace)
  4165. // $namespace .= ':';
  4166. foreach($loop as $node) {
  4167. if ($node instanceof DOMDOCUMENT) {
  4168. $return[] = '';
  4169. continue;
  4170. }
  4171. $xpath = array();
  4172. while(! ($node instanceof DOMDOCUMENT)) {
  4173. $i = 1;
  4174. $sibling = $node;
  4175. while($sibling->previousSibling) {
  4176. $sibling = $sibling->previousSibling;
  4177. $isElement = $sibling instanceof DOMELEMENT;
  4178. if ($isElement && $sibling->tagName == $node->tagName)
  4179. $i++;
  4180. }
  4181. $xpath[] = $this->isXML()
  4182. ? "*[local-name()='{$node->tagName}'][{$i}]"
  4183. : "{$node->tagName}[{$i}]";
  4184. $node = $node->parentNode;
  4185. }
  4186. $xpath = join('/', array_reverse($xpath));
  4187. $return[] = '/'.$xpath;
  4188. }
  4189. return $oneNode
  4190. ? $return[0]
  4191. : $return;
  4192. }
  4193. // HELPERS
  4194. public function whois($oneNode = null) {
  4195. $return = array();
  4196. $loop = $oneNode
  4197. ? array( $oneNode )
  4198. : $this->elements;
  4199. foreach($loop as $node) {
  4200. if (isset($node->tagName)) {
  4201. $tag = in_array($node->tagName, array('php', 'js'))
  4202. ? strtoupper($node->tagName)
  4203. : $node->tagName;
  4204. $return[] = $tag
  4205. .($node->getAttribute('id')
  4206. ? '#'.$node->getAttribute('id'):'')
  4207. .($node->getAttribute('class')
  4208. ? '.'.join('.', explode(' ', $node->getAttribute('class'))):'')
  4209. .($node->getAttribute('name')
  4210. ? '[name="'.$node->getAttribute('name').'"]':'')
  4211. .($node->getAttribute('value') && strpos($node->getAttribute('value'), '<'.'?php') === false
  4212. ? '[value="'.substr(str_replace("\n", '', $node->getAttribute('value')), 0, 15).'"]':'')
  4213. .($node->getAttribute('value') && strpos($node->getAttribute('value'), '<'.'?php') !== false
  4214. ? '[value=PHP]':'')
  4215. .($node->getAttribute('selected')
  4216. ? '[selected]':'')
  4217. .($node->getAttribute('checked')
  4218. ? '[checked]':'')
  4219. ;
  4220. } else if ($node instanceof DOMTEXT) {
  4221. if (trim($node->textContent))
  4222. $return[] = 'Text:'.substr(str_replace("\n", ' ', $node->textContent), 0, 15);
  4223. } else {
  4224. }
  4225. }
  4226. return $oneNode && isset($return[0])
  4227. ? $return[0]
  4228. : $return;
  4229. }
  4230. /**
  4231. * Dump htmlOuter and preserve chain. Usefull for debugging.
  4232. *
  4233. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4234. *
  4235. */
  4236. public function dump() {
  4237. print 'DUMP #'.(phpQuery::$dumpCount++).' ';
  4238. $debug = phpQuery::$debug;
  4239. phpQuery::$debug = false;
  4240. // print __FILE__.':'.__LINE__."\n";
  4241. var_dump($this->htmlOuter());
  4242. return $this;
  4243. }
  4244. public function dumpWhois() {
  4245. print 'DUMP #'.(phpQuery::$dumpCount++).' ';
  4246. $debug = phpQuery::$debug;
  4247. phpQuery::$debug = false;
  4248. // print __FILE__.':'.__LINE__."\n";
  4249. var_dump('whois', $this->whois());
  4250. phpQuery::$debug = $debug;
  4251. return $this;
  4252. }
  4253. public function dumpLength() {
  4254. print 'DUMP #'.(phpQuery::$dumpCount++).' ';
  4255. $debug = phpQuery::$debug;
  4256. phpQuery::$debug = false;
  4257. // print __FILE__.':'.__LINE__."\n";
  4258. var_dump('length', $this->length());
  4259. phpQuery::$debug = $debug;
  4260. return $this;
  4261. }
  4262. public function dumpTree($html = true, $title = true) {
  4263. $output = $title
  4264. ? 'DUMP #'.(phpQuery::$dumpCount++)." \n" : '';
  4265. $debug = phpQuery::$debug;
  4266. phpQuery::$debug = false;
  4267. foreach($this->stack() as $node)
  4268. $output .= $this->__dumpTree($node);
  4269. phpQuery::$debug = $debug;
  4270. print $html
  4271. ? nl2br(str_replace(' ', '&nbsp;', $output))
  4272. : $output;
  4273. return $this;
  4274. }
  4275. private function __dumpTree($node, $intend = 0) {
  4276. $whois = $this->whois($node);
  4277. $return = '';
  4278. if ($whois)
  4279. $return .= str_repeat(' - ', $intend).$whois."\n";
  4280. if (isset($node->childNodes))
  4281. foreach($node->childNodes as $chNode)
  4282. $return .= $this->__dumpTree($chNode, $intend+1);
  4283. return $return;
  4284. }
  4285. /**
  4286. * Dump htmlOuter and stop script execution. Usefull for debugging.
  4287. *
  4288. */
  4289. public function dumpDie() {
  4290. print __FILE__.':'.__LINE__;
  4291. var_dump($this->htmlOuter());
  4292. die();
  4293. }
  4294. }
  4295. // -- Multibyte Compatibility functions ---------------------------------------
  4296. // http://svn.iphonewebdev.com/lace/lib/mb_compat.php
  4297. /**
  4298. * mb_internal_encoding()
  4299. *
  4300. * Included for mbstring pseudo-compatability.
  4301. */
  4302. if (!function_exists('mb_internal_encoding'))
  4303. {
  4304. function mb_internal_encoding($enc) {return true; }
  4305. }
  4306. /**
  4307. * mb_regex_encoding()
  4308. *
  4309. * Included for mbstring pseudo-compatability.
  4310. */
  4311. if (!function_exists('mb_regex_encoding'))
  4312. {
  4313. function mb_regex_encoding($enc) {return true; }
  4314. }
  4315. /**
  4316. * mb_strlen()
  4317. *
  4318. * Included for mbstring pseudo-compatability.
  4319. */
  4320. if (!function_exists('mb_strlen'))
  4321. {
  4322. function mb_strlen($str)
  4323. {
  4324. return strlen($str);
  4325. }
  4326. }
  4327. /**
  4328. * mb_strpos()
  4329. *
  4330. * Included for mbstring pseudo-compatability.
  4331. */
  4332. if (!function_exists('mb_strpos'))
  4333. {
  4334. function mb_strpos($haystack, $needle, $offset=0)
  4335. {
  4336. return strpos($haystack, $needle, $offset);
  4337. }
  4338. }
  4339. /**
  4340. * mb_stripos()
  4341. *
  4342. * Included for mbstring pseudo-compatability.
  4343. */
  4344. if (!function_exists('mb_stripos'))
  4345. {
  4346. function mb_stripos($haystack, $needle, $offset=0)
  4347. {
  4348. return stripos($haystack, $needle, $offset);
  4349. }
  4350. }
  4351. /**
  4352. * mb_substr()
  4353. *
  4354. * Included for mbstring pseudo-compatability.
  4355. */
  4356. if (!function_exists('mb_substr'))
  4357. {
  4358. function mb_substr($str, $start, $length=0)
  4359. {
  4360. return substr($str, $start, $length);
  4361. }
  4362. }
  4363. /**
  4364. * mb_substr_count()
  4365. *
  4366. * Included for mbstring pseudo-compatability.
  4367. */
  4368. if (!function_exists('mb_substr_count'))
  4369. {
  4370. function mb_substr_count($haystack, $needle)
  4371. {
  4372. return substr_count($haystack, $needle);
  4373. }
  4374. }
  4375. /**
  4376. * Static namespace for phpQuery functions.
  4377. *
  4378. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  4379. * @package phpQuery
  4380. */
  4381. abstract class phpQuery {
  4382. /**
  4383. * XXX: Workaround for mbstring problems
  4384. *
  4385. * @var bool
  4386. */
  4387. public static $mbstringSupport = true;
  4388. public static $debug = false;
  4389. public static $documents = array();
  4390. public static $defaultDocumentID = null;
  4391. // public static $defaultDoctype = 'html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"';
  4392. /**
  4393. * Applies only to HTML.
  4394. *
  4395. * @var unknown_type
  4396. */
  4397. public static $defaultDoctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  4398. "http://www.w3.org/TR/html4/loose.dtd">';
  4399. public static $defaultCharset = 'UTF-8';
  4400. /**
  4401. * Static namespace for plugins.
  4402. *
  4403. * @var object
  4404. */
  4405. public static $plugins = array();
  4406. /**
  4407. * List of loaded plugins.
  4408. *
  4409. * @var unknown_type
  4410. */
  4411. public static $pluginsLoaded = array();
  4412. public static $pluginsMethods = array();
  4413. public static $pluginsStaticMethods = array();
  4414. public static $extendMethods = array();
  4415. /**
  4416. * @TODO implement
  4417. */
  4418. public static $extendStaticMethods = array();
  4419. /**
  4420. * Hosts allowed for AJAX connections.
  4421. * Dot '.' means $_SERVER['HTTP_HOST'] (if any).
  4422. *
  4423. * @var array
  4424. */
  4425. public static $ajaxAllowedHosts = array(
  4426. '.'
  4427. );
  4428. /**
  4429. * AJAX settings.
  4430. *
  4431. * @var array
  4432. * XXX should it be static or not ?
  4433. */
  4434. public static $ajaxSettings = array(
  4435. 'url' => '',//TODO
  4436. 'global' => true,
  4437. 'type' => "GET",
  4438. 'timeout' => null,
  4439. 'contentType' => "application/x-www-form-urlencoded",
  4440. 'processData' => true,
  4441. // 'async' => true,
  4442. 'data' => null,
  4443. 'username' => null,
  4444. 'password' => null,
  4445. 'accepts' => array(
  4446. 'xml' => "application/xml, text/xml",
  4447. 'html' => "text/html",
  4448. 'script' => "text/javascript, application/javascript",
  4449. 'json' => "application/json, text/javascript",
  4450. 'text' => "text/plain",
  4451. '_default' => "*/*"
  4452. )
  4453. );
  4454. public static $lastModified = null;
  4455. public static $active = 0;
  4456. public static $dumpCount = 0;
  4457. /**
  4458. * Multi-purpose function.
  4459. * Use pq() as shortcut.
  4460. *
  4461. * In below examples, $pq is any result of pq(); function.
  4462. *
  4463. * 1. Import markup into existing document (without any attaching):
  4464. * - Import into selected document:
  4465. * pq('<div/>') // DOESNT accept text nodes at beginning of input string !
  4466. * - Import into document with ID from $pq->getDocumentID():
  4467. * pq('<div/>', $pq->getDocumentID())
  4468. * - Import into same document as DOMNode belongs to:
  4469. * pq('<div/>', DOMNode)
  4470. * - Import into document from phpQuery object:
  4471. * pq('<div/>', $pq)
  4472. *
  4473. * 2. Run query:
  4474. * - Run query on last selected document:
  4475. * pq('div.myClass')
  4476. * - Run query on document with ID from $pq->getDocumentID():
  4477. * pq('div.myClass', $pq->getDocumentID())
  4478. * - Run query on same document as DOMNode belongs to and use node(s)as root for query:
  4479. * pq('div.myClass', DOMNode)
  4480. * - Run query on document from phpQuery object
  4481. * and use object's stack as root node(s) for query:
  4482. * pq('div.myClass', $pq)
  4483. *
  4484. * @param string|DOMNode|DOMNodeList|array $arg1 HTML markup, CSS Selector, DOMNode or array of DOMNodes
  4485. * @param string|phpQueryObject|DOMNode $context DOM ID from $pq->getDocumentID(), phpQuery object (determines also query root) or DOMNode (determines also query root)
  4486. *
  4487. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery|QueryTemplatesPhpQuery|false
  4488. * phpQuery object or false in case of error.
  4489. */
  4490. public static function pq($arg1, $context = null) {
  4491. if ($arg1 instanceof DOMNODE && ! isset($context)) {
  4492. foreach(phpQuery::$documents as $documentWrapper) {
  4493. $compare = $arg1 instanceof DOMDocument
  4494. ? $arg1 : $arg1->ownerDocument;
  4495. if ($documentWrapper->document->isSameNode($compare))
  4496. $context = $documentWrapper->id;
  4497. }
  4498. }
  4499. if (! $context) {
  4500. $domId = self::$defaultDocumentID;
  4501. if (! $domId)
  4502. throw new Exception("Can't use last created DOM, because there isn't any. Use phpQuery::newDocument() first.");
  4503. // } else if (is_object($context) && ($context instanceof PHPQUERY || is_subclass_of($context, 'phpQueryObject')))
  4504. } else if (is_object($context) && $context instanceof phpQueryObject)
  4505. $domId = $context->getDocumentID();
  4506. else if ($context instanceof DOMDOCUMENT) {
  4507. $domId = self::getDocumentID($context);
  4508. if (! $domId) {
  4509. //throw new Exception('Orphaned DOMDocument');
  4510. $domId = self::newDocument($context)->getDocumentID();
  4511. }
  4512. } else if ($context instanceof DOMNODE) {
  4513. $domId = self::getDocumentID($context);
  4514. if (! $domId) {
  4515. throw new Exception('Orphaned DOMNode');
  4516. // $domId = self::newDocument($context->ownerDocument);
  4517. }
  4518. } else
  4519. $domId = $context;
  4520. if ($arg1 instanceof phpQueryObject) {
  4521. // if (is_object($arg1) && (get_class($arg1) == 'phpQueryObject' || $arg1 instanceof PHPQUERY || is_subclass_of($arg1, 'phpQueryObject'))) {
  4522. /**
  4523. * Return $arg1 or import $arg1 stack if document differs:
  4524. * pq(pq('<div/>'))
  4525. */
  4526. if ($arg1->getDocumentID() == $domId)
  4527. return $arg1;
  4528. $class = get_class($arg1);
  4529. // support inheritance by passing old object to overloaded constructor
  4530. $phpQuery = $class != 'phpQuery'
  4531. ? new $class($arg1, $domId)
  4532. : new phpQueryObject($domId);
  4533. $phpQuery->elements = array();
  4534. foreach($arg1->elements as $node)
  4535. $phpQuery->elements[] = $phpQuery->document->importNode($node, true);
  4536. return $phpQuery;
  4537. } else if ($arg1 instanceof DOMNODE || (is_array($arg1) && isset($arg1[0]) && $arg1[0] instanceof DOMNODE)) {
  4538. /*
  4539. * Wrap DOM nodes with phpQuery object, import into document when needed:
  4540. * pq(array($domNode1, $domNode2))
  4541. */
  4542. $phpQuery = new phpQueryObject($domId);
  4543. if (!($arg1 instanceof DOMNODELIST) && ! is_array($arg1))
  4544. $arg1 = array($arg1);
  4545. $phpQuery->elements = array();
  4546. foreach($arg1 as $node) {
  4547. $sameDocument = $node->ownerDocument instanceof DOMDOCUMENT
  4548. && ! $node->ownerDocument->isSameNode($phpQuery->document);
  4549. $phpQuery->elements[] = $sameDocument
  4550. ? $phpQuery->document->importNode($node, true)
  4551. : $node;
  4552. }
  4553. return $phpQuery;
  4554. } else if (self::isMarkup($arg1)) {
  4555. /**
  4556. * Import HTML:
  4557. * pq('<div/>')
  4558. */
  4559. $phpQuery = new phpQueryObject($domId);
  4560. return $phpQuery->newInstance(
  4561. $phpQuery->documentWrapper->import($arg1)
  4562. );
  4563. } else {
  4564. /**
  4565. * Run CSS query:
  4566. * pq('div.myClass')
  4567. */
  4568. $phpQuery = new phpQueryObject($domId);
  4569. // if ($context && ($context instanceof PHPQUERY || is_subclass_of($context, 'phpQueryObject')))
  4570. if ($context && $context instanceof phpQueryObject)
  4571. $phpQuery->elements = $context->elements;
  4572. else if ($context && $context instanceof DOMNODELIST) {
  4573. $phpQuery->elements = array();
  4574. foreach($context as $node)
  4575. $phpQuery->elements[] = $node;
  4576. } else if ($context && $context instanceof DOMNODE)
  4577. $phpQuery->elements = array($context);
  4578. return $phpQuery->find($arg1);
  4579. }
  4580. }
  4581. /**
  4582. * Sets default document to $id. Document has to be loaded prior
  4583. * to using this method.
  4584. * $id can be retrived via getDocumentID() or getDocumentIDRef().
  4585. *
  4586. * @param unknown_type $id
  4587. */
  4588. public static function selectDocument($id) {
  4589. $id = self::getDocumentID($id);
  4590. self::debug("Selecting document '$id' as default one");
  4591. self::$defaultDocumentID = self::getDocumentID($id);
  4592. }
  4593. /**
  4594. * Returns document with id $id or last used as phpQueryObject.
  4595. * $id can be retrived via getDocumentID() or getDocumentIDRef().
  4596. * Chainable.
  4597. *
  4598. * @see phpQuery::selectDocument()
  4599. * @param unknown_type $id
  4600. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4601. */
  4602. public static function getDocument($id = null) {
  4603. if ($id)
  4604. phpQuery::selectDocument($id);
  4605. else
  4606. $id = phpQuery::$defaultDocumentID;
  4607. return new phpQueryObject($id);
  4608. }
  4609. /**
  4610. * Creates new document from markup.
  4611. * Chainable.
  4612. *
  4613. * @param unknown_type $markup
  4614. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4615. */
  4616. public static function newDocument($markup = null, $contentType = null) {
  4617. if (! $markup)
  4618. $markup = '';
  4619. $documentID = phpQuery::createDocumentWrapper($markup, $contentType);
  4620. return new phpQueryObject($documentID);
  4621. }
  4622. /**
  4623. * Creates new document from markup.
  4624. * Chainable.
  4625. *
  4626. * @param unknown_type $markup
  4627. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4628. */
  4629. public static function newDocumentHTML($markup = null, $charset = null) {
  4630. $contentType = $charset
  4631. ? ";charset=$charset"
  4632. : '';
  4633. return self::newDocument($markup, "text/html{$contentType}");
  4634. }
  4635. /**
  4636. * Creates new document from markup.
  4637. * Chainable.
  4638. *
  4639. * @param unknown_type $markup
  4640. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4641. */
  4642. public static function newDocumentXML($markup = null, $charset = null) {
  4643. $contentType = $charset
  4644. ? ";charset=$charset"
  4645. : '';
  4646. return self::newDocument($markup, "text/xml{$contentType}");
  4647. }
  4648. /**
  4649. * Creates new document from markup.
  4650. * Chainable.
  4651. *
  4652. * @param unknown_type $markup
  4653. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4654. */
  4655. public static function newDocumentXHTML($markup = null, $charset = null) {
  4656. $contentType = $charset
  4657. ? ";charset=$charset"
  4658. : '';
  4659. return self::newDocument($markup, "application/xhtml+xml{$contentType}");
  4660. }
  4661. /**
  4662. * Creates new document from markup.
  4663. * Chainable.
  4664. *
  4665. * @param unknown_type $markup
  4666. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4667. */
  4668. public static function newDocumentPHP($markup = null, $contentType = "text/html") {
  4669. // TODO pass charset to phpToMarkup if possible (use DOMDocumentWrapper function)
  4670. $markup = phpQuery::phpToMarkup($markup, self::$defaultCharset);
  4671. return self::newDocument($markup, $contentType);
  4672. }
  4673. public static function phpToMarkup($php, $charset = 'utf-8') {
  4674. $regexes = array(
  4675. '@(<(?!\\?)(?:[^>]|\\?>)+\\w+\\s*=\\s*)(\')([^\']*)<'.'?php?(.*?)(?:\\?>)([^\']*)\'@s',
  4676. '@(<(?!\\?)(?:[^>]|\\?>)+\\w+\\s*=\\s*)(")([^"]*)<'.'?php?(.*?)(?:\\?>)([^"]*)"@s',
  4677. );
  4678. foreach($regexes as $regex)
  4679. while (preg_match($regex, $php, $matches)) {
  4680. $php = preg_replace_callback(
  4681. $regex,
  4682. // create_function('$m, $charset = "'.$charset.'"',
  4683. // 'return $m[1].$m[2]
  4684. // .htmlspecialchars("<"."?php".$m[4]."?".">", ENT_QUOTES|ENT_NOQUOTES, $charset)
  4685. // .$m[5].$m[2];'
  4686. // ),
  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($php, $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. // create_function('$m',
  4719. // 'return "<'.'?php ".htmlspecialchars_decode($m[1])." ?'.'>";'
  4720. // ),
  4721. array('phpQuery', '_markupToPHPCallback'),
  4722. $content
  4723. );
  4724. /* <node attr='< ?php ? >'> extra space added to save highlighters */
  4725. $regexes = array(
  4726. '@(<(?!\\?)(?:[^>]|\\?>)+\\w+\\s*=\\s*)(\')([^\']*)(?:&lt;|%3C)\\?(?:php)?(.*?)(?:\\?(?:&gt;|%3E))([^\']*)\'@s',
  4727. '@(<(?!\\?)(?:[^>]|\\?>)+\\w+\\s*=\\s*)(")([^"]*)(?:&lt;|%3C)\\?(?:php)?(.*?)(?:\\?(?:&gt;|%3E))([^"]*)"@s',
  4728. );
  4729. foreach($regexes as $regex)
  4730. while (preg_match($regex, $content))
  4731. $content = preg_replace_callback(
  4732. $regex,
  4733. create_function('$m',
  4734. 'return $m[1].$m[2].$m[3]."<?php "
  4735. .str_replace(
  4736. array("%20", "%3E", "%09", "&#10;", "&#9;", "%7B", "%24", "%7D", "%22", "%5B", "%5D"),
  4737. array(" ", ">", " ", "\n", " ", "{", "$", "}", \'"\', "[", "]"),
  4738. htmlspecialchars_decode($m[4])
  4739. )
  4740. ." ?>".$m[5].$m[2];'
  4741. ),
  4742. $content
  4743. );
  4744. return $content;
  4745. }
  4746. /**
  4747. * Creates new document from file $file.
  4748. * Chainable.
  4749. *
  4750. * @param string $file URLs allowed. See File wrapper page at php.net for more supported sources.
  4751. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4752. */
  4753. public static function newDocumentFile($file, $contentType = null) {
  4754. $documentID = self::createDocumentWrapper(
  4755. file_get_contents($file), $contentType
  4756. );
  4757. return new phpQueryObject($documentID);
  4758. }
  4759. /**
  4760. * Creates new document from markup.
  4761. * Chainable.
  4762. *
  4763. * @param unknown_type $markup
  4764. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4765. */
  4766. public static function newDocumentFileHTML($file, $charset = null) {
  4767. $contentType = $charset
  4768. ? ";charset=$charset"
  4769. : '';
  4770. return self::newDocumentFile($file, "text/html{$contentType}");
  4771. }
  4772. /**
  4773. * Creates new document from markup.
  4774. * Chainable.
  4775. *
  4776. * @param unknown_type $markup
  4777. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4778. */
  4779. public static function newDocumentFileXML($file, $charset = null) {
  4780. $contentType = $charset
  4781. ? ";charset=$charset"
  4782. : '';
  4783. return self::newDocumentFile($file, "text/xml{$contentType}");
  4784. }
  4785. /**
  4786. * Creates new document from markup.
  4787. * Chainable.
  4788. *
  4789. * @param unknown_type $markup
  4790. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4791. */
  4792. public static function newDocumentFileXHTML($file, $charset = null) {
  4793. $contentType = $charset
  4794. ? ";charset=$charset"
  4795. : '';
  4796. return self::newDocumentFile($file, "application/xhtml+xml{$contentType}");
  4797. }
  4798. /**
  4799. * Creates new document from markup.
  4800. * Chainable.
  4801. *
  4802. * @param unknown_type $markup
  4803. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4804. */
  4805. public static function newDocumentFilePHP($file, $contentType = null) {
  4806. return self::newDocumentPHP(file_get_contents($file), $contentType);
  4807. }
  4808. /**
  4809. * Reuses existing DOMDocument object.
  4810. * Chainable.
  4811. *
  4812. * @param $document DOMDocument
  4813. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4814. * @TODO support DOMDocument
  4815. */
  4816. public static function loadDocument($document) {
  4817. // TODO
  4818. die('TODO loadDocument');
  4819. }
  4820. /**
  4821. * Enter description here...
  4822. *
  4823. * @param unknown_type $html
  4824. * @param unknown_type $domId
  4825. * @return unknown New DOM ID
  4826. * @todo support PHP tags in input
  4827. * @todo support passing DOMDocument object from self::loadDocument
  4828. */
  4829. protected static function createDocumentWrapper($html, $contentType = null, $documentID = null) {
  4830. if (function_exists('domxml_open_mem'))
  4831. throw new Exception("Old PHP4 DOM XML extension detected. phpQuery won't work until this extension is enabled.");
  4832. // $id = $documentID
  4833. // ? $documentID
  4834. // : md5(microtime());
  4835. $document = null;
  4836. if ($html instanceof DOMDOCUMENT) {
  4837. if (self::getDocumentID($html)) {
  4838. // document already exists in phpQuery::$documents, make a copy
  4839. $document = clone $html;
  4840. } else {
  4841. // new document, add it to phpQuery::$documents
  4842. $wrapper = new DOMDocumentWrapper($html, $contentType, $documentID);
  4843. }
  4844. } else {
  4845. $wrapper = new DOMDocumentWrapper($html, $contentType, $documentID);
  4846. }
  4847. // $wrapper->id = $id;
  4848. // bind document
  4849. phpQuery::$documents[$wrapper->id] = $wrapper;
  4850. // remember last loaded document
  4851. phpQuery::selectDocument($wrapper->id);
  4852. return $wrapper->id;
  4853. }
  4854. /**
  4855. * Extend class namespace.
  4856. *
  4857. * @param string|array $target
  4858. * @param array $source
  4859. * @TODO support string $source
  4860. * @return unknown_type
  4861. */
  4862. public static function extend($target, $source) {
  4863. switch($target) {
  4864. case 'phpQueryObject':
  4865. $targetRef = &self::$extendMethods;
  4866. $targetRef2 = &self::$pluginsMethods;
  4867. break;
  4868. case 'phpQuery':
  4869. $targetRef = &self::$extendStaticMethods;
  4870. $targetRef2 = &self::$pluginsStaticMethods;
  4871. break;
  4872. default:
  4873. throw new Exception("Unsupported \$target type");
  4874. }
  4875. if (is_string($source))
  4876. $source = array($source => $source);
  4877. foreach($source as $method => $callback) {
  4878. if (isset($targetRef[$method])) {
  4879. // throw new Exception
  4880. self::debug("Duplicate method '{$method}', can\'t extend '{$target}'");
  4881. continue;
  4882. }
  4883. if (isset($targetRef2[$method])) {
  4884. // throw new Exception
  4885. self::debug("Duplicate method '{$method}' from plugin '{$targetRef2[$method]}',"
  4886. ." can\'t extend '{$target}'");
  4887. continue;
  4888. }
  4889. $targetRef[$method] = $callback;
  4890. }
  4891. return true;
  4892. }
  4893. /**
  4894. * Extend phpQuery with $class from $file.
  4895. *
  4896. * @param string $class Extending class name. Real class name can be prepended phpQuery_.
  4897. * @param string $file Filename to include. Defaults to "{$class}.php".
  4898. */
  4899. public static function plugin($class, $file = null) {
  4900. // TODO $class checked agains phpQuery_$class
  4901. // if (strpos($class, 'phpQuery') === 0)
  4902. // $class = substr($class, 8);
  4903. if (in_array($class, self::$pluginsLoaded))
  4904. return true;
  4905. if (! $file)
  4906. $file = $class.'.php';
  4907. $objectClassExists = class_exists('phpQueryObjectPlugin_'.$class);
  4908. $staticClassExists = class_exists('phpQueryPlugin_'.$class);
  4909. if (! $objectClassExists && ! $staticClassExists)
  4910. require_once($file);
  4911. self::$pluginsLoaded[] = $class;
  4912. // static methods
  4913. if (class_exists('phpQueryPlugin_'.$class)) {
  4914. $realClass = 'phpQueryPlugin_'.$class;
  4915. $vars = get_class_vars($realClass);
  4916. $loop = isset($vars['phpQueryMethods'])
  4917. && ! is_null($vars['phpQueryMethods'])
  4918. ? $vars['phpQueryMethods']
  4919. : get_class_methods($realClass);
  4920. foreach($loop as $method) {
  4921. if ($method == '__initialize')
  4922. continue;
  4923. if (! is_callable(array($realClass, $method)))
  4924. continue;
  4925. if (isset(self::$pluginsStaticMethods[$method])) {
  4926. throw new Exception("Duplicate method '{$method}' from plugin '{$c}' conflicts with same method from plugin '".self::$pluginsStaticMethods[$method]."'");
  4927. return;
  4928. }
  4929. self::$pluginsStaticMethods[$method] = $class;
  4930. }
  4931. if (method_exists($realClass, '__initialize'))
  4932. call_user_func_array(array($realClass, '__initialize'), array());
  4933. }
  4934. // object methods
  4935. if (class_exists('phpQueryObjectPlugin_'.$class)) {
  4936. $realClass = 'phpQueryObjectPlugin_'.$class;
  4937. $vars = get_class_vars($realClass);
  4938. $loop = isset($vars['phpQueryMethods'])
  4939. && ! is_null($vars['phpQueryMethods'])
  4940. ? $vars['phpQueryMethods']
  4941. : get_class_methods($realClass);
  4942. foreach($loop as $method) {
  4943. if (! is_callable(array($realClass, $method)))
  4944. continue;
  4945. if (isset(self::$pluginsMethods[$method])) {
  4946. throw new Exception("Duplicate method '{$method}' from plugin '{$c}' conflicts with same method from plugin '".self::$pluginsMethods[$method]."'");
  4947. continue;
  4948. }
  4949. self::$pluginsMethods[$method] = $class;
  4950. }
  4951. }
  4952. return true;
  4953. }
  4954. /**
  4955. * Unloades all or specified document from memory.
  4956. *
  4957. * @param mixed $documentID @see phpQuery::getDocumentID() for supported types.
  4958. */
  4959. public static function unloadDocuments($id = null) {
  4960. if (isset($id)) {
  4961. if ($id = self::getDocumentID($id))
  4962. unset(phpQuery::$documents[$id]);
  4963. } else {
  4964. foreach(phpQuery::$documents as $k => $v) {
  4965. unset(phpQuery::$documents[$k]);
  4966. }
  4967. }
  4968. }
  4969. /**
  4970. * Parses phpQuery object or HTML result against PHP tags and makes them active.
  4971. *
  4972. * @param phpQuery|string $content
  4973. * @deprecated
  4974. * @return string
  4975. */
  4976. public static function unsafePHPTags($content) {
  4977. return self::markupToPHP($content);
  4978. }
  4979. public static function DOMNodeListToArray($DOMNodeList) {
  4980. $array = array();
  4981. if (! $DOMNodeList)
  4982. return $array;
  4983. foreach($DOMNodeList as $node)
  4984. $array[] = $node;
  4985. return $array;
  4986. }
  4987. /**
  4988. * Checks if $input is HTML string, which has to start with '<'.
  4989. *
  4990. * @deprecated
  4991. * @param String $input
  4992. * @return Bool
  4993. * @todo still used ?
  4994. */
  4995. public static function isMarkup($input) {
  4996. return ! is_array($input) && substr(trim($input), 0, 1) == '<';
  4997. }
  4998. public static function debug($text) {
  4999. if (self::$debug)
  5000. print var_dump($text);
  5001. }
  5002. /**
  5003. * Make an AJAX request.
  5004. *
  5005. * @param array See $options http://docs.jquery.com/Ajax/jQuery.ajax#toptions
  5006. * Additional options are:
  5007. * 'document' - document for global events, @see phpQuery::getDocumentID()
  5008. * 'referer' - implemented
  5009. * 'requested_with' - TODO; not implemented (X-Requested-With)
  5010. * @return Zend_Http_Client
  5011. * @link http://docs.jquery.com/Ajax/jQuery.ajax
  5012. *
  5013. * @TODO $options['cache']
  5014. * @TODO $options['processData']
  5015. * @TODO $options['xhr']
  5016. * @TODO $options['data'] as string
  5017. * @TODO XHR interface
  5018. */
  5019. public static function ajax($options = array(), $xhr = null) {
  5020. $options = array_merge(
  5021. self::$ajaxSettings, $options
  5022. );
  5023. $documentID = isset($options['document'])
  5024. ? self::getDocumentID($options['document'])
  5025. : null;
  5026. if ($xhr) {
  5027. // reuse existing XHR object, but clean it up
  5028. $client = $xhr;
  5029. // $client->setParameterPost(null);
  5030. // $client->setParameterGet(null);
  5031. $client->setAuth(false);
  5032. $client->setHeaders("If-Modified-Since", null);
  5033. $client->setHeaders("Referer", null);
  5034. $client->resetParameters();
  5035. } else {
  5036. // create new XHR object
  5037. require_once('Zend/Http/Client.php');
  5038. $client = new Zend_Http_Client();
  5039. $client->setCookieJar();
  5040. }
  5041. if (isset($options['timeout']))
  5042. $client->setConfig(array(
  5043. 'timeout' => $options['timeout'],
  5044. ));
  5045. // 'maxredirects' => 0,
  5046. foreach(self::$ajaxAllowedHosts as $k => $host)
  5047. if ($host == '.' && isset($_SERVER['HTTP_HOST']))
  5048. self::$ajaxAllowedHosts[$k] = $_SERVER['HTTP_HOST'];
  5049. $host = parse_url($options['url'], PHP_URL_HOST);
  5050. if (! in_array($host, self::$ajaxAllowedHosts)) {
  5051. throw new Exception("Request not permitted, host '$host' not present in "
  5052. ."phpQuery::\$ajaxAllowedHosts");
  5053. }
  5054. // JSONP
  5055. $jsre = "/=\\?(&|$)/";
  5056. if (isset($options['dataType']) && $options['dataType'] == 'jsonp') {
  5057. $jsonpCallbackParam = $options['jsonp']
  5058. ? $options['jsonp'] : 'callback';
  5059. if (strtolower($options['type']) == 'get') {
  5060. if (! preg_match($jsre, $options['url'])) {
  5061. $sep = strpos($options['url'], '?')
  5062. ? '&' : '?';
  5063. $options['url'] .= "$sep$jsonpCallbackParam=?";
  5064. }
  5065. } else if ($options['data']) {
  5066. $jsonp = false;
  5067. foreach($options['data'] as $n => $v) {
  5068. if ($v == '?')
  5069. $jsonp = true;
  5070. }
  5071. if (! $jsonp) {
  5072. $options['data'][$jsonpCallbackParam] = '?';
  5073. }
  5074. }
  5075. $options['dataType'] = 'json';
  5076. }
  5077. if (isset($options['dataType']) && $options['dataType'] == 'json') {
  5078. $jsonpCallback = 'json_'.md5(microtime());
  5079. $jsonpData = $jsonpUrl = false;
  5080. if ($options['data']) {
  5081. foreach($options['data'] as $n => $v) {
  5082. if ($v == '?')
  5083. $jsonpData = $n;
  5084. }
  5085. }
  5086. if (preg_match($jsre, $options['url']))
  5087. $jsonpUrl = true;
  5088. if ($jsonpData !== false || $jsonpUrl) {
  5089. // remember callback name for httpData()
  5090. $options['_jsonp'] = $jsonpCallback;
  5091. if ($jsonpData !== false)
  5092. $options['data'][$jsonpData] = $jsonpCallback;
  5093. if ($jsonpUrl)
  5094. $options['url'] = preg_replace($jsre, "=$jsonpCallback\\1", $options['url']);
  5095. }
  5096. }
  5097. $client->setUri($options['url']);
  5098. $client->setMethod(strtoupper($options['type']));
  5099. if (isset($options['referer']) && $options['referer'])
  5100. $client->setHeaders('Referer', $options['referer']);
  5101. $client->setHeaders(array(
  5102. // 'content-type' => $options['contentType'],
  5103. 'User-Agent' => 'Mozilla/5.0 (X11; U; Linux x86; en-US; rv:1.9.0.5) Gecko'
  5104. .'/2008122010 Firefox/3.0.5',
  5105. // TODO custom charset
  5106. 'Accept-Charset' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  5107. // 'Connection' => 'keep-alive',
  5108. // 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  5109. 'Accept-Language' => 'en-us,en;q=0.5',
  5110. ));
  5111. if ($options['username'])
  5112. $client->setAuth($options['username'], $options['password']);
  5113. if (isset($options['ifModified']) && $options['ifModified'])
  5114. $client->setHeaders("If-Modified-Since",
  5115. self::$lastModified
  5116. ? self::$lastModified
  5117. : "Thu, 01 Jan 1970 00:00:00 GMT"
  5118. );
  5119. $client->setHeaders("Accept",
  5120. isset($options['dataType'])
  5121. && isset(self::$ajaxSettings['accepts'][ $options['dataType'] ])
  5122. ? self::$ajaxSettings['accepts'][ $options['dataType'] ].", */*"
  5123. : self::$ajaxSettings['accepts']['_default']
  5124. );
  5125. // TODO $options['processData']
  5126. if ($options['data'] instanceof phpQueryObject) {
  5127. $serialized = $options['data']->serializeArray($options['data']);
  5128. $options['data'] = array();
  5129. foreach($serialized as $r)
  5130. $options['data'][ $r['name'] ] = $r['value'];
  5131. }
  5132. if (strtolower($options['type']) == 'get') {
  5133. $client->setParameterGet($options['data']);
  5134. } else if (strtolower($options['type']) == 'post') {
  5135. $client->setEncType($options['contentType']);
  5136. $client->setParameterPost($options['data']);
  5137. }
  5138. if (self::$active == 0 && $options['global'])
  5139. phpQueryEvents::trigger($documentID, 'ajaxStart');
  5140. self::$active++;
  5141. // beforeSend callback
  5142. if (isset($options['beforeSend']) && $options['beforeSend'])
  5143. phpQuery::callbackRun($options['beforeSend'], array($client));
  5144. // ajaxSend event
  5145. if ($options['global'])
  5146. phpQueryEvents::trigger($documentID, 'ajaxSend', array($client, $options));
  5147. if (phpQuery::$debug) {
  5148. self::debug("{$options['type']}: {$options['url']}\n");
  5149. self::debug("Options: <pre>".var_export($options, true)."</pre>\n");
  5150. // if ($client->getCookieJar())
  5151. // self::debug("Cookies: <pre>".var_export($client->getCookieJar()->getMatchingCookies($options['url']), true)."</pre>\n");
  5152. }
  5153. // request
  5154. $response = $client->request();
  5155. if (phpQuery::$debug) {
  5156. self::debug('Status: '.$response->getStatus().' / '.$response->getMessage());
  5157. self::debug($client->getLastRequest());
  5158. self::debug($response->getHeaders());
  5159. }
  5160. if ($response->isSuccessful()) {
  5161. // XXX tempolary
  5162. self::$lastModified = $response->getHeader('Last-Modified');
  5163. $data = self::httpData($response->getBody(), $options['dataType'], $options);
  5164. if (isset($options['success']) && $options['success'])
  5165. phpQuery::callbackRun($options['success'], array($data, $response->getStatus(), $options));
  5166. if ($options['global'])
  5167. phpQueryEvents::trigger($documentID, 'ajaxSuccess', array($client, $options));
  5168. } else {
  5169. if (isset($options['error']) && $options['error'])
  5170. phpQuery::callbackRun($options['error'], array($client, $response->getStatus(), $response->getMessage()));
  5171. if ($options['global'])
  5172. phpQueryEvents::trigger($documentID, 'ajaxError', array($client, /*$response->getStatus(),*/$response->getMessage(), $options));
  5173. }
  5174. if (isset($options['complete']) && $options['complete'])
  5175. phpQuery::callbackRun($options['complete'], array($client, $response->getStatus()));
  5176. if ($options['global'])
  5177. phpQueryEvents::trigger($documentID, 'ajaxComplete', array($client, $options));
  5178. if ($options['global'] && ! --self::$active)
  5179. phpQueryEvents::trigger($documentID, 'ajaxStop');
  5180. return $client;
  5181. // if (is_null($domId))
  5182. // $domId = self::$defaultDocumentID ? self::$defaultDocumentID : false;
  5183. // return new phpQueryAjaxResponse($response, $domId);
  5184. }
  5185. protected static function httpData($data, $type, $options) {
  5186. if (isset($options['dataFilter']) && $options['dataFilter'])
  5187. $data = self::callbackRun($options['dataFilter'], array($data, $type));
  5188. if (is_string($data)) {
  5189. if ($type == "json") {
  5190. if (isset($options['_jsonp']) && $options['_jsonp']) {
  5191. $data = preg_replace('/^\s*\w+\((.*)\)\s*$/s', '$1', $data);
  5192. }
  5193. $data = self::parseJSON($data);
  5194. }
  5195. }
  5196. return $data;
  5197. }
  5198. /**
  5199. * Enter description here...
  5200. *
  5201. * @param array|phpQuery $data
  5202. *
  5203. */
  5204. public static function param($data) {
  5205. return http_build_query($data, null, '&');
  5206. }
  5207. public static function get($url, $data = null, $callback = null, $type = null) {
  5208. if (!is_array($data)) {
  5209. $callback = $data;
  5210. $data = null;
  5211. }
  5212. // TODO some array_values on this shit
  5213. return phpQuery::ajax(array(
  5214. 'type' => 'GET',
  5215. 'url' => $url,
  5216. 'data' => $data,
  5217. 'success' => $callback,
  5218. 'dataType' => $type,
  5219. ));
  5220. }
  5221. public static function post($url, $data = null, $callback = null, $type = null) {
  5222. if (!is_array($data)) {
  5223. $callback = $data;
  5224. $data = null;
  5225. }
  5226. return phpQuery::ajax(array(
  5227. 'type' => 'POST',
  5228. 'url' => $url,
  5229. 'data' => $data,
  5230. 'success' => $callback,
  5231. 'dataType' => $type,
  5232. ));
  5233. }
  5234. public static function getJSON($url, $data = null, $callback = null) {
  5235. if (!is_array($data)) {
  5236. $callback = $data;
  5237. $data = null;
  5238. }
  5239. // TODO some array_values on this shit
  5240. return phpQuery::ajax(array(
  5241. 'type' => 'GET',
  5242. 'url' => $url,
  5243. 'data' => $data,
  5244. 'success' => $callback,
  5245. 'dataType' => 'json',
  5246. ));
  5247. }
  5248. public static function ajaxSetup($options) {
  5249. self::$ajaxSettings = array_merge(
  5250. self::$ajaxSettings,
  5251. $options
  5252. );
  5253. }
  5254. public static function ajaxAllowHost($host1, $host2 = null, $host3 = null) {
  5255. $loop = is_array($host1)
  5256. ? $host1
  5257. : func_get_args();
  5258. foreach($loop as $host) {
  5259. if ($host && ! in_array($host, phpQuery::$ajaxAllowedHosts)) {
  5260. phpQuery::$ajaxAllowedHosts[] = $host;
  5261. }
  5262. }
  5263. }
  5264. public static function ajaxAllowURL($url1, $url2 = null, $url3 = null) {
  5265. $loop = is_array($url1)
  5266. ? $url1
  5267. : func_get_args();
  5268. foreach($loop as $url)
  5269. phpQuery::ajaxAllowHost(parse_url($url, PHP_URL_HOST));
  5270. }
  5271. /**
  5272. * Returns JSON representation of $data.
  5273. *
  5274. * @static
  5275. * @param mixed $data
  5276. * @return string
  5277. */
  5278. public static function toJSON($data) {
  5279. if (function_exists('json_encode'))
  5280. return json_encode($data);
  5281. require_once('Zend/Json/Encoder.php');
  5282. return Zend_Json_Encoder::encode($data);
  5283. }
  5284. /**
  5285. * Parses JSON into proper PHP type.
  5286. *
  5287. * @static
  5288. * @param string $json
  5289. * @return mixed
  5290. */
  5291. public static function parseJSON($json) {
  5292. if (function_exists('json_decode')) {
  5293. $return = json_decode(trim($json), true);
  5294. // json_decode and UTF8 issues
  5295. if (isset($return))
  5296. return $return;
  5297. }
  5298. require_once('Zend/Json/Decoder.php');
  5299. return Zend_Json_Decoder::decode($json);
  5300. }
  5301. /**
  5302. * Returns source's document ID.
  5303. *
  5304. * @param $source DOMNode|phpQueryObject
  5305. * @return string
  5306. */
  5307. public static function getDocumentID($source) {
  5308. if ($source instanceof DOMDOCUMENT) {
  5309. foreach(phpQuery::$documents as $id => $document) {
  5310. if ($source->isSameNode($document->document))
  5311. return $id;
  5312. }
  5313. } else if ($source instanceof DOMNODE) {
  5314. foreach(phpQuery::$documents as $id => $document) {
  5315. if ($source->ownerDocument->isSameNode($document->document))
  5316. return $id;
  5317. }
  5318. } else if ($source instanceof phpQueryObject)
  5319. return $source->getDocumentID();
  5320. else if (is_string($source) && isset(phpQuery::$documents[$source]))
  5321. return $source;
  5322. }
  5323. /**
  5324. * Get DOMDocument object related to $source.
  5325. * Returns null if such document doesn't exist.
  5326. *
  5327. * @param $source DOMNode|phpQueryObject|string
  5328. * @return string
  5329. */
  5330. public static function getDOMDocument($source) {
  5331. if ($source instanceof DOMDOCUMENT)
  5332. return $source;
  5333. $source = self::getDocumentID($source);
  5334. return $source
  5335. ? self::$documents[$id]['document']
  5336. : null;
  5337. }
  5338. // UTILITIES
  5339. // http://docs.jquery.com/Utilities
  5340. /**
  5341. *
  5342. * @return unknown_type
  5343. * @link http://docs.jquery.com/Utilities/jQuery.makeArray
  5344. */
  5345. public static function makeArray($obj) {
  5346. $array = array();
  5347. if (is_object($object) && $object instanceof DOMNODELIST) {
  5348. foreach($object as $value)
  5349. $array[] = $value;
  5350. } else if (is_object($object) && ! ($object instanceof Iterator)) {
  5351. foreach(get_object_vars($object) as $name => $value)
  5352. $array[0][$name] = $value;
  5353. } else {
  5354. foreach($object as $name => $value)
  5355. $array[0][$name] = $value;
  5356. }
  5357. return $array;
  5358. }
  5359. public static function inArray($value, $array) {
  5360. return in_array($value, $array);
  5361. }
  5362. /**
  5363. *
  5364. * @param $object
  5365. * @param $callback
  5366. * @return unknown_type
  5367. * @link http://docs.jquery.com/Utilities/jQuery.each
  5368. */
  5369. public static function each($object, $callback, $param1 = null, $param2 = null, $param3 = null) {
  5370. $paramStructure = null;
  5371. if (func_num_args() > 2) {
  5372. $paramStructure = func_get_args();
  5373. $paramStructure = array_slice($paramStructure, 2);
  5374. }
  5375. if (is_object($object) && ! ($object instanceof Iterator)) {
  5376. foreach(get_object_vars($object) as $name => $value)
  5377. phpQuery::callbackRun($callback, array($name, $value), $paramStructure);
  5378. } else {
  5379. foreach($object as $name => $value)
  5380. phpQuery::callbackRun($callback, array($name, $value), $paramStructure);
  5381. }
  5382. }
  5383. /**
  5384. *
  5385. * @link http://docs.jquery.com/Utilities/jQuery.map
  5386. */
  5387. public static function map($array, $callback, $param1 = null, $param2 = null, $param3 = null) {
  5388. $result = array();
  5389. $paramStructure = null;
  5390. if (func_num_args() > 2) {
  5391. $paramStructure = func_get_args();
  5392. $paramStructure = array_slice($paramStructure, 2);
  5393. }
  5394. foreach($array as $v) {
  5395. $vv = phpQuery::callbackRun($callback, array($v), $paramStructure);
  5396. // $callbackArgs = $args;
  5397. // foreach($args as $i => $arg) {
  5398. // $callbackArgs[$i] = $arg instanceof CallbackParam
  5399. // ? $v
  5400. // : $arg;
  5401. // }
  5402. // $vv = call_user_func_array($callback, $callbackArgs);
  5403. if (is_array($vv)) {
  5404. foreach($vv as $vvv)
  5405. $result[] = $vvv;
  5406. } else if ($vv !== null) {
  5407. $result[] = $vv;
  5408. }
  5409. }
  5410. return $result;
  5411. }
  5412. /**
  5413. *
  5414. * @param $callback Callback
  5415. * @param $params
  5416. * @param $paramStructure
  5417. * @return unknown_type
  5418. */
  5419. public static function callbackRun($callback, $params = array(), $paramStructure = null) {
  5420. if (! $callback)
  5421. return;
  5422. if ($callback instanceof CallbackParameterToReference) {
  5423. // TODO support ParamStructure to select which $param push to reference
  5424. if (isset($params[0]))
  5425. $callback->callback = $params[0];
  5426. return true;
  5427. }
  5428. if ($callback instanceof Callback) {
  5429. $paramStructure = $callback->params;
  5430. $callback = $callback->callback;
  5431. }
  5432. if (! $paramStructure)
  5433. return call_user_func_array($callback, $params);
  5434. $p = 0;
  5435. foreach($paramStructure as $i => $v) {
  5436. $paramStructure[$i] = $v instanceof CallbackParam
  5437. ? $params[$p++]
  5438. : $v;
  5439. }
  5440. return call_user_func_array($callback, $paramStructure);
  5441. }
  5442. /**
  5443. * Merge 2 phpQuery objects.
  5444. * @param array $one
  5445. * @param array $two
  5446. * @protected
  5447. * @todo node lists, phpQueryObject
  5448. */
  5449. public static function merge($one, $two) {
  5450. $elements = $one->elements;
  5451. foreach($two->elements as $node) {
  5452. $exists = false;
  5453. foreach($elements as $node2) {
  5454. if ($node2->isSameNode($node))
  5455. $exists = true;
  5456. }
  5457. if (! $exists)
  5458. $elements[] = $node;
  5459. }
  5460. return $elements;
  5461. // $one = $one->newInstance();
  5462. // $one->elements = $elements;
  5463. // return $one;
  5464. }
  5465. /**
  5466. *
  5467. * @param $array
  5468. * @param $callback
  5469. * @param $invert
  5470. * @return unknown_type
  5471. * @link http://docs.jquery.com/Utilities/jQuery.grep
  5472. */
  5473. public static function grep($array, $callback, $invert = false) {
  5474. $result = array();
  5475. foreach($array as $k => $v) {
  5476. $r = call_user_func_array($callback, array($v, $k));
  5477. if ($r === !(bool)$invert)
  5478. $result[] = $v;
  5479. }
  5480. return $result;
  5481. }
  5482. public static function unique($array) {
  5483. return array_unique($array);
  5484. }
  5485. /**
  5486. *
  5487. * @param $function
  5488. * @return unknown_type
  5489. * @TODO there are problems with non-static methods, second parameter pass it
  5490. * but doesnt verify is method is really callable
  5491. */
  5492. public static function isFunction($function) {
  5493. return is_callable($function);
  5494. }
  5495. public static function trim($str) {
  5496. return trim($str);
  5497. }
  5498. /* PLUGINS NAMESPACE */
  5499. /**
  5500. *
  5501. * @param $url
  5502. * @param $callback
  5503. * @param $param1
  5504. * @param $param2
  5505. * @param $param3
  5506. * @return phpQueryObject
  5507. */
  5508. public static function browserGet($url, $callback, $param1 = null, $param2 = null, $param3 = null) {
  5509. if (self::plugin('WebBrowser')) {
  5510. $params = func_get_args();
  5511. return self::callbackRun(array(self::$plugins, 'browserGet'), $params);
  5512. } else {
  5513. self::debug('WebBrowser plugin not available...');
  5514. }
  5515. }
  5516. /**
  5517. *
  5518. * @param $url
  5519. * @param $data
  5520. * @param $callback
  5521. * @param $param1
  5522. * @param $param2
  5523. * @param $param3
  5524. * @return phpQueryObject
  5525. */
  5526. public static function browserPost($url, $data, $callback, $param1 = null, $param2 = null, $param3 = null) {
  5527. if (self::plugin('WebBrowser')) {
  5528. $params = func_get_args();
  5529. return self::callbackRun(array(self::$plugins, 'browserPost'), $params);
  5530. } else {
  5531. self::debug('WebBrowser plugin not available...');
  5532. }
  5533. }
  5534. /**
  5535. *
  5536. * @param $ajaxSettings
  5537. * @param $callback
  5538. * @param $param1
  5539. * @param $param2
  5540. * @param $param3
  5541. * @return phpQueryObject
  5542. */
  5543. public static function browser($ajaxSettings, $callback, $param1 = null, $param2 = null, $param3 = null) {
  5544. if (self::plugin('WebBrowser')) {
  5545. $params = func_get_args();
  5546. return self::callbackRun(array(self::$plugins, 'browser'), $params);
  5547. } else {
  5548. self::debug('WebBrowser plugin not available...');
  5549. }
  5550. }
  5551. /**
  5552. *
  5553. * @param $code
  5554. * @return string
  5555. */
  5556. public static function php($code) {
  5557. return self::code('php', $code);
  5558. }
  5559. /**
  5560. *
  5561. * @param $type
  5562. * @param $code
  5563. * @return string
  5564. */
  5565. public static function code($type, $code) {
  5566. return "<$type><!-- ".trim($code)." --></$type>";
  5567. }
  5568. public static function __callStatic($method, $params) {
  5569. return call_user_func_array(
  5570. array(phpQuery::$plugins, $method),
  5571. $params
  5572. );
  5573. }
  5574. protected static function dataSetupNode($node, $documentID) {
  5575. // search are return if alredy exists
  5576. foreach(phpQuery::$documents[$documentID]->dataNodes as $dataNode) {
  5577. if ($node->isSameNode($dataNode))
  5578. return $dataNode;
  5579. }
  5580. // if doesn't, add it
  5581. phpQuery::$documents[$documentID]->dataNodes[] = $node;
  5582. return $node;
  5583. }
  5584. protected static function dataRemoveNode($node, $documentID) {
  5585. // search are return if alredy exists
  5586. foreach(phpQuery::$documents[$documentID]->dataNodes as $k => $dataNode) {
  5587. if ($node->isSameNode($dataNode)) {
  5588. unset(self::$documents[$documentID]->dataNodes[$k]);
  5589. unset(self::$documents[$documentID]->data[ $dataNode->dataID ]);
  5590. }
  5591. }
  5592. }
  5593. public static function data($node, $name, $data, $documentID = null) {
  5594. if (! $documentID)
  5595. // TODO check if this works
  5596. $documentID = self::getDocumentID($node);
  5597. $document = phpQuery::$documents[$documentID];
  5598. $node = self::dataSetupNode($node, $documentID);
  5599. if (! isset($node->dataID))
  5600. $node->dataID = ++phpQuery::$documents[$documentID]->uuid;
  5601. $id = $node->dataID;
  5602. if (! isset($document->data[$id]))
  5603. $document->data[$id] = array();
  5604. if (! is_null($data))
  5605. $document->data[$id][$name] = $data;
  5606. if ($name) {
  5607. if (isset($document->data[$id][$name]))
  5608. return $document->data[$id][$name];
  5609. } else
  5610. return $id;
  5611. }
  5612. public static function removeData($node, $name, $documentID) {
  5613. if (! $documentID)
  5614. // TODO check if this works
  5615. $documentID = self::getDocumentID($node);
  5616. $document = phpQuery::$documents[$documentID];
  5617. $node = self::dataSetupNode($node, $documentID);
  5618. $id = $node->dataID;
  5619. if ($name) {
  5620. if (isset($document->data[$id][$name]))
  5621. unset($document->data[$id][$name]);
  5622. $name = null;
  5623. foreach($document->data[$id] as $name)
  5624. break;
  5625. if (! $name)
  5626. self::removeData($node, $name, $documentID);
  5627. } else {
  5628. self::dataRemoveNode($node, $documentID);
  5629. }
  5630. }
  5631. }
  5632. /**
  5633. * Plugins static namespace class.
  5634. *
  5635. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  5636. * @package phpQuery
  5637. * @todo move plugin methods here (as statics)
  5638. */
  5639. class phpQueryPlugins {
  5640. public function __call($method, $args) {
  5641. if (isset(phpQuery::$extendStaticMethods[$method])) {
  5642. $return = call_user_func_array(
  5643. phpQuery::$extendStaticMethods[$method],
  5644. $args
  5645. );
  5646. } else if (isset(phpQuery::$pluginsStaticMethods[$method])) {
  5647. $class = phpQuery::$pluginsStaticMethods[$method];
  5648. $realClass = "phpQueryPlugin_$class";
  5649. $return = call_user_func_array(
  5650. array($realClass, $method),
  5651. $args
  5652. );
  5653. return isset($return)
  5654. ? $return
  5655. : $this;
  5656. } else
  5657. throw new Exception("Method '{$method}' doesnt exist");
  5658. }
  5659. }
  5660. /**
  5661. * Shortcut to phpQuery::pq($arg1, $context)
  5662. * Chainable.
  5663. *
  5664. * @see phpQuery::pq()
  5665. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  5666. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  5667. * @package phpQuery
  5668. */
  5669. function pq($arg1, $context = null) {
  5670. $args = func_get_args();
  5671. return call_user_func_array(
  5672. array('phpQuery', 'pq'),
  5673. $args
  5674. );
  5675. }
  5676. // add plugins dir and Zend framework to include path
  5677. set_include_path(
  5678. get_include_path()
  5679. .PATH_SEPARATOR.dirname(__FILE__).'/phpQuery/'
  5680. .PATH_SEPARATOR.dirname(__FILE__).'/phpQuery/plugins/'
  5681. );
  5682. // why ? no __call nor __get for statics in php...
  5683. // XXX __callStatic will be available in PHP 5.3
  5684. phpQuery::$plugins = new phpQueryPlugins();
  5685. // include bootstrap file (personal library config)
  5686. if (file_exists(dirname(__FILE__).'/phpQuery/bootstrap.php'))
  5687. require_once dirname(__FILE__).'/phpQuery/bootstrap.php';