4
0

lib_phpQuery.php 163 KB

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