phpQuery.php 170 KB

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