PageRenderTime 61ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full file

  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 =

Large files files are truncated, but you can click here to view the full file