phpQueryObject.php 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236
  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', (string)$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 (!is_null($index) && is_int($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 (!is_null($index) && is_int($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 = preg_split("/[\s\t\r\n]+/", $node->getAttribute('class'),-1, PREG_SPLIT_NO_EMPTY);
  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. preg_split("/[\s\t\r\n]+/", $node->getAttribute('class'),-1, PREG_SPLIT_NO_EMPTY)
  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. function ($node) {
  971. return $node instanceof DOMELEMENT && $node->childNodes->length
  972. ? $node : null;
  973. }
  974. )->elements;
  975. break;
  976. case 'empty':
  977. $this->elements = $this->map(
  978. function ($node) {
  979. return $node instanceof DOMELEMENT && $node->childNodes->length
  980. ? null : $node;
  981. }
  982. )->elements;
  983. break;
  984. case 'disabled':
  985. case 'selected':
  986. case 'checked':
  987. $this->elements = $this->map(
  988. array($this, 'is'),
  989. "[$class]", new CallbackParam()
  990. )->elements;
  991. break;
  992. case 'enabled':
  993. $this->elements = $this->map(
  994. function ($node) {
  995. return pq($node)->not(":disabled") ? $node : null;
  996. }
  997. )->elements;
  998. break;
  999. case 'header':
  1000. $this->elements = $this->map(
  1001. function ($node) {
  1002. $isHeader = isset($node->tagName) && in_array($node->tagName, array(
  1003. "h1", "h2", "h3", "h4", "h5", "h6", "h7"
  1004. ));
  1005. return $isHeader
  1006. ? $node
  1007. : null;
  1008. }
  1009. )->elements;
  1010. // $this->elements = $this->map(
  1011. // create_function('$node', '$node = pq($node);
  1012. // return $node->is("h1")
  1013. // || $node->is("h2")
  1014. // || $node->is("h3")
  1015. // || $node->is("h4")
  1016. // || $node->is("h5")
  1017. // || $node->is("h6")
  1018. // || $node->is("h7")
  1019. // ? $node
  1020. // : null;')
  1021. // )->elements;
  1022. break;
  1023. case 'only-child':
  1024. $this->elements = $this->map(
  1025. function ($node) {
  1026. return pq($node)->siblings()->size() == 0 ? $node : null;
  1027. }
  1028. )->elements;
  1029. break;
  1030. case 'first-child':
  1031. $this->elements = $this->map(
  1032. function ($node) { return pq($node)->prevAll()->size() == 0 ? $node : null; }
  1033. )->elements;
  1034. break;
  1035. case 'last-child':
  1036. $this->elements = $this->map(
  1037. function ($node) { return pq($node)->nextAll()->size() == 0 ? $node : null; }
  1038. )->elements;
  1039. break;
  1040. case 'nth-child':
  1041. $param = trim($args, "\"'");
  1042. if (! $param)
  1043. break;
  1044. // nth-child(n+b) to nth-child(1n+b)
  1045. if (substr($param, 0, 1) == 'n')
  1046. $param = '1'.$param;
  1047. // :nth-child(index/even/odd/equation)
  1048. if ($param == 'even' || $param == 'odd')
  1049. $mapped = $this->map(
  1050. function ($node, $param) {
  1051. $index = pq($node)->prevAll()->size()+1;
  1052. if ($param == "even" && ($index%2) == 0)
  1053. return $node;
  1054. else if ($param == "odd" && $index%2 == 1)
  1055. return $node;
  1056. else
  1057. return null;
  1058. },
  1059. new CallbackParam(), $param
  1060. );
  1061. else if (mb_strlen($param) > 1 && preg_match('/^(\d*)n([-+]?)(\d*)/', $param) === 1)
  1062. // an+b
  1063. $mapped = $this->map(
  1064. function ($node, $param) {
  1065. $prevs = pq($node)->prevAll()->size();
  1066. $index = 1+$prevs;
  1067. preg_match("/^(\d*)n([-+]?)(\d*)/", $param, $matches);
  1068. $a = intval($matches[1]);
  1069. $b = intval($matches[3]);
  1070. if( $matches[2] === "-" ) {
  1071. $b = -$b;
  1072. }
  1073. if ($a > 0) {
  1074. return ($index-$b)%$a == 0
  1075. ? $node
  1076. : null;
  1077. phpQuery::debug($a."*".floor($index/$a)."+$b-1 == ".($a*floor($index/$a)+$b-1)." ?= $prevs");
  1078. return $a*floor($index/$a)+$b-1 == $prevs
  1079. ? $node
  1080. : null;
  1081. } else if ($a == 0)
  1082. return $index == $b
  1083. ? $node
  1084. : null;
  1085. else
  1086. // negative value
  1087. return $index <= $b
  1088. ? $node
  1089. : null;
  1090. // if (! $b)
  1091. // return $index%$a == 0
  1092. // ? $node
  1093. // : null;
  1094. // else
  1095. // return ($index-$b)%$a == 0
  1096. // ? $node
  1097. // : null;
  1098. },
  1099. new CallbackParam(), $param
  1100. );
  1101. else
  1102. // index
  1103. $mapped = $this->map(
  1104. function ($node, $index) {
  1105. $prevs = pq($node)->prevAll()->size();
  1106. if ($prevs && $prevs == $index-1)
  1107. return $node;
  1108. else if (! $prevs && $index == 1)
  1109. return $node;
  1110. else
  1111. return null;
  1112. },
  1113. new CallbackParam(), $param
  1114. );
  1115. $this->elements = $mapped->elements;
  1116. break;
  1117. default:
  1118. $this->debug("Unknown pseudoclass '{$class}', skipping...");
  1119. }
  1120. }
  1121. /**
  1122. * @access private
  1123. */
  1124. protected function __pseudoClassParam($paramsString) {
  1125. // TODO;
  1126. }
  1127. /**
  1128. * Enter description here...
  1129. *
  1130. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1131. */
  1132. public function is($selector, $nodes = null) {
  1133. phpQuery::debug(array("Is:", $selector));
  1134. if (! $selector)
  1135. return false;
  1136. $oldStack = $this->elements;
  1137. $returnArray = false;
  1138. if ($nodes && is_array($nodes)) {
  1139. $this->elements = $nodes;
  1140. } else if ($nodes)
  1141. $this->elements = array($nodes);
  1142. $this->filter($selector, true);
  1143. $stack = $this->elements;
  1144. $this->elements = $oldStack;
  1145. if ($nodes)
  1146. return $stack ? $stack : null;
  1147. return (bool)count($stack);
  1148. }
  1149. /**
  1150. * Enter description here...
  1151. * jQuery difference.
  1152. *
  1153. * Callback:
  1154. * - $index int
  1155. * - $node DOMNode
  1156. *
  1157. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1158. * @link http://docs.jquery.com/Traversing/filter
  1159. */
  1160. public function filterCallback($callback, $_skipHistory = false) {
  1161. if (! $_skipHistory) {
  1162. $this->elementsBackup = $this->elements;
  1163. $this->debug("Filtering by callback");
  1164. }
  1165. $newStack = array();
  1166. foreach($this->elements as $index => $node) {
  1167. $result = phpQuery::callbackRun($callback, array($index, $node));
  1168. if (is_null($result) || (! is_null($result) && $result))
  1169. $newStack[] = $node;
  1170. }
  1171. $this->elements = $newStack;
  1172. return $_skipHistory
  1173. ? $this
  1174. : $this->newInstance();
  1175. }
  1176. /**
  1177. * Enter description here...
  1178. *
  1179. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1180. * @link http://docs.jquery.com/Traversing/filter
  1181. */
  1182. public function filter($selectors, $_skipHistory = false) {
  1183. if ($selectors instanceof Callback OR $selectors instanceof Closure)
  1184. return $this->filterCallback($selectors, $_skipHistory);
  1185. if (! $_skipHistory)
  1186. $this->elementsBackup = $this->elements;
  1187. $notSimpleSelector = array(' ', '>', '~', '+', '/');
  1188. if (! is_array($selectors))
  1189. $selectors = $this->parseSelector($selectors);
  1190. if (! $_skipHistory)
  1191. $this->debug(array("Filtering:", $selectors));
  1192. $finalStack = array();
  1193. foreach($selectors as $selector) {
  1194. $stack = array();
  1195. if (! $selector)
  1196. break;
  1197. // avoid first space or /
  1198. if (in_array($selector[0], $notSimpleSelector))
  1199. $selector = array_slice($selector, 1);
  1200. // PER NODE selector chunks
  1201. foreach($this->stack() as $node) {
  1202. $break = false;
  1203. foreach($selector as $s) {
  1204. if (!($node instanceof DOMELEMENT)) {
  1205. // all besides DOMElement
  1206. if ( $s[0] == '[') {
  1207. $attr = trim($s, '[]');
  1208. if ( mb_strpos($attr, '=')) {
  1209. list( $attr, $val ) = explode('=', $attr);
  1210. if ($attr == 'nodeType' && $node->nodeType != $val)
  1211. $break = true;
  1212. }
  1213. } else
  1214. $break = true;
  1215. } else {
  1216. // DOMElement only
  1217. // ID
  1218. if ( $s[0] == '#') {
  1219. if ( $node->getAttribute('id') != substr($s, 1) )
  1220. $break = true;
  1221. // CLASSES
  1222. } else if ( $s[0] == '.') {
  1223. if (! $this->matchClasses( $s, $node ) )
  1224. $break = true;
  1225. // ATTRS
  1226. } else if ( $s[0] == '[') {
  1227. // strip side brackets
  1228. $attr = trim($s, '[]');
  1229. if (mb_strpos($attr, '=')) {
  1230. list($attr, $val) = explode('=', $attr);
  1231. $val = self::unQuote($val);
  1232. if ($attr == 'nodeType') {
  1233. if ($val != $node->nodeType)
  1234. $break = true;
  1235. } else if ($this->isRegexp($attr)) {
  1236. $val = extension_loaded('mbstring') && phpQuery::$mbstringSupport
  1237. ? quotemeta(trim($val, '"\''))
  1238. : preg_quote(trim($val, '"\''), '@');
  1239. // switch last character
  1240. switch( substr($attr, -1)) {
  1241. // quotemeta used insted of preg_quote
  1242. // http://code.google.com/p/phpquery/issues/detail?id=76
  1243. case '^':
  1244. $pattern = '^'.$val;
  1245. break;
  1246. case '*':
  1247. $pattern = '.*'.$val.'.*';
  1248. break;
  1249. case '$':
  1250. $pattern = '.*'.$val.'$';
  1251. break;
  1252. }
  1253. // cut last character
  1254. $attr = substr($attr, 0, -1);
  1255. $isMatch = extension_loaded('mbstring') && phpQuery::$mbstringSupport
  1256. ? mb_ereg_match($pattern, $node->getAttribute($attr))
  1257. : preg_match("@{$pattern}@", $node->getAttribute($attr));
  1258. if (! $isMatch)
  1259. $break = true;
  1260. } else if ($node->getAttribute($attr) != $val)
  1261. $break = true;
  1262. } else if (! $node->hasAttribute($attr))
  1263. $break = true;
  1264. // PSEUDO CLASSES
  1265. } else if ( $s[0] == ':') {
  1266. // skip
  1267. // TAG
  1268. } else if (trim($s)) {
  1269. if ($s != '*') {
  1270. // TODO namespaces
  1271. if (isset($node->tagName)) {
  1272. if ($node->tagName != $s)
  1273. $break = true;
  1274. } else if ($s == 'html' && ! $this->isRoot($node))
  1275. $break = true;
  1276. }
  1277. // AVOID NON-SIMPLE SELECTORS
  1278. } else if (in_array($s, $notSimpleSelector)) {
  1279. $break = true;
  1280. $this->debug(array('Skipping non simple selector', $selector));
  1281. }
  1282. }
  1283. if ($break)
  1284. break;
  1285. }
  1286. // if element passed all chunks of selector - add it to new stack
  1287. if (! $break )
  1288. $stack[] = $node;
  1289. }
  1290. $tmpStack = $this->elements;
  1291. $this->elements = $stack;
  1292. // PER ALL NODES selector chunks
  1293. foreach($selector as $s)
  1294. // PSEUDO CLASSES
  1295. if ($s[0] == ':')
  1296. $this->pseudoClasses($s);
  1297. foreach($this->elements as $node)
  1298. // XXX it should be merged without duplicates
  1299. // but jQuery doesnt do that
  1300. $finalStack[] = $node;
  1301. $this->elements = $tmpStack;
  1302. }
  1303. $this->elements = $finalStack;
  1304. if ($_skipHistory) {
  1305. return $this;
  1306. } else {
  1307. $this->debug("Stack length after filter(): ".count($finalStack));
  1308. return $this->newInstance();
  1309. }
  1310. }
  1311. /**
  1312. *
  1313. * @param $value
  1314. * @return unknown_type
  1315. * @TODO implement in all methods using passed parameters
  1316. */
  1317. protected static function unQuote($value) {
  1318. return $value[0] == '\'' || $value[0] == '"'
  1319. ? substr($value, 1, -1)
  1320. : $value;
  1321. }
  1322. /**
  1323. * Enter description here...
  1324. *
  1325. * @link http://docs.jquery.com/Ajax/load
  1326. * @return phpQuery|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1327. * @todo Support $selector
  1328. */
  1329. public function load($url, $data = null, $callback = null) {
  1330. if ($data && ! is_array($data)) {
  1331. $callback = $data;
  1332. $data = null;
  1333. }
  1334. if (mb_strpos($url, ' ') !== false) {
  1335. $matches = null;
  1336. if (extension_loaded('mbstring') && phpQuery::$mbstringSupport)
  1337. mb_ereg('^([^ ]+) (.*)$', $url, $matches);
  1338. else
  1339. preg_match('@^([^ ]+) (.*)$@', $url, $matches);
  1340. $url = $matches[1];
  1341. $selector = $matches[2];
  1342. // FIXME this sucks, pass as callback param
  1343. $this->_loadSelector = $selector;
  1344. }
  1345. $ajax = array(
  1346. 'url' => $url,
  1347. 'type' => $data ? 'POST' : 'GET',
  1348. 'data' => $data,
  1349. 'complete' => $callback,
  1350. 'success' => array($this, '__loadSuccess')
  1351. );
  1352. phpQuery::ajax($ajax);
  1353. return $this;
  1354. }
  1355. /**
  1356. * @access private
  1357. * @param $html
  1358. * @return unknown_type
  1359. */
  1360. public function __loadSuccess($html) {
  1361. if ($this->_loadSelector) {
  1362. $html = phpQuery::newDocument($html)->find($this->_loadSelector);
  1363. unset($this->_loadSelector);
  1364. }
  1365. foreach($this->stack(1) as $node) {
  1366. phpQuery::pq($node, $this->getDocumentID())
  1367. ->markup($html);
  1368. }
  1369. }
  1370. /**
  1371. * Enter description here...
  1372. *
  1373. * @return phpQuery|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1374. * @todo
  1375. */
  1376. public function css() {
  1377. // TODO
  1378. return $this;
  1379. }
  1380. /**
  1381. * @todo
  1382. *
  1383. */
  1384. public function show(){
  1385. // TODO
  1386. return $this;
  1387. }
  1388. /**
  1389. * @todo
  1390. *
  1391. */
  1392. public function hide(){
  1393. // TODO
  1394. return $this;
  1395. }
  1396. /**
  1397. * Trigger a type of event on every matched element.
  1398. *
  1399. * @param unknown_type $type
  1400. * @param unknown_type $data
  1401. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1402. * @TODO support more than event in $type (space-separated)
  1403. */
  1404. public function trigger($type, $data = array()) {
  1405. foreach($this->elements as $node)
  1406. phpQueryEvents::trigger($this->getDocumentID(), $type, $data, $node);
  1407. return $this;
  1408. }
  1409. /**
  1410. * This particular method triggers all bound event handlers on an element (for a specific event type) WITHOUT executing the browsers default actions.
  1411. *
  1412. * @param unknown_type $type
  1413. * @param unknown_type $data
  1414. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1415. * @TODO
  1416. */
  1417. public function triggerHandler($type, $data = array()) {
  1418. // TODO;
  1419. }
  1420. /**
  1421. * Binds a handler to one or more events (like click) for each matched element.
  1422. * Can also bind custom events.
  1423. *
  1424. * @param unknown_type $type
  1425. * @param unknown_type $data Optional
  1426. * @param unknown_type $callback
  1427. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1428. * @TODO support '!' (exclusive) events
  1429. * @TODO support more than event in $type (space-separated)
  1430. */
  1431. public function bind($type, $data, $callback = null) {
  1432. // TODO check if $data is callable, not using is_callable
  1433. if (! isset($callback)) {
  1434. $callback = $data;
  1435. $data = null;
  1436. }
  1437. foreach($this->elements as $node)
  1438. phpQueryEvents::add($this->getDocumentID(), $node, $type, $data, $callback);
  1439. return $this;
  1440. }
  1441. /**
  1442. * Enter description here...
  1443. *
  1444. * @param unknown_type $type
  1445. * @param unknown_type $callback
  1446. * @return unknown
  1447. * @TODO namespace events
  1448. * @TODO support more than event in $type (space-separated)
  1449. */
  1450. public function unbind($type = null, $callback = null) {
  1451. foreach($this->elements as $node)
  1452. phpQueryEvents::remove($this->getDocumentID(), $node, $type, $callback);
  1453. return $this;
  1454. }
  1455. /**
  1456. * Enter description here...
  1457. *
  1458. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1459. */
  1460. public function change($callback = null) {
  1461. if ($callback)
  1462. return $this->bind('change', $callback);
  1463. return $this->trigger('change');
  1464. }
  1465. /**
  1466. * Enter description here...
  1467. *
  1468. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1469. */
  1470. public function submit($callback = null) {
  1471. if ($callback)
  1472. return $this->bind('submit', $callback);
  1473. return $this->trigger('submit');
  1474. }
  1475. /**
  1476. * Enter description here...
  1477. *
  1478. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1479. */
  1480. public function click($callback = null) {
  1481. if ($callback)
  1482. return $this->bind('click', $callback);
  1483. return $this->trigger('click');
  1484. }
  1485. /**
  1486. * Enter description here...
  1487. *
  1488. * @param String|phpQuery
  1489. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1490. */
  1491. public function wrapAllOld($wrapper) {
  1492. $wrapper = pq($wrapper)->_clone();
  1493. if (! $wrapper->length() || ! $this->length() )
  1494. return $this;
  1495. $wrapper->insertBefore($this->elements[0]);
  1496. $deepest = $wrapper->elements[0];
  1497. while($deepest->firstChild && $deepest->firstChild instanceof DOMELEMENT)
  1498. $deepest = $deepest->firstChild;
  1499. pq($deepest)->append($this);
  1500. return $this;
  1501. }
  1502. /**
  1503. * Enter description here...
  1504. *
  1505. * TODO testme...
  1506. * @param String|phpQuery
  1507. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1508. */
  1509. public function wrapAll($wrapper) {
  1510. if (! $this->length())
  1511. return $this;
  1512. return phpQuery::pq($wrapper, $this->getDocumentID())
  1513. ->clone()
  1514. ->insertBefore($this->get(0))
  1515. ->map(array($this, '___wrapAllCallback'))
  1516. ->append($this);
  1517. }
  1518. /**
  1519. *
  1520. * @param $node
  1521. * @return unknown_type
  1522. * @access private
  1523. */
  1524. public function ___wrapAllCallback($node) {
  1525. $deepest = $node;
  1526. while($deepest->firstChild && $deepest->firstChild instanceof DOMELEMENT)
  1527. $deepest = $deepest->firstChild;
  1528. return $deepest;
  1529. }
  1530. /**
  1531. * Enter description here...
  1532. * NON JQUERY METHOD
  1533. *
  1534. * @param String|phpQuery
  1535. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1536. */
  1537. public function wrapAllPHP($codeBefore, $codeAfter) {
  1538. return $this
  1539. ->slice(0, 1)
  1540. ->beforePHP($codeBefore)
  1541. ->end()
  1542. ->slice(-1)
  1543. ->afterPHP($codeAfter)
  1544. ->end();
  1545. }
  1546. /**
  1547. * Enter description here...
  1548. *
  1549. * @param String|phpQuery
  1550. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1551. */
  1552. public function wrap($wrapper) {
  1553. foreach($this->stack() as $node)
  1554. phpQuery::pq($node, $this->getDocumentID())->wrapAll($wrapper);
  1555. return $this;
  1556. }
  1557. /**
  1558. * Enter description here...
  1559. *
  1560. * @param String|phpQuery
  1561. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1562. */
  1563. public function wrapPHP($codeBefore, $codeAfter) {
  1564. foreach($this->stack() as $node)
  1565. phpQuery::pq($node, $this->getDocumentID())->wrapAllPHP($codeBefore, $codeAfter);
  1566. return $this;
  1567. }
  1568. /**
  1569. * Enter description here...
  1570. *
  1571. * @param String|phpQuery
  1572. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1573. */
  1574. public function wrapInner($wrapper) {
  1575. foreach($this->stack() as $node)
  1576. phpQuery::pq($node, $this->getDocumentID())->contents()->wrapAll($wrapper);
  1577. return $this;
  1578. }
  1579. /**
  1580. * Enter description here...
  1581. *
  1582. * @param String|phpQuery
  1583. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1584. */
  1585. public function wrapInnerPHP($codeBefore, $codeAfter) {
  1586. foreach($this->stack(1) as $node)
  1587. phpQuery::pq($node, $this->getDocumentID())->contents()
  1588. ->wrapAllPHP($codeBefore, $codeAfter);
  1589. return $this;
  1590. }
  1591. /**
  1592. * Enter description here...
  1593. *
  1594. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1595. * @testme Support for text nodes
  1596. */
  1597. public function contents() {
  1598. $stack = array();
  1599. foreach($this->stack(1) as $el) {
  1600. // FIXME (fixed) http://code.google.com/p/phpquery/issues/detail?id=56
  1601. // if (! isset($el->childNodes))
  1602. // continue;
  1603. foreach($el->childNodes as $node) {
  1604. $stack[] = $node;
  1605. }
  1606. }
  1607. return $this->newInstance($stack);
  1608. }
  1609. /**
  1610. * Enter description here...
  1611. *
  1612. * jQuery difference.
  1613. *
  1614. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1615. */
  1616. public function contentsUnwrap() {
  1617. foreach($this->stack(1) as $node) {
  1618. if (! $node->parentNode )
  1619. continue;
  1620. $childNodes = array();
  1621. // any modification in DOM tree breaks childNodes iteration, so cache them first
  1622. foreach($node->childNodes as $chNode )
  1623. $childNodes[] = $chNode;
  1624. foreach($childNodes as $chNode )
  1625. // $node->parentNode->appendChild($chNode);
  1626. $node->parentNode->insertBefore($chNode, $node);
  1627. $node->parentNode->removeChild($node);
  1628. }
  1629. return $this;
  1630. }
  1631. /**
  1632. * Enter description here...
  1633. *
  1634. * jQuery difference.
  1635. */
  1636. public function switchWith($markup) {
  1637. $markup = pq($markup, $this->getDocumentID());
  1638. $content = null;
  1639. foreach($this->stack(1) as $node) {
  1640. pq($node)
  1641. ->contents()->toReference($content)->end()
  1642. ->replaceWith($markup->clone()->append($content));
  1643. }
  1644. return $this;
  1645. }
  1646. /**
  1647. * Enter description here...
  1648. *
  1649. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1650. */
  1651. public function eq($num) {
  1652. $oldStack = $this->elements;
  1653. $this->elementsBackup = $this->elements;
  1654. $this->elements = array();
  1655. if ( isset($oldStack[$num]) )
  1656. $this->elements[] = $oldStack[$num];
  1657. return $this->newInstance();
  1658. }
  1659. /**
  1660. * Enter description here...
  1661. *
  1662. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1663. */
  1664. #[\ReturnTypeWillChange]
  1665. public function size() {
  1666. return count($this->elements);
  1667. }
  1668. /**
  1669. * Enter description here...
  1670. *
  1671. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1672. * @deprecated Use length as attribute
  1673. */
  1674. #[\ReturnTypeWillChange]
  1675. public function length() {
  1676. return $this->size();
  1677. }
  1678. #[\ReturnTypeWillChange]
  1679. public function count() {
  1680. return $this->size();
  1681. }
  1682. /**
  1683. * Enter description here...
  1684. *
  1685. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1686. * @todo $level
  1687. */
  1688. #[\ReturnTypeWillChange]
  1689. public function end($level = 1) {
  1690. // $this->elements = array_pop( $this->history );
  1691. // return $this;
  1692. // $this->previous->DOM = $this->DOM;
  1693. // $this->previous->XPath = $this->XPath;
  1694. return $this->previous
  1695. ? $this->previous
  1696. : $this;
  1697. }
  1698. /**
  1699. * Enter description here...
  1700. * Normal use ->clone() .
  1701. *
  1702. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1703. * @access private
  1704. */
  1705. public function _clone() {
  1706. $newStack = array();
  1707. //pr(array('copy... ', $this->whois()));
  1708. //$this->dumpHistory('copy');
  1709. $this->elementsBackup = $this->elements;
  1710. foreach($this->elements as $node) {
  1711. $newStack[] = $node->cloneNode(true);
  1712. }
  1713. $this->elements = $newStack;
  1714. return $this->newInstance();
  1715. }
  1716. /**
  1717. * Enter description here...
  1718. *
  1719. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1720. */
  1721. public function replaceWithPHP($code) {
  1722. return $this->replaceWith(phpQuery::php($code));
  1723. }
  1724. /**
  1725. * Enter description here...
  1726. *
  1727. * @param String|phpQuery $content
  1728. * @link http://docs.jquery.com/Manipulation/replaceWith#content
  1729. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1730. */
  1731. public function replaceWith($content) {
  1732. return $this->after($content)->remove();
  1733. }
  1734. /**
  1735. * Enter description here...
  1736. *
  1737. * @param String $selector
  1738. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1739. * @todo this works ?
  1740. */
  1741. public function replaceAll($selector) {
  1742. foreach(phpQuery::pq($selector, $this->getDocumentID()) as $node)
  1743. phpQuery::pq($node, $this->getDocumentID())
  1744. ->after($this->_clone())
  1745. ->remove();
  1746. return $this;
  1747. }
  1748. /**
  1749. * Enter description here...
  1750. *
  1751. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1752. */
  1753. public function remove($selector = null) {
  1754. $loop = $selector
  1755. ? $this->filter($selector)->elements
  1756. : $this->elements;
  1757. foreach($loop as $node) {
  1758. if (! $node->parentNode )
  1759. continue;
  1760. if (isset($node->tagName))
  1761. $this->debug("Removing '{$node->tagName}'");
  1762. $node->parentNode->removeChild($node);
  1763. // Mutation event
  1764. $event = new DOMEvent(array(
  1765. 'target' => $node,
  1766. 'type' => 'DOMNodeRemoved'
  1767. ));
  1768. phpQueryEvents::trigger($this->getDocumentID(),
  1769. $event->type, array($event), $node
  1770. );
  1771. }
  1772. return $this;
  1773. }
  1774. protected function markupEvents($newMarkup, $oldMarkup, $node) {
  1775. if ($node->tagName == 'textarea' && $newMarkup != $oldMarkup) {
  1776. $event = new DOMEvent(array(
  1777. 'target' => $node,
  1778. 'type' => 'change'
  1779. ));
  1780. phpQueryEvents::trigger($this->getDocumentID(),
  1781. $event->type, array($event), $node
  1782. );
  1783. }
  1784. }
  1785. /**
  1786. * jQuey difference
  1787. *
  1788. * @param $markup
  1789. * @return unknown_type
  1790. * @TODO trigger change event for textarea
  1791. */
  1792. public function markup($markup = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  1793. $args = func_get_args();
  1794. if ($this->documentWrapper->isXML)
  1795. return call_user_func_array(array($this, 'xml'), $args);
  1796. else
  1797. return call_user_func_array(array($this, 'html'), $args);
  1798. }
  1799. /**
  1800. * jQuey difference
  1801. *
  1802. * @param $markup
  1803. * @return unknown_type
  1804. */
  1805. public function markupOuter($callback1 = null, $callback2 = null, $callback3 = null) {
  1806. $args = func_get_args();
  1807. if ($this->documentWrapper->isXML)
  1808. return call_user_func_array(array($this, 'xmlOuter'), $args);
  1809. else
  1810. return call_user_func_array(array($this, 'htmlOuter'), $args);
  1811. }
  1812. /**
  1813. * Enter description here...
  1814. *
  1815. * @param unknown_type $html
  1816. * @return string|phpQuery|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1817. * @TODO force html result
  1818. */
  1819. public function html($html = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  1820. if (isset($html)) {
  1821. // INSERT
  1822. $nodes = $this->documentWrapper->import($html);
  1823. $this->empty();
  1824. foreach($this->stack(1) as $alreadyAdded => $node) {
  1825. // for now, limit events for textarea
  1826. if (($this->isXHTML() || $this->isHTML()) && $node->tagName == 'textarea')
  1827. $oldHtml = pq($node, $this->getDocumentID())->markup();
  1828. foreach($nodes as $newNode) {
  1829. $node->appendChild($alreadyAdded
  1830. ? $newNode->cloneNode(true)
  1831. : $newNode
  1832. );
  1833. }
  1834. // for now, limit events for textarea
  1835. if (($this->isXHTML() || $this->isHTML()) && $node->tagName == 'textarea')
  1836. $this->markupEvents($html, $oldHtml, $node);
  1837. }
  1838. return $this;
  1839. } else {
  1840. // FETCH
  1841. $return = $this->documentWrapper->markup($this->elements, true);
  1842. $args = func_get_args();
  1843. foreach(array_slice($args, 1) as $callback) {
  1844. $return = phpQuery::callbackRun($callback, array($return));
  1845. }
  1846. return $return;
  1847. }
  1848. }
  1849. /**
  1850. * @TODO force xml result
  1851. */
  1852. public function xml($xml = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  1853. $args = func_get_args();
  1854. return call_user_func_array(array($this, 'html'), $args);
  1855. }
  1856. /**
  1857. * Enter description here...
  1858. * @TODO force html result
  1859. *
  1860. * @return String
  1861. */
  1862. public function htmlOuter($callback1 = null, $callback2 = null, $callback3 = null) {
  1863. $markup = $this->documentWrapper->markup($this->elements);
  1864. // pass thou callbacks
  1865. $args = func_get_args();
  1866. foreach($args as $callback) {
  1867. $markup = phpQuery::callbackRun($callback, array($markup));
  1868. }
  1869. return $markup;
  1870. }
  1871. /**
  1872. * @TODO force xml result
  1873. */
  1874. public function xmlOuter($callback1 = null, $callback2 = null, $callback3 = null) {
  1875. $args = func_get_args();
  1876. return call_user_func_array(array($this, 'htmlOuter'), $args);
  1877. }
  1878. public function __toString() {
  1879. return $this->markupOuter();
  1880. }
  1881. /**
  1882. * Just like html(), but returns markup with VALID (dangerous) PHP tags.
  1883. *
  1884. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1885. * @todo support returning markup with PHP tags when called without param
  1886. */
  1887. public function php($code = null) {
  1888. return $this->markupPHP($code);
  1889. }
  1890. /**
  1891. * Enter description here...
  1892. *
  1893. * @param $code
  1894. * @return unknown_type
  1895. */
  1896. public function markupPHP($code = null) {
  1897. return isset($code)
  1898. ? $this->markup(phpQuery::php($code))
  1899. : phpQuery::markupToPHP($this->markup());
  1900. }
  1901. /**
  1902. * Enter description here...
  1903. *
  1904. * @param $code
  1905. * @return unknown_type
  1906. */
  1907. public function markupOuterPHP() {
  1908. return phpQuery::markupToPHP($this->markupOuter());
  1909. }
  1910. /**
  1911. * Enter description here...
  1912. *
  1913. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1914. */
  1915. public function children($selector = null) {
  1916. $stack = array();
  1917. foreach($this->stack(1) as $node) {
  1918. // foreach($node->getElementsByTagName('*') as $newNode) {
  1919. foreach($node->childNodes as $newNode) {
  1920. if ($newNode->nodeType != 1)
  1921. continue;
  1922. if ($selector && ! $this->is($selector, $newNode))
  1923. continue;
  1924. if ($this->elementsContainsNode($newNode, $stack))
  1925. continue;
  1926. $stack[] = $newNode;
  1927. }
  1928. }
  1929. $this->elementsBackup = $this->elements;
  1930. $this->elements = $stack;
  1931. return $this->newInstance();
  1932. }
  1933. /**
  1934. * Enter description here...
  1935. *
  1936. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1937. */
  1938. public function ancestors($selector = null) {
  1939. return $this->children( $selector );
  1940. }
  1941. /**
  1942. * Enter description here...
  1943. *
  1944. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1945. */
  1946. public function append( $content) {
  1947. return $this->insert($content, __FUNCTION__);
  1948. }
  1949. /**
  1950. * Enter description here...
  1951. *
  1952. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1953. */
  1954. public function appendPHP( $content) {
  1955. return $this->insert("<php><!-- {$content} --></php>", 'append');
  1956. }
  1957. /**
  1958. * Enter description here...
  1959. *
  1960. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1961. */
  1962. public function appendTo( $seletor) {
  1963. return $this->insert($seletor, __FUNCTION__);
  1964. }
  1965. /**
  1966. * Enter description here...
  1967. *
  1968. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1969. */
  1970. public function prepend( $content) {
  1971. return $this->insert($content, __FUNCTION__);
  1972. }
  1973. /**
  1974. * Enter description here...
  1975. *
  1976. * @todo accept many arguments, which are joined, arrays maybe also
  1977. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1978. */
  1979. public function prependPHP( $content) {
  1980. return $this->insert("<php><!-- {$content} --></php>", 'prepend');
  1981. }
  1982. /**
  1983. * Enter description here...
  1984. *
  1985. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1986. */
  1987. public function prependTo( $seletor) {
  1988. return $this->insert($seletor, __FUNCTION__);
  1989. }
  1990. /**
  1991. * Enter description here...
  1992. *
  1993. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  1994. */
  1995. public function before($content) {
  1996. return $this->insert($content, __FUNCTION__);
  1997. }
  1998. /**
  1999. * Enter description here...
  2000. *
  2001. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2002. */
  2003. public function beforePHP( $content) {
  2004. return $this->insert("<php><!-- {$content} --></php>", 'before');
  2005. }
  2006. /**
  2007. * Enter description here...
  2008. *
  2009. * @param String|phpQuery
  2010. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2011. */
  2012. public function insertBefore( $seletor) {
  2013. return $this->insert($seletor, __FUNCTION__);
  2014. }
  2015. /**
  2016. * Enter description here...
  2017. *
  2018. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2019. */
  2020. public function after( $content) {
  2021. return $this->insert($content, __FUNCTION__);
  2022. }
  2023. /**
  2024. * Enter description here...
  2025. *
  2026. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2027. */
  2028. public function afterPHP( $content) {
  2029. return $this->insert("<php><!-- {$content} --></php>", 'after');
  2030. }
  2031. /**
  2032. * Enter description here...
  2033. *
  2034. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2035. */
  2036. public function insertAfter( $seletor) {
  2037. return $this->insert($seletor, __FUNCTION__);
  2038. }
  2039. /**
  2040. * Internal insert method. Don't use it.
  2041. *
  2042. * @param unknown_type $target
  2043. * @param unknown_type $type
  2044. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2045. * @access private
  2046. */
  2047. public function insert($target, $type) {
  2048. $this->debug("Inserting data with '{$type}'");
  2049. $to = false;
  2050. switch( $type) {
  2051. case 'appendTo':
  2052. case 'prependTo':
  2053. case 'insertBefore':
  2054. case 'insertAfter':
  2055. $to = true;
  2056. }
  2057. switch(gettype($target)) {
  2058. case 'string':
  2059. $insertFrom = $insertTo = array();
  2060. if ($to) {
  2061. // INSERT TO
  2062. $insertFrom = $this->elements;
  2063. if (phpQuery::isMarkup($target)) {
  2064. // $target is new markup, import it
  2065. $insertTo = $this->documentWrapper->import($target);
  2066. // insert into selected element
  2067. } else {
  2068. // $tagret is a selector
  2069. $thisStack = $this->elements;
  2070. $this->toRoot();
  2071. $insertTo = $this->find($target)->elements;
  2072. $this->elements = $thisStack;
  2073. }
  2074. } else {
  2075. // INSERT FROM
  2076. $insertTo = $this->elements;
  2077. $insertFrom = $this->documentWrapper->import($target);
  2078. }
  2079. break;
  2080. case 'object':
  2081. $insertFrom = $insertTo = array();
  2082. // phpQuery
  2083. if ($target instanceof self) {
  2084. if ($to) {
  2085. $insertTo = $target->elements;
  2086. if ($this->documentFragment && $this->stackIsRoot())
  2087. // get all body children
  2088. // $loop = $this->find('body > *')->elements;
  2089. // TODO test it, test it hard...
  2090. // $loop = $this->newInstance($this->root)->find('> *')->elements;
  2091. $loop = $this->root->childNodes;
  2092. else
  2093. $loop = $this->elements;
  2094. // import nodes if needed
  2095. $insertFrom = $this->getDocumentID() == $target->getDocumentID()
  2096. ? $loop
  2097. : $target->documentWrapper->import($loop);
  2098. } else {
  2099. $insertTo = $this->elements;
  2100. if ( $target->documentFragment && $target->stackIsRoot() )
  2101. // get all body children
  2102. // $loop = $target->find('body > *')->elements;
  2103. $loop = $target->root->childNodes;
  2104. else
  2105. $loop = $target->elements;
  2106. // import nodes if needed
  2107. $insertFrom = $this->getDocumentID() == $target->getDocumentID()
  2108. ? $loop
  2109. : $this->documentWrapper->import($loop);
  2110. }
  2111. // DOMNODE
  2112. } elseif ($target instanceof DOMNODE) {
  2113. // import node if needed
  2114. // if ( $target->ownerDocument != $this->DOM )
  2115. // $target = $this->DOM->importNode($target, true);
  2116. if ( $to) {
  2117. $insertTo = array($target);
  2118. if ($this->documentFragment && $this->stackIsRoot())
  2119. // get all body children
  2120. $loop = $this->root->childNodes;
  2121. // $loop = $this->find('body > *')->elements;
  2122. else
  2123. $loop = $this->elements;
  2124. foreach($loop as $fromNode)
  2125. // import nodes if needed
  2126. $insertFrom[] = ! $fromNode->ownerDocument->isSameNode($target->ownerDocument)
  2127. ? $target->ownerDocument->importNode($fromNode, true)
  2128. : $fromNode;
  2129. } else {
  2130. // import node if needed
  2131. if (! $target->ownerDocument->isSameNode($this->document))
  2132. $target = $this->document->importNode($target, true);
  2133. $insertTo = $this->elements;
  2134. $insertFrom[] = $target;
  2135. }
  2136. }
  2137. break;
  2138. }
  2139. phpQuery::debug("From ".count($insertFrom)."; To ".count($insertTo)." nodes");
  2140. foreach($insertTo as $insertNumber => $toNode) {
  2141. // we need static relative elements in some cases
  2142. switch( $type) {
  2143. case 'prependTo':
  2144. case 'prepend':
  2145. $firstChild = $toNode->firstChild;
  2146. break;
  2147. case 'insertAfter':
  2148. case 'after':
  2149. $nextSibling = $toNode->nextSibling;
  2150. break;
  2151. }
  2152. foreach($insertFrom as $fromNode) {
  2153. // clone if inserted already before
  2154. $insert = $insertNumber
  2155. ? $fromNode->cloneNode(true)
  2156. : $fromNode;
  2157. switch($type) {
  2158. case 'appendTo':
  2159. case 'append':
  2160. // $toNode->insertBefore(
  2161. // $fromNode,
  2162. // $toNode->lastChild->nextSibling
  2163. // );
  2164. $toNode->appendChild($insert);
  2165. $eventTarget = $insert;
  2166. break;
  2167. case 'prependTo':
  2168. case 'prepend':
  2169. $toNode->insertBefore(
  2170. $insert,
  2171. $firstChild
  2172. );
  2173. break;
  2174. case 'insertBefore':
  2175. case 'before':
  2176. if (! $toNode->parentNode)
  2177. throw new Exception("No parentNode, can't do {$type}()");
  2178. else
  2179. $toNode->parentNode->insertBefore(
  2180. $insert,
  2181. $toNode
  2182. );
  2183. break;
  2184. case 'insertAfter':
  2185. case 'after':
  2186. if (! $toNode->parentNode)
  2187. throw new Exception("No parentNode, can't do {$type}()");
  2188. else
  2189. $toNode->parentNode->insertBefore(
  2190. $insert,
  2191. $nextSibling
  2192. );
  2193. break;
  2194. }
  2195. // Mutation event
  2196. $event = new DOMEvent(array(
  2197. 'target' => $insert,
  2198. 'type' => 'DOMNodeInserted'
  2199. ));
  2200. phpQueryEvents::trigger($this->getDocumentID(),
  2201. $event->type, array($event), $insert
  2202. );
  2203. }
  2204. }
  2205. return $this;
  2206. }
  2207. /**
  2208. * Enter description here...
  2209. *
  2210. * @return Int
  2211. */
  2212. public function index($subject) {
  2213. $index = -1;
  2214. $subject = $subject instanceof phpQueryObject
  2215. ? $subject->elements[0]
  2216. : $subject;
  2217. foreach($this->newInstance() as $k => $node) {
  2218. if ($node->isSameNode($subject))
  2219. $index = $k;
  2220. }
  2221. return $index;
  2222. }
  2223. /**
  2224. * Enter description here...
  2225. *
  2226. * @param unknown_type $start
  2227. * @param unknown_type $end
  2228. *
  2229. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2230. * @testme
  2231. */
  2232. public function slice($start, $end = null) {
  2233. // $last = count($this->elements)-1;
  2234. // $end = $end
  2235. // ? min($end, $last)
  2236. // : $last;
  2237. // if ($start < 0)
  2238. // $start = $last+$start;
  2239. // if ($start > $last)
  2240. // return array();
  2241. if ($end > 0)
  2242. $end = $end-$start;
  2243. return $this->newInstance(
  2244. array_slice($this->elements, $start, $end)
  2245. );
  2246. }
  2247. /**
  2248. * Enter description here...
  2249. *
  2250. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2251. */
  2252. public function reverse() {
  2253. $this->elementsBackup = $this->elements;
  2254. $this->elements = array_reverse($this->elements);
  2255. return $this->newInstance();
  2256. }
  2257. /**
  2258. * Return joined text content.
  2259. * @return String
  2260. */
  2261. public function text($text = null, $callback1 = null, $callback2 = null, $callback3 = null) {
  2262. if (isset($text))
  2263. return $this->html(htmlspecialchars($text));
  2264. $args = func_get_args();
  2265. $args = array_slice($args, 1);
  2266. $return = '';
  2267. foreach($this->elements as $node) {
  2268. $text = $node->textContent;
  2269. if (count($this->elements) > 1 && $text)
  2270. $text .= "\n";
  2271. foreach($args as $callback) {
  2272. $text = phpQuery::callbackRun($callback, array($text));
  2273. }
  2274. $return .= $text;
  2275. }
  2276. return $return;
  2277. }
  2278. /**
  2279. * @return The text content of each matching element, like
  2280. * text() but returns an array with one entry per matched element.
  2281. * Read only.
  2282. */
  2283. public function texts($attr = null) {
  2284. $results = array();
  2285. foreach($this->elements as $node) {
  2286. $results[] = $node->textContent;
  2287. }
  2288. return $results;
  2289. }
  2290. /**
  2291. * Enter description here...
  2292. *
  2293. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2294. */
  2295. public function plugin($class, $file = null) {
  2296. phpQuery::plugin($class, $file);
  2297. return $this;
  2298. }
  2299. /**
  2300. * Deprecated, use $pq->plugin() instead.
  2301. *
  2302. * @deprecated
  2303. * @param $class
  2304. * @param $file
  2305. * @return unknown_type
  2306. */
  2307. public static function extend($class, $file = null) {
  2308. return $this->plugin($class, $file);
  2309. }
  2310. /**
  2311. *
  2312. * @access private
  2313. * @param $method
  2314. * @param $args
  2315. * @return unknown_type
  2316. */
  2317. public function __call($method, $args) {
  2318. $aliasMethods = array('clone', 'empty');
  2319. if (isset(phpQuery::$extendMethods[$method])) {
  2320. array_unshift($args, $this);
  2321. return phpQuery::callbackRun(
  2322. phpQuery::$extendMethods[$method], $args
  2323. );
  2324. } else if (isset(phpQuery::$pluginsMethods[$method])) {
  2325. array_unshift($args, $this);
  2326. $class = phpQuery::$pluginsMethods[$method];
  2327. $realClass = "phpQueryObjectPlugin_$class";
  2328. $return = call_user_func_array(
  2329. array($realClass, $method),
  2330. $args
  2331. );
  2332. // XXX deprecate ?
  2333. return is_null($return)
  2334. ? $this
  2335. : $return;
  2336. } else if (in_array($method, $aliasMethods)) {
  2337. return call_user_func_array(array($this, '_'.$method), $args);
  2338. } else
  2339. throw new Exception("Method '{$method}' doesnt exist");
  2340. }
  2341. /**
  2342. * Safe rename of next().
  2343. *
  2344. * Use it ONLY when need to call next() on an iterated object (in same time).
  2345. * Normaly there is no need to do such thing ;)
  2346. *
  2347. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2348. * @access private
  2349. */
  2350. public function _next($selector = null) {
  2351. return $this->newInstance(
  2352. $this->getElementSiblings('nextSibling', $selector, true)
  2353. );
  2354. }
  2355. /**
  2356. * Use prev() and next().
  2357. *
  2358. * @deprecated
  2359. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2360. * @access private
  2361. */
  2362. public function _prev($selector = null) {
  2363. return $this->prev($selector);
  2364. }
  2365. /**
  2366. * Enter description here...
  2367. *
  2368. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2369. */
  2370. public function prev($selector = null) {
  2371. return $this->newInstance(
  2372. $this->getElementSiblings('previousSibling', $selector, true)
  2373. );
  2374. }
  2375. /**
  2376. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2377. * @todo
  2378. */
  2379. public function prevAll($selector = null) {
  2380. return $this->newInstance(
  2381. $this->getElementSiblings('previousSibling', $selector)
  2382. );
  2383. }
  2384. /**
  2385. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2386. * @todo FIXME: returns source elements insted of next siblings
  2387. */
  2388. public function nextAll($selector = null) {
  2389. return $this->newInstance(
  2390. $this->getElementSiblings('nextSibling', $selector)
  2391. );
  2392. }
  2393. /**
  2394. * @access private
  2395. */
  2396. protected function getElementSiblings($direction, $selector = null, $limitToOne = false) {
  2397. $stack = array();
  2398. $count = 0;
  2399. foreach($this->stack() as $node) {
  2400. $test = $node;
  2401. while( isset($test->{$direction}) && $test->{$direction}) {
  2402. $test = $test->{$direction};
  2403. if (! $test instanceof DOMELEMENT)
  2404. continue;
  2405. $stack[] = $test;
  2406. if ($limitToOne)
  2407. break;
  2408. }
  2409. }
  2410. if ($selector) {
  2411. $stackOld = $this->elements;
  2412. $this->elements = $stack;
  2413. $stack = $this->filter($selector, true)->stack();
  2414. $this->elements = $stackOld;
  2415. }
  2416. return $stack;
  2417. }
  2418. /**
  2419. * Enter description here...
  2420. *
  2421. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2422. */
  2423. public function siblings($selector = null) {
  2424. $stack = array();
  2425. $siblings = array_merge(
  2426. $this->getElementSiblings('previousSibling', $selector),
  2427. $this->getElementSiblings('nextSibling', $selector)
  2428. );
  2429. foreach($siblings as $node) {
  2430. if (! $this->elementsContainsNode($node, $stack))
  2431. $stack[] = $node;
  2432. }
  2433. return $this->newInstance($stack);
  2434. }
  2435. /**
  2436. * Enter description here...
  2437. *
  2438. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2439. */
  2440. public function not($selector = null) {
  2441. if (is_string($selector))
  2442. phpQuery::debug(array('not', $selector));
  2443. else
  2444. phpQuery::debug('not');
  2445. $stack = array();
  2446. if ($selector instanceof self || $selector instanceof DOMNODE) {
  2447. foreach($this->stack() as $node) {
  2448. if ($selector instanceof self) {
  2449. $matchFound = false;
  2450. foreach($selector->stack() as $notNode) {
  2451. if ($notNode->isSameNode($node))
  2452. $matchFound = true;
  2453. }
  2454. if (! $matchFound)
  2455. $stack[] = $node;
  2456. } else if ($selector instanceof DOMNODE) {
  2457. if (! $selector->isSameNode($node))
  2458. $stack[] = $node;
  2459. } else {
  2460. if (! $this->is($selector))
  2461. $stack[] = $node;
  2462. }
  2463. }
  2464. } else {
  2465. $orgStack = $this->stack();
  2466. $matched = $this->filter($selector, true)->stack();
  2467. // $matched = array();
  2468. // // simulate OR in filter() instead of AND 5y
  2469. // foreach($this->parseSelector($selector) as $s) {
  2470. // $matched = array_merge($matched,
  2471. // $this->filter(array($s))->stack()
  2472. // );
  2473. // }
  2474. foreach($orgStack as $node)
  2475. if (! $this->elementsContainsNode($node, $matched))
  2476. $stack[] = $node;
  2477. }
  2478. return $this->newInstance($stack);
  2479. }
  2480. /**
  2481. * Enter description here...
  2482. *
  2483. * @param string|phpQueryObject
  2484. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2485. */
  2486. public function add($selector = null) {
  2487. if (! $selector)
  2488. return $this;
  2489. $stack = array();
  2490. $this->elementsBackup = $this->elements;
  2491. $found = phpQuery::pq($selector, $this->getDocumentID());
  2492. $this->merge($found->elements);
  2493. return $this->newInstance();
  2494. }
  2495. /**
  2496. * @access private
  2497. */
  2498. protected function merge() {
  2499. foreach(func_get_args() as $nodes)
  2500. foreach($nodes as $newNode )
  2501. if (! $this->elementsContainsNode($newNode) )
  2502. $this->elements[] = $newNode;
  2503. }
  2504. /**
  2505. * @access private
  2506. * TODO refactor to stackContainsNode
  2507. */
  2508. protected function elementsContainsNode($nodeToCheck, $elementsStack = null) {
  2509. $loop = ! is_null($elementsStack)
  2510. ? $elementsStack
  2511. : $this->elements;
  2512. foreach($loop as $node) {
  2513. if ( $node->isSameNode( $nodeToCheck ) )
  2514. return true;
  2515. }
  2516. return false;
  2517. }
  2518. /**
  2519. * Enter description here...
  2520. *
  2521. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2522. */
  2523. public function parent($selector = null) {
  2524. $stack = array();
  2525. foreach($this->elements as $node )
  2526. if ( $node->parentNode && ! $this->elementsContainsNode($node->parentNode, $stack) )
  2527. $stack[] = $node->parentNode;
  2528. $this->elementsBackup = $this->elements;
  2529. $this->elements = $stack;
  2530. if ( $selector )
  2531. $this->filter($selector, true);
  2532. return $this->newInstance();
  2533. }
  2534. /**
  2535. * Enter description here...
  2536. *
  2537. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2538. */
  2539. public function parents($selector = null) {
  2540. $stack = array();
  2541. if (! $this->elements )
  2542. $this->debug('parents() - stack empty');
  2543. foreach($this->elements as $node) {
  2544. $test = $node;
  2545. while( $test->parentNode) {
  2546. $test = $test->parentNode;
  2547. if ($this->isRoot($test))
  2548. break;
  2549. if (! $this->elementsContainsNode($test, $stack)) {
  2550. $stack[] = $test;
  2551. continue;
  2552. }
  2553. }
  2554. }
  2555. $this->elementsBackup = $this->elements;
  2556. $this->elements = $stack;
  2557. if ( $selector )
  2558. $this->filter($selector, true);
  2559. return $this->newInstance();
  2560. }
  2561. /**
  2562. * Internal stack iterator.
  2563. *
  2564. * @access private
  2565. * @return {Array.<DOMNode>}
  2566. */
  2567. public function stack($nodeTypes = null) {
  2568. if (!isset($nodeTypes))
  2569. return $this->elements;
  2570. if (!is_array($nodeTypes))
  2571. $nodeTypes = array($nodeTypes);
  2572. $return = array();
  2573. foreach($this->elements as $node) {
  2574. if (in_array($node->nodeType, $nodeTypes))
  2575. $return[] = $node;
  2576. }
  2577. return $return;
  2578. }
  2579. // TODO phpdoc; $oldAttr is result of hasAttribute, before any changes
  2580. protected function attrEvents($attr, $oldAttr, $oldValue, $node) {
  2581. // skip events for XML documents
  2582. if (! $this->isXHTML() && ! $this->isHTML())
  2583. return;
  2584. $event = null;
  2585. // identify
  2586. $isInputValue = $node->tagName == 'input'
  2587. && (
  2588. in_array($node->getAttribute('type'),
  2589. array('text', 'password', 'hidden'))
  2590. || !$node->getAttribute('type')
  2591. );
  2592. $isRadio = $node->tagName == 'input'
  2593. && $node->getAttribute('type') == 'radio';
  2594. $isCheckbox = $node->tagName == 'input'
  2595. && $node->getAttribute('type') == 'checkbox';
  2596. $isOption = $node->tagName == 'option';
  2597. if ($isInputValue && $attr == 'value' && $oldValue != $node->getAttribute($attr)) {
  2598. $event = new DOMEvent(array(
  2599. 'target' => $node,
  2600. 'type' => 'change'
  2601. ));
  2602. } else if (($isRadio || $isCheckbox) && $attr == 'checked' && (
  2603. // check
  2604. (! $oldAttr && $node->hasAttribute($attr))
  2605. // un-check
  2606. || (! $node->hasAttribute($attr) && $oldAttr)
  2607. )) {
  2608. $event = new DOMEvent(array(
  2609. 'target' => $node,
  2610. 'type' => 'change'
  2611. ));
  2612. } else if ($isOption && $node->parentNode && $attr == 'selected' && (
  2613. // select
  2614. (! $oldAttr && $node->hasAttribute($attr))
  2615. // un-select
  2616. || (! $node->hasAttribute($attr) && $oldAttr)
  2617. )) {
  2618. $event = new DOMEvent(array(
  2619. 'target' => $node->parentNode,
  2620. 'type' => 'change'
  2621. ));
  2622. }
  2623. if ($event) {
  2624. phpQueryEvents::trigger($this->getDocumentID(),
  2625. $event->type, array($event), $node
  2626. );
  2627. }
  2628. }
  2629. public function attr($attr = null, $value = null) {
  2630. foreach($this->stack(1) as $node) {
  2631. if (! is_null($value)) {
  2632. $loop = $attr == '*'
  2633. ? $this->getNodeAttrs($node)
  2634. : array($attr);
  2635. foreach($loop as $a) {
  2636. $oldValue = $node->getAttribute($a);
  2637. $oldAttr = $node->hasAttribute($a);
  2638. // TODO raises an error when charset other than UTF-8
  2639. // while document's charset is also not UTF-8
  2640. @$node->setAttribute($a, $value);
  2641. $this->attrEvents($a, $oldAttr, $oldValue, $node);
  2642. }
  2643. } else if ($attr == '*') {
  2644. // jQuery difference
  2645. $return = array();
  2646. foreach($node->attributes as $n => $v)
  2647. $return[$n] = $v->value;
  2648. return $return;
  2649. } else
  2650. return $node->hasAttribute($attr)
  2651. ? $node->getAttribute($attr)
  2652. : null;
  2653. }
  2654. return is_null($value)
  2655. ? '' : $this;
  2656. }
  2657. /**
  2658. * @return The same attribute of each matching element, like
  2659. * attr() but returns an array with one entry per matched element.
  2660. * Read only.
  2661. */
  2662. public function attrs($attr = null) {
  2663. $results = array();
  2664. foreach($this->stack(1) as $node) {
  2665. $results[] = $node->hasAttribute($attr)
  2666. ? $node->getAttribute($attr)
  2667. : null;
  2668. }
  2669. return $results;
  2670. }
  2671. /**
  2672. * @access private
  2673. */
  2674. protected function getNodeAttrs($node) {
  2675. $return = array();
  2676. foreach($node->attributes as $n => $o)
  2677. $return[] = $n;
  2678. return $return;
  2679. }
  2680. /**
  2681. * Enter description here...
  2682. *
  2683. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2684. * @todo check CDATA ???
  2685. */
  2686. public function attrPHP($attr, $code) {
  2687. if (! is_null($code)) {
  2688. $value = '<'.'?php '.$code.' ?'.'>';
  2689. // TODO tempolary solution
  2690. // http://code.google.com/p/phpquery/issues/detail?id=17
  2691. // if (function_exists('mb_detect_encoding') && mb_detect_encoding($value) == 'ASCII')
  2692. // $value = mb_convert_encoding($value, 'UTF-8', 'HTML-ENTITIES');
  2693. }
  2694. foreach($this->stack(1) as $node) {
  2695. if (! is_null($code)) {
  2696. // $attrNode = $this->DOM->createAttribute($attr);
  2697. $node->setAttribute($attr, $value);
  2698. // $attrNode->value = $value;
  2699. // $node->appendChild($attrNode);
  2700. } else if ( $attr == '*') {
  2701. // jQuery diff
  2702. $return = array();
  2703. foreach($node->attributes as $n => $v)
  2704. $return[$n] = $v->value;
  2705. return $return;
  2706. } else
  2707. return $node->getAttribute($attr);
  2708. }
  2709. return $this;
  2710. }
  2711. /**
  2712. * Enter description here...
  2713. *
  2714. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2715. */
  2716. public function removeAttr($attr) {
  2717. foreach($this->stack(1) as $node) {
  2718. $loop = $attr == '*'
  2719. ? $this->getNodeAttrs($node)
  2720. : array($attr);
  2721. foreach($loop as $a) {
  2722. $oldValue = $node->getAttribute($a);
  2723. $node->removeAttribute($a);
  2724. $this->attrEvents($a, $oldValue, null, $node);
  2725. }
  2726. }
  2727. return $this;
  2728. }
  2729. /**
  2730. * Return form element value.
  2731. *
  2732. * @return String Fields value.
  2733. */
  2734. public function val($val = null) {
  2735. if (! isset($val)) {
  2736. if ($this->eq(0)->is('select')) {
  2737. $selected = $this->eq(0)->find('option[selected=selected]');
  2738. if ($selected->is('[value]'))
  2739. return $selected->attr('value');
  2740. else
  2741. return $selected->text();
  2742. } else if ($this->eq(0)->is('textarea'))
  2743. return $this->eq(0)->markup();
  2744. else
  2745. return $this->eq(0)->attr('value');
  2746. } else {
  2747. $_val = null;
  2748. foreach($this->stack(1) as $node) {
  2749. $node = pq($node, $this->getDocumentID());
  2750. if (is_array($val) && in_array($node->attr('type'), array('checkbox', 'radio'))) {
  2751. $isChecked = in_array($node->attr('value'), $val)
  2752. || in_array($node->attr('name'), $val);
  2753. if ($isChecked)
  2754. $node->attr('checked', 'checked');
  2755. else
  2756. $node->removeAttr('checked');
  2757. } else if ($node->get(0)->tagName == 'select') {
  2758. if (! isset($_val)) {
  2759. $_val = array();
  2760. if (! is_array($val))
  2761. $_val = array((string)$val);
  2762. else
  2763. foreach($val as $v)
  2764. $_val[] = $v;
  2765. }
  2766. foreach($node['option']->stack(1) as $option) {
  2767. $option = pq($option, $this->getDocumentID());
  2768. $selected = false;
  2769. // XXX: workaround for string comparsion, see issue #96
  2770. // http://code.google.com/p/phpquery/issues/detail?id=96
  2771. $selected = is_null($option->attr('value'))
  2772. ? in_array($option->markup(), $_val)
  2773. : in_array($option->attr('value'), $_val);
  2774. // $optionValue = $option->attr('value');
  2775. // $optionText = $option->text();
  2776. // $optionTextLenght = mb_strlen($optionText);
  2777. // foreach($_val as $v)
  2778. // if ($optionValue == $v)
  2779. // $selected = true;
  2780. // else if ($optionText == $v && $optionTextLenght == mb_strlen($v))
  2781. // $selected = true;
  2782. if ($selected)
  2783. $option->attr('selected', 'selected');
  2784. else
  2785. $option->removeAttr('selected');
  2786. }
  2787. } else if ($node->get(0)->tagName == 'textarea')
  2788. $node->markup($val);
  2789. else
  2790. $node->attr('value', $val);
  2791. }
  2792. }
  2793. return $this;
  2794. }
  2795. /**
  2796. * Enter description here...
  2797. *
  2798. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2799. */
  2800. public function andSelf() {
  2801. if ( $this->previous )
  2802. $this->elements = array_merge($this->elements, $this->previous->elements);
  2803. return $this;
  2804. }
  2805. /**
  2806. * Enter description here...
  2807. *
  2808. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2809. */
  2810. public function addClass( $className) {
  2811. if (! $className)
  2812. return $this;
  2813. foreach($this->stack(1) as $node) {
  2814. if (! $this->is(".$className", $node))
  2815. $node->setAttribute(
  2816. 'class',
  2817. trim($node->getAttribute('class').' '.$className)
  2818. );
  2819. }
  2820. return $this;
  2821. }
  2822. /**
  2823. * Enter description here...
  2824. *
  2825. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2826. */
  2827. public function addClassPHP( $className) {
  2828. foreach($this->stack(1) as $node) {
  2829. $classes = $node->getAttribute('class');
  2830. $newValue = $classes
  2831. ? $classes.' <'.'?php '.$className.' ?'.'>'
  2832. : '<'.'?php '.$className.' ?'.'>';
  2833. $node->setAttribute('class', $newValue);
  2834. }
  2835. return $this;
  2836. }
  2837. /**
  2838. * Enter description here...
  2839. *
  2840. * @param string $className
  2841. * @return bool
  2842. */
  2843. public function hasClass($className) {
  2844. foreach($this->stack(1) as $node) {
  2845. if ( $this->is(".$className", $node))
  2846. return true;
  2847. }
  2848. return false;
  2849. }
  2850. /**
  2851. * Enter description here...
  2852. *
  2853. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2854. */
  2855. public function removeClass($className) {
  2856. foreach($this->stack(1) as $node) {
  2857. $classes = explode( ' ', $node->getAttribute('class'));
  2858. if ( in_array($className, $classes)) {
  2859. $classes = array_diff($classes, array($className));
  2860. if ( $classes )
  2861. $node->setAttribute('class', implode(' ', $classes));
  2862. else
  2863. $node->removeAttribute('class');
  2864. }
  2865. }
  2866. return $this;
  2867. }
  2868. /**
  2869. * Enter description here...
  2870. *
  2871. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2872. */
  2873. public function toggleClass($className) {
  2874. foreach($this->stack(1) as $node) {
  2875. if ( $this->is( $node, '.'.$className ))
  2876. $this->removeClass($className);
  2877. else
  2878. $this->addClass($className);
  2879. }
  2880. return $this;
  2881. }
  2882. /**
  2883. * Proper name without underscore (just ->empty()) also works.
  2884. *
  2885. * Removes all child nodes from the set of matched elements.
  2886. *
  2887. * Example:
  2888. * pq("p")._empty()
  2889. *
  2890. * HTML:
  2891. * <p>Hello, <span>Person</span> <a href="#">and person</a></p>
  2892. *
  2893. * Result:
  2894. * [ <p></p> ]
  2895. *
  2896. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2897. * @access private
  2898. */
  2899. public function _empty() {
  2900. foreach($this->stack(1) as $node) {
  2901. // thx to 'dave at dgx dot cz'
  2902. $node->nodeValue = '';
  2903. }
  2904. return $this;
  2905. }
  2906. /**
  2907. * Enter description here...
  2908. *
  2909. * @param array|string $callback Expects $node as first param, $index as second
  2910. * @param array $scope External variables passed to callback. Use compact('varName1', 'varName2'...) and extract($scope)
  2911. * @param array $arg1 Will ba passed as third and futher args to callback.
  2912. * @param array $arg2 Will ba passed as fourth and futher args to callback, and so on...
  2913. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2914. */
  2915. public function each($callback, $param1 = null, $param2 = null, $param3 = null) {
  2916. $paramStructure = null;
  2917. if (func_num_args() > 1) {
  2918. $paramStructure = func_get_args();
  2919. $paramStructure = array_slice($paramStructure, 1);
  2920. }
  2921. foreach($this->elements as $v)
  2922. phpQuery::callbackRun($callback, array($v), $paramStructure);
  2923. return $this;
  2924. }
  2925. /**
  2926. * Run callback on actual object.
  2927. *
  2928. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2929. */
  2930. public function callback($callback, $param1 = null, $param2 = null, $param3 = null) {
  2931. $params = func_get_args();
  2932. $params[0] = $this;
  2933. phpQuery::callbackRun($callback, $params);
  2934. return $this;
  2935. }
  2936. /**
  2937. * Enter description here...
  2938. *
  2939. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  2940. * @todo add $scope and $args as in each() ???
  2941. */
  2942. public function map($callback, $param1 = null, $param2 = null, $param3 = null) {
  2943. // $stack = array();
  2944. //// foreach($this->newInstance() as $node) {
  2945. // foreach($this->newInstance() as $node) {
  2946. // $result = call_user_func($callback, $node);
  2947. // if ($result)
  2948. // $stack[] = $result;
  2949. // }
  2950. $params = func_get_args();
  2951. array_unshift($params, $this->elements);
  2952. return $this->newInstance(
  2953. call_user_func_array(array('phpQuery', 'map'), $params)
  2954. // phpQuery::map($this->elements, $callback)
  2955. );
  2956. }
  2957. /**
  2958. * Enter description here...
  2959. *
  2960. * @param <type> $key
  2961. * @param <type> $value
  2962. */
  2963. public function data($key, $value = null) {
  2964. if (! isset($value)) {
  2965. // TODO? implement specific jQuery behavior od returning parent values
  2966. // is child which we look up doesn't exist
  2967. return phpQuery::data($this->get(0), $key, $value, $this->getDocumentID());
  2968. } else {
  2969. foreach($this as $node)
  2970. phpQuery::data($node, $key, $value, $this->getDocumentID());
  2971. return $this;
  2972. }
  2973. }
  2974. /**
  2975. * Enter description here...
  2976. *
  2977. * @param <type> $key
  2978. */
  2979. public function removeData($key) {
  2980. foreach($this as $node)
  2981. phpQuery::removeData($node, $key, $this->getDocumentID());
  2982. return $this;
  2983. }
  2984. // INTERFACE IMPLEMENTATIONS
  2985. // ITERATOR INTERFACE
  2986. /**
  2987. * @access private
  2988. */
  2989. #[\ReturnTypeWillChange]
  2990. public function rewind(){
  2991. $this->debug('iterating foreach');
  2992. // phpQuery::selectDocument($this->getDocumentID());
  2993. $this->elementsBackup = $this->elements;
  2994. $this->elementsInterator = $this->elements;
  2995. $this->valid = isset( $this->elements[0] )
  2996. ? 1 : 0;
  2997. // $this->elements = $this->valid
  2998. // ? array($this->elements[0])
  2999. // : array();
  3000. $this->current = 0;
  3001. }
  3002. /**
  3003. * @access private
  3004. */
  3005. #[\ReturnTypeWillChange]
  3006. public function current(){
  3007. return $this->elementsInterator[ $this->current ];
  3008. }
  3009. /**
  3010. * @access private
  3011. */
  3012. #[\ReturnTypeWillChange]
  3013. public function key(){
  3014. return $this->current;
  3015. }
  3016. /**
  3017. * Double-function method.
  3018. *
  3019. * First: main iterator interface method.
  3020. * Second: Returning next sibling, alias for _next().
  3021. *
  3022. * Proper functionality is choosed automagicaly.
  3023. *
  3024. * @see phpQueryObject::_next()
  3025. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3026. */
  3027. #[\ReturnTypeWillChange]
  3028. public function next($cssSelector = null){
  3029. // if ($cssSelector || $this->valid)
  3030. // return $this->_next($cssSelector);
  3031. $this->valid = isset( $this->elementsInterator[ $this->current+1 ] )
  3032. ? true
  3033. : false;
  3034. if (! $this->valid && $this->elementsInterator) {
  3035. $this->elementsInterator = null;
  3036. } else if ($this->valid) {
  3037. $this->current++;
  3038. } else {
  3039. return $this->_next($cssSelector);
  3040. }
  3041. }
  3042. /**
  3043. * @access private
  3044. */
  3045. #[\ReturnTypeWillChange]
  3046. public function valid(){
  3047. return $this->valid;
  3048. }
  3049. // ITERATOR INTERFACE END
  3050. // ARRAYACCESS INTERFACE
  3051. /**
  3052. * @access private
  3053. */
  3054. #[\ReturnTypeWillChange]
  3055. public function offsetExists($offset) {
  3056. return $this->find($offset)->size() > 0;
  3057. }
  3058. /**
  3059. * @access private
  3060. */
  3061. #[\ReturnTypeWillChange]
  3062. public function offsetGet($offset) {
  3063. return $this->find($offset);
  3064. }
  3065. /**
  3066. * @access private
  3067. */
  3068. #[\ReturnTypeWillChange]
  3069. public function offsetSet($offset, $value) {
  3070. // $this->find($offset)->replaceWith($value);
  3071. $this->find($offset)->html($value);
  3072. }
  3073. /**
  3074. * @access private
  3075. */
  3076. #[\ReturnTypeWillChange]
  3077. public function offsetUnset($offset) {
  3078. // empty
  3079. throw new Exception("Can't do unset, use array interface only for calling queries and replacing HTML.");
  3080. }
  3081. // ARRAYACCESS INTERFACE END
  3082. /**
  3083. * Returns node's XPath.
  3084. *
  3085. * @param unknown_type $oneNode
  3086. * @return string
  3087. * @TODO use native getNodePath is avaible
  3088. * @access private
  3089. */
  3090. protected function getNodeXpath($oneNode = null, $namespace = null) {
  3091. $return = array();
  3092. $loop = $oneNode
  3093. ? array($oneNode)
  3094. : $this->elements;
  3095. // if ($namespace)
  3096. // $namespace .= ':';
  3097. foreach($loop as $node) {
  3098. if ($node instanceof DOMDOCUMENT) {
  3099. $return[] = '';
  3100. continue;
  3101. }
  3102. $xpath = array();
  3103. while(! ($node instanceof DOMDOCUMENT)) {
  3104. $i = 1;
  3105. $sibling = $node;
  3106. while($sibling->previousSibling) {
  3107. $sibling = $sibling->previousSibling;
  3108. $isElement = $sibling instanceof DOMELEMENT;
  3109. if ($isElement && $sibling->tagName == $node->tagName)
  3110. $i++;
  3111. }
  3112. $xpath[] = $this->isXML()
  3113. ? "*[local-name()='{$node->tagName}'][{$i}]"
  3114. : "{$node->tagName}[{$i}]";
  3115. $node = $node->parentNode;
  3116. }
  3117. $xpath = implode('/', array_reverse($xpath));
  3118. $return[] = '/'.$xpath;
  3119. }
  3120. return $oneNode
  3121. ? $return[0]
  3122. : $return;
  3123. }
  3124. // HELPERS
  3125. public function whois($oneNode = null) {
  3126. $return = array();
  3127. $loop = $oneNode
  3128. ? array( $oneNode )
  3129. : $this->elements;
  3130. foreach($loop as $node) {
  3131. if (isset($node->tagName)) {
  3132. $tag = in_array($node->tagName, array('php', 'js'))
  3133. ? strtoupper($node->tagName)
  3134. : $node->tagName;
  3135. $return[] = $tag
  3136. .($node->getAttribute('id')
  3137. ? '#'.$node->getAttribute('id'):'')
  3138. .($node->getAttribute('class')
  3139. ? '.'.implode('.', explode(' ', $node->getAttribute('class'))):'')
  3140. .($node->getAttribute('name')
  3141. ? '[name="'.$node->getAttribute('name').'"]':'')
  3142. .($node->getAttribute('value') && strpos($node->getAttribute('value'), '<'.'?php') === false
  3143. ? '[value="'.substr(str_replace("\n", '', $node->getAttribute('value')), 0, 15).'"]':'')
  3144. .($node->getAttribute('value') && strpos($node->getAttribute('value'), '<'.'?php') !== false
  3145. ? '[value=PHP]':'')
  3146. .($node->getAttribute('selected')
  3147. ? '[selected]':'')
  3148. .($node->getAttribute('checked')
  3149. ? '[checked]':'')
  3150. ;
  3151. } else if ($node instanceof DOMTEXT) {
  3152. if (trim($node->textContent))
  3153. $return[] = 'Text:'.substr(str_replace("\n", ' ', $node->textContent), 0, 15);
  3154. } else {
  3155. }
  3156. }
  3157. return $oneNode && isset($return[0])
  3158. ? $return[0]
  3159. : $return;
  3160. }
  3161. /**
  3162. * Dump htmlOuter and preserve chain. Usefull for debugging.
  3163. *
  3164. * @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
  3165. *
  3166. */
  3167. public function dump() {
  3168. print 'DUMP #'.(phpQuery::$dumpCount++).' ';
  3169. $debug = phpQuery::$debug;
  3170. phpQuery::$debug = false;
  3171. // print __FILE__.':'.__LINE__."\n";
  3172. var_dump($this->htmlOuter());
  3173. return $this;
  3174. }
  3175. public function dumpWhois() {
  3176. print 'DUMP #'.(phpQuery::$dumpCount++).' ';
  3177. $debug = phpQuery::$debug;
  3178. phpQuery::$debug = false;
  3179. // print __FILE__.':'.__LINE__."\n";
  3180. var_dump('whois', $this->whois());
  3181. phpQuery::$debug = $debug;
  3182. return $this;
  3183. }
  3184. public function dumpLength() {
  3185. print 'DUMP #'.(phpQuery::$dumpCount++).' ';
  3186. $debug = phpQuery::$debug;
  3187. phpQuery::$debug = false;
  3188. // print __FILE__.':'.__LINE__."\n";
  3189. var_dump('length', $this->length());
  3190. phpQuery::$debug = $debug;
  3191. return $this;
  3192. }
  3193. public function dumpTree($html = true, $title = true) {
  3194. $output = $title
  3195. ? 'DUMP #'.(phpQuery::$dumpCount++)." \n" : '';
  3196. $debug = phpQuery::$debug;
  3197. phpQuery::$debug = false;
  3198. foreach($this->stack() as $node)
  3199. $output .= $this->__dumpTree($node);
  3200. phpQuery::$debug = $debug;
  3201. print $html
  3202. ? nl2br(str_replace(' ', '&nbsp;', $output))
  3203. : $output;
  3204. return $this;
  3205. }
  3206. private function __dumpTree($node, $intend = 0) {
  3207. $whois = $this->whois($node);
  3208. $return = '';
  3209. if ($whois)
  3210. $return .= str_repeat(' - ', $intend).$whois."\n";
  3211. if (isset($node->childNodes))
  3212. foreach($node->childNodes as $chNode)
  3213. $return .= $this->__dumpTree($chNode, $intend+1);
  3214. return $return;
  3215. }
  3216. /**
  3217. * Dump htmlOuter and stop script execution. Usefull for debugging.
  3218. *
  3219. */
  3220. public function dumpDie() {
  3221. print __FILE__.':'.__LINE__;
  3222. var_dump($this->htmlOuter());
  3223. die();
  3224. }
  3225. }