phpQueryObject.php 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211
  1. <?php
  2. /**
  3. * Class representing phpQuery objects.
  4. *
  5. * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
  6. * @package phpQuery
  7. * @method phpQueryObject clone() clone()
  8. * @method phpQueryObject empty() empty()
  9. * @method phpQueryObject next() next($selector = null)
  10. * @method phpQueryObject prev() prev($selector = null)
  11. * @property Int $length
  12. */
  13. class phpQueryObject
  14. implements Iterator, Countable, ArrayAccess {
  15. public $documentID = null;
  16. /**
  17. * DOMDocument class.
  18. *
  19. * @var DOMDocument
  20. */
  21. public $document = null;
  22. public $charset = null;
  23. /**
  24. *
  25. * @var DOMDocumentWrapper
  26. */
  27. public $documentWrapper = null;
  28. /**
  29. * XPath interface.
  30. *
  31. * @var DOMXPath
  32. */
  33. public $xpath = null;
  34. /**
  35. * Stack of selected elements.
  36. * @TODO refactor to ->nodes
  37. * @var array
  38. */
  39. public $elements = array();
  40. /**
  41. * @access private
  42. */
  43. protected $elementsBackup = array();
  44. /**
  45. * @access private
  46. */
  47. protected $previous = null;
  48. /**
  49. * @access private
  50. * @TODO deprecate
  51. */
  52. protected $root = array();
  53. /**
  54. * Indicated if doument is just a fragment (no <html> tag).
  55. *
  56. * Every document is realy a full document, so even documentFragments can
  57. * be queried against <html>, but getDocument(id)->htmlOuter() will return
  58. * only contents of <body>.
  59. *
  60. * @var bool
  61. */
  62. public $documentFragment = true;
  63. /**
  64. * Iterator interface helper
  65. * @access private
  66. */
  67. protected $elementsInterator = array();
  68. /**
  69. * Iterator interface helper
  70. * @access private
  71. */
  72. protected $valid = false;
  73. /**
  74. * Iterator interface helper
  75. * @access private
  76. */
  77. protected $current = null;
  78. /**
  79. * Enter description here...
  80. *
  81. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  82. */
  83. public function __construct($documentID) {
  84. // if ($documentID instanceof self)
  85. // var_dump($documentID->getDocumentID());
  86. $id = $documentID instanceof self
  87. ? $documentID->getDocumentID()
  88. : $documentID;
  89. // var_dump($id);
  90. if (! isset(phpQuery::$documents[$id] )) {
  91. // var_dump(phpQuery::$documents);
  92. throw new Exception("Document with ID '{$id}' isn't loaded. Use phpQuery::newDocument(\$html) or phpQuery::newDocumentFile(\$file) first.");
  93. }
  94. $this->documentID = $id;
  95. $this->documentWrapper =& phpQuery::$documents[$id];
  96. $this->document =& $this->documentWrapper->document;
  97. $this->xpath =& $this->documentWrapper->xpath;
  98. $this->charset =& $this->documentWrapper->charset;
  99. $this->documentFragment =& $this->documentWrapper->isDocumentFragment;
  100. // TODO check $this->DOM->documentElement;
  101. // $this->root = $this->document->documentElement;
  102. $this->root =& $this->documentWrapper->root;
  103. // $this->toRoot();
  104. $this->elements = array($this->root);
  105. }
  106. /**
  107. *
  108. * @access private
  109. * @param $attr
  110. * @return unknown_type
  111. */
  112. public function __get($attr) {
  113. switch($attr) {
  114. // FIXME doesnt work at all ?
  115. case 'length':
  116. return $this->size();
  117. break;
  118. default:
  119. return $this->$attr;
  120. }
  121. }
  122. /**
  123. * Saves actual object to $var by reference.
  124. * Useful when need to break chain.
  125. * @param phpQueryObject $var
  126. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  127. */
  128. public function toReference(&$var) {
  129. return $var = $this;
  130. }
  131. public function documentFragment($state = null) {
  132. if ($state) {
  133. phpQuery::$documents[$this->getDocumentID()]['documentFragment'] = $state;
  134. return $this;
  135. }
  136. return $this->documentFragment;
  137. }
  138. /**
  139. * @access private
  140. * @TODO documentWrapper
  141. */
  142. protected function isRoot( $node) {
  143. // return $node instanceof DOMDOCUMENT || $node->tagName == 'html';
  144. return $node instanceof DOMDOCUMENT
  145. || ($node instanceof DOMELEMENT && $node->tagName == 'html')
  146. || $this->root->isSameNode($node);
  147. }
  148. /**
  149. * @access private
  150. */
  151. protected function stackIsRoot() {
  152. return $this->size() == 1 && $this->isRoot($this->elements[0]);
  153. }
  154. /**
  155. * Enter description here...
  156. * NON JQUERY METHOD
  157. *
  158. * Watch out, it doesn't creates new instance, can be reverted with end().
  159. *
  160. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  161. */
  162. public function toRoot() {
  163. $this->elements = array($this->root);
  164. return $this;
  165. // return $this->newInstance(array($this->root));
  166. }
  167. /**
  168. * Saves object's DocumentID to $var by reference.
  169. * <code>
  170. * $myDocumentId;
  171. * phpQuery::newDocument('<div/>')
  172. * ->getDocumentIDRef($myDocumentId)
  173. * ->find('div')->...
  174. * </code>
  175. *
  176. * @param unknown_type $domId
  177. * @see phpQuery::newDocument
  178. * @see phpQuery::newDocumentFile
  179. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  180. */
  181. public function getDocumentIDRef(&$documentID) {
  182. $documentID = $this->getDocumentID();
  183. return $this;
  184. }
  185. /**
  186. * Returns object with stack set to document root.
  187. *
  188. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  189. */
  190. public function getDocument() {
  191. return phpQuery::getDocument($this->getDocumentID());
  192. }
  193. /**
  194. *
  195. * @return DOMDocument
  196. */
  197. public function getDOMDocument() {
  198. return $this->document;
  199. }
  200. /**
  201. * Get object's Document ID.
  202. *
  203. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  204. */
  205. public function getDocumentID() {
  206. return $this->documentID;
  207. }
  208. /**
  209. * Unloads whole document from memory.
  210. * CAUTION! None further operations will be possible on this document.
  211. * All objects refering to it will be useless.
  212. *
  213. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  214. */
  215. public function unloadDocument() {
  216. phpQuery::unloadDocuments($this->getDocumentID());
  217. }
  218. public function isHTML() {
  219. return $this->documentWrapper->isHTML;
  220. }
  221. public function isXHTML() {
  222. return $this->documentWrapper->isXHTML;
  223. }
  224. public function isXML() {
  225. return $this->documentWrapper->isXML;
  226. }
  227. /**
  228. * Enter description here...
  229. *
  230. * @link http://docs.jquery.com/Ajax/serialize
  231. * @return string
  232. */
  233. public function serialize() {
  234. return phpQuery::param($this->serializeArray());
  235. }
  236. /**
  237. * Enter description here...
  238. *
  239. * @link http://docs.jquery.com/Ajax/serializeArray
  240. * @return array
  241. */
  242. public function serializeArray($submit = null) {
  243. $source = $this->filter('form, input, select, textarea')
  244. ->find('input, select, textarea')
  245. ->andSelf()
  246. ->not('form');
  247. $return = array();
  248. // $source->dumpDie();
  249. foreach($source as $input) {
  250. $input = phpQuery::pq($input);
  251. if ($input->is('[disabled]'))
  252. continue;
  253. if (!$input->is('[name]'))
  254. continue;
  255. if ($input->is('[type=checkbox]') && !$input->is('[checked]'))
  256. continue;
  257. // jquery diff
  258. if ($submit && $input->is('[type=submit]')) {
  259. if ($submit instanceof DOMELEMENT && ! $input->elements[0]->isSameNode($submit))
  260. continue;
  261. else if (is_string($submit) && $input->attr('name') != $submit)
  262. continue;
  263. }
  264. $return[] = array(
  265. 'name' => $input->attr('name'),
  266. 'value' => $input->val(),
  267. );
  268. }
  269. return $return;
  270. }
  271. /**
  272. * @access private
  273. */
  274. protected function debug($in) {
  275. if (! phpQuery::$debug )
  276. return;
  277. print('<pre>');
  278. print_r($in);
  279. // file debug
  280. // file_put_contents(dirname(__FILE__).'/phpQuery.log', print_r($in, true)."\n", FILE_APPEND);
  281. // quite handy debug trace
  282. // if ( is_array($in))
  283. // print_r(array_slice(debug_backtrace(), 3));
  284. print("</pre>\n");
  285. }
  286. /**
  287. * @access private
  288. */
  289. protected function isRegexp($pattern) {
  290. return in_array(
  291. $pattern[ mb_strlen($pattern)-1 ],
  292. array('^','*','$')
  293. );
  294. }
  295. /**
  296. * Determines if $char is really a char.
  297. *
  298. * @param string $char
  299. * @return bool
  300. * @todo rewrite me to charcode range ! ;)
  301. * @access private
  302. */
  303. protected function isChar($char) {
  304. return extension_loaded('mbstring') && phpQuery::$mbstringSupport
  305. ? mb_eregi('\w', $char)
  306. : preg_match('@\w@', $char);
  307. }
  308. /**
  309. * @access private
  310. */
  311. protected function parseSelector($query) {
  312. // clean spaces
  313. // TODO include this inside parsing ?
  314. $query = trim(
  315. preg_replace('@\s+@', ' ',
  316. preg_replace('@\s*(>|\\+|~)\s*@', '\\1', $query)
  317. )
  318. );
  319. $queries = array(array());
  320. if (! $query)
  321. return $queries;
  322. $return =& $queries[0];
  323. $specialChars = array('>',' ');
  324. // $specialCharsMapping = array('/' => '>');
  325. $specialCharsMapping = array();
  326. $strlen = mb_strlen($query);
  327. $classChars = array('.', '-');
  328. $pseudoChars = array('-');
  329. $tagChars = array('*', '|', '-');
  330. // split multibyte string
  331. // http://code.google.com/p/phpquery/issues/detail?id=76
  332. $_query = array();
  333. for ($i=0; $i<$strlen; $i++)
  334. $_query[] = mb_substr($query, $i, 1);
  335. $query = $_query;
  336. // it works, but i dont like it...
  337. $i = 0;
  338. while( $i < $strlen) {
  339. $c = $query[$i];
  340. $tmp = '';
  341. // TAG
  342. if ($this->isChar($c) || in_array($c, $tagChars)) {
  343. while(isset($query[$i])
  344. && ($this->isChar($query[$i]) || in_array($query[$i], $tagChars))) {
  345. $tmp .= $query[$i];
  346. $i++;
  347. }
  348. $return[] = $tmp;
  349. // IDs
  350. } else if ( $c == '#') {
  351. $i++;
  352. while( isset($query[$i]) && ($this->isChar($query[$i]) || $query[$i] == '-')) {
  353. $tmp .= $query[$i];
  354. $i++;
  355. }
  356. $return[] = '#'.$tmp;
  357. // SPECIAL CHARS
  358. } else if (in_array($c, $specialChars)) {
  359. $return[] = $c;
  360. $i++;
  361. // MAPPED SPECIAL MULTICHARS
  362. // } else if ( $c.$query[$i+1] == '//') {
  363. // $return[] = ' ';
  364. // $i = $i+2;
  365. // MAPPED SPECIAL CHARS
  366. } else if ( isset($specialCharsMapping[$c])) {
  367. $return[] = $specialCharsMapping[$c];
  368. $i++;
  369. // COMMA
  370. } else if ( $c == ',') {
  371. $queries[] = array();
  372. $return =& $queries[ count($queries)-1 ];
  373. $i++;
  374. while( isset($query[$i]) && $query[$i] == ' ')
  375. $i++;
  376. // CLASSES
  377. } else if ($c == '.') {
  378. while( isset($query[$i]) && ($this->isChar($query[$i]) || in_array($query[$i], $classChars))) {
  379. $tmp .= $query[$i];
  380. $i++;
  381. }
  382. $return[] = $tmp;
  383. // ~ General Sibling Selector
  384. } else if ($c == '~') {
  385. $spaceAllowed = true;
  386. $tmp .= $query[$i++];
  387. while( isset($query[$i])
  388. && ($this->isChar($query[$i])
  389. || in_array($query[$i], $classChars)
  390. || $query[$i] == '*'
  391. || ($query[$i] == ' ' && $spaceAllowed)
  392. )) {
  393. if ($query[$i] != ' ')
  394. $spaceAllowed = false;
  395. $tmp .= $query[$i];
  396. $i++;
  397. }
  398. $return[] = $tmp;
  399. // + Adjacent sibling selectors
  400. } else if ($c == '+') {
  401. $spaceAllowed = true;
  402. $tmp .= $query[$i++];
  403. while( isset($query[$i])
  404. && ($this->isChar($query[$i])
  405. || in_array($query[$i], $classChars)
  406. || $query[$i] == '*'
  407. || ($spaceAllowed && $query[$i] == ' ')
  408. )) {
  409. if ($query[$i] != ' ')
  410. $spaceAllowed = false;
  411. $tmp .= $query[$i];
  412. $i++;
  413. }
  414. $return[] = $tmp;
  415. // ATTRS
  416. } else if ($c == '[') {
  417. $stack = 1;
  418. $tmp .= $c;
  419. while( isset($query[++$i])) {
  420. $tmp .= $query[$i];
  421. if ( $query[$i] == '[') {
  422. $stack++;
  423. } else if ( $query[$i] == ']') {
  424. $stack--;
  425. if (! $stack )
  426. break;
  427. }
  428. }
  429. $return[] = $tmp;
  430. $i++;
  431. // PSEUDO CLASSES
  432. } else if ($c == ':') {
  433. $stack = 1;
  434. $tmp .= $query[$i++];
  435. while( isset($query[$i]) && ($this->isChar($query[$i]) || in_array($query[$i], $pseudoChars))) {
  436. $tmp .= $query[$i];
  437. $i++;
  438. }
  439. // with arguments ?
  440. if ( isset($query[$i]) && $query[$i] == '(') {
  441. $tmp .= $query[$i];
  442. $stack = 1;
  443. while( isset($query[++$i])) {
  444. $tmp .= $query[$i];
  445. if ( $query[$i] == '(') {
  446. $stack++;
  447. } else if ( $query[$i] == ')') {
  448. $stack--;
  449. if (! $stack )
  450. break;
  451. }
  452. }
  453. $return[] = $tmp;
  454. $i++;
  455. } else {
  456. $return[] = $tmp;
  457. }
  458. } else {
  459. $i++;
  460. }
  461. }
  462. foreach($queries as $k => $q) {
  463. if (isset($q[0])) {
  464. if (isset($q[0][0]) && $q[0][0] == ':')
  465. array_unshift($queries[$k], '*');
  466. if ($q[0] != '>')
  467. array_unshift($queries[$k], ' ');
  468. }
  469. }
  470. return $queries;
  471. }
  472. /**
  473. * Return matched DOM nodes.
  474. *
  475. * @param int $index
  476. * @return array|DOMElement Single DOMElement or array of DOMElement.
  477. */
  478. public function get($index = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  479. $return = isset($index)
  480. ? (isset($this->elements[$index]) ? $this->elements[$index] : null)
  481. : $this->elements;
  482. // pass thou callbacks
  483. $args = func_get_args();
  484. $args = array_slice($args, 1);
  485. foreach($args as $callback) {
  486. if (is_array($return))
  487. foreach($return as $k => $v)
  488. $return[$k] = phpQuery::callbackRun($callback, array($v));
  489. else
  490. $return = phpQuery::callbackRun($callback, array($return));
  491. }
  492. return $return;
  493. }
  494. /**
  495. * Return matched DOM nodes.
  496. * jQuery difference.
  497. *
  498. * @param int $index
  499. * @return array|string Returns string if $index != null
  500. * @todo implement callbacks
  501. * @todo return only arrays ?
  502. * @todo maybe other name...
  503. */
  504. public function getString($index = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  505. if ($index)
  506. $return = $this->eq($index)->text();
  507. else {
  508. $return = array();
  509. for($i = 0; $i < $this->size(); $i++) {
  510. $return[] = $this->eq($i)->text();
  511. }
  512. }
  513. // pass thou callbacks
  514. $args = func_get_args();
  515. $args = array_slice($args, 1);
  516. foreach($args as $callback) {
  517. $return = phpQuery::callbackRun($callback, array($return));
  518. }
  519. return $return;
  520. }
  521. /**
  522. * Return matched DOM nodes.
  523. * jQuery difference.
  524. *
  525. * @param int $index
  526. * @return array|string Returns string if $index != null
  527. * @todo implement callbacks
  528. * @todo return only arrays ?
  529. * @todo maybe other name...
  530. */
  531. public function getStrings($index = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  532. if ($index)
  533. $return = $this->eq($index)->text();
  534. else {
  535. $return = array();
  536. for($i = 0; $i < $this->size(); $i++) {
  537. $return[] = $this->eq($i)->text();
  538. }
  539. // pass thou callbacks
  540. $args = func_get_args();
  541. $args = array_slice($args, 1);
  542. }
  543. foreach($args as $callback) {
  544. if (is_array($return))
  545. foreach($return as $k => $v)
  546. $return[$k] = phpQuery::callbackRun($callback, array($v));
  547. else
  548. $return = phpQuery::callbackRun($callback, array($return));
  549. }
  550. return $return;
  551. }
  552. /**
  553. * Returns new instance of actual class.
  554. *
  555. * @param array $newStack Optional. Will replace old stack with new and move old one to history.c
  556. */
  557. public function newInstance($newStack = null) {
  558. $class = get_class($this);
  559. // support inheritance by passing old object to overloaded constructor
  560. $new = $class != 'phpQuery'
  561. ? new $class($this, $this->getDocumentID())
  562. : new phpQueryObject($this->getDocumentID());
  563. $new->previous = $this;
  564. if (is_null($newStack)) {
  565. $new->elements = $this->elements;
  566. if ($this->elementsBackup)
  567. $this->elements = $this->elementsBackup;
  568. } else if (is_string($newStack)) {
  569. $new->elements = phpQuery::pq($newStack, $this->getDocumentID())->stack();
  570. } else {
  571. $new->elements = $newStack;
  572. }
  573. return $new;
  574. }
  575. /**
  576. * Enter description here...
  577. *
  578. * In the future, when PHP will support XLS 2.0, then we would do that this way:
  579. * contains(tokenize(@class, '\s'), "something")
  580. * @param unknown_type $class
  581. * @param unknown_type $node
  582. * @return boolean
  583. * @access private
  584. */
  585. protected function matchClasses($class, $node) {
  586. // multi-class
  587. if ( mb_strpos($class, '.', 1)) {
  588. $classes = explode('.', substr($class, 1));
  589. $classesCount = count( $classes );
  590. $nodeClasses = explode(' ', $node->getAttribute('class') );
  591. $nodeClassesCount = count( $nodeClasses );
  592. if ( $classesCount > $nodeClassesCount )
  593. return false;
  594. $diff = count(
  595. array_diff(
  596. $classes,
  597. $nodeClasses
  598. )
  599. );
  600. if (! $diff )
  601. return true;
  602. // single-class
  603. } else {
  604. return in_array(
  605. // strip leading dot from class name
  606. substr($class, 1),
  607. // get classes for element as array
  608. explode(' ', $node->getAttribute('class') )
  609. );
  610. }
  611. }
  612. /**
  613. * @access private
  614. */
  615. protected function runQuery($XQuery, $selector = null, $compare = null) {
  616. if ($compare && ! method_exists($this, $compare))
  617. return false;
  618. $stack = array();
  619. if (! $this->elements)
  620. $this->debug('Stack empty, skipping...');
  621. // var_dump($this->elements[0]->nodeType);
  622. // element, document
  623. foreach($this->stack(array(1, 9, 13)) as $k => $stackNode) {
  624. $detachAfter = false;
  625. // to work on detached nodes we need temporary place them somewhere
  626. // thats because context xpath queries sucks ;]
  627. $testNode = $stackNode;
  628. while ($testNode) {
  629. if (! $testNode->parentNode && ! $this->isRoot($testNode)) {
  630. $this->root->appendChild($testNode);
  631. $detachAfter = $testNode;
  632. break;
  633. }
  634. $testNode = isset($testNode->parentNode)
  635. ? $testNode->parentNode
  636. : null;
  637. }
  638. // XXX tmp ?
  639. $xpath = $this->documentWrapper->isXHTML
  640. ? $this->getNodeXpath($stackNode, 'html')
  641. : $this->getNodeXpath($stackNode);
  642. // FIXME pseudoclasses-only query, support XML
  643. $query = $XQuery == '//' && $xpath == '/html[1]'
  644. ? '//*'
  645. : $xpath.$XQuery;
  646. $this->debug("XPATH: {$query}");
  647. // run query, get elements
  648. $nodes = $this->xpath->query($query);
  649. $this->debug("QUERY FETCHED");
  650. if (! $nodes->length )
  651. $this->debug('Nothing found');
  652. $debug = array();
  653. foreach($nodes as $node) {
  654. $matched = false;
  655. if ( $compare) {
  656. phpQuery::$debug ?
  657. $this->debug("Found: ".$this->whois( $node ).", comparing with {$compare}()")
  658. : null;
  659. $phpQueryDebug = phpQuery::$debug;
  660. phpQuery::$debug = false;
  661. // TODO ??? use phpQuery::callbackRun()
  662. if (call_user_func_array(array($this, $compare), array($selector, $node)))
  663. $matched = true;
  664. phpQuery::$debug = $phpQueryDebug;
  665. } else {
  666. $matched = true;
  667. }
  668. if ( $matched) {
  669. if (phpQuery::$debug)
  670. $debug[] = $this->whois( $node );
  671. $stack[] = $node;
  672. }
  673. }
  674. if (phpQuery::$debug) {
  675. $this->debug("Matched ".count($debug).": ".implode(', ', $debug));
  676. }
  677. if ($detachAfter)
  678. $this->root->removeChild($detachAfter);
  679. }
  680. $this->elements = $stack;
  681. }
  682. /**
  683. * Enter description here...
  684. *
  685. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  686. */
  687. public function find($selectors, $context = null, $noHistory = false) {
  688. if (!$noHistory)
  689. // backup last stack /for end()/
  690. $this->elementsBackup = $this->elements;
  691. // allow to define context
  692. // TODO combine code below with phpQuery::pq() context guessing code
  693. // as generic function
  694. if ($context) {
  695. if (! is_array($context) && $context instanceof DOMELEMENT)
  696. $this->elements = array($context);
  697. else if (is_array($context)) {
  698. $this->elements = array();
  699. foreach ($context as $c)
  700. if ($c instanceof DOMELEMENT)
  701. $this->elements[] = $c;
  702. } else if ( $context instanceof self )
  703. $this->elements = $context->elements;
  704. }
  705. $queries = $this->parseSelector($selectors);
  706. $this->debug(array('FIND', $selectors, $queries));
  707. $XQuery = '';
  708. // remember stack state because of multi-queries
  709. $oldStack = $this->elements;
  710. // here we will be keeping found elements
  711. $stack = array();
  712. foreach($queries as $selector) {
  713. $this->elements = $oldStack;
  714. $delimiterBefore = false;
  715. foreach($selector as $s) {
  716. // TAG
  717. $isTag = extension_loaded('mbstring') && phpQuery::$mbstringSupport
  718. ? mb_ereg_match('^[\w|\||-]+$', $s) || $s == '*'
  719. : preg_match('@^[\w|\||-]+$@', $s) || $s == '*';
  720. if ($isTag) {
  721. if ($this->isXML()) {
  722. // namespace support
  723. if (mb_strpos($s, '|') !== false) {
  724. $ns = $tag = null;
  725. list($ns, $tag) = explode('|', $s);
  726. $XQuery .= "$ns:$tag";
  727. } else if ($s == '*') {
  728. $XQuery .= "*";
  729. } else {
  730. $XQuery .= "*[local-name()='$s']";
  731. }
  732. } else {
  733. $XQuery .= $s;
  734. }
  735. // ID
  736. } else if ($s[0] == '#') {
  737. if ($delimiterBefore)
  738. $XQuery .= '*';
  739. $XQuery .= "[@id='".substr($s, 1)."']";
  740. // ATTRIBUTES
  741. } else if ($s[0] == '[') {
  742. if ($delimiterBefore)
  743. $XQuery .= '*';
  744. // strip side brackets
  745. $attr = trim($s, '][');
  746. $execute = false;
  747. // attr with specifed value
  748. if (mb_strpos($s, '=')) {
  749. $value = null;
  750. list($attr, $value) = explode('=', $attr);
  751. $value = trim($value, "'\"");
  752. if ($this->isRegexp($attr)) {
  753. // cut regexp character
  754. $attr = substr($attr, 0, -1);
  755. $execute = true;
  756. $XQuery .= "[@{$attr}]";
  757. } else {
  758. $XQuery .= "[@{$attr}='{$value}']";
  759. }
  760. // attr without specified value
  761. } else {
  762. $XQuery .= "[@{$attr}]";
  763. }
  764. if ($execute) {
  765. $this->runQuery($XQuery, $s, 'is');
  766. $XQuery = '';
  767. if (! $this->length())
  768. break;
  769. }
  770. // CLASSES
  771. } else if ($s[0] == '.') {
  772. // TODO use return $this->find("./self::*[contains(concat(\" \",@class,\" \"), \" $class \")]");
  773. // thx wizDom ;)
  774. if ($delimiterBefore)
  775. $XQuery .= '*';
  776. $XQuery .= '[@class]';
  777. $this->runQuery($XQuery, $s, 'matchClasses');
  778. $XQuery = '';
  779. if (! $this->length() )
  780. break;
  781. // ~ General Sibling Selector
  782. } else if ($s[0] == '~') {
  783. $this->runQuery($XQuery);
  784. $XQuery = '';
  785. $this->elements = $this
  786. ->siblings(
  787. substr($s, 1)
  788. )->elements;
  789. if (! $this->length() )
  790. break;
  791. // + Adjacent sibling selectors
  792. } else if ($s[0] == '+') {
  793. // TODO /following-sibling::
  794. $this->runQuery($XQuery);
  795. $XQuery = '';
  796. $subSelector = substr($s, 1);
  797. $subElements = $this->elements;
  798. $this->elements = array();
  799. foreach($subElements as $node) {
  800. // search first DOMElement sibling
  801. $test = $node->nextSibling;
  802. while($test && ! ($test instanceof DOMELEMENT))
  803. $test = $test->nextSibling;
  804. if ($test && $this->is($subSelector, $test))
  805. $this->elements[] = $test;
  806. }
  807. if (! $this->length() )
  808. break;
  809. // PSEUDO CLASSES
  810. } else if ($s[0] == ':') {
  811. // TODO optimization for :first :last
  812. if ($XQuery) {
  813. $this->runQuery($XQuery);
  814. $XQuery = '';
  815. }
  816. if (! $this->length())
  817. break;
  818. $this->pseudoClasses($s);
  819. if (! $this->length())
  820. break;
  821. // DIRECT DESCENDANDS
  822. } else if ($s == '>') {
  823. $XQuery .= '/';
  824. $delimiterBefore = 2;
  825. // ALL DESCENDANDS
  826. } else if ($s == ' ') {
  827. $XQuery .= '//';
  828. $delimiterBefore = 2;
  829. // ERRORS
  830. } else {
  831. phpQuery::debug("Unrecognized token '$s'");
  832. }
  833. $delimiterBefore = $delimiterBefore === 2;
  834. }
  835. // run query if any
  836. if ($XQuery && $XQuery != '//') {
  837. $this->runQuery($XQuery);
  838. $XQuery = '';
  839. }
  840. foreach($this->elements as $node)
  841. if (! $this->elementsContainsNode($node, $stack))
  842. $stack[] = $node;
  843. }
  844. $this->elements = $stack;
  845. return $this->newInstance();
  846. }
  847. /**
  848. * @todo create API for classes with pseudoselectors
  849. * @access private
  850. */
  851. protected function pseudoClasses($class) {
  852. // TODO clean args parsing ?
  853. $class = ltrim($class, ':');
  854. $haveArgs = mb_strpos($class, '(');
  855. if ($haveArgs !== false) {
  856. $args = substr($class, $haveArgs+1, -1);
  857. $class = substr($class, 0, $haveArgs);
  858. }
  859. switch($class) {
  860. case 'even':
  861. case 'odd':
  862. $stack = array();
  863. foreach($this->elements as $i => $node) {
  864. if ($class == 'even' && ($i%2) == 0)
  865. $stack[] = $node;
  866. else if ( $class == 'odd' && $i % 2 )
  867. $stack[] = $node;
  868. }
  869. $this->elements = $stack;
  870. break;
  871. case 'eq':
  872. $k = intval($args);
  873. $this->elements = isset( $this->elements[$k] )
  874. ? array( $this->elements[$k] )
  875. : array();
  876. break;
  877. case 'gt':
  878. $this->elements = array_slice($this->elements, $args+1);
  879. break;
  880. case 'lt':
  881. $this->elements = array_slice($this->elements, 0, $args+1);
  882. break;
  883. case 'first':
  884. if (isset($this->elements[0]))
  885. $this->elements = array($this->elements[0]);
  886. break;
  887. case 'last':
  888. if ($this->elements)
  889. $this->elements = array($this->elements[count($this->elements)-1]);
  890. break;
  891. /*case 'parent':
  892. $stack = array();
  893. foreach($this->elements as $node) {
  894. if ( $node->childNodes->length )
  895. $stack[] = $node;
  896. }
  897. $this->elements = $stack;
  898. break;*/
  899. case 'contains':
  900. $text = trim($args, "\"'");
  901. $stack = array();
  902. foreach($this->elements as $node) {
  903. if (mb_stripos($node->textContent, $text) === false)
  904. continue;
  905. $stack[] = $node;
  906. }
  907. $this->elements = $stack;
  908. break;
  909. case 'not':
  910. $selector = self::unQuote($args);
  911. $this->elements = $this->not($selector)->stack();
  912. break;
  913. case 'slice':
  914. // TODO jQuery difference ?
  915. $args = explode(',',
  916. str_replace(', ', ',', trim($args, "\"'"))
  917. );
  918. $start = $args[0];
  919. $end = isset($args[1])
  920. ? $args[1]
  921. : null;
  922. if ($end > 0)
  923. $end = $end-$start;
  924. $this->elements = array_slice($this->elements, $start, $end);
  925. break;
  926. case 'has':
  927. $selector = trim($args, "\"'");
  928. $stack = array();
  929. foreach($this->stack(1) as $el) {
  930. if ($this->find($selector, $el, true)->length)
  931. $stack[] = $el;
  932. }
  933. $this->elements = $stack;
  934. break;
  935. case 'submit':
  936. case 'reset':
  937. $this->elements = phpQuery::merge(
  938. $this->map(array($this, 'is'),
  939. "input[type=$class]", new CallbackParam()
  940. ),
  941. $this->map(array($this, 'is'),
  942. "button[type=$class]", new CallbackParam()
  943. )
  944. );
  945. break;
  946. // $stack = array();
  947. // foreach($this->elements as $node)
  948. // if ($node->is('input[type=submit]') || $node->is('button[type=submit]'))
  949. // $stack[] = $el;
  950. // $this->elements = $stack;
  951. case 'input':
  952. $this->elements = $this->map(
  953. array($this, 'is'),
  954. 'input', new CallbackParam()
  955. )->elements;
  956. break;
  957. case 'password':
  958. case 'checkbox':
  959. case 'radio':
  960. case 'hidden':
  961. case 'image':
  962. case 'file':
  963. $this->elements = $this->map(
  964. array($this, 'is'),
  965. "input[type=$class]", new CallbackParam()
  966. )->elements;
  967. break;
  968. case 'parent':
  969. $this->elements = $this->map(
  970. create_function('$node', '
  971. return $node instanceof DOMELEMENT && $node->childNodes->length
  972. ? $node : null;')
  973. )->elements;
  974. break;
  975. case 'empty':
  976. $this->elements = $this->map(
  977. create_function('$node', '
  978. return $node instanceof DOMELEMENT && $node->childNodes->length
  979. ? null : $node;')
  980. )->elements;
  981. break;
  982. case 'disabled':
  983. case 'selected':
  984. case 'checked':
  985. $this->elements = $this->map(
  986. array($this, 'is'),
  987. "[$class]", new CallbackParam()
  988. )->elements;
  989. break;
  990. case 'enabled':
  991. $this->elements = $this->map(
  992. create_function('$node', '
  993. return pq($node)->not(":disabled") ? $node : null;')
  994. )->elements;
  995. break;
  996. case 'header':
  997. $this->elements = $this->map(
  998. create_function('$node',
  999. '$isHeader = isset($node->tagName) && in_array($node->tagName, array(
  1000. "h1", "h2", "h3", "h4", "h5", "h6", "h7"
  1001. ));
  1002. return $isHeader
  1003. ? $node
  1004. : null;')
  1005. )->elements;
  1006. // $this->elements = $this->map(
  1007. // create_function('$node', '$node = pq($node);
  1008. // return $node->is("h1")
  1009. // || $node->is("h2")
  1010. // || $node->is("h3")
  1011. // || $node->is("h4")
  1012. // || $node->is("h5")
  1013. // || $node->is("h6")
  1014. // || $node->is("h7")
  1015. // ? $node
  1016. // : null;')
  1017. // )->elements;
  1018. break;
  1019. case 'only-child':
  1020. $this->elements = $this->map(
  1021. create_function('$node',
  1022. 'return pq($node)->siblings()->size() == 0 ? $node : null;')
  1023. )->elements;
  1024. break;
  1025. case 'first-child':
  1026. $this->elements = $this->map(
  1027. create_function('$node', 'return pq($node)->prevAll()->size() == 0 ? $node : null;')
  1028. )->elements;
  1029. break;
  1030. case 'last-child':
  1031. $this->elements = $this->map(
  1032. create_function('$node', 'return pq($node)->nextAll()->size() == 0 ? $node : null;')
  1033. )->elements;
  1034. break;
  1035. case 'nth-child':
  1036. $param = trim($args, "\"'");
  1037. if (! $param)
  1038. break;
  1039. // nth-child(n+b) to nth-child(1n+b)
  1040. if ($param[0] == 'n')
  1041. $param = '1'.$param;
  1042. // :nth-child(index/even/odd/equation)
  1043. if ($param == 'even' || $param == 'odd')
  1044. $mapped = $this->map(
  1045. create_function('$node, $param',
  1046. '$index = pq($node)->prevAll()->size()+1;
  1047. if ($param == "even" && ($index%2) == 0)
  1048. return $node;
  1049. else if ($param == "odd" && $index%2 == 1)
  1050. return $node;
  1051. else
  1052. return null;'),
  1053. new CallbackParam(), $param
  1054. );
  1055. else if (mb_strlen($param) > 1 && $param[1] == 'n')
  1056. // an+b
  1057. $mapped = $this->map(
  1058. create_function('$node, $param',
  1059. '$prevs = pq($node)->prevAll()->size();
  1060. $index = 1+$prevs;
  1061. $b = mb_strlen($param) > 3
  1062. ? $param{3}
  1063. : 0;
  1064. $a = $param{0};
  1065. if ($b && $param{2} == "-")
  1066. $b = -$b;
  1067. if ($a > 0) {
  1068. return ($index-$b)%$a == 0
  1069. ? $node
  1070. : null;
  1071. phpQuery::debug($a."*".floor($index/$a)."+$b-1 == ".($a*floor($index/$a)+$b-1)." ?= $prevs");
  1072. return $a*floor($index/$a)+$b-1 == $prevs
  1073. ? $node
  1074. : null;
  1075. } else if ($a == 0)
  1076. return $index == $b
  1077. ? $node
  1078. : null;
  1079. else
  1080. // negative value
  1081. return $index <= $b
  1082. ? $node
  1083. : null;
  1084. // if (! $b)
  1085. // return $index%$a == 0
  1086. // ? $node
  1087. // : null;
  1088. // else
  1089. // return ($index-$b)%$a == 0
  1090. // ? $node
  1091. // : null;
  1092. '),
  1093. new CallbackParam(), $param
  1094. );
  1095. else
  1096. // index
  1097. $mapped = $this->map(
  1098. create_function('$node, $index',
  1099. '$prevs = pq($node)->prevAll()->size();
  1100. if ($prevs && $prevs == $index-1)
  1101. return $node;
  1102. else if (! $prevs && $index == 1)
  1103. return $node;
  1104. else
  1105. return null;'),
  1106. new CallbackParam(), $param
  1107. );
  1108. $this->elements = $mapped->elements;
  1109. break;
  1110. default:
  1111. $this->debug("Unknown pseudoclass '{$class}', skipping...");
  1112. }
  1113. }
  1114. /**
  1115. * @access private
  1116. */
  1117. protected function __pseudoClassParam($paramsString) {
  1118. // TODO;
  1119. }
  1120. /**
  1121. * Enter description here...
  1122. *
  1123. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1124. */
  1125. public function is($selector, $nodes = null) {
  1126. phpQuery::debug(array("Is:", $selector));
  1127. if (! $selector)
  1128. return false;
  1129. $oldStack = $this->elements;
  1130. $returnArray = false;
  1131. if ($nodes && is_array($nodes)) {
  1132. $this->elements = $nodes;
  1133. } else if ($nodes)
  1134. $this->elements = array($nodes);
  1135. $this->filter($selector, true);
  1136. $stack = $this->elements;
  1137. $this->elements = $oldStack;
  1138. if ($nodes)
  1139. return $stack ? $stack : null;
  1140. return (bool)count($stack);
  1141. }
  1142. /**
  1143. * Enter description here...
  1144. * jQuery difference.
  1145. *
  1146. * Callback:
  1147. * - $index int
  1148. * - $node DOMNode
  1149. *
  1150. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1151. * @link http://docs.jquery.com/Traversing/filter
  1152. */
  1153. public function filterCallback($callback, $_skipHistory = false) {
  1154. if (! $_skipHistory) {
  1155. $this->elementsBackup = $this->elements;
  1156. $this->debug("Filtering by callback");
  1157. }
  1158. $newStack = array();
  1159. foreach($this->elements as $index => $node) {
  1160. $result = phpQuery::callbackRun($callback, array($index, $node));
  1161. if (is_null($result) || (! is_null($result) && $result))
  1162. $newStack[] = $node;
  1163. }
  1164. $this->elements = $newStack;
  1165. return $_skipHistory
  1166. ? $this
  1167. : $this->newInstance();
  1168. }
  1169. /**
  1170. * Enter description here...
  1171. *
  1172. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1173. * @link http://docs.jquery.com/Traversing/filter
  1174. */
  1175. public function filter($selectors, $_skipHistory = false) {
  1176. if ($selectors instanceof Callback OR $selectors instanceof Closure)
  1177. return $this->filterCallback($selectors, $_skipHistory);
  1178. if (! $_skipHistory)
  1179. $this->elementsBackup = $this->elements;
  1180. $notSimpleSelector = array(' ', '>', '~', '+', '/');
  1181. if (! is_array($selectors))
  1182. $selectors = $this->parseSelector($selectors);
  1183. if (! $_skipHistory)
  1184. $this->debug(array("Filtering:", $selectors));
  1185. $finalStack = array();
  1186. foreach($selectors as $selector) {
  1187. $stack = array();
  1188. if (! $selector)
  1189. break;
  1190. // avoid first space or /
  1191. if (in_array($selector[0], $notSimpleSelector))
  1192. $selector = array_slice($selector, 1);
  1193. // PER NODE selector chunks
  1194. foreach($this->stack() as $node) {
  1195. $break = false;
  1196. foreach($selector as $s) {
  1197. if (!($node instanceof DOMELEMENT)) {
  1198. // all besides DOMElement
  1199. if ( $s[0] == '[') {
  1200. $attr = trim($s, '[]');
  1201. if ( mb_strpos($attr, '=')) {
  1202. list( $attr, $val ) = explode('=', $attr);
  1203. if ($attr == 'nodeType' && $node->nodeType != $val)
  1204. $break = true;
  1205. }
  1206. } else
  1207. $break = true;
  1208. } else {
  1209. // DOMElement only
  1210. // ID
  1211. if ( $s[0] == '#') {
  1212. if ( $node->getAttribute('id') != substr($s, 1) )
  1213. $break = true;
  1214. // CLASSES
  1215. } else if ( $s[0] == '.') {
  1216. if (! $this->matchClasses( $s, $node ) )
  1217. $break = true;
  1218. // ATTRS
  1219. } else if ( $s[0] == '[') {
  1220. // strip side brackets
  1221. $attr = trim($s, '[]');
  1222. if (mb_strpos($attr, '=')) {
  1223. list($attr, $val) = explode('=', $attr);
  1224. $val = self::unQuote($val);
  1225. if ($attr == 'nodeType') {
  1226. if ($val != $node->nodeType)
  1227. $break = true;
  1228. } else if ($this->isRegexp($attr)) {
  1229. $val = extension_loaded('mbstring') && phpQuery::$mbstringSupport
  1230. ? quotemeta(trim($val, '"\''))
  1231. : preg_quote(trim($val, '"\''), '@');
  1232. // switch last character
  1233. switch( substr($attr, -1)) {
  1234. // quotemeta used insted of preg_quote
  1235. // http://code.google.com/p/phpquery/issues/detail?id=76
  1236. case '^':
  1237. $pattern = '^'.$val;
  1238. break;
  1239. case '*':
  1240. $pattern = '.*'.$val.'.*';
  1241. break;
  1242. case '$':
  1243. $pattern = '.*'.$val.'$';
  1244. break;
  1245. }
  1246. // cut last character
  1247. $attr = substr($attr, 0, -1);
  1248. $isMatch = extension_loaded('mbstring') && phpQuery::$mbstringSupport
  1249. ? mb_ereg_match($pattern, $node->getAttribute($attr))
  1250. : preg_match("@{$pattern}@", $node->getAttribute($attr));
  1251. if (! $isMatch)
  1252. $break = true;
  1253. } else if ($node->getAttribute($attr) != $val)
  1254. $break = true;
  1255. } else if (! $node->hasAttribute($attr))
  1256. $break = true;
  1257. // PSEUDO CLASSES
  1258. } else if ( $s[0] == ':') {
  1259. // skip
  1260. // TAG
  1261. } else if (trim($s)) {
  1262. if ($s != '*') {
  1263. // TODO namespaces
  1264. if (isset($node->tagName)) {
  1265. if ($node->tagName != $s)
  1266. $break = true;
  1267. } else if ($s == 'html' && ! $this->isRoot($node))
  1268. $break = true;
  1269. }
  1270. // AVOID NON-SIMPLE SELECTORS
  1271. } else if (in_array($s, $notSimpleSelector)) {
  1272. $break = true;
  1273. $this->debug(array('Skipping non simple selector', $selector));
  1274. }
  1275. }
  1276. if ($break)
  1277. break;
  1278. }
  1279. // if element passed all chunks of selector - add it to new stack
  1280. if (! $break )
  1281. $stack[] = $node;
  1282. }
  1283. $tmpStack = $this->elements;
  1284. $this->elements = $stack;
  1285. // PER ALL NODES selector chunks
  1286. foreach($selector as $s)
  1287. // PSEUDO CLASSES
  1288. if ($s[0] == ':')
  1289. $this->pseudoClasses($s);
  1290. foreach($this->elements as $node)
  1291. // XXX it should be merged without duplicates
  1292. // but jQuery doesnt do that
  1293. $finalStack[] = $node;
  1294. $this->elements = $tmpStack;
  1295. }
  1296. $this->elements = $finalStack;
  1297. if ($_skipHistory) {
  1298. return $this;
  1299. } else {
  1300. $this->debug("Stack length after filter(): ".count($finalStack));
  1301. return $this->newInstance();
  1302. }
  1303. }
  1304. /**
  1305. *
  1306. * @param $value
  1307. * @return unknown_type
  1308. * @TODO implement in all methods using passed parameters
  1309. */
  1310. protected static function unQuote($value) {
  1311. return $value[0] == '\'' || $value[0] == '"'
  1312. ? substr($value, 1, -1)
  1313. : $value;
  1314. }
  1315. /**
  1316. * Enter description here...
  1317. *
  1318. * @link http://docs.jquery.com/Ajax/load
  1319. * @return phpQuery|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1320. * @todo Support $selector
  1321. */
  1322. public function load($url, $data = null, $callback = null) {
  1323. if ($data && ! is_array($data)) {
  1324. $callback = $data;
  1325. $data = null;
  1326. }
  1327. if (mb_strpos($url, ' ') !== false) {
  1328. $matches = null;
  1329. if (extension_loaded('mbstring') && phpQuery::$mbstringSupport)
  1330. mb_ereg('^([^ ]+) (.*)$', $url, $matches);
  1331. else
  1332. preg_match('@^([^ ]+) (.*)$@', $url, $matches);
  1333. $url = $matches[1];
  1334. $selector = $matches[2];
  1335. // FIXME this sucks, pass as callback param
  1336. $this->_loadSelector = $selector;
  1337. }
  1338. $ajax = array(
  1339. 'url' => $url,
  1340. 'type' => $data ? 'POST' : 'GET',
  1341. 'data' => $data,
  1342. 'complete' => $callback,
  1343. 'success' => array($this, '__loadSuccess')
  1344. );
  1345. phpQuery::ajax($ajax);
  1346. return $this;
  1347. }
  1348. /**
  1349. * @access private
  1350. * @param $html
  1351. * @return unknown_type
  1352. */
  1353. public function __loadSuccess($html) {
  1354. if ($this->_loadSelector) {
  1355. $html = phpQuery::newDocument($html)->find($this->_loadSelector);
  1356. unset($this->_loadSelector);
  1357. }
  1358. foreach($this->stack(1) as $node) {
  1359. phpQuery::pq($node, $this->getDocumentID())
  1360. ->markup($html);
  1361. }
  1362. }
  1363. /**
  1364. * Enter description here...
  1365. *
  1366. * @return phpQuery|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1367. * @todo
  1368. */
  1369. public function css() {
  1370. // TODO
  1371. return $this;
  1372. }
  1373. /**
  1374. * @todo
  1375. *
  1376. */
  1377. public function show(){
  1378. // TODO
  1379. return $this;
  1380. }
  1381. /**
  1382. * @todo
  1383. *
  1384. */
  1385. public function hide(){
  1386. // TODO
  1387. return $this;
  1388. }
  1389. /**
  1390. * Trigger a type of event on every matched element.
  1391. *
  1392. * @param unknown_type $type
  1393. * @param unknown_type $data
  1394. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1395. * @TODO support more than event in $type (space-separated)
  1396. */
  1397. public function trigger($type, $data = array()) {
  1398. foreach($this->elements as $node)
  1399. phpQueryEvents::trigger($this->getDocumentID(), $type, $data, $node);
  1400. return $this;
  1401. }
  1402. /**
  1403. * This particular method triggers all bound event handlers on an element (for a specific event type) WITHOUT executing the browsers default actions.
  1404. *
  1405. * @param unknown_type $type
  1406. * @param unknown_type $data
  1407. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1408. * @TODO
  1409. */
  1410. public function triggerHandler($type, $data = array()) {
  1411. // TODO;
  1412. }
  1413. /**
  1414. * Binds a handler to one or more events (like click) for each matched element.
  1415. * Can also bind custom events.
  1416. *
  1417. * @param unknown_type $type
  1418. * @param unknown_type $data Optional
  1419. * @param unknown_type $callback
  1420. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1421. * @TODO support '!' (exclusive) events
  1422. * @TODO support more than event in $type (space-separated)
  1423. */
  1424. public function bind($type, $data, $callback = null) {
  1425. // TODO check if $data is callable, not using is_callable
  1426. if (! isset($callback)) {
  1427. $callback = $data;
  1428. $data = null;
  1429. }
  1430. foreach($this->elements as $node)
  1431. phpQueryEvents::add($this->getDocumentID(), $node, $type, $data, $callback);
  1432. return $this;
  1433. }
  1434. /**
  1435. * Enter description here...
  1436. *
  1437. * @param unknown_type $type
  1438. * @param unknown_type $callback
  1439. * @return unknown
  1440. * @TODO namespace events
  1441. * @TODO support more than event in $type (space-separated)
  1442. */
  1443. public function unbind($type = null, $callback = null) {
  1444. foreach($this->elements as $node)
  1445. phpQueryEvents::remove($this->getDocumentID(), $node, $type, $callback);
  1446. return $this;
  1447. }
  1448. /**
  1449. * Enter description here...
  1450. *
  1451. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1452. */
  1453. public function change($callback = null) {
  1454. if ($callback)
  1455. return $this->bind('change', $callback);
  1456. return $this->trigger('change');
  1457. }
  1458. /**
  1459. * Enter description here...
  1460. *
  1461. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1462. */
  1463. public function submit($callback = null) {
  1464. if ($callback)
  1465. return $this->bind('submit', $callback);
  1466. return $this->trigger('submit');
  1467. }
  1468. /**
  1469. * Enter description here...
  1470. *
  1471. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1472. */
  1473. public function click($callback = null) {
  1474. if ($callback)
  1475. return $this->bind('click', $callback);
  1476. return $this->trigger('click');
  1477. }
  1478. /**
  1479. * Enter description here...
  1480. *
  1481. * @param String|phpQuery
  1482. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1483. */
  1484. public function wrapAllOld($wrapper) {
  1485. $wrapper = pq($wrapper)->_clone();
  1486. if (! $wrapper->length() || ! $this->length() )
  1487. return $this;
  1488. $wrapper->insertBefore($this->elements[0]);
  1489. $deepest = $wrapper->elements[0];
  1490. while($deepest->firstChild && $deepest->firstChild instanceof DOMELEMENT)
  1491. $deepest = $deepest->firstChild;
  1492. pq($deepest)->append($this);
  1493. return $this;
  1494. }
  1495. /**
  1496. * Enter description here...
  1497. *
  1498. * TODO testme...
  1499. * @param String|phpQuery
  1500. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1501. */
  1502. public function wrapAll($wrapper) {
  1503. if (! $this->length())
  1504. return $this;
  1505. return phpQuery::pq($wrapper, $this->getDocumentID())
  1506. ->clone()
  1507. ->insertBefore($this->get(0))
  1508. ->map(array($this, '___wrapAllCallback'))
  1509. ->append($this);
  1510. }
  1511. /**
  1512. *
  1513. * @param $node
  1514. * @return unknown_type
  1515. * @access private
  1516. */
  1517. public function ___wrapAllCallback($node) {
  1518. $deepest = $node;
  1519. while($deepest->firstChild && $deepest->firstChild instanceof DOMELEMENT)
  1520. $deepest = $deepest->firstChild;
  1521. return $deepest;
  1522. }
  1523. /**
  1524. * Enter description here...
  1525. * NON JQUERY METHOD
  1526. *
  1527. * @param String|phpQuery
  1528. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1529. */
  1530. public function wrapAllPHP($codeBefore, $codeAfter) {
  1531. return $this
  1532. ->slice(0, 1)
  1533. ->beforePHP($codeBefore)
  1534. ->end()
  1535. ->slice(-1)
  1536. ->afterPHP($codeAfter)
  1537. ->end();
  1538. }
  1539. /**
  1540. * Enter description here...
  1541. *
  1542. * @param String|phpQuery
  1543. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1544. */
  1545. public function wrap($wrapper) {
  1546. foreach($this->stack() as $node)
  1547. phpQuery::pq($node, $this->getDocumentID())->wrapAll($wrapper);
  1548. return $this;
  1549. }
  1550. /**
  1551. * Enter description here...
  1552. *
  1553. * @param String|phpQuery
  1554. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1555. */
  1556. public function wrapPHP($codeBefore, $codeAfter) {
  1557. foreach($this->stack() as $node)
  1558. phpQuery::pq($node, $this->getDocumentID())->wrapAllPHP($codeBefore, $codeAfter);
  1559. return $this;
  1560. }
  1561. /**
  1562. * Enter description here...
  1563. *
  1564. * @param String|phpQuery
  1565. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1566. */
  1567. public function wrapInner($wrapper) {
  1568. foreach($this->stack() as $node)
  1569. phpQuery::pq($node, $this->getDocumentID())->contents()->wrapAll($wrapper);
  1570. return $this;
  1571. }
  1572. /**
  1573. * Enter description here...
  1574. *
  1575. * @param String|phpQuery
  1576. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1577. */
  1578. public function wrapInnerPHP($codeBefore, $codeAfter) {
  1579. foreach($this->stack(1) as $node)
  1580. phpQuery::pq($node, $this->getDocumentID())->contents()
  1581. ->wrapAllPHP($codeBefore, $codeAfter);
  1582. return $this;
  1583. }
  1584. /**
  1585. * Enter description here...
  1586. *
  1587. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1588. * @testme Support for text nodes
  1589. */
  1590. public function contents() {
  1591. $stack = array();
  1592. foreach($this->stack(1) as $el) {
  1593. // FIXME (fixed) http://code.google.com/p/phpquery/issues/detail?id=56
  1594. // if (! isset($el->childNodes))
  1595. // continue;
  1596. foreach($el->childNodes as $node) {
  1597. $stack[] = $node;
  1598. }
  1599. }
  1600. return $this->newInstance($stack);
  1601. }
  1602. /**
  1603. * Enter description here...
  1604. *
  1605. * jQuery difference.
  1606. *
  1607. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1608. */
  1609. public function contentsUnwrap() {
  1610. foreach($this->stack(1) as $node) {
  1611. if (! $node->parentNode )
  1612. continue;
  1613. $childNodes = array();
  1614. // any modification in DOM tree breaks childNodes iteration, so cache them first
  1615. foreach($node->childNodes as $chNode )
  1616. $childNodes[] = $chNode;
  1617. foreach($childNodes as $chNode )
  1618. // $node->parentNode->appendChild($chNode);
  1619. $node->parentNode->insertBefore($chNode, $node);
  1620. $node->parentNode->removeChild($node);
  1621. }
  1622. return $this;
  1623. }
  1624. /**
  1625. * Enter description here...
  1626. *
  1627. * jQuery difference.
  1628. */
  1629. public function switchWith($markup) {
  1630. $markup = pq($markup, $this->getDocumentID());
  1631. $content = null;
  1632. foreach($this->stack(1) as $node) {
  1633. pq($node)
  1634. ->contents()->toReference($content)->end()
  1635. ->replaceWith($markup->clone()->append($content));
  1636. }
  1637. return $this;
  1638. }
  1639. /**
  1640. * Enter description here...
  1641. *
  1642. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1643. */
  1644. public function eq($num) {
  1645. $oldStack = $this->elements;
  1646. $this->elementsBackup = $this->elements;
  1647. $this->elements = array();
  1648. if ( isset($oldStack[$num]) )
  1649. $this->elements[] = $oldStack[$num];
  1650. return $this->newInstance();
  1651. }
  1652. /**
  1653. * Enter description here...
  1654. *
  1655. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1656. */
  1657. public function size() {
  1658. return count($this->elements);
  1659. }
  1660. /**
  1661. * Enter description here...
  1662. *
  1663. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1664. * @deprecated Use length as attribute
  1665. */
  1666. public function length() {
  1667. return $this->size();
  1668. }
  1669. public function count() {
  1670. return $this->size();
  1671. }
  1672. /**
  1673. * Enter description here...
  1674. *
  1675. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1676. * @todo $level
  1677. */
  1678. public function end($level = 1) {
  1679. // $this->elements = array_pop( $this->history );
  1680. // return $this;
  1681. // $this->previous->DOM = $this->DOM;
  1682. // $this->previous->XPath = $this->XPath;
  1683. return $this->previous
  1684. ? $this->previous
  1685. : $this;
  1686. }
  1687. /**
  1688. * Enter description here...
  1689. * Normal use ->clone() .
  1690. *
  1691. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1692. * @access private
  1693. */
  1694. public function _clone() {
  1695. $newStack = array();
  1696. //pr(array('copy... ', $this->whois()));
  1697. //$this->dumpHistory('copy');
  1698. $this->elementsBackup = $this->elements;
  1699. foreach($this->elements as $node) {
  1700. $newStack[] = $node->cloneNode(true);
  1701. }
  1702. $this->elements = $newStack;
  1703. return $this->newInstance();
  1704. }
  1705. /**
  1706. * Enter description here...
  1707. *
  1708. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1709. */
  1710. public function replaceWithPHP($code) {
  1711. return $this->replaceWith(phpQuery::php($code));
  1712. }
  1713. /**
  1714. * Enter description here...
  1715. *
  1716. * @param String|phpQuery $content
  1717. * @link http://docs.jquery.com/Manipulation/replaceWith#content
  1718. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1719. */
  1720. public function replaceWith($content) {
  1721. return $this->after($content)->remove();
  1722. }
  1723. /**
  1724. * Enter description here...
  1725. *
  1726. * @param String $selector
  1727. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1728. * @todo this works ?
  1729. */
  1730. public function replaceAll($selector) {
  1731. foreach(phpQuery::pq($selector, $this->getDocumentID()) as $node)
  1732. phpQuery::pq($node, $this->getDocumentID())
  1733. ->after($this->_clone())
  1734. ->remove();
  1735. return $this;
  1736. }
  1737. /**
  1738. * Enter description here...
  1739. *
  1740. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1741. */
  1742. public function remove($selector = null) {
  1743. $loop = $selector
  1744. ? $this->filter($selector)->elements
  1745. : $this->elements;
  1746. foreach($loop as $node) {
  1747. if (! $node->parentNode )
  1748. continue;
  1749. if (isset($node->tagName))
  1750. $this->debug("Removing '{$node->tagName}'");
  1751. $node->parentNode->removeChild($node);
  1752. // Mutation event
  1753. $event = new DOMEvent(array(
  1754. 'target' => $node,
  1755. 'type' => 'DOMNodeRemoved'
  1756. ));
  1757. phpQueryEvents::trigger($this->getDocumentID(),
  1758. $event->type, array($event), $node
  1759. );
  1760. }
  1761. return $this;
  1762. }
  1763. protected function markupEvents($newMarkup, $oldMarkup, $node) {
  1764. if ($node->tagName == 'textarea' && $newMarkup != $oldMarkup) {
  1765. $event = new DOMEvent(array(
  1766. 'target' => $node,
  1767. 'type' => 'change'
  1768. ));
  1769. phpQueryEvents::trigger($this->getDocumentID(),
  1770. $event->type, array($event), $node
  1771. );
  1772. }
  1773. }
  1774. /**
  1775. * jQuey difference
  1776. *
  1777. * @param $markup
  1778. * @return unknown_type
  1779. * @TODO trigger change event for textarea
  1780. */
  1781. public function markup($markup = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  1782. $args = func_get_args();
  1783. if ($this->documentWrapper->isXML)
  1784. return call_user_func_array(array($this, 'xml'), $args);
  1785. else
  1786. return call_user_func_array(array($this, 'html'), $args);
  1787. }
  1788. /**
  1789. * jQuey difference
  1790. *
  1791. * @param $markup
  1792. * @return unknown_type
  1793. */
  1794. public function markupOuter($callback1 = null, $callback2 = null, $callback3 = null) {
  1795. $args = func_get_args();
  1796. if ($this->documentWrapper->isXML)
  1797. return call_user_func_array(array($this, 'xmlOuter'), $args);
  1798. else
  1799. return call_user_func_array(array($this, 'htmlOuter'), $args);
  1800. }
  1801. /**
  1802. * Enter description here...
  1803. *
  1804. * @param unknown_type $html
  1805. * @return string|phpQuery|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1806. * @TODO force html result
  1807. */
  1808. public function html($html = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  1809. if (isset($html)) {
  1810. // INSERT
  1811. $nodes = $this->documentWrapper->import($html);
  1812. $this->empty();
  1813. foreach($this->stack(1) as $alreadyAdded => $node) {
  1814. // for now, limit events for textarea
  1815. if (($this->isXHTML() || $this->isHTML()) && $node->tagName == 'textarea')
  1816. $oldHtml = pq($node, $this->getDocumentID())->markup();
  1817. foreach($nodes as $newNode) {
  1818. $node->appendChild($alreadyAdded
  1819. ? $newNode->cloneNode(true)
  1820. : $newNode
  1821. );
  1822. }
  1823. // for now, limit events for textarea
  1824. if (($this->isXHTML() || $this->isHTML()) && $node->tagName == 'textarea')
  1825. $this->markupEvents($html, $oldHtml, $node);
  1826. }
  1827. return $this;
  1828. } else {
  1829. // FETCH
  1830. $return = $this->documentWrapper->markup($this->elements, true);
  1831. $args = func_get_args();
  1832. foreach(array_slice($args, 1) as $callback) {
  1833. $return = phpQuery::callbackRun($callback, array($return));
  1834. }
  1835. return $return;
  1836. }
  1837. }
  1838. /**
  1839. * @TODO force xml result
  1840. */
  1841. public function xml($xml = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  1842. $args = func_get_args();
  1843. return call_user_func_array(array($this, 'html'), $args);
  1844. }
  1845. /**
  1846. * Enter description here...
  1847. * @TODO force html result
  1848. *
  1849. * @return String
  1850. */
  1851. public function htmlOuter($callback1 = null, $callback2 = null, $callback3 = null) {
  1852. $markup = $this->documentWrapper->markup($this->elements);
  1853. // pass thou callbacks
  1854. $args = func_get_args();
  1855. foreach($args as $callback) {
  1856. $markup = phpQuery::callbackRun($callback, array($markup));
  1857. }
  1858. return $markup;
  1859. }
  1860. /**
  1861. * @TODO force xml result
  1862. */
  1863. public function xmlOuter($callback1 = null, $callback2 = null, $callback3 = null) {
  1864. $args = func_get_args();
  1865. return call_user_func_array(array($this, 'htmlOuter'), $args);
  1866. }
  1867. public function __toString() {
  1868. return $this->markupOuter();
  1869. }
  1870. /**
  1871. * Just like html(), but returns markup with VALID (dangerous) PHP tags.
  1872. *
  1873. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1874. * @todo support returning markup with PHP tags when called without param
  1875. */
  1876. public function php($code = null) {
  1877. return $this->markupPHP($code);
  1878. }
  1879. /**
  1880. * Enter description here...
  1881. *
  1882. * @param $code
  1883. * @return unknown_type
  1884. */
  1885. public function markupPHP($code = null) {
  1886. return isset($code)
  1887. ? $this->markup(phpQuery::php($code))
  1888. : phpQuery::markupToPHP($this->markup());
  1889. }
  1890. /**
  1891. * Enter description here...
  1892. *
  1893. * @param $code
  1894. * @return unknown_type
  1895. */
  1896. public function markupOuterPHP() {
  1897. return phpQuery::markupToPHP($this->markupOuter());
  1898. }
  1899. /**
  1900. * Enter description here...
  1901. *
  1902. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1903. */
  1904. public function children($selector = null) {
  1905. $stack = array();
  1906. foreach($this->stack(1) as $node) {
  1907. // foreach($node->getElementsByTagName('*') as $newNode) {
  1908. foreach($node->childNodes as $newNode) {
  1909. if ($newNode->nodeType != 1)
  1910. continue;
  1911. if ($selector && ! $this->is($selector, $newNode))
  1912. continue;
  1913. if ($this->elementsContainsNode($newNode, $stack))
  1914. continue;
  1915. $stack[] = $newNode;
  1916. }
  1917. }
  1918. $this->elementsBackup = $this->elements;
  1919. $this->elements = $stack;
  1920. return $this->newInstance();
  1921. }
  1922. /**
  1923. * Enter description here...
  1924. *
  1925. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1926. */
  1927. public function ancestors($selector = null) {
  1928. return $this->children( $selector );
  1929. }
  1930. /**
  1931. * Enter description here...
  1932. *
  1933. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1934. */
  1935. public function append( $content) {
  1936. return $this->insert($content, __FUNCTION__);
  1937. }
  1938. /**
  1939. * Enter description here...
  1940. *
  1941. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1942. */
  1943. public function appendPHP( $content) {
  1944. return $this->insert("<php><!-- {$content} --></php>", 'append');
  1945. }
  1946. /**
  1947. * Enter description here...
  1948. *
  1949. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1950. */
  1951. public function appendTo( $seletor) {
  1952. return $this->insert($seletor, __FUNCTION__);
  1953. }
  1954. /**
  1955. * Enter description here...
  1956. *
  1957. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1958. */
  1959. public function prepend( $content) {
  1960. return $this->insert($content, __FUNCTION__);
  1961. }
  1962. /**
  1963. * Enter description here...
  1964. *
  1965. * @todo accept many arguments, which are joined, arrays maybe also
  1966. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1967. */
  1968. public function prependPHP( $content) {
  1969. return $this->insert("<php><!-- {$content} --></php>", 'prepend');
  1970. }
  1971. /**
  1972. * Enter description here...
  1973. *
  1974. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1975. */
  1976. public function prependTo( $seletor) {
  1977. return $this->insert($seletor, __FUNCTION__);
  1978. }
  1979. /**
  1980. * Enter description here...
  1981. *
  1982. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1983. */
  1984. public function before($content) {
  1985. return $this->insert($content, __FUNCTION__);
  1986. }
  1987. /**
  1988. * Enter description here...
  1989. *
  1990. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1991. */
  1992. public function beforePHP( $content) {
  1993. return $this->insert("<php><!-- {$content} --></php>", 'before');
  1994. }
  1995. /**
  1996. * Enter description here...
  1997. *
  1998. * @param String|phpQuery
  1999. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2000. */
  2001. public function insertBefore( $seletor) {
  2002. return $this->insert($seletor, __FUNCTION__);
  2003. }
  2004. /**
  2005. * Enter description here...
  2006. *
  2007. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2008. */
  2009. public function after( $content) {
  2010. return $this->insert($content, __FUNCTION__);
  2011. }
  2012. /**
  2013. * Enter description here...
  2014. *
  2015. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2016. */
  2017. public function afterPHP( $content) {
  2018. return $this->insert("<php><!-- {$content} --></php>", 'after');
  2019. }
  2020. /**
  2021. * Enter description here...
  2022. *
  2023. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2024. */
  2025. public function insertAfter( $seletor) {
  2026. return $this->insert($seletor, __FUNCTION__);
  2027. }
  2028. /**
  2029. * Internal insert method. Don't use it.
  2030. *
  2031. * @param unknown_type $target
  2032. * @param unknown_type $type
  2033. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2034. * @access private
  2035. */
  2036. public function insert($target, $type) {
  2037. $this->debug("Inserting data with '{$type}'");
  2038. $to = false;
  2039. switch( $type) {
  2040. case 'appendTo':
  2041. case 'prependTo':
  2042. case 'insertBefore':
  2043. case 'insertAfter':
  2044. $to = true;
  2045. }
  2046. switch(gettype($target)) {
  2047. case 'string':
  2048. $insertFrom = $insertTo = array();
  2049. if ($to) {
  2050. // INSERT TO
  2051. $insertFrom = $this->elements;
  2052. if (phpQuery::isMarkup($target)) {
  2053. // $target is new markup, import it
  2054. $insertTo = $this->documentWrapper->import($target);
  2055. // insert into selected element
  2056. } else {
  2057. // $tagret is a selector
  2058. $thisStack = $this->elements;
  2059. $this->toRoot();
  2060. $insertTo = $this->find($target)->elements;
  2061. $this->elements = $thisStack;
  2062. }
  2063. } else {
  2064. // INSERT FROM
  2065. $insertTo = $this->elements;
  2066. $insertFrom = $this->documentWrapper->import($target);
  2067. }
  2068. break;
  2069. case 'object':
  2070. $insertFrom = $insertTo = array();
  2071. // phpQuery
  2072. if ($target instanceof self) {
  2073. if ($to) {
  2074. $insertTo = $target->elements;
  2075. if ($this->documentFragment && $this->stackIsRoot())
  2076. // get all body children
  2077. // $loop = $this->find('body > *')->elements;
  2078. // TODO test it, test it hard...
  2079. // $loop = $this->newInstance($this->root)->find('> *')->elements;
  2080. $loop = $this->root->childNodes;
  2081. else
  2082. $loop = $this->elements;
  2083. // import nodes if needed
  2084. $insertFrom = $this->getDocumentID() == $target->getDocumentID()
  2085. ? $loop
  2086. : $target->documentWrapper->import($loop);
  2087. } else {
  2088. $insertTo = $this->elements;
  2089. if ( $target->documentFragment && $target->stackIsRoot() )
  2090. // get all body children
  2091. // $loop = $target->find('body > *')->elements;
  2092. $loop = $target->root->childNodes;
  2093. else
  2094. $loop = $target->elements;
  2095. // import nodes if needed
  2096. $insertFrom = $this->getDocumentID() == $target->getDocumentID()
  2097. ? $loop
  2098. : $this->documentWrapper->import($loop);
  2099. }
  2100. // DOMNODE
  2101. } elseif ($target instanceof DOMNODE) {
  2102. // import node if needed
  2103. // if ( $target->ownerDocument != $this->DOM )
  2104. // $target = $this->DOM->importNode($target, true);
  2105. if ( $to) {
  2106. $insertTo = array($target);
  2107. if ($this->documentFragment && $this->stackIsRoot())
  2108. // get all body children
  2109. $loop = $this->root->childNodes;
  2110. // $loop = $this->find('body > *')->elements;
  2111. else
  2112. $loop = $this->elements;
  2113. foreach($loop as $fromNode)
  2114. // import nodes if needed
  2115. $insertFrom[] = ! $fromNode->ownerDocument->isSameNode($target->ownerDocument)
  2116. ? $target->ownerDocument->importNode($fromNode, true)
  2117. : $fromNode;
  2118. } else {
  2119. // import node if needed
  2120. if (! $target->ownerDocument->isSameNode($this->document))
  2121. $target = $this->document->importNode($target, true);
  2122. $insertTo = $this->elements;
  2123. $insertFrom[] = $target;
  2124. }
  2125. }
  2126. break;
  2127. }
  2128. phpQuery::debug("From ".count($insertFrom)."; To ".count($insertTo)." nodes");
  2129. foreach($insertTo as $insertNumber => $toNode) {
  2130. // we need static relative elements in some cases
  2131. switch( $type) {
  2132. case 'prependTo':
  2133. case 'prepend':
  2134. $firstChild = $toNode->firstChild;
  2135. break;
  2136. case 'insertAfter':
  2137. case 'after':
  2138. $nextSibling = $toNode->nextSibling;
  2139. break;
  2140. }
  2141. foreach($insertFrom as $fromNode) {
  2142. // clone if inserted already before
  2143. $insert = $insertNumber
  2144. ? $fromNode->cloneNode(true)
  2145. : $fromNode;
  2146. switch($type) {
  2147. case 'appendTo':
  2148. case 'append':
  2149. // $toNode->insertBefore(
  2150. // $fromNode,
  2151. // $toNode->lastChild->nextSibling
  2152. // );
  2153. $toNode->appendChild($insert);
  2154. $eventTarget = $insert;
  2155. break;
  2156. case 'prependTo':
  2157. case 'prepend':
  2158. $toNode->insertBefore(
  2159. $insert,
  2160. $firstChild
  2161. );
  2162. break;
  2163. case 'insertBefore':
  2164. case 'before':
  2165. if (! $toNode->parentNode)
  2166. throw new Exception("No parentNode, can't do {$type}()");
  2167. else
  2168. $toNode->parentNode->insertBefore(
  2169. $insert,
  2170. $toNode
  2171. );
  2172. break;
  2173. case 'insertAfter':
  2174. case 'after':
  2175. if (! $toNode->parentNode)
  2176. throw new Exception("No parentNode, can't do {$type}()");
  2177. else
  2178. $toNode->parentNode->insertBefore(
  2179. $insert,
  2180. $nextSibling
  2181. );
  2182. break;
  2183. }
  2184. // Mutation event
  2185. $event = new DOMEvent(array(
  2186. 'target' => $insert,
  2187. 'type' => 'DOMNodeInserted'
  2188. ));
  2189. phpQueryEvents::trigger($this->getDocumentID(),
  2190. $event->type, array($event), $insert
  2191. );
  2192. }
  2193. }
  2194. return $this;
  2195. }
  2196. /**
  2197. * Enter description here...
  2198. *
  2199. * @return Int
  2200. */
  2201. public function index($subject) {
  2202. $index = -1;
  2203. $subject = $subject instanceof phpQueryObject
  2204. ? $subject->elements[0]
  2205. : $subject;
  2206. foreach($this->newInstance() as $k => $node) {
  2207. if ($node->isSameNode($subject))
  2208. $index = $k;
  2209. }
  2210. return $index;
  2211. }
  2212. /**
  2213. * Enter description here...
  2214. *
  2215. * @param unknown_type $start
  2216. * @param unknown_type $end
  2217. *
  2218. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2219. * @testme
  2220. */
  2221. public function slice($start, $end = null) {
  2222. // $last = count($this->elements)-1;
  2223. // $end = $end
  2224. // ? min($end, $last)
  2225. // : $last;
  2226. // if ($start < 0)
  2227. // $start = $last+$start;
  2228. // if ($start > $last)
  2229. // return array();
  2230. if ($end > 0)
  2231. $end = $end-$start;
  2232. return $this->newInstance(
  2233. array_slice($this->elements, $start, $end)
  2234. );
  2235. }
  2236. /**
  2237. * Enter description here...
  2238. *
  2239. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2240. */
  2241. public function reverse() {
  2242. $this->elementsBackup = $this->elements;
  2243. $this->elements = array_reverse($this->elements);
  2244. return $this->newInstance();
  2245. }
  2246. /**
  2247. * Return joined text content.
  2248. * @return String
  2249. */
  2250. public function text($text = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  2251. if (isset($text))
  2252. return $this->html(htmlspecialchars($text));
  2253. $args = func_get_args();
  2254. $args = array_slice($args, 1);
  2255. $return = '';
  2256. foreach($this->elements as $node) {
  2257. $text = $node->textContent;
  2258. if (count($this->elements) > 1 && $text)
  2259. $text .= "\n";
  2260. foreach($args as $callback) {
  2261. $text = phpQuery::callbackRun($callback, array($text));
  2262. }
  2263. $return .= $text;
  2264. }
  2265. return $return;
  2266. }
  2267. /**
  2268. * @return The text content of each matching element, like
  2269. * text() but returns an array with one entry per matched element.
  2270. * Read only.
  2271. */
  2272. public function texts($attr = null) {
  2273. $results = array();
  2274. foreach($this->elements as $node) {
  2275. $results[] = $node->textContent;
  2276. }
  2277. return $results;
  2278. }
  2279. /**
  2280. * Enter description here...
  2281. *
  2282. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2283. */
  2284. public function plugin($class, $file = null) {
  2285. phpQuery::plugin($class, $file);
  2286. return $this;
  2287. }
  2288. /**
  2289. * Deprecated, use $pq->plugin() instead.
  2290. *
  2291. * @deprecated
  2292. * @param $class
  2293. * @param $file
  2294. * @return unknown_type
  2295. */
  2296. public static function extend($class, $file = null) {
  2297. return $this->plugin($class, $file);
  2298. }
  2299. /**
  2300. *
  2301. * @access private
  2302. * @param $method
  2303. * @param $args
  2304. * @return unknown_type
  2305. */
  2306. public function __call($method, $args) {
  2307. $aliasMethods = array('clone', 'empty');
  2308. if (isset(phpQuery::$extendMethods[$method])) {
  2309. array_unshift($args, $this);
  2310. return phpQuery::callbackRun(
  2311. phpQuery::$extendMethods[$method], $args
  2312. );
  2313. } else if (isset(phpQuery::$pluginsMethods[$method])) {
  2314. array_unshift($args, $this);
  2315. $class = phpQuery::$pluginsMethods[$method];
  2316. $realClass = "phpQueryObjectPlugin_$class";
  2317. $return = call_user_func_array(
  2318. array($realClass, $method),
  2319. $args
  2320. );
  2321. // XXX deprecate ?
  2322. return is_null($return)
  2323. ? $this
  2324. : $return;
  2325. } else if (in_array($method, $aliasMethods)) {
  2326. return call_user_func_array(array($this, '_'.$method), $args);
  2327. } else
  2328. throw new Exception("Method '{$method}' doesnt exist");
  2329. }
  2330. /**
  2331. * Safe rename of next().
  2332. *
  2333. * Use it ONLY when need to call next() on an iterated object (in same time).
  2334. * Normaly there is no need to do such thing ;)
  2335. *
  2336. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2337. * @access private
  2338. */
  2339. public function _next($selector = null) {
  2340. return $this->newInstance(
  2341. $this->getElementSiblings('nextSibling', $selector, true)
  2342. );
  2343. }
  2344. /**
  2345. * Use prev() and next().
  2346. *
  2347. * @deprecated
  2348. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2349. * @access private
  2350. */
  2351. public function _prev($selector = null) {
  2352. return $this->prev($selector);
  2353. }
  2354. /**
  2355. * Enter description here...
  2356. *
  2357. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2358. */
  2359. public function prev($selector = null) {
  2360. return $this->newInstance(
  2361. $this->getElementSiblings('previousSibling', $selector, true)
  2362. );
  2363. }
  2364. /**
  2365. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2366. * @todo
  2367. */
  2368. public function prevAll($selector = null) {
  2369. return $this->newInstance(
  2370. $this->getElementSiblings('previousSibling', $selector)
  2371. );
  2372. }
  2373. /**
  2374. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2375. * @todo FIXME: returns source elements insted of next siblings
  2376. */
  2377. public function nextAll($selector = null) {
  2378. return $this->newInstance(
  2379. $this->getElementSiblings('nextSibling', $selector)
  2380. );
  2381. }
  2382. /**
  2383. * @access private
  2384. */
  2385. protected function getElementSiblings($direction, $selector = null, $limitToOne = false) {
  2386. $stack = array();
  2387. $count = 0;
  2388. foreach($this->stack() as $node) {
  2389. $test = $node;
  2390. while( isset($test->{$direction}) && $test->{$direction}) {
  2391. $test = $test->{$direction};
  2392. if (! $test instanceof DOMELEMENT)
  2393. continue;
  2394. $stack[] = $test;
  2395. if ($limitToOne)
  2396. break;
  2397. }
  2398. }
  2399. if ($selector) {
  2400. $stackOld = $this->elements;
  2401. $this->elements = $stack;
  2402. $stack = $this->filter($selector, true)->stack();
  2403. $this->elements = $stackOld;
  2404. }
  2405. return $stack;
  2406. }
  2407. /**
  2408. * Enter description here...
  2409. *
  2410. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2411. */
  2412. public function siblings($selector = null) {
  2413. $stack = array();
  2414. $siblings = array_merge(
  2415. $this->getElementSiblings('previousSibling', $selector),
  2416. $this->getElementSiblings('nextSibling', $selector)
  2417. );
  2418. foreach($siblings as $node) {
  2419. if (! $this->elementsContainsNode($node, $stack))
  2420. $stack[] = $node;
  2421. }
  2422. return $this->newInstance($stack);
  2423. }
  2424. /**
  2425. * Enter description here...
  2426. *
  2427. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2428. */
  2429. public function not($selector = null) {
  2430. if (is_string($selector))
  2431. phpQuery::debug(array('not', $selector));
  2432. else
  2433. phpQuery::debug('not');
  2434. $stack = array();
  2435. if ($selector instanceof self || $selector instanceof DOMNODE) {
  2436. foreach($this->stack() as $node) {
  2437. if ($selector instanceof self) {
  2438. $matchFound = false;
  2439. foreach($selector->stack() as $notNode) {
  2440. if ($notNode->isSameNode($node))
  2441. $matchFound = true;
  2442. }
  2443. if (! $matchFound)
  2444. $stack[] = $node;
  2445. } else if ($selector instanceof DOMNODE) {
  2446. if (! $selector->isSameNode($node))
  2447. $stack[] = $node;
  2448. } else {
  2449. if (! $this->is($selector))
  2450. $stack[] = $node;
  2451. }
  2452. }
  2453. } else {
  2454. $orgStack = $this->stack();
  2455. $matched = $this->filter($selector, true)->stack();
  2456. // $matched = array();
  2457. // // simulate OR in filter() instead of AND 5y
  2458. // foreach($this->parseSelector($selector) as $s) {
  2459. // $matched = array_merge($matched,
  2460. // $this->filter(array($s))->stack()
  2461. // );
  2462. // }
  2463. foreach($orgStack as $node)
  2464. if (! $this->elementsContainsNode($node, $matched))
  2465. $stack[] = $node;
  2466. }
  2467. return $this->newInstance($stack);
  2468. }
  2469. /**
  2470. * Enter description here...
  2471. *
  2472. * @param string|phpQueryObject
  2473. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2474. */
  2475. public function add($selector = null) {
  2476. if (! $selector)
  2477. return $this;
  2478. $stack = array();
  2479. $this->elementsBackup = $this->elements;
  2480. $found = phpQuery::pq($selector, $this->getDocumentID());
  2481. $this->merge($found->elements);
  2482. return $this->newInstance();
  2483. }
  2484. /**
  2485. * @access private
  2486. */
  2487. protected function merge() {
  2488. foreach(func_get_args() as $nodes)
  2489. foreach($nodes as $newNode )
  2490. if (! $this->elementsContainsNode($newNode) )
  2491. $this->elements[] = $newNode;
  2492. }
  2493. /**
  2494. * @access private
  2495. * TODO refactor to stackContainsNode
  2496. */
  2497. protected function elementsContainsNode($nodeToCheck, $elementsStack = null) {
  2498. $loop = ! is_null($elementsStack)
  2499. ? $elementsStack
  2500. : $this->elements;
  2501. foreach($loop as $node) {
  2502. if ( $node->isSameNode( $nodeToCheck ) )
  2503. return true;
  2504. }
  2505. return false;
  2506. }
  2507. /**
  2508. * Enter description here...
  2509. *
  2510. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2511. */
  2512. public function parent($selector = null) {
  2513. $stack = array();
  2514. foreach($this->elements as $node )
  2515. if ( $node->parentNode && ! $this->elementsContainsNode($node->parentNode, $stack) )
  2516. $stack[] = $node->parentNode;
  2517. $this->elementsBackup = $this->elements;
  2518. $this->elements = $stack;
  2519. if ( $selector )
  2520. $this->filter($selector, true);
  2521. return $this->newInstance();
  2522. }
  2523. /**
  2524. * Enter description here...
  2525. *
  2526. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2527. */
  2528. public function parents($selector = null) {
  2529. $stack = array();
  2530. if (! $this->elements )
  2531. $this->debug('parents() - stack empty');
  2532. foreach($this->elements as $node) {
  2533. $test = $node;
  2534. while( $test->parentNode) {
  2535. $test = $test->parentNode;
  2536. if ($this->isRoot($test))
  2537. break;
  2538. if (! $this->elementsContainsNode($test, $stack)) {
  2539. $stack[] = $test;
  2540. continue;
  2541. }
  2542. }
  2543. }
  2544. $this->elementsBackup = $this->elements;
  2545. $this->elements = $stack;
  2546. if ( $selector )
  2547. $this->filter($selector, true);
  2548. return $this->newInstance();
  2549. }
  2550. /**
  2551. * Internal stack iterator.
  2552. *
  2553. * @access private
  2554. * @return {Array.<DOMNode>}
  2555. */
  2556. public function stack($nodeTypes = null) {
  2557. if (!isset($nodeTypes))
  2558. return $this->elements;
  2559. if (!is_array($nodeTypes))
  2560. $nodeTypes = array($nodeTypes);
  2561. $return = array();
  2562. foreach($this->elements as $node) {
  2563. if (in_array($node->nodeType, $nodeTypes))
  2564. $return[] = $node;
  2565. }
  2566. return $return;
  2567. }
  2568. // TODO phpdoc; $oldAttr is result of hasAttribute, before any changes
  2569. protected function attrEvents($attr, $oldAttr, $oldValue, $node) {
  2570. // skip events for XML documents
  2571. if (! $this->isXHTML() && ! $this->isHTML())
  2572. return;
  2573. $event = null;
  2574. // identify
  2575. $isInputValue = $node->tagName == 'input'
  2576. && (
  2577. in_array($node->getAttribute('type'),
  2578. array('text', 'password', 'hidden'))
  2579. || !$node->getAttribute('type')
  2580. );
  2581. $isRadio = $node->tagName == 'input'
  2582. && $node->getAttribute('type') == 'radio';
  2583. $isCheckbox = $node->tagName == 'input'
  2584. && $node->getAttribute('type') == 'checkbox';
  2585. $isOption = $node->tagName == 'option';
  2586. if ($isInputValue && $attr == 'value' && $oldValue != $node->getAttribute($attr)) {
  2587. $event = new DOMEvent(array(
  2588. 'target' => $node,
  2589. 'type' => 'change'
  2590. ));
  2591. } else if (($isRadio || $isCheckbox) && $attr == 'checked' && (
  2592. // check
  2593. (! $oldAttr && $node->hasAttribute($attr))
  2594. // un-check
  2595. || (! $node->hasAttribute($attr) && $oldAttr)
  2596. )) {
  2597. $event = new DOMEvent(array(
  2598. 'target' => $node,
  2599. 'type' => 'change'
  2600. ));
  2601. } else if ($isOption && $node->parentNode && $attr == 'selected' && (
  2602. // select
  2603. (! $oldAttr && $node->hasAttribute($attr))
  2604. // un-select
  2605. || (! $node->hasAttribute($attr) && $oldAttr)
  2606. )) {
  2607. $event = new DOMEvent(array(
  2608. 'target' => $node->parentNode,
  2609. 'type' => 'change'
  2610. ));
  2611. }
  2612. if ($event) {
  2613. phpQueryEvents::trigger($this->getDocumentID(),
  2614. $event->type, array($event), $node
  2615. );
  2616. }
  2617. }
  2618. public function attr($attr = null, $value = null) {
  2619. foreach($this->stack(1) as $node) {
  2620. if (! is_null($value)) {
  2621. $loop = $attr == '*'
  2622. ? $this->getNodeAttrs($node)
  2623. : array($attr);
  2624. foreach($loop as $a) {
  2625. $oldValue = $node->getAttribute($a);
  2626. $oldAttr = $node->hasAttribute($a);
  2627. // TODO raises an error when charset other than UTF-8
  2628. // while document's charset is also not UTF-8
  2629. @$node->setAttribute($a, $value);
  2630. $this->attrEvents($a, $oldAttr, $oldValue, $node);
  2631. }
  2632. } else if ($attr == '*') {
  2633. // jQuery difference
  2634. $return = array();
  2635. foreach($node->attributes as $n => $v)
  2636. $return[$n] = $v->value;
  2637. return $return;
  2638. } else
  2639. return $node->hasAttribute($attr)
  2640. ? $node->getAttribute($attr)
  2641. : null;
  2642. }
  2643. return is_null($value)
  2644. ? '' : $this;
  2645. }
  2646. /**
  2647. * @return The same attribute of each matching element, like
  2648. * attr() but returns an array with one entry per matched element.
  2649. * Read only.
  2650. */
  2651. public function attrs($attr = null) {
  2652. $results = array();
  2653. foreach($this->stack(1) as $node) {
  2654. $results[] = $node->hasAttribute($attr)
  2655. ? $node->getAttribute($attr)
  2656. : null;
  2657. }
  2658. return $results;
  2659. }
  2660. /**
  2661. * @access private
  2662. */
  2663. protected function getNodeAttrs($node) {
  2664. $return = array();
  2665. foreach($node->attributes as $n => $o)
  2666. $return[] = $n;
  2667. return $return;
  2668. }
  2669. /**
  2670. * Enter description here...
  2671. *
  2672. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2673. * @todo check CDATA ???
  2674. */
  2675. public function attrPHP($attr, $code) {
  2676. if (! is_null($code)) {
  2677. $value = '<'.'?php '.$code.' ?'.'>';
  2678. // TODO tempolary solution
  2679. // http://code.google.com/p/phpquery/issues/detail?id=17
  2680. // if (function_exists('mb_detect_encoding') && mb_detect_encoding($value) == 'ASCII')
  2681. // $value = mb_convert_encoding($value, 'UTF-8', 'HTML-ENTITIES');
  2682. }
  2683. foreach($this->stack(1) as $node) {
  2684. if (! is_null($code)) {
  2685. // $attrNode = $this->DOM->createAttribute($attr);
  2686. $node->setAttribute($attr, $value);
  2687. // $attrNode->value = $value;
  2688. // $node->appendChild($attrNode);
  2689. } else if ( $attr == '*') {
  2690. // jQuery diff
  2691. $return = array();
  2692. foreach($node->attributes as $n => $v)
  2693. $return[$n] = $v->value;
  2694. return $return;
  2695. } else
  2696. return $node->getAttribute($attr);
  2697. }
  2698. return $this;
  2699. }
  2700. /**
  2701. * Enter description here...
  2702. *
  2703. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2704. */
  2705. public function removeAttr($attr) {
  2706. foreach($this->stack(1) as $node) {
  2707. $loop = $attr == '*'
  2708. ? $this->getNodeAttrs($node)
  2709. : array($attr);
  2710. foreach($loop as $a) {
  2711. $oldValue = $node->getAttribute($a);
  2712. $node->removeAttribute($a);
  2713. $this->attrEvents($a, $oldValue, null, $node);
  2714. }
  2715. }
  2716. return $this;
  2717. }
  2718. /**
  2719. * Return form element value.
  2720. *
  2721. * @return String Fields value.
  2722. */
  2723. public function val($val = null) {
  2724. if (! isset($val)) {
  2725. if ($this->eq(0)->is('select')) {
  2726. $selected = $this->eq(0)->find('option[selected=selected]');
  2727. if ($selected->is('[value]'))
  2728. return $selected->attr('value');
  2729. else
  2730. return $selected->text();
  2731. } else if ($this->eq(0)->is('textarea'))
  2732. return $this->eq(0)->markup();
  2733. else
  2734. return $this->eq(0)->attr('value');
  2735. } else {
  2736. $_val = null;
  2737. foreach($this->stack(1) as $node) {
  2738. $node = pq($node, $this->getDocumentID());
  2739. if (is_array($val) && in_array($node->attr('type'), array('checkbox', 'radio'))) {
  2740. $isChecked = in_array($node->attr('value'), $val)
  2741. || in_array($node->attr('name'), $val);
  2742. if ($isChecked)
  2743. $node->attr('checked', 'checked');
  2744. else
  2745. $node->removeAttr('checked');
  2746. } else if ($node->get(0)->tagName == 'select') {
  2747. if (! isset($_val)) {
  2748. $_val = array();
  2749. if (! is_array($val))
  2750. $_val = array((string)$val);
  2751. else
  2752. foreach($val as $v)
  2753. $_val[] = $v;
  2754. }
  2755. foreach($node['option']->stack(1) as $option) {
  2756. $option = pq($option, $this->getDocumentID());
  2757. $selected = false;
  2758. // XXX: workaround for string comparsion, see issue #96
  2759. // http://code.google.com/p/phpquery/issues/detail?id=96
  2760. $selected = is_null($option->attr('value'))
  2761. ? in_array($option->markup(), $_val)
  2762. : in_array($option->attr('value'), $_val);
  2763. // $optionValue = $option->attr('value');
  2764. // $optionText = $option->text();
  2765. // $optionTextLenght = mb_strlen($optionText);
  2766. // foreach($_val as $v)
  2767. // if ($optionValue == $v)
  2768. // $selected = true;
  2769. // else if ($optionText == $v && $optionTextLenght == mb_strlen($v))
  2770. // $selected = true;
  2771. if ($selected)
  2772. $option->attr('selected', 'selected');
  2773. else
  2774. $option->removeAttr('selected');
  2775. }
  2776. } else if ($node->get(0)->tagName == 'textarea')
  2777. $node->markup($val);
  2778. else
  2779. $node->attr('value', $val);
  2780. }
  2781. }
  2782. return $this;
  2783. }
  2784. /**
  2785. * Enter description here...
  2786. *
  2787. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2788. */
  2789. public function andSelf() {
  2790. if ( $this->previous )
  2791. $this->elements = array_merge($this->elements, $this->previous->elements);
  2792. return $this;
  2793. }
  2794. /**
  2795. * Enter description here...
  2796. *
  2797. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2798. */
  2799. public function addClass( $className) {
  2800. if (! $className)
  2801. return $this;
  2802. foreach($this->stack(1) as $node) {
  2803. if (! $this->is(".$className", $node))
  2804. $node->setAttribute(
  2805. 'class',
  2806. trim($node->getAttribute('class').' '.$className)
  2807. );
  2808. }
  2809. return $this;
  2810. }
  2811. /**
  2812. * Enter description here...
  2813. *
  2814. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2815. */
  2816. public function addClassPHP( $className) {
  2817. foreach($this->stack(1) as $node) {
  2818. $classes = $node->getAttribute('class');
  2819. $newValue = $classes
  2820. ? $classes.' <'.'?php '.$className.' ?'.'>'
  2821. : '<'.'?php '.$className.' ?'.'>';
  2822. $node->setAttribute('class', $newValue);
  2823. }
  2824. return $this;
  2825. }
  2826. /**
  2827. * Enter description here...
  2828. *
  2829. * @param string $className
  2830. * @return bool
  2831. */
  2832. public function hasClass($className) {
  2833. foreach($this->stack(1) as $node) {
  2834. if ( $this->is(".$className", $node))
  2835. return true;
  2836. }
  2837. return false;
  2838. }
  2839. /**
  2840. * Enter description here...
  2841. *
  2842. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2843. */
  2844. public function removeClass($className) {
  2845. foreach($this->stack(1) as $node) {
  2846. $classes = explode( ' ', $node->getAttribute('class'));
  2847. if ( in_array($className, $classes)) {
  2848. $classes = array_diff($classes, array($className));
  2849. if ( $classes )
  2850. $node->setAttribute('class', implode(' ', $classes));
  2851. else
  2852. $node->removeAttribute('class');
  2853. }
  2854. }
  2855. return $this;
  2856. }
  2857. /**
  2858. * Enter description here...
  2859. *
  2860. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2861. */
  2862. public function toggleClass($className) {
  2863. foreach($this->stack(1) as $node) {
  2864. if ( $this->is( $node, '.'.$className ))
  2865. $this->removeClass($className);
  2866. else
  2867. $this->addClass($className);
  2868. }
  2869. return $this;
  2870. }
  2871. /**
  2872. * Proper name without underscore (just ->empty()) also works.
  2873. *
  2874. * Removes all child nodes from the set of matched elements.
  2875. *
  2876. * Example:
  2877. * pq("p")._empty()
  2878. *
  2879. * HTML:
  2880. * <p>Hello, <span>Person</span> <a href="#">and person</a></p>
  2881. *
  2882. * Result:
  2883. * [ <p></p> ]
  2884. *
  2885. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2886. * @access private
  2887. */
  2888. public function _empty() {
  2889. foreach($this->stack(1) as $node) {
  2890. // thx to 'dave at dgx dot cz'
  2891. $node->nodeValue = '';
  2892. }
  2893. return $this;
  2894. }
  2895. /**
  2896. * Enter description here...
  2897. *
  2898. * @param array|string $callback Expects $node as first param, $index as second
  2899. * @param array $scope External variables passed to callback. Use compact('varName1', 'varName2'...) and extract($scope)
  2900. * @param array $arg1 Will ba passed as third and futher args to callback.
  2901. * @param array $arg2 Will ba passed as fourth and futher args to callback, and so on...
  2902. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2903. */
  2904. public function each($callback, $param1 = null, $param2 = null, $param3 = null) {
  2905. $paramStructure = null;
  2906. if (func_num_args() > 1) {
  2907. $paramStructure = func_get_args();
  2908. $paramStructure = array_slice($paramStructure, 1);
  2909. }
  2910. foreach($this->elements as $v)
  2911. phpQuery::callbackRun($callback, array($v), $paramStructure);
  2912. return $this;
  2913. }
  2914. /**
  2915. * Run callback on actual object.
  2916. *
  2917. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2918. */
  2919. public function callback($callback, $param1 = null, $param2 = null, $param3 = null) {
  2920. $params = func_get_args();
  2921. $params[0] = $this;
  2922. phpQuery::callbackRun($callback, $params);
  2923. return $this;
  2924. }
  2925. /**
  2926. * Enter description here...
  2927. *
  2928. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2929. * @todo add $scope and $args as in each() ???
  2930. */
  2931. public function map($callback, $param1 = null, $param2 = null, $param3 = null) {
  2932. // $stack = array();
  2933. //// foreach($this->newInstance() as $node) {
  2934. // foreach($this->newInstance() as $node) {
  2935. // $result = call_user_func($callback, $node);
  2936. // if ($result)
  2937. // $stack[] = $result;
  2938. // }
  2939. $params = func_get_args();
  2940. array_unshift($params, $this->elements);
  2941. return $this->newInstance(
  2942. call_user_func_array(array('phpQuery', 'map'), $params)
  2943. // phpQuery::map($this->elements, $callback)
  2944. );
  2945. }
  2946. /**
  2947. * Enter description here...
  2948. *
  2949. * @param <type> $key
  2950. * @param <type> $value
  2951. */
  2952. public function data($key, $value = null) {
  2953. if (! isset($value)) {
  2954. // TODO? implement specific jQuery behavior od returning parent values
  2955. // is child which we look up doesn't exist
  2956. return phpQuery::data($this->get(0), $key, $value, $this->getDocumentID());
  2957. } else {
  2958. foreach($this as $node)
  2959. phpQuery::data($node, $key, $value, $this->getDocumentID());
  2960. return $this;
  2961. }
  2962. }
  2963. /**
  2964. * Enter description here...
  2965. *
  2966. * @param <type> $key
  2967. */
  2968. public function removeData($key) {
  2969. foreach($this as $node)
  2970. phpQuery::removeData($node, $key, $this->getDocumentID());
  2971. return $this;
  2972. }
  2973. // INTERFACE IMPLEMENTATIONS
  2974. // ITERATOR INTERFACE
  2975. /**
  2976. * @access private
  2977. */
  2978. public function rewind(){
  2979. $this->debug('iterating foreach');
  2980. // phpQuery::selectDocument($this->getDocumentID());
  2981. $this->elementsBackup = $this->elements;
  2982. $this->elementsInterator = $this->elements;
  2983. $this->valid = isset( $this->elements[0] )
  2984. ? 1 : 0;
  2985. // $this->elements = $this->valid
  2986. // ? array($this->elements[0])
  2987. // : array();
  2988. $this->current = 0;
  2989. }
  2990. /**
  2991. * @access private
  2992. */
  2993. public function current(){
  2994. return $this->elementsInterator[ $this->current ];
  2995. }
  2996. /**
  2997. * @access private
  2998. */
  2999. public function key(){
  3000. return $this->current;
  3001. }
  3002. /**
  3003. * Double-function method.
  3004. *
  3005. * First: main iterator interface method.
  3006. * Second: Returning next sibling, alias for _next().
  3007. *
  3008. * Proper functionality is choosed automagicaly.
  3009. *
  3010. * @see phpQueryObject::_next()
  3011. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3012. */
  3013. public function next($cssSelector = null){
  3014. // if ($cssSelector || $this->valid)
  3015. // return $this->_next($cssSelector);
  3016. $this->valid = isset( $this->elementsInterator[ $this->current+1 ] )
  3017. ? true
  3018. : false;
  3019. if (! $this->valid && $this->elementsInterator) {
  3020. $this->elementsInterator = null;
  3021. } else if ($this->valid) {
  3022. $this->current++;
  3023. } else {
  3024. return $this->_next($cssSelector);
  3025. }
  3026. }
  3027. /**
  3028. * @access private
  3029. */
  3030. public function valid(){
  3031. return $this->valid;
  3032. }
  3033. // ITERATOR INTERFACE END
  3034. // ARRAYACCESS INTERFACE
  3035. /**
  3036. * @access private
  3037. */
  3038. public function offsetExists($offset) {
  3039. return $this->find($offset)->size() > 0;
  3040. }
  3041. /**
  3042. * @access private
  3043. */
  3044. public function offsetGet($offset) {
  3045. return $this->find($offset);
  3046. }
  3047. /**
  3048. * @access private
  3049. */
  3050. public function offsetSet($offset, $value) {
  3051. // $this->find($offset)->replaceWith($value);
  3052. $this->find($offset)->html($value);
  3053. }
  3054. /**
  3055. * @access private
  3056. */
  3057. public function offsetUnset($offset) {
  3058. // empty
  3059. throw new Exception("Can't do unset, use array interface only for calling queries and replacing HTML.");
  3060. }
  3061. // ARRAYACCESS INTERFACE END
  3062. /**
  3063. * Returns node's XPath.
  3064. *
  3065. * @param unknown_type $oneNode
  3066. * @return string
  3067. * @TODO use native getNodePath is avaible
  3068. * @access private
  3069. */
  3070. protected function getNodeXpath($oneNode = null, $namespace = null) {
  3071. $return = array();
  3072. $loop = $oneNode
  3073. ? array($oneNode)
  3074. : $this->elements;
  3075. // if ($namespace)
  3076. // $namespace .= ':';
  3077. foreach($loop as $node) {
  3078. if ($node instanceof DOMDOCUMENT) {
  3079. $return[] = '';
  3080. continue;
  3081. }
  3082. $xpath = array();
  3083. while(! ($node instanceof DOMDOCUMENT)) {
  3084. $i = 1;
  3085. $sibling = $node;
  3086. while($sibling->previousSibling) {
  3087. $sibling = $sibling->previousSibling;
  3088. $isElement = $sibling instanceof DOMELEMENT;
  3089. if ($isElement && $sibling->tagName == $node->tagName)
  3090. $i++;
  3091. }
  3092. $xpath[] = $this->isXML()
  3093. ? "*[local-name()='{$node->tagName}'][{$i}]"
  3094. : "{$node->tagName}[{$i}]";
  3095. $node = $node->parentNode;
  3096. }
  3097. $xpath = join('/', array_reverse($xpath));
  3098. $return[] = '/'.$xpath;
  3099. }
  3100. return $oneNode
  3101. ? $return[0]
  3102. : $return;
  3103. }
  3104. // HELPERS
  3105. public function whois($oneNode = null) {
  3106. $return = array();
  3107. $loop = $oneNode
  3108. ? array( $oneNode )
  3109. : $this->elements;
  3110. foreach($loop as $node) {
  3111. if (isset($node->tagName)) {
  3112. $tag = in_array($node->tagName, array('php', 'js'))
  3113. ? strtoupper($node->tagName)
  3114. : $node->tagName;
  3115. $return[] = $tag
  3116. .($node->getAttribute('id')
  3117. ? '#'.$node->getAttribute('id'):'')
  3118. .($node->getAttribute('class')
  3119. ? '.'.join('.', split(' ', $node->getAttribute('class'))):'')
  3120. .($node->getAttribute('name')
  3121. ? '[name="'.$node->getAttribute('name').'"]':'')
  3122. .($node->getAttribute('value') && strpos($node->getAttribute('value'), '<'.'?php') === false
  3123. ? '[value="'.substr(str_replace("\n", '', $node->getAttribute('value')), 0, 15).'"]':'')
  3124. .($node->getAttribute('value') && strpos($node->getAttribute('value'), '<'.'?php') !== false
  3125. ? '[value=PHP]':'')
  3126. .($node->getAttribute('selected')
  3127. ? '[selected]':'')
  3128. .($node->getAttribute('checked')
  3129. ? '[checked]':'')
  3130. ;
  3131. } else if ($node instanceof DOMTEXT) {
  3132. if (trim($node->textContent))
  3133. $return[] = 'Text:'.substr(str_replace("\n", ' ', $node->textContent), 0, 15);
  3134. } else {
  3135. }
  3136. }
  3137. return $oneNode && isset($return[0])
  3138. ? $return[0]
  3139. : $return;
  3140. }
  3141. /**
  3142. * Dump htmlOuter and preserve chain. Usefull for debugging.
  3143. *
  3144. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3145. *
  3146. */
  3147. public function dump() {
  3148. print 'DUMP #'.(phpQuery::$dumpCount++).' ';
  3149. $debug = phpQuery::$debug;
  3150. phpQuery::$debug = false;
  3151. // print __FILE__.':'.__LINE__."\n";
  3152. var_dump($this->htmlOuter());
  3153. return $this;
  3154. }
  3155. public function dumpWhois() {
  3156. print 'DUMP #'.(phpQuery::$dumpCount++).' ';
  3157. $debug = phpQuery::$debug;
  3158. phpQuery::$debug = false;
  3159. // print __FILE__.':'.__LINE__."\n";
  3160. var_dump('whois', $this->whois());
  3161. phpQuery::$debug = $debug;
  3162. return $this;
  3163. }
  3164. public function dumpLength() {
  3165. print 'DUMP #'.(phpQuery::$dumpCount++).' ';
  3166. $debug = phpQuery::$debug;
  3167. phpQuery::$debug = false;
  3168. // print __FILE__.':'.__LINE__."\n";
  3169. var_dump('length', $this->length());
  3170. phpQuery::$debug = $debug;
  3171. return $this;
  3172. }
  3173. public function dumpTree($html = true, $title = true) {
  3174. $output = $title
  3175. ? 'DUMP #'.(phpQuery::$dumpCount++)." \n" : '';
  3176. $debug = phpQuery::$debug;
  3177. phpQuery::$debug = false;
  3178. foreach($this->stack() as $node)
  3179. $output .= $this->__dumpTree($node);
  3180. phpQuery::$debug = $debug;
  3181. print $html
  3182. ? nl2br(str_replace(' ', '&nbsp;', $output))
  3183. : $output;
  3184. return $this;
  3185. }
  3186. private function __dumpTree($node, $intend = 0) {
  3187. $whois = $this->whois($node);
  3188. $return = '';
  3189. if ($whois)
  3190. $return .= str_repeat(' - ', $intend).$whois."\n";
  3191. if (isset($node->childNodes))
  3192. foreach($node->childNodes as $chNode)
  3193. $return .= $this->__dumpTree($chNode, $intend+1);
  3194. return $return;
  3195. }
  3196. /**
  3197. * Dump htmlOuter and stop script execution. Usefull for debugging.
  3198. *
  3199. */
  3200. public function dumpDie() {
  3201. print __FILE__.':'.__LINE__;
  3202. var_dump($this->htmlOuter());
  3203. die();
  3204. }
  3205. }