lib_phpQuery.php 163 KB

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