class.phpquery.php 163 KB

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