lib_phpQuery.php 163 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703
  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. * Enter description here...
  1793. *
  1794. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1795. */
  1796. public function find($selectors, $context = null, $noHistory = false) {
  1797. if (!$noHistory)
  1798. // backup last stack /for end()/
  1799. $this->elementsBackup = $this->elements;
  1800. // allow to define context
  1801. // TODO combine code below with phpQuery::pq() context guessing code
  1802. // as generic function
  1803. if ($context) {
  1804. if (! is_array($context) && $context instanceof DOMELEMENT)
  1805. $this->elements = array($context);
  1806. else if (is_array($context)) {
  1807. $this->elements = array();
  1808. foreach ($context as $c)
  1809. if ($c instanceof DOMELEMENT)
  1810. $this->elements[] = $c;
  1811. } else if ( $context instanceof self )
  1812. $this->elements = $context->elements;
  1813. }
  1814. $queries = $this->parseSelector($selectors);
  1815. $this->debug(array('FIND', $selectors, $queries));
  1816. $XQuery = '';
  1817. // remember stack state because of multi-queries
  1818. $oldStack = $this->elements;
  1819. // here we will be keeping found elements
  1820. $stack = array();
  1821. foreach($queries as $selector) {
  1822. $this->elements = $oldStack;
  1823. $delimiterBefore = false;
  1824. foreach($selector as $s) {
  1825. // TAG
  1826. $isTag = extension_loaded('mbstring') && phpQuery::$mbstringSupport
  1827. ? mb_ereg_match('^[\w|\||-]+$', $s) || $s == '*'
  1828. : preg_match('@^[\w|\||-]+$@', $s) || $s == '*';
  1829. if ($isTag) {
  1830. if ($this->isXML()) {
  1831. // namespace support
  1832. if (mb_strpos($s, '|') !== false) {
  1833. $ns = $tag = null;
  1834. list($ns, $tag) = explode('|', $s);
  1835. $XQuery .= "$ns:$tag";
  1836. } else if ($s == '*') {
  1837. $XQuery .= "*";
  1838. } else {
  1839. $XQuery .= "*[local-name()='$s']";
  1840. }
  1841. } else {
  1842. $XQuery .= $s;
  1843. }
  1844. // ID
  1845. } else if ($s[0] == '#') {
  1846. if ($delimiterBefore)
  1847. $XQuery .= '*';
  1848. $XQuery .= "[@id='".substr($s, 1)."']";
  1849. // ATTRIBUTES
  1850. } else if ($s[0] == '[') {
  1851. if ($delimiterBefore)
  1852. $XQuery .= '*';
  1853. // strip side brackets
  1854. $attr = trim($s, '][');
  1855. $execute = false;
  1856. // attr with specifed value
  1857. if (mb_strpos($s, '=')) {
  1858. $value = null;
  1859. list($attr, $value) = explode('=', $attr);
  1860. $value = trim($value, "'\"");
  1861. if ($this->isRegexp($attr)) {
  1862. // cut regexp character
  1863. $attr = substr($attr, 0, -1);
  1864. $execute = true;
  1865. $XQuery .= "[@{$attr}]";
  1866. } else {
  1867. $XQuery .= "[@{$attr}='{$value}']";
  1868. }
  1869. // attr without specified value
  1870. } else {
  1871. $XQuery .= "[@{$attr}]";
  1872. }
  1873. if ($execute) {
  1874. $this->runQuery($XQuery, $s, 'is');
  1875. $XQuery = '';
  1876. if (! $this->length())
  1877. break;
  1878. }
  1879. // CLASSES
  1880. } else if ($s[0] == '.') {
  1881. // TODO use return $this->find("./self::*[contains(concat(\" \",@class,\" \"), \" $class \")]");
  1882. // thx wizDom ;)
  1883. if ($delimiterBefore)
  1884. $XQuery .= '*';
  1885. $XQuery .= '[@class]';
  1886. $this->runQuery($XQuery, $s, 'matchClasses');
  1887. $XQuery = '';
  1888. if (! $this->length() )
  1889. break;
  1890. // ~ General Sibling Selector
  1891. } else if ($s[0] == '~') {
  1892. $this->runQuery($XQuery);
  1893. $XQuery = '';
  1894. $this->elements = $this
  1895. ->siblings(
  1896. substr($s, 1)
  1897. )->elements;
  1898. if (! $this->length() )
  1899. break;
  1900. // + Adjacent sibling selectors
  1901. } else if ($s[0] == '+') {
  1902. // TODO /following-sibling::
  1903. $this->runQuery($XQuery);
  1904. $XQuery = '';
  1905. $subSelector = substr($s, 1);
  1906. $subElements = $this->elements;
  1907. $this->elements = array();
  1908. foreach($subElements as $node) {
  1909. // search first DOMElement sibling
  1910. $test = $node->nextSibling;
  1911. while($test && ! ($test instanceof DOMELEMENT))
  1912. $test = $test->nextSibling;
  1913. if ($test && $this->is($subSelector, $test))
  1914. $this->elements[] = $test;
  1915. }
  1916. if (! $this->length() )
  1917. break;
  1918. // PSEUDO CLASSES
  1919. } else if ($s[0] == ':') {
  1920. // TODO optimization for :first :last
  1921. if ($XQuery) {
  1922. $this->runQuery($XQuery);
  1923. $XQuery = '';
  1924. }
  1925. if (! $this->length())
  1926. break;
  1927. $this->pseudoClasses($s);
  1928. if (! $this->length())
  1929. break;
  1930. // DIRECT DESCENDANDS
  1931. } else if ($s == '>') {
  1932. $XQuery .= '/';
  1933. $delimiterBefore = 2;
  1934. // ALL DESCENDANDS
  1935. } else if ($s == ' ') {
  1936. $XQuery .= '//';
  1937. $delimiterBefore = 2;
  1938. // ERRORS
  1939. } else {
  1940. phpQuery::debug("Unrecognized token '$s'");
  1941. }
  1942. $delimiterBefore = $delimiterBefore === 2;
  1943. }
  1944. // run query if any
  1945. if ($XQuery && $XQuery != '//') {
  1946. $this->runQuery($XQuery);
  1947. $XQuery = '';
  1948. }
  1949. foreach($this->elements as $node)
  1950. if (! $this->elementsContainsNode($node, $stack))
  1951. $stack[] = $node;
  1952. }
  1953. $this->elements = $stack;
  1954. return $this->newInstance();
  1955. }
  1956. /**
  1957. * @todo create API for classes with pseudoselectors
  1958. * @access private
  1959. */
  1960. protected function pseudoClasses($class) {
  1961. // TODO clean args parsing ?
  1962. $class = ltrim($class, ':');
  1963. $haveArgs = mb_strpos($class, '(');
  1964. if ($haveArgs !== false) {
  1965. $args = substr($class, $haveArgs+1, -1);
  1966. $class = substr($class, 0, $haveArgs);
  1967. }
  1968. switch($class) {
  1969. case 'even':
  1970. case 'odd':
  1971. $stack = array();
  1972. foreach($this->elements as $i => $node) {
  1973. if ($class == 'even' && ($i%2) == 0)
  1974. $stack[] = $node;
  1975. else if ( $class == 'odd' && $i % 2 )
  1976. $stack[] = $node;
  1977. }
  1978. $this->elements = $stack;
  1979. break;
  1980. case 'eq':
  1981. $k = intval($args);
  1982. $this->elements = isset( $this->elements[$k] )
  1983. ? array( $this->elements[$k] )
  1984. : array();
  1985. break;
  1986. case 'gt':
  1987. $this->elements = array_slice($this->elements, $args+1);
  1988. break;
  1989. case 'lt':
  1990. $this->elements = array_slice($this->elements, 0, $args+1);
  1991. break;
  1992. case 'first':
  1993. if (isset($this->elements[0]))
  1994. $this->elements = array($this->elements[0]);
  1995. break;
  1996. case 'last':
  1997. if ($this->elements)
  1998. $this->elements = array($this->elements[count($this->elements)-1]);
  1999. break;
  2000. /*case 'parent':
  2001. $stack = array();
  2002. foreach($this->elements as $node) {
  2003. if ( $node->childNodes->length )
  2004. $stack[] = $node;
  2005. }
  2006. $this->elements = $stack;
  2007. break;*/
  2008. case 'contains':
  2009. $text = trim($args, "\"'");
  2010. $stack = array();
  2011. foreach($this->elements as $node) {
  2012. if (mb_stripos($node->textContent, $text) === false)
  2013. continue;
  2014. $stack[] = $node;
  2015. }
  2016. $this->elements = $stack;
  2017. break;
  2018. case 'not':
  2019. $selector = self::unQuote($args);
  2020. $this->elements = $this->not($selector)->stack();
  2021. break;
  2022. case 'slice':
  2023. // TODO jQuery difference ?
  2024. $args = explode(',',
  2025. str_replace(', ', ',', trim($args, "\"'"))
  2026. );
  2027. $start = $args[0];
  2028. $end = isset($args[1])
  2029. ? $args[1]
  2030. : null;
  2031. if ($end > 0)
  2032. $end = $end-$start;
  2033. $this->elements = array_slice($this->elements, $start, $end);
  2034. break;
  2035. case 'has':
  2036. $selector = trim($args, "\"'");
  2037. $stack = array();
  2038. foreach($this->stack(1) as $el) {
  2039. if ($this->find($selector, $el, true)->length)
  2040. $stack[] = $el;
  2041. }
  2042. $this->elements = $stack;
  2043. break;
  2044. case 'submit':
  2045. case 'reset':
  2046. $this->elements = phpQuery::merge(
  2047. $this->map(array($this, 'is'),
  2048. "input[type=$class]", new CallbackParam()
  2049. ),
  2050. $this->map(array($this, 'is'),
  2051. "button[type=$class]", new CallbackParam()
  2052. )
  2053. );
  2054. break;
  2055. // $stack = array();
  2056. // foreach($this->elements as $node)
  2057. // if ($node->is('input[type=submit]') || $node->is('button[type=submit]'))
  2058. // $stack[] = $el;
  2059. // $this->elements = $stack;
  2060. case 'input':
  2061. $this->elements = $this->map(
  2062. array($this, 'is'),
  2063. 'input', new CallbackParam()
  2064. )->elements;
  2065. break;
  2066. case 'password':
  2067. case 'checkbox':
  2068. case 'radio':
  2069. case 'hidden':
  2070. case 'image':
  2071. case 'file':
  2072. $this->elements = $this->map(
  2073. array($this, 'is'),
  2074. "input[type=$class]", new CallbackParam()
  2075. )->elements;
  2076. break;
  2077. case 'parent':
  2078. $this->elements = $this->map(
  2079. create_function('$node', '
  2080. return $node instanceof DOMELEMENT && $node->childNodes->length
  2081. ? $node : null;')
  2082. )->elements;
  2083. break;
  2084. case 'empty':
  2085. $this->elements = $this->map(
  2086. create_function('$node', '
  2087. return $node instanceof DOMELEMENT && $node->childNodes->length
  2088. ? null : $node;')
  2089. )->elements;
  2090. break;
  2091. case 'disabled':
  2092. case 'selected':
  2093. case 'checked':
  2094. $this->elements = $this->map(
  2095. array($this, 'is'),
  2096. "[$class]", new CallbackParam()
  2097. )->elements;
  2098. break;
  2099. case 'enabled':
  2100. $this->elements = $this->map(
  2101. create_function('$node', '
  2102. return pq($node)->not(":disabled") ? $node : null;')
  2103. )->elements;
  2104. break;
  2105. case 'header':
  2106. $this->elements = $this->map(
  2107. create_function('$node',
  2108. '$isHeader = isset($node->tagName) && in_array($node->tagName, array(
  2109. "h1", "h2", "h3", "h4", "h5", "h6", "h7"
  2110. ));
  2111. return $isHeader
  2112. ? $node
  2113. : null;')
  2114. )->elements;
  2115. // $this->elements = $this->map(
  2116. // create_function('$node', '$node = pq($node);
  2117. // return $node->is("h1")
  2118. // || $node->is("h2")
  2119. // || $node->is("h3")
  2120. // || $node->is("h4")
  2121. // || $node->is("h5")
  2122. // || $node->is("h6")
  2123. // || $node->is("h7")
  2124. // ? $node
  2125. // : null;')
  2126. // )->elements;
  2127. break;
  2128. case 'only-child':
  2129. $this->elements = $this->map(
  2130. create_function('$node',
  2131. 'return pq($node)->siblings()->size() == 0 ? $node : null;')
  2132. )->elements;
  2133. break;
  2134. case 'first-child':
  2135. $this->elements = $this->map(
  2136. create_function('$node', 'return pq($node)->prevAll()->size() == 0 ? $node : null;')
  2137. )->elements;
  2138. break;
  2139. case 'last-child':
  2140. $this->elements = $this->map(
  2141. create_function('$node', 'return pq($node)->nextAll()->size() == 0 ? $node : null;')
  2142. )->elements;
  2143. break;
  2144. case 'nth-child':
  2145. $param = trim($args, "\"'");
  2146. if (! $param)
  2147. break;
  2148. // nth-child(n+b) to nth-child(1n+b)
  2149. if ($param{0} == 'n')
  2150. $param = '1'.$param;
  2151. // :nth-child(index/even/odd/equation)
  2152. if ($param == 'even' || $param == 'odd')
  2153. $mapped = $this->map(
  2154. create_function('$node, $param',
  2155. '$index = pq($node)->prevAll()->size()+1;
  2156. if ($param == "even" && ($index%2) == 0)
  2157. return $node;
  2158. else if ($param == "odd" && $index%2 == 1)
  2159. return $node;
  2160. else
  2161. return null;'),
  2162. new CallbackParam(), $param
  2163. );
  2164. else if (mb_strlen($param) > 1 && $param{1} == 'n')
  2165. // an+b
  2166. $mapped = $this->map(
  2167. create_function('$node, $param',
  2168. '$prevs = pq($node)->prevAll()->size();
  2169. $index = 1+$prevs;
  2170. $b = mb_strlen($param) > 3
  2171. ? $param{3}
  2172. : 0;
  2173. $a = $param{0};
  2174. if ($b && $param{2} == "-")
  2175. $b = -$b;
  2176. if ($a > 0) {
  2177. return ($index-$b)%$a == 0
  2178. ? $node
  2179. : null;
  2180. phpQuery::debug($a."*".floor($index/$a)."+$b-1 == ".($a*floor($index/$a)+$b-1)." ?= $prevs");
  2181. return $a*floor($index/$a)+$b-1 == $prevs
  2182. ? $node
  2183. : null;
  2184. } else if ($a == 0)
  2185. return $index == $b
  2186. ? $node
  2187. : null;
  2188. else
  2189. // negative value
  2190. return $index <= $b
  2191. ? $node
  2192. : null;
  2193. // if (! $b)
  2194. // return $index%$a == 0
  2195. // ? $node
  2196. // : null;
  2197. // else
  2198. // return ($index-$b)%$a == 0
  2199. // ? $node
  2200. // : null;
  2201. '),
  2202. new CallbackParam(), $param
  2203. );
  2204. else
  2205. // index
  2206. $mapped = $this->map(
  2207. create_function('$node, $index',
  2208. '$prevs = pq($node)->prevAll()->size();
  2209. if ($prevs && $prevs == $index-1)
  2210. return $node;
  2211. else if (! $prevs && $index == 1)
  2212. return $node;
  2213. else
  2214. return null;'),
  2215. new CallbackParam(), $param
  2216. );
  2217. $this->elements = $mapped->elements;
  2218. break;
  2219. default:
  2220. $this->debug("Unknown pseudoclass '{$class}', skipping...");
  2221. }
  2222. }
  2223. /**
  2224. * @access private
  2225. */
  2226. protected function __pseudoClassParam($paramsString) {
  2227. // TODO;
  2228. }
  2229. /**
  2230. * Enter description here...
  2231. *
  2232. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2233. */
  2234. public function is($selector, $nodes = null) {
  2235. phpQuery::debug(array("Is:", $selector));
  2236. if (! $selector)
  2237. return false;
  2238. $oldStack = $this->elements;
  2239. $returnArray = false;
  2240. if ($nodes && is_array($nodes)) {
  2241. $this->elements = $nodes;
  2242. } else if ($nodes)
  2243. $this->elements = array($nodes);
  2244. $this->filter($selector, true);
  2245. $stack = $this->elements;
  2246. $this->elements = $oldStack;
  2247. if ($nodes)
  2248. return $stack ? $stack : null;
  2249. return (bool)count($stack);
  2250. }
  2251. /**
  2252. * Enter description here...
  2253. * jQuery difference.
  2254. *
  2255. * Callback:
  2256. * - $index int
  2257. * - $node DOMNode
  2258. *
  2259. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2260. * @link http://docs.jquery.com/Traversing/filter
  2261. */
  2262. public function filterCallback($callback, $_skipHistory = false) {
  2263. if (! $_skipHistory) {
  2264. $this->elementsBackup = $this->elements;
  2265. $this->debug("Filtering by callback");
  2266. }
  2267. $newStack = array();
  2268. foreach($this->elements as $index => $node) {
  2269. $result = phpQuery::callbackRun($callback, array($index, $node));
  2270. if (is_null($result) || (! is_null($result) && $result))
  2271. $newStack[] = $node;
  2272. }
  2273. $this->elements = $newStack;
  2274. return $_skipHistory
  2275. ? $this
  2276. : $this->newInstance();
  2277. }
  2278. /**
  2279. * Enter description here...
  2280. *
  2281. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2282. * @link http://docs.jquery.com/Traversing/filter
  2283. */
  2284. public function filter($selectors, $_skipHistory = false) {
  2285. if ($selectors instanceof Callback OR $selectors instanceof Closure)
  2286. return $this->filterCallback($selectors, $_skipHistory);
  2287. if (! $_skipHistory)
  2288. $this->elementsBackup = $this->elements;
  2289. $notSimpleSelector = array(' ', '>', '~', '+', '/');
  2290. if (! is_array($selectors))
  2291. $selectors = $this->parseSelector($selectors);
  2292. if (! $_skipHistory)
  2293. $this->debug(array("Filtering:", $selectors));
  2294. $finalStack = array();
  2295. foreach($selectors as $selector) {
  2296. $stack = array();
  2297. if (! $selector)
  2298. break;
  2299. // avoid first space or /
  2300. if (in_array($selector[0], $notSimpleSelector))
  2301. $selector = array_slice($selector, 1);
  2302. // PER NODE selector chunks
  2303. foreach($this->stack() as $node) {
  2304. $break = false;
  2305. foreach($selector as $s) {
  2306. if (!($node instanceof DOMELEMENT)) {
  2307. // all besides DOMElement
  2308. if ( $s[0] == '[') {
  2309. $attr = trim($s, '[]');
  2310. if ( mb_strpos($attr, '=')) {
  2311. list( $attr, $val ) = explode('=', $attr);
  2312. if ($attr == 'nodeType' && $node->nodeType != $val)
  2313. $break = true;
  2314. }
  2315. } else
  2316. $break = true;
  2317. } else {
  2318. // DOMElement only
  2319. // ID
  2320. if ( $s[0] == '#') {
  2321. if ( $node->getAttribute('id') != substr($s, 1) )
  2322. $break = true;
  2323. // CLASSES
  2324. } else if ( $s[0] == '.') {
  2325. if (! $this->matchClasses( $s, $node ) )
  2326. $break = true;
  2327. // ATTRS
  2328. } else if ( $s[0] == '[') {
  2329. // strip side brackets
  2330. $attr = trim($s, '[]');
  2331. if (mb_strpos($attr, '=')) {
  2332. list($attr, $val) = explode('=', $attr);
  2333. $val = self::unQuote($val);
  2334. if ($attr == 'nodeType') {
  2335. if ($val != $node->nodeType)
  2336. $break = true;
  2337. } else if ($this->isRegexp($attr)) {
  2338. $val = extension_loaded('mbstring') && phpQuery::$mbstringSupport
  2339. ? quotemeta(trim($val, '"\''))
  2340. : preg_quote(trim($val, '"\''), '@');
  2341. // switch last character
  2342. switch( substr($attr, -1)) {
  2343. // quotemeta used insted of preg_quote
  2344. // http://code.google.com/p/phpquery/issues/detail?id=76
  2345. case '^':
  2346. $pattern = '^'.$val;
  2347. break;
  2348. case '*':
  2349. $pattern = '.*'.$val.'.*';
  2350. break;
  2351. case '$':
  2352. $pattern = '.*'.$val.'$';
  2353. break;
  2354. }
  2355. // cut last character
  2356. $attr = substr($attr, 0, -1);
  2357. $isMatch = extension_loaded('mbstring') && phpQuery::$mbstringSupport
  2358. ? mb_ereg_match($pattern, $node->getAttribute($attr))
  2359. : preg_match("@{$pattern}@", $node->getAttribute($attr));
  2360. if (! $isMatch)
  2361. $break = true;
  2362. } else if ($node->getAttribute($attr) != $val)
  2363. $break = true;
  2364. } else if (! $node->hasAttribute($attr))
  2365. $break = true;
  2366. // PSEUDO CLASSES
  2367. } else if ( $s[0] == ':') {
  2368. // skip
  2369. // TAG
  2370. } else if (trim($s)) {
  2371. if ($s != '*') {
  2372. // TODO namespaces
  2373. if (isset($node->tagName)) {
  2374. if ($node->tagName != $s)
  2375. $break = true;
  2376. } else if ($s == 'html' && ! $this->isRoot($node))
  2377. $break = true;
  2378. }
  2379. // AVOID NON-SIMPLE SELECTORS
  2380. } else if (in_array($s, $notSimpleSelector)) {
  2381. $break = true;
  2382. $this->debug(array('Skipping non simple selector', $selector));
  2383. }
  2384. }
  2385. if ($break)
  2386. break;
  2387. }
  2388. // if element passed all chunks of selector - add it to new stack
  2389. if (! $break )
  2390. $stack[] = $node;
  2391. }
  2392. $tmpStack = $this->elements;
  2393. $this->elements = $stack;
  2394. // PER ALL NODES selector chunks
  2395. foreach($selector as $s)
  2396. // PSEUDO CLASSES
  2397. if ($s[0] == ':')
  2398. $this->pseudoClasses($s);
  2399. foreach($this->elements as $node)
  2400. // XXX it should be merged without duplicates
  2401. // but jQuery doesnt do that
  2402. $finalStack[] = $node;
  2403. $this->elements = $tmpStack;
  2404. }
  2405. $this->elements = $finalStack;
  2406. if ($_skipHistory) {
  2407. return $this;
  2408. } else {
  2409. $this->debug("Stack length after filter(): ".count($finalStack));
  2410. return $this->newInstance();
  2411. }
  2412. }
  2413. /**
  2414. *
  2415. * @param $value
  2416. * @return unknown_type
  2417. * @TODO implement in all methods using passed parameters
  2418. */
  2419. protected static function unQuote($value) {
  2420. return $value[0] == '\'' || $value[0] == '"'
  2421. ? substr($value, 1, -1)
  2422. : $value;
  2423. }
  2424. /**
  2425. * Enter description here...
  2426. *
  2427. * @link http://docs.jquery.com/Ajax/load
  2428. * @return phpQuery|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2429. * @todo Support $selector
  2430. */
  2431. public function load($url, $data = null, $callback = null) {
  2432. if ($data && ! is_array($data)) {
  2433. $callback = $data;
  2434. $data = null;
  2435. }
  2436. if (mb_strpos($url, ' ') !== false) {
  2437. $matches = null;
  2438. if (extension_loaded('mbstring') && phpQuery::$mbstringSupport)
  2439. mb_ereg('^([^ ]+) (.*)$', $url, $matches);
  2440. else
  2441. preg_match('^([^ ]+) (.*)$', $url, $matches);
  2442. $url = $matches[1];
  2443. $selector = $matches[2];
  2444. // FIXME this sucks, pass as callback param
  2445. $this->_loadSelector = $selector;
  2446. }
  2447. $ajax = array(
  2448. 'url' => $url,
  2449. 'type' => $data ? 'POST' : 'GET',
  2450. 'data' => $data,
  2451. 'complete' => $callback,
  2452. 'success' => array($this, '__loadSuccess')
  2453. );
  2454. phpQuery::ajax($ajax);
  2455. return $this;
  2456. }
  2457. /**
  2458. * @access private
  2459. * @param $html
  2460. * @return unknown_type
  2461. */
  2462. public function __loadSuccess($html) {
  2463. if ($this->_loadSelector) {
  2464. $html = phpQuery::newDocument($html)->find($this->_loadSelector);
  2465. unset($this->_loadSelector);
  2466. }
  2467. foreach($this->stack(1) as $node) {
  2468. phpQuery::pq($node, $this->getDocumentID())
  2469. ->markup($html);
  2470. }
  2471. }
  2472. /**
  2473. * Enter description here...
  2474. *
  2475. * @return phpQuery|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2476. * @todo
  2477. */
  2478. public function css() {
  2479. // TODO
  2480. return $this;
  2481. }
  2482. /**
  2483. * @todo
  2484. *
  2485. */
  2486. public function show(){
  2487. // TODO
  2488. return $this;
  2489. }
  2490. /**
  2491. * @todo
  2492. *
  2493. */
  2494. public function hide(){
  2495. // TODO
  2496. return $this;
  2497. }
  2498. /**
  2499. * Trigger a type of event on every matched element.
  2500. *
  2501. * @param unknown_type $type
  2502. * @param unknown_type $data
  2503. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2504. * @TODO support more than event in $type (space-separated)
  2505. */
  2506. public function trigger($type, $data = array()) {
  2507. foreach($this->elements as $node)
  2508. phpQueryEvents::trigger($this->getDocumentID(), $type, $data, $node);
  2509. return $this;
  2510. }
  2511. /**
  2512. * This particular method triggers all bound event handlers on an element (for a specific event type) WITHOUT executing the browsers default actions.
  2513. *
  2514. * @param unknown_type $type
  2515. * @param unknown_type $data
  2516. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2517. * @TODO
  2518. */
  2519. public function triggerHandler($type, $data = array()) {
  2520. // TODO;
  2521. }
  2522. /**
  2523. * Binds a handler to one or more events (like click) for each matched element.
  2524. * Can also bind custom events.
  2525. *
  2526. * @param unknown_type $type
  2527. * @param unknown_type $data Optional
  2528. * @param unknown_type $callback
  2529. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2530. * @TODO support '!' (exclusive) events
  2531. * @TODO support more than event in $type (space-separated)
  2532. */
  2533. public function bind($type, $data, $callback = null) {
  2534. // TODO check if $data is callable, not using is_callable
  2535. if (! isset($callback)) {
  2536. $callback = $data;
  2537. $data = null;
  2538. }
  2539. foreach($this->elements as $node)
  2540. phpQueryEvents::add($this->getDocumentID(), $node, $type, $data, $callback);
  2541. return $this;
  2542. }
  2543. /**
  2544. * Enter description here...
  2545. *
  2546. * @param unknown_type $type
  2547. * @param unknown_type $callback
  2548. * @return unknown
  2549. * @TODO namespace events
  2550. * @TODO support more than event in $type (space-separated)
  2551. */
  2552. public function unbind($type = null, $callback = null) {
  2553. foreach($this->elements as $node)
  2554. phpQueryEvents::remove($this->getDocumentID(), $node, $type, $callback);
  2555. return $this;
  2556. }
  2557. /**
  2558. * Enter description here...
  2559. *
  2560. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2561. */
  2562. public function change($callback = null) {
  2563. if ($callback)
  2564. return $this->bind('change', $callback);
  2565. return $this->trigger('change');
  2566. }
  2567. /**
  2568. * Enter description here...
  2569. *
  2570. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2571. */
  2572. public function submit($callback = null) {
  2573. if ($callback)
  2574. return $this->bind('submit', $callback);
  2575. return $this->trigger('submit');
  2576. }
  2577. /**
  2578. * Enter description here...
  2579. *
  2580. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2581. */
  2582. public function click($callback = null) {
  2583. if ($callback)
  2584. return $this->bind('click', $callback);
  2585. return $this->trigger('click');
  2586. }
  2587. /**
  2588. * Enter description here...
  2589. *
  2590. * @param String|phpQuery
  2591. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2592. */
  2593. public function wrapAllOld($wrapper) {
  2594. $wrapper = pq($wrapper)->_clone();
  2595. if (! $wrapper->length() || ! $this->length() )
  2596. return $this;
  2597. $wrapper->insertBefore($this->elements[0]);
  2598. $deepest = $wrapper->elements[0];
  2599. while($deepest->firstChild && $deepest->firstChild instanceof DOMELEMENT)
  2600. $deepest = $deepest->firstChild;
  2601. pq($deepest)->append($this);
  2602. return $this;
  2603. }
  2604. /**
  2605. * Enter description here...
  2606. *
  2607. * TODO testme...
  2608. * @param String|phpQuery
  2609. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2610. */
  2611. public function wrapAll($wrapper) {
  2612. if (! $this->length())
  2613. return $this;
  2614. return phpQuery::pq($wrapper, $this->getDocumentID())
  2615. ->clone()
  2616. ->insertBefore($this->get(0))
  2617. ->map(array($this, '___wrapAllCallback'))
  2618. ->append($this);
  2619. }
  2620. /**
  2621. *
  2622. * @param $node
  2623. * @return unknown_type
  2624. * @access private
  2625. */
  2626. public function ___wrapAllCallback($node) {
  2627. $deepest = $node;
  2628. while($deepest->firstChild && $deepest->firstChild instanceof DOMELEMENT)
  2629. $deepest = $deepest->firstChild;
  2630. return $deepest;
  2631. }
  2632. /**
  2633. * Enter description here...
  2634. * NON JQUERY METHOD
  2635. *
  2636. * @param String|phpQuery
  2637. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2638. */
  2639. public function wrapAllPHP($codeBefore, $codeAfter) {
  2640. return $this
  2641. ->slice(0, 1)
  2642. ->beforePHP($codeBefore)
  2643. ->end()
  2644. ->slice(-1)
  2645. ->afterPHP($codeAfter)
  2646. ->end();
  2647. }
  2648. /**
  2649. * Enter description here...
  2650. *
  2651. * @param String|phpQuery
  2652. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2653. */
  2654. public function wrap($wrapper) {
  2655. foreach($this->stack() as $node)
  2656. phpQuery::pq($node, $this->getDocumentID())->wrapAll($wrapper);
  2657. return $this;
  2658. }
  2659. /**
  2660. * Enter description here...
  2661. *
  2662. * @param String|phpQuery
  2663. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2664. */
  2665. public function wrapPHP($codeBefore, $codeAfter) {
  2666. foreach($this->stack() as $node)
  2667. phpQuery::pq($node, $this->getDocumentID())->wrapAllPHP($codeBefore, $codeAfter);
  2668. return $this;
  2669. }
  2670. /**
  2671. * Enter description here...
  2672. *
  2673. * @param String|phpQuery
  2674. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2675. */
  2676. public function wrapInner($wrapper) {
  2677. foreach($this->stack() as $node)
  2678. phpQuery::pq($node, $this->getDocumentID())->contents()->wrapAll($wrapper);
  2679. return $this;
  2680. }
  2681. /**
  2682. * Enter description here...
  2683. *
  2684. * @param String|phpQuery
  2685. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2686. */
  2687. public function wrapInnerPHP($codeBefore, $codeAfter) {
  2688. foreach($this->stack(1) as $node)
  2689. phpQuery::pq($node, $this->getDocumentID())->contents()
  2690. ->wrapAllPHP($codeBefore, $codeAfter);
  2691. return $this;
  2692. }
  2693. /**
  2694. * Enter description here...
  2695. *
  2696. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2697. * @testme Support for text nodes
  2698. */
  2699. public function contents() {
  2700. $stack = array();
  2701. foreach($this->stack(1) as $el) {
  2702. // FIXME (fixed) http://code.google.com/p/phpquery/issues/detail?id=56
  2703. // if (! isset($el->childNodes))
  2704. // continue;
  2705. foreach($el->childNodes as $node) {
  2706. $stack[] = $node;
  2707. }
  2708. }
  2709. return $this->newInstance($stack);
  2710. }
  2711. /**
  2712. * Enter description here...
  2713. *
  2714. * jQuery difference.
  2715. *
  2716. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2717. */
  2718. public function contentsUnwrap() {
  2719. foreach($this->stack(1) as $node) {
  2720. if (! $node->parentNode )
  2721. continue;
  2722. $childNodes = array();
  2723. // any modification in DOM tree breaks childNodes iteration, so cache them first
  2724. foreach($node->childNodes as $chNode )
  2725. $childNodes[] = $chNode;
  2726. foreach($childNodes as $chNode )
  2727. // $node->parentNode->appendChild($chNode);
  2728. $node->parentNode->insertBefore($chNode, $node);
  2729. $node->parentNode->removeChild($node);
  2730. }
  2731. return $this;
  2732. }
  2733. /**
  2734. * Enter description here...
  2735. *
  2736. * jQuery difference.
  2737. */
  2738. public function switchWith($markup) {
  2739. $markup = pq($markup, $this->getDocumentID());
  2740. $content = null;
  2741. foreach($this->stack(1) as $node) {
  2742. pq($node)
  2743. ->contents()->toReference($content)->end()
  2744. ->replaceWith($markup->clone()->append($content));
  2745. }
  2746. return $this;
  2747. }
  2748. /**
  2749. * Enter description here...
  2750. *
  2751. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2752. */
  2753. public function eq($num) {
  2754. $oldStack = $this->elements;
  2755. $this->elementsBackup = $this->elements;
  2756. $this->elements = array();
  2757. if ( isset($oldStack[$num]) )
  2758. $this->elements[] = $oldStack[$num];
  2759. return $this->newInstance();
  2760. }
  2761. /**
  2762. * Enter description here...
  2763. *
  2764. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2765. */
  2766. public function size() {
  2767. return count($this->elements);
  2768. }
  2769. /**
  2770. * Enter description here...
  2771. *
  2772. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2773. * @deprecated Use length as attribute
  2774. */
  2775. public function length() {
  2776. return $this->size();
  2777. }
  2778. public function count() {
  2779. return $this->size();
  2780. }
  2781. /**
  2782. * Enter description here...
  2783. *
  2784. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2785. * @todo $level
  2786. */
  2787. public function end($level = 1) {
  2788. // $this->elements = array_pop( $this->history );
  2789. // return $this;
  2790. // $this->previous->DOM = $this->DOM;
  2791. // $this->previous->XPath = $this->XPath;
  2792. return $this->previous
  2793. ? $this->previous
  2794. : $this;
  2795. }
  2796. /**
  2797. * Enter description here...
  2798. * Normal use ->clone() .
  2799. *
  2800. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2801. * @access private
  2802. */
  2803. public function _clone() {
  2804. $newStack = array();
  2805. //pr(array('copy... ', $this->whois()));
  2806. //$this->dumpHistory('copy');
  2807. $this->elementsBackup = $this->elements;
  2808. foreach($this->elements as $node) {
  2809. $newStack[] = $node->cloneNode(true);
  2810. }
  2811. $this->elements = $newStack;
  2812. return $this->newInstance();
  2813. }
  2814. /**
  2815. * Enter description here...
  2816. *
  2817. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2818. */
  2819. public function replaceWithPHP($code) {
  2820. return $this->replaceWith(phpQuery::php($code));
  2821. }
  2822. /**
  2823. * Enter description here...
  2824. *
  2825. * @param String|phpQuery $content
  2826. * @link http://docs.jquery.com/Manipulation/replaceWith#content
  2827. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2828. */
  2829. public function replaceWith($content) {
  2830. return $this->after($content)->remove();
  2831. }
  2832. /**
  2833. * Enter description here...
  2834. *
  2835. * @param String $selector
  2836. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2837. * @todo this works ?
  2838. */
  2839. public function replaceAll($selector) {
  2840. foreach(phpQuery::pq($selector, $this->getDocumentID()) as $node)
  2841. phpQuery::pq($node, $this->getDocumentID())
  2842. ->after($this->_clone())
  2843. ->remove();
  2844. return $this;
  2845. }
  2846. /**
  2847. * Enter description here...
  2848. *
  2849. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2850. */
  2851. public function remove($selector = null) {
  2852. $loop = $selector
  2853. ? $this->filter($selector)->elements
  2854. : $this->elements;
  2855. foreach($loop as $node) {
  2856. if (! $node->parentNode )
  2857. continue;
  2858. if (isset($node->tagName))
  2859. $this->debug("Removing '{$node->tagName}'");
  2860. $node->parentNode->removeChild($node);
  2861. // Mutation event
  2862. $event = new DOMEvent(array(
  2863. 'target' => $node,
  2864. 'type' => 'DOMNodeRemoved'
  2865. ));
  2866. phpQueryEvents::trigger($this->getDocumentID(),
  2867. $event->type, array($event), $node
  2868. );
  2869. }
  2870. return $this;
  2871. }
  2872. protected function markupEvents($newMarkup, $oldMarkup, $node) {
  2873. if ($node->tagName == 'textarea' && $newMarkup != $oldMarkup) {
  2874. $event = new DOMEvent(array(
  2875. 'target' => $node,
  2876. 'type' => 'change'
  2877. ));
  2878. phpQueryEvents::trigger($this->getDocumentID(),
  2879. $event->type, array($event), $node
  2880. );
  2881. }
  2882. }
  2883. /**
  2884. * jQuey difference
  2885. *
  2886. * @param $markup
  2887. * @return unknown_type
  2888. * @TODO trigger change event for textarea
  2889. */
  2890. public function markup($markup = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  2891. $args = func_get_args();
  2892. if ($this->documentWrapper->isXML)
  2893. return call_user_func_array(array($this, 'xml'), $args);
  2894. else
  2895. return call_user_func_array(array($this, 'html'), $args);
  2896. }
  2897. /**
  2898. * jQuey difference
  2899. *
  2900. * @param $markup
  2901. * @return unknown_type
  2902. */
  2903. public function markupOuter($callback1 = null, $callback2 = null, $callback3 = null) {
  2904. $args = func_get_args();
  2905. if ($this->documentWrapper->isXML)
  2906. return call_user_func_array(array($this, 'xmlOuter'), $args);
  2907. else
  2908. return call_user_func_array(array($this, 'htmlOuter'), $args);
  2909. }
  2910. /**
  2911. * Enter description here...
  2912. *
  2913. * @param unknown_type $html
  2914. * @return string|phpQuery|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2915. * @TODO force html result
  2916. */
  2917. public function html($html = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  2918. if (isset($html)) {
  2919. // INSERT
  2920. $nodes = $this->documentWrapper->import($html);
  2921. $this->empty();
  2922. foreach($this->stack(1) as $alreadyAdded => $node) {
  2923. // for now, limit events for textarea
  2924. if (($this->isXHTML() || $this->isHTML()) && $node->tagName == 'textarea')
  2925. $oldHtml = pq($node, $this->getDocumentID())->markup();
  2926. foreach($nodes as $newNode) {
  2927. $node->appendChild($alreadyAdded
  2928. ? $newNode->cloneNode(true)
  2929. : $newNode
  2930. );
  2931. }
  2932. // for now, limit events for textarea
  2933. if (($this->isXHTML() || $this->isHTML()) && $node->tagName == 'textarea')
  2934. $this->markupEvents($html, $oldHtml, $node);
  2935. }
  2936. return $this;
  2937. } else {
  2938. // FETCH
  2939. $return = $this->documentWrapper->markup($this->elements, true);
  2940. $args = func_get_args();
  2941. foreach(array_slice($args, 1) as $callback) {
  2942. $return = phpQuery::callbackRun($callback, array($return));
  2943. }
  2944. return $return;
  2945. }
  2946. }
  2947. /**
  2948. * @TODO force xml result
  2949. */
  2950. public function xml($xml = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  2951. $args = func_get_args();
  2952. return call_user_func_array(array($this, 'html'), $args);
  2953. }
  2954. /**
  2955. * Enter description here...
  2956. * @TODO force html result
  2957. *
  2958. * @return String
  2959. */
  2960. public function htmlOuter($callback1 = null, $callback2 = null, $callback3 = null) {
  2961. $markup = $this->documentWrapper->markup($this->elements);
  2962. // pass thou callbacks
  2963. $args = func_get_args();
  2964. foreach($args as $callback) {
  2965. $markup = phpQuery::callbackRun($callback, array($markup));
  2966. }
  2967. return $markup;
  2968. }
  2969. /**
  2970. * @TODO force xml result
  2971. */
  2972. public function xmlOuter($callback1 = null, $callback2 = null, $callback3 = null) {
  2973. $args = func_get_args();
  2974. return call_user_func_array(array($this, 'htmlOuter'), $args);
  2975. }
  2976. public function __toString() {
  2977. return $this->markupOuter();
  2978. }
  2979. /**
  2980. * Just like html(), but returns markup with VALID (dangerous) PHP tags.
  2981. *
  2982. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2983. * @todo support returning markup with PHP tags when called without param
  2984. */
  2985. public function php($code = null) {
  2986. return $this->markupPHP($code);
  2987. }
  2988. /**
  2989. * Enter description here...
  2990. *
  2991. * @param $code
  2992. * @return unknown_type
  2993. */
  2994. public function markupPHP($code = null) {
  2995. return isset($code)
  2996. ? $this->markup(phpQuery::php($code))
  2997. : phpQuery::markupToPHP($this->markup());
  2998. }
  2999. /**
  3000. * Enter description here...
  3001. *
  3002. * @param $code
  3003. * @return unknown_type
  3004. */
  3005. public function markupOuterPHP() {
  3006. return phpQuery::markupToPHP($this->markupOuter());
  3007. }
  3008. /**
  3009. * Enter description here...
  3010. *
  3011. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3012. */
  3013. public function children($selector = null) {
  3014. $stack = array();
  3015. foreach($this->stack(1) as $node) {
  3016. // foreach($node->getElementsByTagName('*') as $newNode) {
  3017. foreach($node->childNodes as $newNode) {
  3018. if ($newNode->nodeType != 1)
  3019. continue;
  3020. if ($selector && ! $this->is($selector, $newNode))
  3021. continue;
  3022. if ($this->elementsContainsNode($newNode, $stack))
  3023. continue;
  3024. $stack[] = $newNode;
  3025. }
  3026. }
  3027. $this->elementsBackup = $this->elements;
  3028. $this->elements = $stack;
  3029. return $this->newInstance();
  3030. }
  3031. /**
  3032. * Enter description here...
  3033. *
  3034. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3035. */
  3036. public function ancestors($selector = null) {
  3037. return $this->children( $selector );
  3038. }
  3039. /**
  3040. * Enter description here...
  3041. *
  3042. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3043. */
  3044. public function append( $content) {
  3045. return $this->insert($content, __FUNCTION__);
  3046. }
  3047. /**
  3048. * Enter description here...
  3049. *
  3050. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3051. */
  3052. public function appendPHP( $content) {
  3053. return $this->insert("<php><!-- {$content} --></php>", 'append');
  3054. }
  3055. /**
  3056. * Enter description here...
  3057. *
  3058. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3059. */
  3060. public function appendTo( $seletor) {
  3061. return $this->insert($seletor, __FUNCTION__);
  3062. }
  3063. /**
  3064. * Enter description here...
  3065. *
  3066. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3067. */
  3068. public function prepend( $content) {
  3069. return $this->insert($content, __FUNCTION__);
  3070. }
  3071. /**
  3072. * Enter description here...
  3073. *
  3074. * @todo accept many arguments, which are joined, arrays maybe also
  3075. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3076. */
  3077. public function prependPHP( $content) {
  3078. return $this->insert("<php><!-- {$content} --></php>", 'prepend');
  3079. }
  3080. /**
  3081. * Enter description here...
  3082. *
  3083. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3084. */
  3085. public function prependTo( $seletor) {
  3086. return $this->insert($seletor, __FUNCTION__);
  3087. }
  3088. /**
  3089. * Enter description here...
  3090. *
  3091. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3092. */
  3093. public function before($content) {
  3094. return $this->insert($content, __FUNCTION__);
  3095. }
  3096. /**
  3097. * Enter description here...
  3098. *
  3099. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3100. */
  3101. public function beforePHP( $content) {
  3102. return $this->insert("<php><!-- {$content} --></php>", 'before');
  3103. }
  3104. /**
  3105. * Enter description here...
  3106. *
  3107. * @param String|phpQuery
  3108. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3109. */
  3110. public function insertBefore( $seletor) {
  3111. return $this->insert($seletor, __FUNCTION__);
  3112. }
  3113. /**
  3114. * Enter description here...
  3115. *
  3116. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3117. */
  3118. public function after( $content) {
  3119. return $this->insert($content, __FUNCTION__);
  3120. }
  3121. /**
  3122. * Enter description here...
  3123. *
  3124. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3125. */
  3126. public function afterPHP( $content) {
  3127. return $this->insert("<php><!-- {$content} --></php>", 'after');
  3128. }
  3129. /**
  3130. * Enter description here...
  3131. *
  3132. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3133. */
  3134. public function insertAfter( $seletor) {
  3135. return $this->insert($seletor, __FUNCTION__);
  3136. }
  3137. /**
  3138. * Internal insert method. Don't use it.
  3139. *
  3140. * @param unknown_type $target
  3141. * @param unknown_type $type
  3142. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3143. * @access private
  3144. */
  3145. public function insert($target, $type) {
  3146. $this->debug("Inserting data with '{$type}'");
  3147. $to = false;
  3148. switch( $type) {
  3149. case 'appendTo':
  3150. case 'prependTo':
  3151. case 'insertBefore':
  3152. case 'insertAfter':
  3153. $to = true;
  3154. }
  3155. switch(gettype($target)) {
  3156. case 'string':
  3157. $insertFrom = $insertTo = array();
  3158. if ($to) {
  3159. // INSERT TO
  3160. $insertFrom = $this->elements;
  3161. if (phpQuery::isMarkup($target)) {
  3162. // $target is new markup, import it
  3163. $insertTo = $this->documentWrapper->import($target);
  3164. // insert into selected element
  3165. } else {
  3166. // $tagret is a selector
  3167. $thisStack = $this->elements;
  3168. $this->toRoot();
  3169. $insertTo = $this->find($target)->elements;
  3170. $this->elements = $thisStack;
  3171. }
  3172. } else {
  3173. // INSERT FROM
  3174. $insertTo = $this->elements;
  3175. $insertFrom = $this->documentWrapper->import($target);
  3176. }
  3177. break;
  3178. case 'object':
  3179. $insertFrom = $insertTo = array();
  3180. // phpQuery
  3181. if ($target instanceof self) {
  3182. if ($to) {
  3183. $insertTo = $target->elements;
  3184. if ($this->documentFragment && $this->stackIsRoot())
  3185. // get all body children
  3186. // $loop = $this->find('body > *')->elements;
  3187. // TODO test it, test it hard...
  3188. // $loop = $this->newInstance($this->root)->find('> *')->elements;
  3189. $loop = $this->root->childNodes;
  3190. else
  3191. $loop = $this->elements;
  3192. // import nodes if needed
  3193. $insertFrom = $this->getDocumentID() == $target->getDocumentID()
  3194. ? $loop
  3195. : $target->documentWrapper->import($loop);
  3196. } else {
  3197. $insertTo = $this->elements;
  3198. if ( $target->documentFragment && $target->stackIsRoot() )
  3199. // get all body children
  3200. // $loop = $target->find('body > *')->elements;
  3201. $loop = $target->root->childNodes;
  3202. else
  3203. $loop = $target->elements;
  3204. // import nodes if needed
  3205. $insertFrom = $this->getDocumentID() == $target->getDocumentID()
  3206. ? $loop
  3207. : $this->documentWrapper->import($loop);
  3208. }
  3209. // DOMNODE
  3210. } elseif ($target instanceof DOMNODE) {
  3211. // import node if needed
  3212. // if ( $target->ownerDocument != $this->DOM )
  3213. // $target = $this->DOM->importNode($target, true);
  3214. if ( $to) {
  3215. $insertTo = array($target);
  3216. if ($this->documentFragment && $this->stackIsRoot())
  3217. // get all body children
  3218. $loop = $this->root->childNodes;
  3219. // $loop = $this->find('body > *')->elements;
  3220. else
  3221. $loop = $this->elements;
  3222. foreach($loop as $fromNode)
  3223. // import nodes if needed
  3224. $insertFrom[] = ! $fromNode->ownerDocument->isSameNode($target->ownerDocument)
  3225. ? $target->ownerDocument->importNode($fromNode, true)
  3226. : $fromNode;
  3227. } else {
  3228. // import node if needed
  3229. if (! $target->ownerDocument->isSameNode($this->document))
  3230. $target = $this->document->importNode($target, true);
  3231. $insertTo = $this->elements;
  3232. $insertFrom[] = $target;
  3233. }
  3234. }
  3235. break;
  3236. }
  3237. phpQuery::debug("From ".count($insertFrom)."; To ".count($insertTo)." nodes");
  3238. foreach($insertTo as $insertNumber => $toNode) {
  3239. // we need static relative elements in some cases
  3240. switch( $type) {
  3241. case 'prependTo':
  3242. case 'prepend':
  3243. $firstChild = $toNode->firstChild;
  3244. break;
  3245. case 'insertAfter':
  3246. case 'after':
  3247. $nextSibling = $toNode->nextSibling;
  3248. break;
  3249. }
  3250. foreach($insertFrom as $fromNode) {
  3251. // clone if inserted already before
  3252. $insert = $insertNumber
  3253. ? $fromNode->cloneNode(true)
  3254. : $fromNode;
  3255. switch($type) {
  3256. case 'appendTo':
  3257. case 'append':
  3258. // $toNode->insertBefore(
  3259. // $fromNode,
  3260. // $toNode->lastChild->nextSibling
  3261. // );
  3262. $toNode->appendChild($insert);
  3263. $eventTarget = $insert;
  3264. break;
  3265. case 'prependTo':
  3266. case 'prepend':
  3267. $toNode->insertBefore(
  3268. $insert,
  3269. $firstChild
  3270. );
  3271. break;
  3272. case 'insertBefore':
  3273. case 'before':
  3274. if (! $toNode->parentNode)
  3275. throw new Exception("No parentNode, can't do {$type}()");
  3276. else
  3277. $toNode->parentNode->insertBefore(
  3278. $insert,
  3279. $toNode
  3280. );
  3281. break;
  3282. case 'insertAfter':
  3283. case 'after':
  3284. if (! $toNode->parentNode)
  3285. throw new Exception("No parentNode, can't do {$type}()");
  3286. else
  3287. $toNode->parentNode->insertBefore(
  3288. $insert,
  3289. $nextSibling
  3290. );
  3291. break;
  3292. }
  3293. // Mutation event
  3294. $event = new DOMEvent(array(
  3295. 'target' => $insert,
  3296. 'type' => 'DOMNodeInserted'
  3297. ));
  3298. phpQueryEvents::trigger($this->getDocumentID(),
  3299. $event->type, array($event), $insert
  3300. );
  3301. }
  3302. }
  3303. return $this;
  3304. }
  3305. /**
  3306. * Enter description here...
  3307. *
  3308. * @return Int
  3309. */
  3310. public function index($subject) {
  3311. $index = -1;
  3312. $subject = $subject instanceof phpQueryObject
  3313. ? $subject->elements[0]
  3314. : $subject;
  3315. foreach($this->newInstance() as $k => $node) {
  3316. if ($node->isSameNode($subject))
  3317. $index = $k;
  3318. }
  3319. return $index;
  3320. }
  3321. /**
  3322. * Enter description here...
  3323. *
  3324. * @param unknown_type $start
  3325. * @param unknown_type $end
  3326. *
  3327. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3328. * @testme
  3329. */
  3330. public function slice($start, $end = null) {
  3331. // $last = count($this->elements)-1;
  3332. // $end = $end
  3333. // ? min($end, $last)
  3334. // : $last;
  3335. // if ($start < 0)
  3336. // $start = $last+$start;
  3337. // if ($start > $last)
  3338. // return array();
  3339. if ($end > 0)
  3340. $end = $end-$start;
  3341. return $this->newInstance(
  3342. array_slice($this->elements, $start, $end)
  3343. );
  3344. }
  3345. /**
  3346. * Enter description here...
  3347. *
  3348. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3349. */
  3350. public function reverse() {
  3351. $this->elementsBackup = $this->elements;
  3352. $this->elements = array_reverse($this->elements);
  3353. return $this->newInstance();
  3354. }
  3355. /**
  3356. * Return joined text content.
  3357. * @return String
  3358. */
  3359. public function text($text = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  3360. if (isset($text))
  3361. return $this->html(htmlspecialchars($text), ENT_NOQUOTES, 'UTF-8');
  3362. $args = func_get_args();
  3363. $args = array_slice($args, 1);
  3364. $return = '';
  3365. foreach($this->elements as $node) {
  3366. $text = $node->textContent;
  3367. if (count($this->elements) > 1 && $text)
  3368. $text .= "\n";
  3369. foreach($args as $callback) {
  3370. $text = phpQuery::callbackRun($callback, array($text));
  3371. }
  3372. $return .= $text;
  3373. }
  3374. return $return;
  3375. }
  3376. /**
  3377. * Enter description here...
  3378. *
  3379. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3380. */
  3381. public function plugin($class, $file = null) {
  3382. phpQuery::plugin($class, $file);
  3383. return $this;
  3384. }
  3385. /**
  3386. * Deprecated, use $pq->plugin() instead.
  3387. *
  3388. * @deprecated
  3389. * @param $class
  3390. * @param $file
  3391. * @return unknown_type
  3392. */
  3393. public static function extend($class, $file = null) {
  3394. return $this->plugin($class, $file);
  3395. }
  3396. /**
  3397. *
  3398. * @access private
  3399. * @param $method
  3400. * @param $args
  3401. * @return unknown_type
  3402. */
  3403. public function __call($method, $args) {
  3404. $aliasMethods = array('clone', 'empty');
  3405. if (isset(phpQuery::$extendMethods[$method])) {
  3406. array_unshift($args, $this);
  3407. return phpQuery::callbackRun(
  3408. phpQuery::$extendMethods[$method], $args
  3409. );
  3410. } else if (isset(phpQuery::$pluginsMethods[$method])) {
  3411. array_unshift($args, $this);
  3412. $class = phpQuery::$pluginsMethods[$method];
  3413. $realClass = "phpQueryObjectPlugin_$class";
  3414. $return = call_user_func_array(
  3415. array($realClass, $method),
  3416. $args
  3417. );
  3418. // XXX deprecate ?
  3419. return is_null($return)
  3420. ? $this
  3421. : $return;
  3422. } else if (in_array($method, $aliasMethods)) {
  3423. return call_user_func_array(array($this, '_'.$method), $args);
  3424. } else
  3425. throw new Exception("Method '{$method}' doesnt exist");
  3426. }
  3427. /**
  3428. * Safe rename of next().
  3429. *
  3430. * Use it ONLY when need to call next() on an iterated object (in same time).
  3431. * Normaly there is no need to do such thing ;)
  3432. *
  3433. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3434. * @access private
  3435. */
  3436. public function _next($selector = null) {
  3437. return $this->newInstance(
  3438. $this->getElementSiblings('nextSibling', $selector, true)
  3439. );
  3440. }
  3441. /**
  3442. * Use prev() and next().
  3443. *
  3444. * @deprecated
  3445. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3446. * @access private
  3447. */
  3448. public function _prev($selector = null) {
  3449. return $this->prev($selector);
  3450. }
  3451. /**
  3452. * Enter description here...
  3453. *
  3454. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3455. */
  3456. public function prev($selector = null) {
  3457. return $this->newInstance(
  3458. $this->getElementSiblings('previousSibling', $selector, true)
  3459. );
  3460. }
  3461. /**
  3462. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3463. * @todo
  3464. */
  3465. public function prevAll($selector = null) {
  3466. return $this->newInstance(
  3467. $this->getElementSiblings('previousSibling', $selector)
  3468. );
  3469. }
  3470. /**
  3471. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3472. * @todo FIXME: returns source elements insted of next siblings
  3473. */
  3474. public function nextAll($selector = null) {
  3475. return $this->newInstance(
  3476. $this->getElementSiblings('nextSibling', $selector)
  3477. );
  3478. }
  3479. /**
  3480. * @access private
  3481. */
  3482. protected function getElementSiblings($direction, $selector = null, $limitToOne = false) {
  3483. $stack = array();
  3484. $count = 0;
  3485. foreach($this->stack() as $node) {
  3486. $test = $node;
  3487. while( isset($test->{$direction}) && $test->{$direction}) {
  3488. $test = $test->{$direction};
  3489. if (! $test instanceof DOMELEMENT)
  3490. continue;
  3491. $stack[] = $test;
  3492. if ($limitToOne)
  3493. break;
  3494. }
  3495. }
  3496. if ($selector) {
  3497. $stackOld = $this->elements;
  3498. $this->elements = $stack;
  3499. $stack = $this->filter($selector, true)->stack();
  3500. $this->elements = $stackOld;
  3501. }
  3502. return $stack;
  3503. }
  3504. /**
  3505. * Enter description here...
  3506. *
  3507. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3508. */
  3509. public function siblings($selector = null) {
  3510. $stack = array();
  3511. $siblings = array_merge(
  3512. $this->getElementSiblings('previousSibling', $selector),
  3513. $this->getElementSiblings('nextSibling', $selector)
  3514. );
  3515. foreach($siblings as $node) {
  3516. if (! $this->elementsContainsNode($node, $stack))
  3517. $stack[] = $node;
  3518. }
  3519. return $this->newInstance($stack);
  3520. }
  3521. /**
  3522. * Enter description here...
  3523. *
  3524. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3525. */
  3526. public function not($selector = null) {
  3527. if (is_string($selector))
  3528. phpQuery::debug(array('not', $selector));
  3529. else
  3530. phpQuery::debug('not');
  3531. $stack = array();
  3532. if ($selector instanceof self || $selector instanceof DOMNODE) {
  3533. foreach($this->stack() as $node) {
  3534. if ($selector instanceof self) {
  3535. $matchFound = false;
  3536. foreach($selector->stack() as $notNode) {
  3537. if ($notNode->isSameNode($node))
  3538. $matchFound = true;
  3539. }
  3540. if (! $matchFound)
  3541. $stack[] = $node;
  3542. } else if ($selector instanceof DOMNODE) {
  3543. if (! $selector->isSameNode($node))
  3544. $stack[] = $node;
  3545. } else {
  3546. if (! $this->is($selector))
  3547. $stack[] = $node;
  3548. }
  3549. }
  3550. } else {
  3551. $orgStack = $this->stack();
  3552. $matched = $this->filter($selector, true)->stack();
  3553. // $matched = array();
  3554. // // simulate OR in filter() instead of AND 5y
  3555. // foreach($this->parseSelector($selector) as $s) {
  3556. // $matched = array_merge($matched,
  3557. // $this->filter(array($s))->stack()
  3558. // );
  3559. // }
  3560. foreach($orgStack as $node)
  3561. if (! $this->elementsContainsNode($node, $matched))
  3562. $stack[] = $node;
  3563. }
  3564. return $this->newInstance($stack);
  3565. }
  3566. /**
  3567. * Enter description here...
  3568. *
  3569. * @param string|phpQueryObject
  3570. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3571. */
  3572. public function add($selector = null) {
  3573. if (! $selector)
  3574. return $this;
  3575. $stack = array();
  3576. $this->elementsBackup = $this->elements;
  3577. $found = phpQuery::pq($selector, $this->getDocumentID());
  3578. $this->merge($found->elements);
  3579. return $this->newInstance();
  3580. }
  3581. /**
  3582. * @access private
  3583. */
  3584. protected function merge() {
  3585. foreach(func_get_args() as $nodes)
  3586. foreach($nodes as $newNode )
  3587. if (! $this->elementsContainsNode($newNode) )
  3588. $this->elements[] = $newNode;
  3589. }
  3590. /**
  3591. * @access private
  3592. * TODO refactor to stackContainsNode
  3593. */
  3594. protected function elementsContainsNode($nodeToCheck, $elementsStack = null) {
  3595. $loop = ! is_null($elementsStack)
  3596. ? $elementsStack
  3597. : $this->elements;
  3598. foreach($loop as $node) {
  3599. if ( $node->isSameNode( $nodeToCheck ) )
  3600. return true;
  3601. }
  3602. return false;
  3603. }
  3604. /**
  3605. * Enter description here...
  3606. *
  3607. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3608. */
  3609. public function parent($selector = null) {
  3610. $stack = array();
  3611. foreach($this->elements as $node )
  3612. if ( $node->parentNode && ! $this->elementsContainsNode($node->parentNode, $stack) )
  3613. $stack[] = $node->parentNode;
  3614. $this->elementsBackup = $this->elements;
  3615. $this->elements = $stack;
  3616. if ( $selector )
  3617. $this->filter($selector, true);
  3618. return $this->newInstance();
  3619. }
  3620. /**
  3621. * Enter description here...
  3622. *
  3623. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3624. */
  3625. public function parents($selector = null) {
  3626. $stack = array();
  3627. if (! $this->elements )
  3628. $this->debug('parents() - stack empty');
  3629. foreach($this->elements as $node) {
  3630. $test = $node;
  3631. while( $test->parentNode) {
  3632. $test = $test->parentNode;
  3633. if ($this->isRoot($test))
  3634. break;
  3635. if (! $this->elementsContainsNode($test, $stack)) {
  3636. $stack[] = $test;
  3637. continue;
  3638. }
  3639. }
  3640. }
  3641. $this->elementsBackup = $this->elements;
  3642. $this->elements = $stack;
  3643. if ( $selector )
  3644. $this->filter($selector, true);
  3645. return $this->newInstance();
  3646. }
  3647. /**
  3648. * Internal stack iterator.
  3649. *
  3650. * @access private
  3651. */
  3652. public function stack($nodeTypes = null) {
  3653. if (!isset($nodeTypes))
  3654. return $this->elements;
  3655. if (!is_array($nodeTypes))
  3656. $nodeTypes = array($nodeTypes);
  3657. $return = array();
  3658. foreach($this->elements as $node) {
  3659. if (in_array($node->nodeType, $nodeTypes))
  3660. $return[] = $node;
  3661. }
  3662. return $return;
  3663. }
  3664. // TODO phpdoc; $oldAttr is result of hasAttribute, before any changes
  3665. protected function attrEvents($attr, $oldAttr, $oldValue, $node) {
  3666. // skip events for XML documents
  3667. if (! $this->isXHTML() && ! $this->isHTML())
  3668. return;
  3669. $event = null;
  3670. // identify
  3671. $isInputValue = $node->tagName == 'input'
  3672. && (
  3673. in_array($node->getAttribute('type'),
  3674. array('text', 'password', 'hidden'))
  3675. || !$node->getAttribute('type')
  3676. );
  3677. $isRadio = $node->tagName == 'input'
  3678. && $node->getAttribute('type') == 'radio';
  3679. $isCheckbox = $node->tagName == 'input'
  3680. && $node->getAttribute('type') == 'checkbox';
  3681. $isOption = $node->tagName == 'option';
  3682. if ($isInputValue && $attr == 'value' && $oldValue != $node->getAttribute($attr)) {
  3683. $event = new DOMEvent(array(
  3684. 'target' => $node,
  3685. 'type' => 'change'
  3686. ));
  3687. } else if (($isRadio || $isCheckbox) && $attr == 'checked' && (
  3688. // check
  3689. (! $oldAttr && $node->hasAttribute($attr))
  3690. // un-check
  3691. || (! $node->hasAttribute($attr) && $oldAttr)
  3692. )) {
  3693. $event = new DOMEvent(array(
  3694. 'target' => $node,
  3695. 'type' => 'change'
  3696. ));
  3697. } else if ($isOption && $node->parentNode && $attr == 'selected' && (
  3698. // select
  3699. (! $oldAttr && $node->hasAttribute($attr))
  3700. // un-select
  3701. || (! $node->hasAttribute($attr) && $oldAttr)
  3702. )) {
  3703. $event = new DOMEvent(array(
  3704. 'target' => $node->parentNode,
  3705. 'type' => 'change'
  3706. ));
  3707. }
  3708. if ($event) {
  3709. phpQueryEvents::trigger($this->getDocumentID(),
  3710. $event->type, array($event), $node
  3711. );
  3712. }
  3713. }
  3714. public function attr($attr = null, $value = null) {
  3715. foreach($this->stack(1) as $node) {
  3716. if (! is_null($value)) {
  3717. $loop = $attr == '*'
  3718. ? $this->getNodeAttrs($node)
  3719. : array($attr);
  3720. foreach($loop as $a) {
  3721. $oldValue = $node->getAttribute($a);
  3722. $oldAttr = $node->hasAttribute($a);
  3723. // TODO raises an error when charset other than UTF-8
  3724. // while document's charset is also not UTF-8
  3725. @$node->setAttribute($a, $value);
  3726. $this->attrEvents($a, $oldAttr, $oldValue, $node);
  3727. }
  3728. } else if ($attr == '*') {
  3729. // jQuery difference
  3730. $return = array();
  3731. foreach($node->attributes as $n => $v)
  3732. $return[$n] = $v->value;
  3733. return $return;
  3734. } else
  3735. return $node->hasAttribute($attr)
  3736. ? $node->getAttribute($attr)
  3737. : null;
  3738. }
  3739. return is_null($value)
  3740. ? '' : $this;
  3741. }
  3742. /**
  3743. * @access private
  3744. */
  3745. protected function getNodeAttrs($node) {
  3746. $return = array();
  3747. foreach($node->attributes as $n => $o)
  3748. $return[] = $n;
  3749. return $return;
  3750. }
  3751. /**
  3752. * Enter description here...
  3753. *
  3754. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3755. * @todo check CDATA ???
  3756. */
  3757. public function attrPHP($attr, $code) {
  3758. if (! is_null($code)) {
  3759. $value = '<'.'?php '.$code.' ?'.'>';
  3760. // TODO tempolary solution
  3761. // http://code.google.com/p/phpquery/issues/detail?id=17
  3762. // if (function_exists('mb_detect_encoding') && mb_detect_encoding($value) == 'ASCII')
  3763. // $value = mb_convert_encoding($value, 'UTF-8', 'HTML-ENTITIES');
  3764. }
  3765. foreach($this->stack(1) as $node) {
  3766. if (! is_null($code)) {
  3767. // $attrNode = $this->DOM->createAttribute($attr);
  3768. $node->setAttribute($attr, $value);
  3769. // $attrNode->value = $value;
  3770. // $node->appendChild($attrNode);
  3771. } else if ( $attr == '*') {
  3772. // jQuery diff
  3773. $return = array();
  3774. foreach($node->attributes as $n => $v)
  3775. $return[$n] = $v->value;
  3776. return $return;
  3777. } else
  3778. return $node->getAttribute($attr);
  3779. }
  3780. return $this;
  3781. }
  3782. /**
  3783. * Enter description here...
  3784. *
  3785. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3786. */
  3787. public function removeAttr($attr) {
  3788. foreach($this->stack(1) as $node) {
  3789. $loop = $attr == '*'
  3790. ? $this->getNodeAttrs($node)
  3791. : array($attr);
  3792. foreach($loop as $a) {
  3793. $oldValue = $node->getAttribute($a);
  3794. $node->removeAttribute($a);
  3795. $this->attrEvents($a, $oldValue, null, $node);
  3796. }
  3797. }
  3798. return $this;
  3799. }
  3800. /**
  3801. * Return form element value.
  3802. *
  3803. * @return String Fields value.
  3804. */
  3805. public function val($val = null) {
  3806. if (! isset($val)) {
  3807. if ($this->eq(0)->is('select')) {
  3808. $selected = $this->eq(0)->find('option[selected=selected]');
  3809. if ($selected->is('[value]'))
  3810. return $selected->attr('value');
  3811. else
  3812. return $selected->text();
  3813. } else if ($this->eq(0)->is('textarea'))
  3814. return $this->eq(0)->markup();
  3815. else
  3816. return $this->eq(0)->attr('value');
  3817. } else {
  3818. $_val = null;
  3819. foreach($this->stack(1) as $node) {
  3820. $node = pq($node, $this->getDocumentID());
  3821. if (is_array($val) && in_array($node->attr('type'), array('checkbox', 'radio'))) {
  3822. $isChecked = in_array($node->attr('value'), $val)
  3823. || in_array($node->attr('name'), $val);
  3824. if ($isChecked)
  3825. $node->attr('checked', 'checked');
  3826. else
  3827. $node->removeAttr('checked');
  3828. } else if ($node->get(0)->tagName == 'select') {
  3829. if (! isset($_val)) {
  3830. $_val = array();
  3831. if (! is_array($val))
  3832. $_val = array((string)$val);
  3833. else
  3834. foreach($val as $v)
  3835. $_val[] = $v;
  3836. }
  3837. foreach($node['option']->stack(1) as $option) {
  3838. $option = pq($option, $this->getDocumentID());
  3839. $selected = false;
  3840. // XXX: workaround for string comparsion, see issue #96
  3841. // http://code.google.com/p/phpquery/issues/detail?id=96
  3842. $selected = is_null($option->attr('value'))
  3843. ? in_array($option->markup(), $_val)
  3844. : in_array($option->attr('value'), $_val);
  3845. // $optionValue = $option->attr('value');
  3846. // $optionText = $option->text();
  3847. // $optionTextLenght = mb_strlen($optionText);
  3848. // foreach($_val as $v)
  3849. // if ($optionValue == $v)
  3850. // $selected = true;
  3851. // else if ($optionText == $v && $optionTextLenght == mb_strlen($v))
  3852. // $selected = true;
  3853. if ($selected)
  3854. $option->attr('selected', 'selected');
  3855. else
  3856. $option->removeAttr('selected');
  3857. }
  3858. } else if ($node->get(0)->tagName == 'textarea')
  3859. $node->markup($val);
  3860. else
  3861. $node->attr('value', $val);
  3862. }
  3863. }
  3864. return $this;
  3865. }
  3866. /**
  3867. * Enter description here...
  3868. *
  3869. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3870. */
  3871. public function andSelf() {
  3872. if ( $this->previous )
  3873. $this->elements = array_merge($this->elements, $this->previous->elements);
  3874. return $this;
  3875. }
  3876. /**
  3877. * Enter description here...
  3878. *
  3879. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3880. */
  3881. public function addClass( $className) {
  3882. if (! $className)
  3883. return $this;
  3884. foreach($this->stack(1) as $node) {
  3885. if (! $this->is(".$className", $node))
  3886. $node->setAttribute(
  3887. 'class',
  3888. trim($node->getAttribute('class').' '.$className)
  3889. );
  3890. }
  3891. return $this;
  3892. }
  3893. /**
  3894. * Enter description here...
  3895. *
  3896. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3897. */
  3898. public function addClassPHP( $className) {
  3899. foreach($this->stack(1) as $node) {
  3900. $classes = $node->getAttribute('class');
  3901. $newValue = $classes
  3902. ? $classes.' <'.'?php '.$className.' ?'.'>'
  3903. : '<'.'?php '.$className.' ?'.'>';
  3904. $node->setAttribute('class', $newValue);
  3905. }
  3906. return $this;
  3907. }
  3908. /**
  3909. * Enter description here...
  3910. *
  3911. * @param string $className
  3912. * @return bool
  3913. */
  3914. public function hasClass($className) {
  3915. foreach($this->stack(1) as $node) {
  3916. if ( $this->is(".$className", $node))
  3917. return true;
  3918. }
  3919. return false;
  3920. }
  3921. /**
  3922. * Enter description here...
  3923. *
  3924. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3925. */
  3926. public function removeClass($className) {
  3927. foreach($this->stack(1) as $node) {
  3928. $classes = explode( ' ', $node->getAttribute('class'));
  3929. if ( in_array($className, $classes)) {
  3930. $classes = array_diff($classes, array($className));
  3931. if ( $classes )
  3932. $node->setAttribute('class', implode(' ', $classes));
  3933. else
  3934. $node->removeAttribute('class');
  3935. }
  3936. }
  3937. return $this;
  3938. }
  3939. /**
  3940. * Enter description here...
  3941. *
  3942. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3943. */
  3944. public function toggleClass($className) {
  3945. foreach($this->stack(1) as $node) {
  3946. if ( $this->is( $node, '.'.$className ))
  3947. $this->removeClass($className);
  3948. else
  3949. $this->addClass($className);
  3950. }
  3951. return $this;
  3952. }
  3953. /**
  3954. * Proper name without underscore (just ->empty()) also works.
  3955. *
  3956. * Removes all child nodes from the set of matched elements.
  3957. *
  3958. * Example:
  3959. * pq("p")._empty()
  3960. *
  3961. * HTML:
  3962. * <p>Hello, <span>Person</span> <a href="#">and person</a></p>
  3963. *
  3964. * Result:
  3965. * [ <p></p> ]
  3966. *
  3967. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3968. * @access private
  3969. */
  3970. public function _empty() {
  3971. foreach($this->stack(1) as $node) {
  3972. // thx to 'dave at dgx dot cz'
  3973. $node->nodeValue = '';
  3974. }
  3975. return $this;
  3976. }
  3977. /**
  3978. * Enter description here...
  3979. *
  3980. * @param array|string $callback Expects $node as first param, $index as second
  3981. * @param array $scope External variables passed to callback. Use compact('varName1', 'varName2'...) and extract($scope)
  3982. * @param array $arg1 Will ba passed as third and futher args to callback.
  3983. * @param array $arg2 Will ba passed as fourth and futher args to callback, and so on...
  3984. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3985. */
  3986. public function each($callback, $param1 = null, $param2 = null, $param3 = null) {
  3987. $paramStructure = null;
  3988. if (func_num_args() > 1) {
  3989. $paramStructure = func_get_args();
  3990. $paramStructure = array_slice($paramStructure, 1);
  3991. }
  3992. foreach($this->elements as $v)
  3993. phpQuery::callbackRun($callback, array($v), $paramStructure);
  3994. return $this;
  3995. }
  3996. /**
  3997. * Run callback on actual object.
  3998. *
  3999. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4000. */
  4001. public function callback($callback, $param1 = null, $param2 = null, $param3 = null) {
  4002. $params = func_get_args();
  4003. $params[0] = $this;
  4004. phpQuery::callbackRun($callback, $params);
  4005. return $this;
  4006. }
  4007. /**
  4008. * Enter description here...
  4009. *
  4010. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4011. * @todo add $scope and $args as in each() ???
  4012. */
  4013. public function map($callback, $param1 = null, $param2 = null, $param3 = null) {
  4014. // $stack = array();
  4015. //// foreach($this->newInstance() as $node) {
  4016. // foreach($this->newInstance() as $node) {
  4017. // $result = call_user_func($callback, $node);
  4018. // if ($result)
  4019. // $stack[] = $result;
  4020. // }
  4021. $params = func_get_args();
  4022. array_unshift($params, $this->elements);
  4023. return $this->newInstance(
  4024. call_user_func_array(array('phpQuery', 'map'), $params)
  4025. // phpQuery::map($this->elements, $callback)
  4026. );
  4027. }
  4028. /**
  4029. * Enter description here...
  4030. *
  4031. * @param <type> $key
  4032. * @param <type> $value
  4033. */
  4034. public function data($key, $value = null) {
  4035. if (! isset($value)) {
  4036. // TODO? implement specific jQuery behavior od returning parent values
  4037. // is child which we look up doesn't exist
  4038. return phpQuery::data($this->get(0), $key, $value, $this->getDocumentID());
  4039. } else {
  4040. foreach($this as $node)
  4041. phpQuery::data($node, $key, $value, $this->getDocumentID());
  4042. return $this;
  4043. }
  4044. }
  4045. /**
  4046. * Enter description here...
  4047. *
  4048. * @param <type> $key
  4049. */
  4050. public function removeData($key) {
  4051. foreach($this as $node)
  4052. phpQuery::removeData($node, $key, $this->getDocumentID());
  4053. return $this;
  4054. }
  4055. // INTERFACE IMPLEMENTATIONS
  4056. // ITERATOR INTERFACE
  4057. /**
  4058. * @access private
  4059. */
  4060. public function rewind(){
  4061. $this->debug('iterating foreach');
  4062. // phpQuery::selectDocument($this->getDocumentID());
  4063. $this->elementsBackup = $this->elements;
  4064. $this->elementsInterator = $this->elements;
  4065. $this->valid = isset( $this->elements[0] )
  4066. ? 1 : 0;
  4067. // $this->elements = $this->valid
  4068. // ? array($this->elements[0])
  4069. // : array();
  4070. $this->current = 0;
  4071. }
  4072. /**
  4073. * @access private
  4074. */
  4075. public function current(){
  4076. return $this->elementsInterator[ $this->current ];
  4077. }
  4078. /**
  4079. * @access private
  4080. */
  4081. public function key(){
  4082. return $this->current;
  4083. }
  4084. /**
  4085. * Double-function method.
  4086. *
  4087. * First: main iterator interface method.
  4088. * Second: Returning next sibling, alias for _next().
  4089. *
  4090. * Proper functionality is choosed automagicaly.
  4091. *
  4092. * @see phpQueryObject::_next()
  4093. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4094. */
  4095. public function next($cssSelector = null){
  4096. // if ($cssSelector || $this->valid)
  4097. // return $this->_next($cssSelector);
  4098. $this->valid = isset( $this->elementsInterator[ $this->current+1 ] )
  4099. ? true
  4100. : false;
  4101. if (! $this->valid && $this->elementsInterator) {
  4102. $this->elementsInterator = null;
  4103. } else if ($this->valid) {
  4104. $this->current++;
  4105. } else {
  4106. return $this->_next($cssSelector);
  4107. }
  4108. }
  4109. /**
  4110. * @access private
  4111. */
  4112. public function valid(){
  4113. return $this->valid;
  4114. }
  4115. // ITERATOR INTERFACE END
  4116. // ARRAYACCESS INTERFACE
  4117. /**
  4118. * @access private
  4119. */
  4120. public function offsetExists($offset) {
  4121. return $this->find($offset)->size() > 0;
  4122. }
  4123. /**
  4124. * @access private
  4125. */
  4126. public function offsetGet($offset) {
  4127. return $this->find($offset);
  4128. }
  4129. /**
  4130. * @access private
  4131. */
  4132. public function offsetSet($offset, $value) {
  4133. // $this->find($offset)->replaceWith($value);
  4134. $this->find($offset)->html($value);
  4135. }
  4136. /**
  4137. * @access private
  4138. */
  4139. public function offsetUnset($offset) {
  4140. // empty
  4141. throw new Exception("Can't do unset, use array interface only for calling queries and replacing HTML.");
  4142. }
  4143. // ARRAYACCESS INTERFACE END
  4144. /**
  4145. * Returns node's XPath.
  4146. *
  4147. * @param unknown_type $oneNode
  4148. * @return string
  4149. * @TODO use native getNodePath is avaible
  4150. * @access private
  4151. */
  4152. protected function getNodeXpath($oneNode = null, $namespace = null) {
  4153. $return = array();
  4154. $loop = $oneNode
  4155. ? array($oneNode)
  4156. : $this->elements;
  4157. // if ($namespace)
  4158. // $namespace .= ':';
  4159. foreach($loop as $node) {
  4160. if ($node instanceof DOMDOCUMENT) {
  4161. $return[] = '';
  4162. continue;
  4163. }
  4164. $xpath = array();
  4165. while(! ($node instanceof DOMDOCUMENT)) {
  4166. $i = 1;
  4167. $sibling = $node;
  4168. while($sibling->previousSibling) {
  4169. $sibling = $sibling->previousSibling;
  4170. $isElement = $sibling instanceof DOMELEMENT;
  4171. if ($isElement && $sibling->tagName == $node->tagName)
  4172. $i++;
  4173. }
  4174. $xpath[] = $this->isXML()
  4175. ? "*[local-name()='{$node->tagName}'][{$i}]"
  4176. : "{$node->tagName}[{$i}]";
  4177. $node = $node->parentNode;
  4178. }
  4179. $xpath = join('/', array_reverse($xpath));
  4180. $return[] = '/'.$xpath;
  4181. }
  4182. return $oneNode
  4183. ? $return[0]
  4184. : $return;
  4185. }
  4186. // HELPERS
  4187. public function whois($oneNode = null) {
  4188. $return = array();
  4189. $loop = $oneNode
  4190. ? array( $oneNode )
  4191. : $this->elements;
  4192. foreach($loop as $node) {
  4193. if (isset($node->tagName)) {
  4194. $tag = in_array($node->tagName, array('php', 'js'))
  4195. ? strtoupper($node->tagName)
  4196. : $node->tagName;
  4197. $return[] = $tag
  4198. .($node->getAttribute('id')
  4199. ? '#'.$node->getAttribute('id'):'')
  4200. .($node->getAttribute('class')
  4201. ? '.'.join('.', explode(' ', $node->getAttribute('class'))):'')
  4202. .($node->getAttribute('name')
  4203. ? '[name="'.$node->getAttribute('name').'"]':'')
  4204. .($node->getAttribute('value') && strpos($node->getAttribute('value'), '<'.'?php') === false
  4205. ? '[value="'.substr(str_replace("\n", '', $node->getAttribute('value')), 0, 15).'"]':'')
  4206. .($node->getAttribute('value') && strpos($node->getAttribute('value'), '<'.'?php') !== false
  4207. ? '[value=PHP]':'')
  4208. .($node->getAttribute('selected')
  4209. ? '[selected]':'')
  4210. .($node->getAttribute('checked')
  4211. ? '[checked]':'')
  4212. ;
  4213. } else if ($node instanceof DOMTEXT) {
  4214. if (trim($node->textContent))
  4215. $return[] = 'Text:'.substr(str_replace("\n", ' ', $node->textContent), 0, 15);
  4216. } else {
  4217. }
  4218. }
  4219. return $oneNode && isset($return[0])
  4220. ? $return[0]
  4221. : $return;
  4222. }
  4223. /**
  4224. * Dump htmlOuter and preserve chain. Usefull for debugging.
  4225. *
  4226. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4227. *
  4228. */
  4229. public function dump() {
  4230. print 'DUMP #'.(phpQuery::$dumpCount++).' ';
  4231. $debug = phpQuery::$debug;
  4232. phpQuery::$debug = false;
  4233. // print __FILE__.':'.__LINE__."\n";
  4234. var_dump($this->htmlOuter());
  4235. return $this;
  4236. }
  4237. public function dumpWhois() {
  4238. print 'DUMP #'.(phpQuery::$dumpCount++).' ';
  4239. $debug = phpQuery::$debug;
  4240. phpQuery::$debug = false;
  4241. // print __FILE__.':'.__LINE__."\n";
  4242. var_dump('whois', $this->whois());
  4243. phpQuery::$debug = $debug;
  4244. return $this;
  4245. }
  4246. public function dumpLength() {
  4247. print 'DUMP #'.(phpQuery::$dumpCount++).' ';
  4248. $debug = phpQuery::$debug;
  4249. phpQuery::$debug = false;
  4250. // print __FILE__.':'.__LINE__."\n";
  4251. var_dump('length', $this->length());
  4252. phpQuery::$debug = $debug;
  4253. return $this;
  4254. }
  4255. public function dumpTree($html = true, $title = true) {
  4256. $output = $title
  4257. ? 'DUMP #'.(phpQuery::$dumpCount++)." \n" : '';
  4258. $debug = phpQuery::$debug;
  4259. phpQuery::$debug = false;
  4260. foreach($this->stack() as $node)
  4261. $output .= $this->__dumpTree($node);
  4262. phpQuery::$debug = $debug;
  4263. print $html
  4264. ? nl2br(str_replace(' ', '&nbsp;', $output))
  4265. : $output;
  4266. return $this;
  4267. }
  4268. private function __dumpTree($node, $intend = 0) {
  4269. $whois = $this->whois($node);
  4270. $return = '';
  4271. if ($whois)
  4272. $return .= str_repeat(' - ', $intend).$whois."\n";
  4273. if (isset($node->childNodes))
  4274. foreach($node->childNodes as $chNode)
  4275. $return .= $this->__dumpTree($chNode, $intend+1);
  4276. return $return;
  4277. }
  4278. /**
  4279. * Dump htmlOuter and stop script execution. Usefull for debugging.
  4280. *
  4281. */
  4282. public function dumpDie() {
  4283. print __FILE__.':'.__LINE__;
  4284. var_dump($this->htmlOuter());
  4285. die();
  4286. }
  4287. }
  4288. // -- Multibyte Compatibility functions ---------------------------------------
  4289. // http://svn.iphonewebdev.com/lace/lib/mb_compat.php
  4290. /**
  4291. * mb_internal_encoding()
  4292. *
  4293. * Included for mbstring pseudo-compatability.
  4294. */
  4295. if (!function_exists('mb_internal_encoding'))
  4296. {
  4297. function mb_internal_encoding($enc) {return true; }
  4298. }
  4299. /**
  4300. * mb_regex_encoding()
  4301. *
  4302. * Included for mbstring pseudo-compatability.
  4303. */
  4304. if (!function_exists('mb_regex_encoding'))
  4305. {
  4306. function mb_regex_encoding($enc) {return true; }
  4307. }
  4308. /**
  4309. * mb_strlen()
  4310. *
  4311. * Included for mbstring pseudo-compatability.
  4312. */
  4313. if (!function_exists('mb_strlen'))
  4314. {
  4315. function mb_strlen($str)
  4316. {
  4317. return strlen($str);
  4318. }
  4319. }
  4320. /**
  4321. * mb_strpos()
  4322. *
  4323. * Included for mbstring pseudo-compatability.
  4324. */
  4325. if (!function_exists('mb_strpos'))
  4326. {
  4327. function mb_strpos($haystack, $needle, $offset=0)
  4328. {
  4329. return strpos($haystack, $needle, $offset);
  4330. }
  4331. }
  4332. /**
  4333. * mb_stripos()
  4334. *
  4335. * Included for mbstring pseudo-compatability.
  4336. */
  4337. if (!function_exists('mb_stripos'))
  4338. {
  4339. function mb_stripos($haystack, $needle, $offset=0)
  4340. {
  4341. return stripos($haystack, $needle, $offset);
  4342. }
  4343. }
  4344. /**
  4345. * mb_substr()
  4346. *
  4347. * Included for mbstring pseudo-compatability.
  4348. */
  4349. if (!function_exists('mb_substr'))
  4350. {
  4351. function mb_substr($str, $start, $length=0)
  4352. {
  4353. return substr($str, $start, $length);
  4354. }
  4355. }
  4356. /**
  4357. * mb_substr_count()
  4358. *
  4359. * Included for mbstring pseudo-compatability.
  4360. */
  4361. if (!function_exists('mb_substr_count'))
  4362. {
  4363. function mb_substr_count($haystack, $needle)
  4364. {
  4365. return substr_count($haystack, $needle);
  4366. }
  4367. }
  4368. /**
  4369. * Static namespace for phpQuery functions.
  4370. *
  4371. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  4372. * @package phpQuery
  4373. */
  4374. abstract class phpQuery {
  4375. /**
  4376. * XXX: Workaround for mbstring problems
  4377. *
  4378. * @var bool
  4379. */
  4380. public static $mbstringSupport = true;
  4381. public static $debug = false;
  4382. public static $documents = array();
  4383. public static $defaultDocumentID = null;
  4384. // public static $defaultDoctype = 'html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"';
  4385. /**
  4386. * Applies only to HTML.
  4387. *
  4388. * @var unknown_type
  4389. */
  4390. public static $defaultDoctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  4391. "http://www.w3.org/TR/html4/loose.dtd">';
  4392. public static $defaultCharset = 'UTF-8';
  4393. /**
  4394. * Static namespace for plugins.
  4395. *
  4396. * @var object
  4397. */
  4398. public static $plugins = array();
  4399. /**
  4400. * List of loaded plugins.
  4401. *
  4402. * @var unknown_type
  4403. */
  4404. public static $pluginsLoaded = array();
  4405. public static $pluginsMethods = array();
  4406. public static $pluginsStaticMethods = array();
  4407. public static $extendMethods = array();
  4408. /**
  4409. * @TODO implement
  4410. */
  4411. public static $extendStaticMethods = array();
  4412. /**
  4413. * Hosts allowed for AJAX connections.
  4414. * Dot '.' means $_SERVER['HTTP_HOST'] (if any).
  4415. *
  4416. * @var array
  4417. */
  4418. public static $ajaxAllowedHosts = array(
  4419. '.'
  4420. );
  4421. /**
  4422. * AJAX settings.
  4423. *
  4424. * @var array
  4425. * XXX should it be static or not ?
  4426. */
  4427. public static $ajaxSettings = array(
  4428. 'url' => '',//TODO
  4429. 'global' => true,
  4430. 'type' => "GET",
  4431. 'timeout' => null,
  4432. 'contentType' => "application/x-www-form-urlencoded",
  4433. 'processData' => true,
  4434. // 'async' => true,
  4435. 'data' => null,
  4436. 'username' => null,
  4437. 'password' => null,
  4438. 'accepts' => array(
  4439. 'xml' => "application/xml, text/xml",
  4440. 'html' => "text/html",
  4441. 'script' => "text/javascript, application/javascript",
  4442. 'json' => "application/json, text/javascript",
  4443. 'text' => "text/plain",
  4444. '_default' => "*/*"
  4445. )
  4446. );
  4447. public static $lastModified = null;
  4448. public static $active = 0;
  4449. public static $dumpCount = 0;
  4450. /**
  4451. * Multi-purpose function.
  4452. * Use pq() as shortcut.
  4453. *
  4454. * In below examples, $pq is any result of pq(); function.
  4455. *
  4456. * 1. Import markup into existing document (without any attaching):
  4457. * - Import into selected document:
  4458. * pq('<div/>') // DOESNT accept text nodes at beginning of input string !
  4459. * - Import into document with ID from $pq->getDocumentID():
  4460. * pq('<div/>', $pq->getDocumentID())
  4461. * - Import into same document as DOMNode belongs to:
  4462. * pq('<div/>', DOMNode)
  4463. * - Import into document from phpQuery object:
  4464. * pq('<div/>', $pq)
  4465. *
  4466. * 2. Run query:
  4467. * - Run query on last selected document:
  4468. * pq('div.myClass')
  4469. * - Run query on document with ID from $pq->getDocumentID():
  4470. * pq('div.myClass', $pq->getDocumentID())
  4471. * - Run query on same document as DOMNode belongs to and use node(s)as root for query:
  4472. * pq('div.myClass', DOMNode)
  4473. * - Run query on document from phpQuery object
  4474. * and use object's stack as root node(s) for query:
  4475. * pq('div.myClass', $pq)
  4476. *
  4477. * @param string|DOMNode|DOMNodeList|array $arg1 HTML markup, CSS Selector, DOMNode or array of DOMNodes
  4478. * @param string|phpQueryObject|DOMNode $context DOM ID from $pq->getDocumentID(), phpQuery object (determines also query root) or DOMNode (determines also query root)
  4479. *
  4480. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery|QueryTemplatesPhpQuery|false
  4481. * phpQuery object or false in case of error.
  4482. */
  4483. public static function pq($arg1, $context = null) {
  4484. if ($arg1 instanceof DOMNODE && ! isset($context)) {
  4485. foreach(phpQuery::$documents as $documentWrapper) {
  4486. $compare = $arg1 instanceof DOMDocument
  4487. ? $arg1 : $arg1->ownerDocument;
  4488. if ($documentWrapper->document->isSameNode($compare))
  4489. $context = $documentWrapper->id;
  4490. }
  4491. }
  4492. if (! $context) {
  4493. $domId = self::$defaultDocumentID;
  4494. if (! $domId)
  4495. throw new Exception("Can't use last created DOM, because there isn't any. Use phpQuery::newDocument() first.");
  4496. // } else if (is_object($context) && ($context instanceof PHPQUERY || is_subclass_of($context, 'phpQueryObject')))
  4497. } else if (is_object($context) && $context instanceof phpQueryObject)
  4498. $domId = $context->getDocumentID();
  4499. else if ($context instanceof DOMDOCUMENT) {
  4500. $domId = self::getDocumentID($context);
  4501. if (! $domId) {
  4502. //throw new Exception('Orphaned DOMDocument');
  4503. $domId = self::newDocument($context)->getDocumentID();
  4504. }
  4505. } else if ($context instanceof DOMNODE) {
  4506. $domId = self::getDocumentID($context);
  4507. if (! $domId) {
  4508. throw new Exception('Orphaned DOMNode');
  4509. // $domId = self::newDocument($context->ownerDocument);
  4510. }
  4511. } else
  4512. $domId = $context;
  4513. if ($arg1 instanceof phpQueryObject) {
  4514. // if (is_object($arg1) && (get_class($arg1) == 'phpQueryObject' || $arg1 instanceof PHPQUERY || is_subclass_of($arg1, 'phpQueryObject'))) {
  4515. /**
  4516. * Return $arg1 or import $arg1 stack if document differs:
  4517. * pq(pq('<div/>'))
  4518. */
  4519. if ($arg1->getDocumentID() == $domId)
  4520. return $arg1;
  4521. $class = get_class($arg1);
  4522. // support inheritance by passing old object to overloaded constructor
  4523. $phpQuery = $class != 'phpQuery'
  4524. ? new $class($arg1, $domId)
  4525. : new phpQueryObject($domId);
  4526. $phpQuery->elements = array();
  4527. foreach($arg1->elements as $node)
  4528. $phpQuery->elements[] = $phpQuery->document->importNode($node, true);
  4529. return $phpQuery;
  4530. } else if ($arg1 instanceof DOMNODE || (is_array($arg1) && isset($arg1[0]) && $arg1[0] instanceof DOMNODE)) {
  4531. /*
  4532. * Wrap DOM nodes with phpQuery object, import into document when needed:
  4533. * pq(array($domNode1, $domNode2))
  4534. */
  4535. $phpQuery = new phpQueryObject($domId);
  4536. if (!($arg1 instanceof DOMNODELIST) && ! is_array($arg1))
  4537. $arg1 = array($arg1);
  4538. $phpQuery->elements = array();
  4539. foreach($arg1 as $node) {
  4540. $sameDocument = $node->ownerDocument instanceof DOMDOCUMENT
  4541. && ! $node->ownerDocument->isSameNode($phpQuery->document);
  4542. $phpQuery->elements[] = $sameDocument
  4543. ? $phpQuery->document->importNode($node, true)
  4544. : $node;
  4545. }
  4546. return $phpQuery;
  4547. } else if (self::isMarkup($arg1)) {
  4548. /**
  4549. * Import HTML:
  4550. * pq('<div/>')
  4551. */
  4552. $phpQuery = new phpQueryObject($domId);
  4553. return $phpQuery->newInstance(
  4554. $phpQuery->documentWrapper->import($arg1)
  4555. );
  4556. } else {
  4557. /**
  4558. * Run CSS query:
  4559. * pq('div.myClass')
  4560. */
  4561. $phpQuery = new phpQueryObject($domId);
  4562. // if ($context && ($context instanceof PHPQUERY || is_subclass_of($context, 'phpQueryObject')))
  4563. if ($context && $context instanceof phpQueryObject)
  4564. $phpQuery->elements = $context->elements;
  4565. else if ($context && $context instanceof DOMNODELIST) {
  4566. $phpQuery->elements = array();
  4567. foreach($context as $node)
  4568. $phpQuery->elements[] = $node;
  4569. } else if ($context && $context instanceof DOMNODE)
  4570. $phpQuery->elements = array($context);
  4571. return $phpQuery->find($arg1);
  4572. }
  4573. }
  4574. /**
  4575. * Sets default document to $id. Document has to be loaded prior
  4576. * to using this method.
  4577. * $id can be retrived via getDocumentID() or getDocumentIDRef().
  4578. *
  4579. * @param unknown_type $id
  4580. */
  4581. public static function selectDocument($id) {
  4582. $id = self::getDocumentID($id);
  4583. self::debug("Selecting document '$id' as default one");
  4584. self::$defaultDocumentID = self::getDocumentID($id);
  4585. }
  4586. /**
  4587. * Returns document with id $id or last used as phpQueryObject.
  4588. * $id can be retrived via getDocumentID() or getDocumentIDRef().
  4589. * Chainable.
  4590. *
  4591. * @see phpQuery::selectDocument()
  4592. * @param unknown_type $id
  4593. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4594. */
  4595. public static function getDocument($id = null) {
  4596. if ($id)
  4597. phpQuery::selectDocument($id);
  4598. else
  4599. $id = phpQuery::$defaultDocumentID;
  4600. return new phpQueryObject($id);
  4601. }
  4602. /**
  4603. * Creates new document from markup.
  4604. * Chainable.
  4605. *
  4606. * @param unknown_type $markup
  4607. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4608. */
  4609. public static function newDocument($markup = null, $contentType = null) {
  4610. if (! $markup)
  4611. $markup = '';
  4612. $documentID = phpQuery::createDocumentWrapper($markup, $contentType);
  4613. return new phpQueryObject($documentID);
  4614. }
  4615. /**
  4616. * Creates new document from markup.
  4617. * Chainable.
  4618. *
  4619. * @param unknown_type $markup
  4620. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4621. */
  4622. public static function newDocumentHTML($markup = null, $charset = null) {
  4623. $contentType = $charset
  4624. ? ";charset=$charset"
  4625. : '';
  4626. return self::newDocument($markup, "text/html{$contentType}");
  4627. }
  4628. /**
  4629. * Creates new document from markup.
  4630. * Chainable.
  4631. *
  4632. * @param unknown_type $markup
  4633. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4634. */
  4635. public static function newDocumentXML($markup = null, $charset = null) {
  4636. $contentType = $charset
  4637. ? ";charset=$charset"
  4638. : '';
  4639. return self::newDocument($markup, "text/xml{$contentType}");
  4640. }
  4641. /**
  4642. * Creates new document from markup.
  4643. * Chainable.
  4644. *
  4645. * @param unknown_type $markup
  4646. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4647. */
  4648. public static function newDocumentXHTML($markup = null, $charset = null) {
  4649. $contentType = $charset
  4650. ? ";charset=$charset"
  4651. : '';
  4652. return self::newDocument($markup, "application/xhtml+xml{$contentType}");
  4653. }
  4654. /**
  4655. * Creates new document from markup.
  4656. * Chainable.
  4657. *
  4658. * @param unknown_type $markup
  4659. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4660. */
  4661. public static function newDocumentPHP($markup = null, $contentType = "text/html") {
  4662. // TODO pass charset to phpToMarkup if possible (use DOMDocumentWrapper function)
  4663. $markup = phpQuery::phpToMarkup($markup, self::$defaultCharset);
  4664. return self::newDocument($markup, $contentType);
  4665. }
  4666. public static function phpToMarkup($php, $charset = 'utf-8') {
  4667. $regexes = array(
  4668. '@(<(?!\\?)(?:[^>]|\\?>)+\\w+\\s*=\\s*)(\')([^\']*)<'.'?php?(.*?)(?:\\?>)([^\']*)\'@s',
  4669. '@(<(?!\\?)(?:[^>]|\\?>)+\\w+\\s*=\\s*)(")([^"]*)<'.'?php?(.*?)(?:\\?>)([^"]*)"@s',
  4670. );
  4671. foreach($regexes as $regex)
  4672. while (preg_match($regex, $php, $matches)) {
  4673. $php = preg_replace_callback(
  4674. $regex,
  4675. // create_function('$m, $charset = "'.$charset.'"',
  4676. // 'return $m[1].$m[2]
  4677. // .htmlspecialchars("<"."?php".$m[4]."?".">", ENT_QUOTES|ENT_NOQUOTES, $charset)
  4678. // .$m[5].$m[2];'
  4679. // ),
  4680. array('phpQuery', '_phpToMarkupCallback'),
  4681. $php
  4682. );
  4683. }
  4684. $regex = '@(^|>[^<]*)+?(<\?php(.*?)(\?>))@s';
  4685. //preg_match_all($regex, $php, $matches);
  4686. //var_dump($matches);
  4687. $php = preg_replace($regex, '\\1<php><!-- \\3 --></php>', $php);
  4688. return $php;
  4689. }
  4690. public static function _phpToMarkupCallback($php, $charset = 'utf-8') {
  4691. return $m[1].$m[2]
  4692. .htmlspecialchars("<"."?php".$m[4]."?".">", ENT_QUOTES|ENT_NOQUOTES, $charset)
  4693. .$m[5].$m[2];
  4694. }
  4695. public static function _markupToPHPCallback($m) {
  4696. return "<"."?php ".htmlspecialchars_decode($m[1])." ?".">";
  4697. }
  4698. /**
  4699. * Converts document markup containing PHP code generated by phpQuery::php()
  4700. * into valid (executable) PHP code syntax.
  4701. *
  4702. * @param string|phpQueryObject $content
  4703. * @return string PHP code.
  4704. */
  4705. public static function markupToPHP($content) {
  4706. if ($content instanceof phpQueryObject)
  4707. $content = $content->markupOuter();
  4708. /* <php>...</php> to <?php...? > */
  4709. $content = preg_replace_callback(
  4710. '@<php>\s*<!--(.*?)-->\s*</php>@s',
  4711. // create_function('$m',
  4712. // 'return "<'.'?php ".htmlspecialchars_decode($m[1])." ?'.'>";'
  4713. // ),
  4714. array('phpQuery', '_markupToPHPCallback'),
  4715. $content
  4716. );
  4717. /* <node attr='< ?php ? >'> extra space added to save highlighters */
  4718. $regexes = array(
  4719. '@(<(?!\\?)(?:[^>]|\\?>)+\\w+\\s*=\\s*)(\')([^\']*)(?:&lt;|%3C)\\?(?:php)?(.*?)(?:\\?(?:&gt;|%3E))([^\']*)\'@s',
  4720. '@(<(?!\\?)(?:[^>]|\\?>)+\\w+\\s*=\\s*)(")([^"]*)(?:&lt;|%3C)\\?(?:php)?(.*?)(?:\\?(?:&gt;|%3E))([^"]*)"@s',
  4721. );
  4722. foreach($regexes as $regex)
  4723. while (preg_match($regex, $content))
  4724. $content = preg_replace_callback(
  4725. $regex,
  4726. create_function('$m',
  4727. 'return $m[1].$m[2].$m[3]."<?php "
  4728. .str_replace(
  4729. array("%20", "%3E", "%09", "&#10;", "&#9;", "%7B", "%24", "%7D", "%22", "%5B", "%5D"),
  4730. array(" ", ">", " ", "\n", " ", "{", "$", "}", \'"\', "[", "]"),
  4731. htmlspecialchars_decode($m[4])
  4732. )
  4733. ." ?>".$m[5].$m[2];'
  4734. ),
  4735. $content
  4736. );
  4737. return $content;
  4738. }
  4739. /**
  4740. * Creates new document from file $file.
  4741. * Chainable.
  4742. *
  4743. * @param string $file URLs allowed. See File wrapper page at php.net for more supported sources.
  4744. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4745. */
  4746. public static function newDocumentFile($file, $contentType = null) {
  4747. $documentID = self::createDocumentWrapper(
  4748. file_get_contents($file), $contentType
  4749. );
  4750. return new phpQueryObject($documentID);
  4751. }
  4752. /**
  4753. * Creates new document from markup.
  4754. * Chainable.
  4755. *
  4756. * @param unknown_type $markup
  4757. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4758. */
  4759. public static function newDocumentFileHTML($file, $charset = null) {
  4760. $contentType = $charset
  4761. ? ";charset=$charset"
  4762. : '';
  4763. return self::newDocumentFile($file, "text/html{$contentType}");
  4764. }
  4765. /**
  4766. * Creates new document from markup.
  4767. * Chainable.
  4768. *
  4769. * @param unknown_type $markup
  4770. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4771. */
  4772. public static function newDocumentFileXML($file, $charset = null) {
  4773. $contentType = $charset
  4774. ? ";charset=$charset"
  4775. : '';
  4776. return self::newDocumentFile($file, "text/xml{$contentType}");
  4777. }
  4778. /**
  4779. * Creates new document from markup.
  4780. * Chainable.
  4781. *
  4782. * @param unknown_type $markup
  4783. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4784. */
  4785. public static function newDocumentFileXHTML($file, $charset = null) {
  4786. $contentType = $charset
  4787. ? ";charset=$charset"
  4788. : '';
  4789. return self::newDocumentFile($file, "application/xhtml+xml{$contentType}");
  4790. }
  4791. /**
  4792. * Creates new document from markup.
  4793. * Chainable.
  4794. *
  4795. * @param unknown_type $markup
  4796. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4797. */
  4798. public static function newDocumentFilePHP($file, $contentType = null) {
  4799. return self::newDocumentPHP(file_get_contents($file), $contentType);
  4800. }
  4801. /**
  4802. * Reuses existing DOMDocument object.
  4803. * Chainable.
  4804. *
  4805. * @param $document DOMDocument
  4806. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  4807. * @TODO support DOMDocument
  4808. */
  4809. public static function loadDocument($document) {
  4810. // TODO
  4811. die('TODO loadDocument');
  4812. }
  4813. /**
  4814. * Enter description here...
  4815. *
  4816. * @param unknown_type $html
  4817. * @param unknown_type $domId
  4818. * @return unknown New DOM ID
  4819. * @todo support PHP tags in input
  4820. * @todo support passing DOMDocument object from self::loadDocument
  4821. */
  4822. protected static function createDocumentWrapper($html, $contentType = null, $documentID = null) {
  4823. if (function_exists('domxml_open_mem'))
  4824. throw new Exception("Old PHP4 DOM XML extension detected. phpQuery won't work until this extension is enabled.");
  4825. // $id = $documentID
  4826. // ? $documentID
  4827. // : md5(microtime());
  4828. $document = null;
  4829. if ($html instanceof DOMDOCUMENT) {
  4830. if (self::getDocumentID($html)) {
  4831. // document already exists in phpQuery::$documents, make a copy
  4832. $document = clone $html;
  4833. } else {
  4834. // new document, add it to phpQuery::$documents
  4835. $wrapper = new DOMDocumentWrapper($html, $contentType, $documentID);
  4836. }
  4837. } else {
  4838. $wrapper = new DOMDocumentWrapper($html, $contentType, $documentID);
  4839. }
  4840. // $wrapper->id = $id;
  4841. // bind document
  4842. phpQuery::$documents[$wrapper->id] = $wrapper;
  4843. // remember last loaded document
  4844. phpQuery::selectDocument($wrapper->id);
  4845. return $wrapper->id;
  4846. }
  4847. /**
  4848. * Extend class namespace.
  4849. *
  4850. * @param string|array $target
  4851. * @param array $source
  4852. * @TODO support string $source
  4853. * @return unknown_type
  4854. */
  4855. public static function extend($target, $source) {
  4856. switch($target) {
  4857. case 'phpQueryObject':
  4858. $targetRef = &self::$extendMethods;
  4859. $targetRef2 = &self::$pluginsMethods;
  4860. break;
  4861. case 'phpQuery':
  4862. $targetRef = &self::$extendStaticMethods;
  4863. $targetRef2 = &self::$pluginsStaticMethods;
  4864. break;
  4865. default:
  4866. throw new Exception("Unsupported \$target type");
  4867. }
  4868. if (is_string($source))
  4869. $source = array($source => $source);
  4870. foreach($source as $method => $callback) {
  4871. if (isset($targetRef[$method])) {
  4872. // throw new Exception
  4873. self::debug("Duplicate method '{$method}', can\'t extend '{$target}'");
  4874. continue;
  4875. }
  4876. if (isset($targetRef2[$method])) {
  4877. // throw new Exception
  4878. self::debug("Duplicate method '{$method}' from plugin '{$targetRef2[$method]}',"
  4879. ." can\'t extend '{$target}'");
  4880. continue;
  4881. }
  4882. $targetRef[$method] = $callback;
  4883. }
  4884. return true;
  4885. }
  4886. /**
  4887. * Extend phpQuery with $class from $file.
  4888. *
  4889. * @param string $class Extending class name. Real class name can be prepended phpQuery_.
  4890. * @param string $file Filename to include. Defaults to "{$class}.php".
  4891. */
  4892. public static function plugin($class, $file = null) {
  4893. // TODO $class checked agains phpQuery_$class
  4894. // if (strpos($class, 'phpQuery') === 0)
  4895. // $class = substr($class, 8);
  4896. if (in_array($class, self::$pluginsLoaded))
  4897. return true;
  4898. if (! $file)
  4899. $file = $class.'.php';
  4900. $objectClassExists = class_exists('phpQueryObjectPlugin_'.$class);
  4901. $staticClassExists = class_exists('phpQueryPlugin_'.$class);
  4902. if (! $objectClassExists && ! $staticClassExists)
  4903. require_once($file);
  4904. self::$pluginsLoaded[] = $class;
  4905. // static methods
  4906. if (class_exists('phpQueryPlugin_'.$class)) {
  4907. $realClass = 'phpQueryPlugin_'.$class;
  4908. $vars = get_class_vars($realClass);
  4909. $loop = isset($vars['phpQueryMethods'])
  4910. && ! is_null($vars['phpQueryMethods'])
  4911. ? $vars['phpQueryMethods']
  4912. : get_class_methods($realClass);
  4913. foreach($loop as $method) {
  4914. if ($method == '__initialize')
  4915. continue;
  4916. if (! is_callable(array($realClass, $method)))
  4917. continue;
  4918. if (isset(self::$pluginsStaticMethods[$method])) {
  4919. throw new Exception("Duplicate method '{$method}' from plugin '{$c}' conflicts with same method from plugin '".self::$pluginsStaticMethods[$method]."'");
  4920. return;
  4921. }
  4922. self::$pluginsStaticMethods[$method] = $class;
  4923. }
  4924. if (method_exists($realClass, '__initialize'))
  4925. call_user_func_array(array($realClass, '__initialize'), array());
  4926. }
  4927. // object methods
  4928. if (class_exists('phpQueryObjectPlugin_'.$class)) {
  4929. $realClass = 'phpQueryObjectPlugin_'.$class;
  4930. $vars = get_class_vars($realClass);
  4931. $loop = isset($vars['phpQueryMethods'])
  4932. && ! is_null($vars['phpQueryMethods'])
  4933. ? $vars['phpQueryMethods']
  4934. : get_class_methods($realClass);
  4935. foreach($loop as $method) {
  4936. if (! is_callable(array($realClass, $method)))
  4937. continue;
  4938. if (isset(self::$pluginsMethods[$method])) {
  4939. throw new Exception("Duplicate method '{$method}' from plugin '{$c}' conflicts with same method from plugin '".self::$pluginsMethods[$method]."'");
  4940. continue;
  4941. }
  4942. self::$pluginsMethods[$method] = $class;
  4943. }
  4944. }
  4945. return true;
  4946. }
  4947. /**
  4948. * Unloades all or specified document from memory.
  4949. *
  4950. * @param mixed $documentID @see phpQuery::getDocumentID() for supported types.
  4951. */
  4952. public static function unloadDocuments($id = null) {
  4953. if (isset($id)) {
  4954. if ($id = self::getDocumentID($id))
  4955. unset(phpQuery::$documents[$id]);
  4956. } else {
  4957. foreach(phpQuery::$documents as $k => $v) {
  4958. unset(phpQuery::$documents[$k]);
  4959. }
  4960. }
  4961. }
  4962. /**
  4963. * Parses phpQuery object or HTML result against PHP tags and makes them active.
  4964. *
  4965. * @param phpQuery|string $content
  4966. * @deprecated
  4967. * @return string
  4968. */
  4969. public static function unsafePHPTags($content) {
  4970. return self::markupToPHP($content);
  4971. }
  4972. public static function DOMNodeListToArray($DOMNodeList) {
  4973. $array = array();
  4974. if (! $DOMNodeList)
  4975. return $array;
  4976. foreach($DOMNodeList as $node)
  4977. $array[] = $node;
  4978. return $array;
  4979. }
  4980. /**
  4981. * Checks if $input is HTML string, which has to start with '<'.
  4982. *
  4983. * @deprecated
  4984. * @param String $input
  4985. * @return Bool
  4986. * @todo still used ?
  4987. */
  4988. public static function isMarkup($input) {
  4989. return ! is_array($input) && substr(trim($input), 0, 1) == '<';
  4990. }
  4991. public static function debug($text) {
  4992. if (self::$debug)
  4993. print var_dump($text);
  4994. }
  4995. /**
  4996. * Make an AJAX request.
  4997. *
  4998. * @param array See $options http://docs.jquery.com/Ajax/jQuery.ajax#toptions
  4999. * Additional options are:
  5000. * 'document' - document for global events, @see phpQuery::getDocumentID()
  5001. * 'referer' - implemented
  5002. * 'requested_with' - TODO; not implemented (X-Requested-With)
  5003. * @return Zend_Http_Client
  5004. * @link http://docs.jquery.com/Ajax/jQuery.ajax
  5005. *
  5006. * @TODO $options['cache']
  5007. * @TODO $options['processData']
  5008. * @TODO $options['xhr']
  5009. * @TODO $options['data'] as string
  5010. * @TODO XHR interface
  5011. */
  5012. public static function ajax($options = array(), $xhr = null) {
  5013. $options = array_merge(
  5014. self::$ajaxSettings, $options
  5015. );
  5016. $documentID = isset($options['document'])
  5017. ? self::getDocumentID($options['document'])
  5018. : null;
  5019. if ($xhr) {
  5020. // reuse existing XHR object, but clean it up
  5021. $client = $xhr;
  5022. // $client->setParameterPost(null);
  5023. // $client->setParameterGet(null);
  5024. $client->setAuth(false);
  5025. $client->setHeaders("If-Modified-Since", null);
  5026. $client->setHeaders("Referer", null);
  5027. $client->resetParameters();
  5028. } else {
  5029. // create new XHR object
  5030. require_once('Zend/Http/Client.php');
  5031. $client = new Zend_Http_Client();
  5032. $client->setCookieJar();
  5033. }
  5034. if (isset($options['timeout']))
  5035. $client->setConfig(array(
  5036. 'timeout' => $options['timeout'],
  5037. ));
  5038. // 'maxredirects' => 0,
  5039. foreach(self::$ajaxAllowedHosts as $k => $host)
  5040. if ($host == '.' && isset($_SERVER['HTTP_HOST']))
  5041. self::$ajaxAllowedHosts[$k] = $_SERVER['HTTP_HOST'];
  5042. $host = parse_url($options['url'], PHP_URL_HOST);
  5043. if (! in_array($host, self::$ajaxAllowedHosts)) {
  5044. throw new Exception("Request not permitted, host '$host' not present in "
  5045. ."phpQuery::\$ajaxAllowedHosts");
  5046. }
  5047. // JSONP
  5048. $jsre = "/=\\?(&|$)/";
  5049. if (isset($options['dataType']) && $options['dataType'] == 'jsonp') {
  5050. $jsonpCallbackParam = $options['jsonp']
  5051. ? $options['jsonp'] : 'callback';
  5052. if (strtolower($options['type']) == 'get') {
  5053. if (! preg_match($jsre, $options['url'])) {
  5054. $sep = strpos($options['url'], '?')
  5055. ? '&' : '?';
  5056. $options['url'] .= "$sep$jsonpCallbackParam=?";
  5057. }
  5058. } else if ($options['data']) {
  5059. $jsonp = false;
  5060. foreach($options['data'] as $n => $v) {
  5061. if ($v == '?')
  5062. $jsonp = true;
  5063. }
  5064. if (! $jsonp) {
  5065. $options['data'][$jsonpCallbackParam] = '?';
  5066. }
  5067. }
  5068. $options['dataType'] = 'json';
  5069. }
  5070. if (isset($options['dataType']) && $options['dataType'] == 'json') {
  5071. $jsonpCallback = 'json_'.md5(microtime());
  5072. $jsonpData = $jsonpUrl = false;
  5073. if ($options['data']) {
  5074. foreach($options['data'] as $n => $v) {
  5075. if ($v == '?')
  5076. $jsonpData = $n;
  5077. }
  5078. }
  5079. if (preg_match($jsre, $options['url']))
  5080. $jsonpUrl = true;
  5081. if ($jsonpData !== false || $jsonpUrl) {
  5082. // remember callback name for httpData()
  5083. $options['_jsonp'] = $jsonpCallback;
  5084. if ($jsonpData !== false)
  5085. $options['data'][$jsonpData] = $jsonpCallback;
  5086. if ($jsonpUrl)
  5087. $options['url'] = preg_replace($jsre, "=$jsonpCallback\\1", $options['url']);
  5088. }
  5089. }
  5090. $client->setUri($options['url']);
  5091. $client->setMethod(strtoupper($options['type']));
  5092. if (isset($options['referer']) && $options['referer'])
  5093. $client->setHeaders('Referer', $options['referer']);
  5094. $client->setHeaders(array(
  5095. // 'content-type' => $options['contentType'],
  5096. 'User-Agent' => 'Mozilla/5.0 (X11; U; Linux x86; en-US; rv:1.9.0.5) Gecko'
  5097. .'/2008122010 Firefox/3.0.5',
  5098. // TODO custom charset
  5099. 'Accept-Charset' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  5100. // 'Connection' => 'keep-alive',
  5101. // 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  5102. 'Accept-Language' => 'en-us,en;q=0.5',
  5103. ));
  5104. if ($options['username'])
  5105. $client->setAuth($options['username'], $options['password']);
  5106. if (isset($options['ifModified']) && $options['ifModified'])
  5107. $client->setHeaders("If-Modified-Since",
  5108. self::$lastModified
  5109. ? self::$lastModified
  5110. : "Thu, 01 Jan 1970 00:00:00 GMT"
  5111. );
  5112. $client->setHeaders("Accept",
  5113. isset($options['dataType'])
  5114. && isset(self::$ajaxSettings['accepts'][ $options['dataType'] ])
  5115. ? self::$ajaxSettings['accepts'][ $options['dataType'] ].", */*"
  5116. : self::$ajaxSettings['accepts']['_default']
  5117. );
  5118. // TODO $options['processData']
  5119. if ($options['data'] instanceof phpQueryObject) {
  5120. $serialized = $options['data']->serializeArray($options['data']);
  5121. $options['data'] = array();
  5122. foreach($serialized as $r)
  5123. $options['data'][ $r['name'] ] = $r['value'];
  5124. }
  5125. if (strtolower($options['type']) == 'get') {
  5126. $client->setParameterGet($options['data']);
  5127. } else if (strtolower($options['type']) == 'post') {
  5128. $client->setEncType($options['contentType']);
  5129. $client->setParameterPost($options['data']);
  5130. }
  5131. if (self::$active == 0 && $options['global'])
  5132. phpQueryEvents::trigger($documentID, 'ajaxStart');
  5133. self::$active++;
  5134. // beforeSend callback
  5135. if (isset($options['beforeSend']) && $options['beforeSend'])
  5136. phpQuery::callbackRun($options['beforeSend'], array($client));
  5137. // ajaxSend event
  5138. if ($options['global'])
  5139. phpQueryEvents::trigger($documentID, 'ajaxSend', array($client, $options));
  5140. if (phpQuery::$debug) {
  5141. self::debug("{$options['type']}: {$options['url']}\n");
  5142. self::debug("Options: <pre>".var_export($options, true)."</pre>\n");
  5143. // if ($client->getCookieJar())
  5144. // self::debug("Cookies: <pre>".var_export($client->getCookieJar()->getMatchingCookies($options['url']), true)."</pre>\n");
  5145. }
  5146. // request
  5147. $response = $client->request();
  5148. if (phpQuery::$debug) {
  5149. self::debug('Status: '.$response->getStatus().' / '.$response->getMessage());
  5150. self::debug($client->getLastRequest());
  5151. self::debug($response->getHeaders());
  5152. }
  5153. if ($response->isSuccessful()) {
  5154. // XXX tempolary
  5155. self::$lastModified = $response->getHeader('Last-Modified');
  5156. $data = self::httpData($response->getBody(), $options['dataType'], $options);
  5157. if (isset($options['success']) && $options['success'])
  5158. phpQuery::callbackRun($options['success'], array($data, $response->getStatus(), $options));
  5159. if ($options['global'])
  5160. phpQueryEvents::trigger($documentID, 'ajaxSuccess', array($client, $options));
  5161. } else {
  5162. if (isset($options['error']) && $options['error'])
  5163. phpQuery::callbackRun($options['error'], array($client, $response->getStatus(), $response->getMessage()));
  5164. if ($options['global'])
  5165. phpQueryEvents::trigger($documentID, 'ajaxError', array($client, /*$response->getStatus(),*/$response->getMessage(), $options));
  5166. }
  5167. if (isset($options['complete']) && $options['complete'])
  5168. phpQuery::callbackRun($options['complete'], array($client, $response->getStatus()));
  5169. if ($options['global'])
  5170. phpQueryEvents::trigger($documentID, 'ajaxComplete', array($client, $options));
  5171. if ($options['global'] && ! --self::$active)
  5172. phpQueryEvents::trigger($documentID, 'ajaxStop');
  5173. return $client;
  5174. // if (is_null($domId))
  5175. // $domId = self::$defaultDocumentID ? self::$defaultDocumentID : false;
  5176. // return new phpQueryAjaxResponse($response, $domId);
  5177. }
  5178. protected static function httpData($data, $type, $options) {
  5179. if (isset($options['dataFilter']) && $options['dataFilter'])
  5180. $data = self::callbackRun($options['dataFilter'], array($data, $type));
  5181. if (is_string($data)) {
  5182. if ($type == "json") {
  5183. if (isset($options['_jsonp']) && $options['_jsonp']) {
  5184. $data = preg_replace('/^\s*\w+\((.*)\)\s*$/s', '$1', $data);
  5185. }
  5186. $data = self::parseJSON($data);
  5187. }
  5188. }
  5189. return $data;
  5190. }
  5191. /**
  5192. * Enter description here...
  5193. *
  5194. * @param array|phpQuery $data
  5195. *
  5196. */
  5197. public static function param($data) {
  5198. return http_build_query($data, null, '&');
  5199. }
  5200. public static function get($url, $data = null, $callback = null, $type = null) {
  5201. if (!is_array($data)) {
  5202. $callback = $data;
  5203. $data = null;
  5204. }
  5205. // TODO some array_values on this shit
  5206. return phpQuery::ajax(array(
  5207. 'type' => 'GET',
  5208. 'url' => $url,
  5209. 'data' => $data,
  5210. 'success' => $callback,
  5211. 'dataType' => $type,
  5212. ));
  5213. }
  5214. public static function post($url, $data = null, $callback = null, $type = null) {
  5215. if (!is_array($data)) {
  5216. $callback = $data;
  5217. $data = null;
  5218. }
  5219. return phpQuery::ajax(array(
  5220. 'type' => 'POST',
  5221. 'url' => $url,
  5222. 'data' => $data,
  5223. 'success' => $callback,
  5224. 'dataType' => $type,
  5225. ));
  5226. }
  5227. public static function getJSON($url, $data = null, $callback = null) {
  5228. if (!is_array($data)) {
  5229. $callback = $data;
  5230. $data = null;
  5231. }
  5232. // TODO some array_values on this shit
  5233. return phpQuery::ajax(array(
  5234. 'type' => 'GET',
  5235. 'url' => $url,
  5236. 'data' => $data,
  5237. 'success' => $callback,
  5238. 'dataType' => 'json',
  5239. ));
  5240. }
  5241. public static function ajaxSetup($options) {
  5242. self::$ajaxSettings = array_merge(
  5243. self::$ajaxSettings,
  5244. $options
  5245. );
  5246. }
  5247. public static function ajaxAllowHost($host1, $host2 = null, $host3 = null) {
  5248. $loop = is_array($host1)
  5249. ? $host1
  5250. : func_get_args();
  5251. foreach($loop as $host) {
  5252. if ($host && ! in_array($host, phpQuery::$ajaxAllowedHosts)) {
  5253. phpQuery::$ajaxAllowedHosts[] = $host;
  5254. }
  5255. }
  5256. }
  5257. public static function ajaxAllowURL($url1, $url2 = null, $url3 = null) {
  5258. $loop = is_array($url1)
  5259. ? $url1
  5260. : func_get_args();
  5261. foreach($loop as $url)
  5262. phpQuery::ajaxAllowHost(parse_url($url, PHP_URL_HOST));
  5263. }
  5264. /**
  5265. * Returns JSON representation of $data.
  5266. *
  5267. * @static
  5268. * @param mixed $data
  5269. * @return string
  5270. */
  5271. public static function toJSON($data) {
  5272. if (function_exists('json_encode'))
  5273. return json_encode($data);
  5274. require_once('Zend/Json/Encoder.php');
  5275. return Zend_Json_Encoder::encode($data);
  5276. }
  5277. /**
  5278. * Parses JSON into proper PHP type.
  5279. *
  5280. * @static
  5281. * @param string $json
  5282. * @return mixed
  5283. */
  5284. public static function parseJSON($json) {
  5285. if (function_exists('json_decode')) {
  5286. $return = json_decode(trim($json), true);
  5287. // json_decode and UTF8 issues
  5288. if (isset($return))
  5289. return $return;
  5290. }
  5291. require_once('Zend/Json/Decoder.php');
  5292. return Zend_Json_Decoder::decode($json);
  5293. }
  5294. /**
  5295. * Returns source's document ID.
  5296. *
  5297. * @param $source DOMNode|phpQueryObject
  5298. * @return string
  5299. */
  5300. public static function getDocumentID($source) {
  5301. if ($source instanceof DOMDOCUMENT) {
  5302. foreach(phpQuery::$documents as $id => $document) {
  5303. if ($source->isSameNode($document->document))
  5304. return $id;
  5305. }
  5306. } else if ($source instanceof DOMNODE) {
  5307. foreach(phpQuery::$documents as $id => $document) {
  5308. if ($source->ownerDocument->isSameNode($document->document))
  5309. return $id;
  5310. }
  5311. } else if ($source instanceof phpQueryObject)
  5312. return $source->getDocumentID();
  5313. else if (is_string($source) && isset(phpQuery::$documents[$source]))
  5314. return $source;
  5315. }
  5316. /**
  5317. * Get DOMDocument object related to $source.
  5318. * Returns null if such document doesn't exist.
  5319. *
  5320. * @param $source DOMNode|phpQueryObject|string
  5321. * @return string
  5322. */
  5323. public static function getDOMDocument($source) {
  5324. if ($source instanceof DOMDOCUMENT)
  5325. return $source;
  5326. $source = self::getDocumentID($source);
  5327. return $source
  5328. ? self::$documents[$id]['document']
  5329. : null;
  5330. }
  5331. // UTILITIES
  5332. // http://docs.jquery.com/Utilities
  5333. /**
  5334. *
  5335. * @return unknown_type
  5336. * @link http://docs.jquery.com/Utilities/jQuery.makeArray
  5337. */
  5338. public static function makeArray($obj) {
  5339. $array = array();
  5340. if (is_object($object) && $object instanceof DOMNODELIST) {
  5341. foreach($object as $value)
  5342. $array[] = $value;
  5343. } else if (is_object($object) && ! ($object instanceof Iterator)) {
  5344. foreach(get_object_vars($object) as $name => $value)
  5345. $array[0][$name] = $value;
  5346. } else {
  5347. foreach($object as $name => $value)
  5348. $array[0][$name] = $value;
  5349. }
  5350. return $array;
  5351. }
  5352. public static function inArray($value, $array) {
  5353. return in_array($value, $array);
  5354. }
  5355. /**
  5356. *
  5357. * @param $object
  5358. * @param $callback
  5359. * @return unknown_type
  5360. * @link http://docs.jquery.com/Utilities/jQuery.each
  5361. */
  5362. public static function each($object, $callback, $param1 = null, $param2 = null, $param3 = null) {
  5363. $paramStructure = null;
  5364. if (func_num_args() > 2) {
  5365. $paramStructure = func_get_args();
  5366. $paramStructure = array_slice($paramStructure, 2);
  5367. }
  5368. if (is_object($object) && ! ($object instanceof Iterator)) {
  5369. foreach(get_object_vars($object) as $name => $value)
  5370. phpQuery::callbackRun($callback, array($name, $value), $paramStructure);
  5371. } else {
  5372. foreach($object as $name => $value)
  5373. phpQuery::callbackRun($callback, array($name, $value), $paramStructure);
  5374. }
  5375. }
  5376. /**
  5377. *
  5378. * @link http://docs.jquery.com/Utilities/jQuery.map
  5379. */
  5380. public static function map($array, $callback, $param1 = null, $param2 = null, $param3 = null) {
  5381. $result = array();
  5382. $paramStructure = null;
  5383. if (func_num_args() > 2) {
  5384. $paramStructure = func_get_args();
  5385. $paramStructure = array_slice($paramStructure, 2);
  5386. }
  5387. foreach($array as $v) {
  5388. $vv = phpQuery::callbackRun($callback, array($v), $paramStructure);
  5389. // $callbackArgs = $args;
  5390. // foreach($args as $i => $arg) {
  5391. // $callbackArgs[$i] = $arg instanceof CallbackParam
  5392. // ? $v
  5393. // : $arg;
  5394. // }
  5395. // $vv = call_user_func_array($callback, $callbackArgs);
  5396. if (is_array($vv)) {
  5397. foreach($vv as $vvv)
  5398. $result[] = $vvv;
  5399. } else if ($vv !== null) {
  5400. $result[] = $vv;
  5401. }
  5402. }
  5403. return $result;
  5404. }
  5405. /**
  5406. *
  5407. * @param $callback Callback
  5408. * @param $params
  5409. * @param $paramStructure
  5410. * @return unknown_type
  5411. */
  5412. public static function callbackRun($callback, $params = array(), $paramStructure = null) {
  5413. if (! $callback)
  5414. return;
  5415. if ($callback instanceof CallbackParameterToReference) {
  5416. // TODO support ParamStructure to select which $param push to reference
  5417. if (isset($params[0]))
  5418. $callback->callback = $params[0];
  5419. return true;
  5420. }
  5421. if ($callback instanceof Callback) {
  5422. $paramStructure = $callback->params;
  5423. $callback = $callback->callback;
  5424. }
  5425. if (! $paramStructure)
  5426. return call_user_func_array($callback, $params);
  5427. $p = 0;
  5428. foreach($paramStructure as $i => $v) {
  5429. $paramStructure[$i] = $v instanceof CallbackParam
  5430. ? $params[$p++]
  5431. : $v;
  5432. }
  5433. return call_user_func_array($callback, $paramStructure);
  5434. }
  5435. /**
  5436. * Merge 2 phpQuery objects.
  5437. * @param array $one
  5438. * @param array $two
  5439. * @protected
  5440. * @todo node lists, phpQueryObject
  5441. */
  5442. public static function merge($one, $two) {
  5443. $elements = $one->elements;
  5444. foreach($two->elements as $node) {
  5445. $exists = false;
  5446. foreach($elements as $node2) {
  5447. if ($node2->isSameNode($node))
  5448. $exists = true;
  5449. }
  5450. if (! $exists)
  5451. $elements[] = $node;
  5452. }
  5453. return $elements;
  5454. // $one = $one->newInstance();
  5455. // $one->elements = $elements;
  5456. // return $one;
  5457. }
  5458. /**
  5459. *
  5460. * @param $array
  5461. * @param $callback
  5462. * @param $invert
  5463. * @return unknown_type
  5464. * @link http://docs.jquery.com/Utilities/jQuery.grep
  5465. */
  5466. public static function grep($array, $callback, $invert = false) {
  5467. $result = array();
  5468. foreach($array as $k => $v) {
  5469. $r = call_user_func_array($callback, array($v, $k));
  5470. if ($r === !(bool)$invert)
  5471. $result[] = $v;
  5472. }
  5473. return $result;
  5474. }
  5475. public static function unique($array) {
  5476. return array_unique($array);
  5477. }
  5478. /**
  5479. *
  5480. * @param $function
  5481. * @return unknown_type
  5482. * @TODO there are problems with non-static methods, second parameter pass it
  5483. * but doesnt verify is method is really callable
  5484. */
  5485. public static function isFunction($function) {
  5486. return is_callable($function);
  5487. }
  5488. public static function trim($str) {
  5489. return trim($str);
  5490. }
  5491. /* PLUGINS NAMESPACE */
  5492. /**
  5493. *
  5494. * @param $url
  5495. * @param $callback
  5496. * @param $param1
  5497. * @param $param2
  5498. * @param $param3
  5499. * @return phpQueryObject
  5500. */
  5501. public static function browserGet($url, $callback, $param1 = null, $param2 = null, $param3 = null) {
  5502. if (self::plugin('WebBrowser')) {
  5503. $params = func_get_args();
  5504. return self::callbackRun(array(self::$plugins, 'browserGet'), $params);
  5505. } else {
  5506. self::debug('WebBrowser plugin not available...');
  5507. }
  5508. }
  5509. /**
  5510. *
  5511. * @param $url
  5512. * @param $data
  5513. * @param $callback
  5514. * @param $param1
  5515. * @param $param2
  5516. * @param $param3
  5517. * @return phpQueryObject
  5518. */
  5519. public static function browserPost($url, $data, $callback, $param1 = null, $param2 = null, $param3 = null) {
  5520. if (self::plugin('WebBrowser')) {
  5521. $params = func_get_args();
  5522. return self::callbackRun(array(self::$plugins, 'browserPost'), $params);
  5523. } else {
  5524. self::debug('WebBrowser plugin not available...');
  5525. }
  5526. }
  5527. /**
  5528. *
  5529. * @param $ajaxSettings
  5530. * @param $callback
  5531. * @param $param1
  5532. * @param $param2
  5533. * @param $param3
  5534. * @return phpQueryObject
  5535. */
  5536. public static function browser($ajaxSettings, $callback, $param1 = null, $param2 = null, $param3 = null) {
  5537. if (self::plugin('WebBrowser')) {
  5538. $params = func_get_args();
  5539. return self::callbackRun(array(self::$plugins, 'browser'), $params);
  5540. } else {
  5541. self::debug('WebBrowser plugin not available...');
  5542. }
  5543. }
  5544. /**
  5545. *
  5546. * @param $code
  5547. * @return string
  5548. */
  5549. public static function php($code) {
  5550. return self::code('php', $code);
  5551. }
  5552. /**
  5553. *
  5554. * @param $type
  5555. * @param $code
  5556. * @return string
  5557. */
  5558. public static function code($type, $code) {
  5559. return "<$type><!-- ".trim($code)." --></$type>";
  5560. }
  5561. public static function __callStatic($method, $params) {
  5562. return call_user_func_array(
  5563. array(phpQuery::$plugins, $method),
  5564. $params
  5565. );
  5566. }
  5567. protected static function dataSetupNode($node, $documentID) {
  5568. // search are return if alredy exists
  5569. foreach(phpQuery::$documents[$documentID]->dataNodes as $dataNode) {
  5570. if ($node->isSameNode($dataNode))
  5571. return $dataNode;
  5572. }
  5573. // if doesn't, add it
  5574. phpQuery::$documents[$documentID]->dataNodes[] = $node;
  5575. return $node;
  5576. }
  5577. protected static function dataRemoveNode($node, $documentID) {
  5578. // search are return if alredy exists
  5579. foreach(phpQuery::$documents[$documentID]->dataNodes as $k => $dataNode) {
  5580. if ($node->isSameNode($dataNode)) {
  5581. unset(self::$documents[$documentID]->dataNodes[$k]);
  5582. unset(self::$documents[$documentID]->data[ $dataNode->dataID ]);
  5583. }
  5584. }
  5585. }
  5586. public static function data($node, $name, $data, $documentID = null) {
  5587. if (! $documentID)
  5588. // TODO check if this works
  5589. $documentID = self::getDocumentID($node);
  5590. $document = phpQuery::$documents[$documentID];
  5591. $node = self::dataSetupNode($node, $documentID);
  5592. if (! isset($node->dataID))
  5593. $node->dataID = ++phpQuery::$documents[$documentID]->uuid;
  5594. $id = $node->dataID;
  5595. if (! isset($document->data[$id]))
  5596. $document->data[$id] = array();
  5597. if (! is_null($data))
  5598. $document->data[$id][$name] = $data;
  5599. if ($name) {
  5600. if (isset($document->data[$id][$name]))
  5601. return $document->data[$id][$name];
  5602. } else
  5603. return $id;
  5604. }
  5605. public static function removeData($node, $name, $documentID) {
  5606. if (! $documentID)
  5607. // TODO check if this works
  5608. $documentID = self::getDocumentID($node);
  5609. $document = phpQuery::$documents[$documentID];
  5610. $node = self::dataSetupNode($node, $documentID);
  5611. $id = $node->dataID;
  5612. if ($name) {
  5613. if (isset($document->data[$id][$name]))
  5614. unset($document->data[$id][$name]);
  5615. $name = null;
  5616. foreach($document->data[$id] as $name)
  5617. break;
  5618. if (! $name)
  5619. self::removeData($node, $name, $documentID);
  5620. } else {
  5621. self::dataRemoveNode($node, $documentID);
  5622. }
  5623. }
  5624. }
  5625. /**
  5626. * Plugins static namespace class.
  5627. *
  5628. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  5629. * @package phpQuery
  5630. * @todo move plugin methods here (as statics)
  5631. */
  5632. class phpQueryPlugins {
  5633. public function __call($method, $args) {
  5634. if (isset(phpQuery::$extendStaticMethods[$method])) {
  5635. $return = call_user_func_array(
  5636. phpQuery::$extendStaticMethods[$method],
  5637. $args
  5638. );
  5639. } else if (isset(phpQuery::$pluginsStaticMethods[$method])) {
  5640. $class = phpQuery::$pluginsStaticMethods[$method];
  5641. $realClass = "phpQueryPlugin_$class";
  5642. $return = call_user_func_array(
  5643. array($realClass, $method),
  5644. $args
  5645. );
  5646. return isset($return)
  5647. ? $return
  5648. : $this;
  5649. } else
  5650. throw new Exception("Method '{$method}' doesnt exist");
  5651. }
  5652. }
  5653. /**
  5654. * Shortcut to phpQuery::pq($arg1, $context)
  5655. * Chainable.
  5656. *
  5657. * @see phpQuery::pq()
  5658. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  5659. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  5660. * @package phpQuery
  5661. */
  5662. function pq($arg1, $context = null) {
  5663. $args = func_get_args();
  5664. return call_user_func_array(
  5665. array('phpQuery', 'pq'),
  5666. $args
  5667. );
  5668. }
  5669. // add plugins dir and Zend framework to include path
  5670. set_include_path(
  5671. get_include_path()
  5672. .PATH_SEPARATOR.dirname(__FILE__).'/phpQuery/'
  5673. .PATH_SEPARATOR.dirname(__FILE__).'/phpQuery/plugins/'
  5674. );
  5675. // why ? no __call nor __get for statics in php...
  5676. // XXX __callStatic will be available in PHP 5.3
  5677. phpQuery::$plugins = new phpQueryPlugins();
  5678. // include bootstrap file (personal library config)
  5679. if (file_exists(dirname(__FILE__).'/phpQuery/bootstrap.php'))
  5680. require_once dirname(__FILE__).'/phpQuery/bootstrap.php';