PageRenderTime 79ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/tmp/busines13_bundle_installer/lib_gantry/libs/phpQuery.php

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