phpQuery.php 164 KB

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