HEX
Server: LiteSpeed
System: Linux atali.colombiahosting.com.co 5.14.0-570.12.1.el9_6.x86_64 #1 SMP PREEMPT_DYNAMIC Tue May 13 06:11:55 EDT 2025 x86_64
User: coopserp (1713)
PHP: 8.2.29
Disabled: dl,exec,passthru,proc_open,proc_close,shell_exec,memory_limit,system,popen,curl_multi_exec,show_source,symlink,link,leak,listen,diskfreespace,tmpfile,ignore_user_abord,highlight_file,source,show_source,fpaththru,virtual,posix_ctermid,posix_getcwd,posix_getegid,posix_geteuid,posix_getgid,posix_getgrgid,posix_getgrnam,posix_getgroups,posix_getlogin,posix_getpgid,posix_getpgrp,posix_getpid,posix,posix_getppid,posix_getpwnam,posix_getpwuid,posix_getrlimit,posix_getsid,posix_getuid,posix_isatty,posix_kill,posix_mkfifo,posix_setegid,posix_seteuid,posix_setgid,posix_setpgid,posix_setsid,posix_setid,posix_times,posix_ttyname,posix_uname,proc_get_status,proc_nice,proc_terminate
Upload Files
File: /home/coopserp/www/lib.tar
plugin-update-checker.php000064400000151651151526435150011455 0ustar00<?php
/**
 * Plugin Update Checker Library 3.2
 * http://w-shadow.com/
 * 
 * Copyright 2016 Janis Elsts
 * Released under the MIT license. See license.txt for details.
 */

if ( !class_exists('SoftaculousProUpdateChecker_3_2', false) ):

/**
 * A custom plugin update checker. 
 * 
 * @author Janis Elsts
 * @copyright 2016
 * @version 3.2
 * @access public
 */
class SoftaculousProUpdateChecker_3_2 {
	public $metadataUrl = ''; //The URL of the plugin's metadata file.
	public $pluginAbsolutePath = ''; //Full path of the main plugin file.
	public $pluginFile = '';  //Plugin filename relative to the plugins directory. Many WP APIs use this to identify plugins.
	public $slug = '';        //Plugin slug.
	public $optionName = '';  //Where to store the update info.
	public $muPluginFile = ''; //For MU plugins, the plugin filename relative to the mu-plugins directory.

	public $debugMode = false; //Set to TRUE to enable error reporting. Errors are raised using trigger_error()
                               //and should be logged to the standard PHP error log.
	public $scheduler;

	protected $upgraderStatus;

	private $debugBarPlugin = null;
	private $cachedInstalledVersion = null;

	private $metadataHost = ''; //The host component of $metadataUrl.

	/**
	 * Class constructor.
	 *
	 * @param string $metadataUrl The URL of the plugin's metadata file.
	 * @param string $pluginFile Fully qualified path to the main plugin file.
	 * @param string $slug The plugin's 'slug'. If not specified, the filename part of $pluginFile sans '.php' will be used as the slug.
	 * @param integer $checkPeriod How often to check for updates (in hours). Defaults to checking every 12 hours. Set to 0 to disable automatic update checks.
	 * @param string $optionName Where to store book-keeping info about update checks. Defaults to 'external_updates-$slug'.
	 * @param string $muPluginFile Optional. The plugin filename relative to the mu-plugins directory.
	 */
	public function __construct($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = ''){
		$this->metadataUrl = $metadataUrl;
		$this->pluginAbsolutePath = $pluginFile;
		$this->pluginFile = plugin_basename($this->pluginAbsolutePath);
		$this->muPluginFile = $muPluginFile;
		$this->slug = $slug;
		$this->optionName = $optionName;
		$this->debugMode = (bool)(constant('WP_DEBUG'));

		//If no slug is specified, use the name of the main plugin file as the slug.
		//For example, 'my-cool-plugin/cool-plugin.php' becomes 'cool-plugin'.
		if ( empty($this->slug) ){
			$this->slug = basename($this->pluginFile, '.php');
		}

		//Plugin slugs must be unique.
		$slugCheckFilter = 'puc_is_slug_in_use-' . $this->slug;
		$slugUsedBy = apply_filters($slugCheckFilter, false);
		if ( $slugUsedBy ) {
			$this->triggerError(sprintf(
				'Plugin slug "%s" is already in use by %s. Slugs must be unique.',
				htmlentities($this->slug),
				htmlentities($slugUsedBy)
			), E_USER_ERROR);
		}
		add_filter($slugCheckFilter, array($this, 'getAbsolutePath'));

		
		if ( empty($this->optionName) ){
			$this->optionName = 'external_updates-' . $this->slug;
		}

		//Backwards compatibility: If the plugin is a mu-plugin but no $muPluginFile is specified, assume
		//it's the same as $pluginFile given that it's not in a subdirectory (WP only looks in the base dir).
		if ( (strpbrk($this->pluginFile, '/\\') === false) && $this->isUnknownMuPlugin() ) {
			$this->muPluginFile = $this->pluginFile;
		}

		$this->scheduler = $this->createScheduler($checkPeriod);
		$this->upgraderStatus = new SoftaculousPro_PucUpgraderStatus_3_2();

		$this->installHooks();
	}

	/**
	 * Create an instance of the scheduler.
	 *
	 * This is implemented as a method to make it possible for plugins to subclass the update checker
	 * and substitute their own scheduler.
	 *
	 * @param int $checkPeriod
	 * @return SoftaculousPro_PucScheduler_3_2
	 */
	protected function createScheduler($checkPeriod) {
		return new SoftaculousPro_PucScheduler_3_2($this, $checkPeriod);
	}
	
	/**
	 * Install the hooks required to run periodic update checks and inject update info 
	 * into WP data structures. 
	 * 
	 * @return void
	 */
	protected function installHooks(){
		//Override requests for plugin information
		add_filter('plugins_api', array($this, 'injectInfo'), 20, 3);
		
		//Insert our update info into the update array maintained by WP.
		add_filter('site_transient_update_plugins', array($this,'injectUpdate')); //WP 3.0+
		add_filter('transient_update_plugins', array($this,'injectUpdate')); //WP 2.8+
		add_filter('site_transient_update_plugins', array($this, 'injectTranslationUpdates'));

		add_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10, 2);
		add_action('admin_init', array($this, 'handleManualCheck'));
		add_action('all_admin_notices', array($this, 'displayManualCheckResult'));

		//Clear the version number cache when something - anything - is upgraded or WP clears the update cache.
		add_filter('upgrader_post_install', array($this, 'clearCachedVersion'));
		add_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion'));
		//Clear translation updates when WP clears the update cache.
		//This needs to be done directly because the library doesn't actually remove obsolete plugin updates,
		//it just hides them (see getUpdate()). We can't do that with translations - too much disk I/O.
		add_action('delete_site_transient_update_plugins', array($this, 'clearCachedTranslationUpdates'));

		if ( did_action('plugins_loaded') ) {
			$this->initDebugBarPanel();
		} else {
			add_action('plugins_loaded', array($this, 'initDebugBarPanel'));
		}

		//Rename the update directory to be the same as the existing directory.
		add_filter('upgrader_source_selection', array($this, 'fixDirectoryName'), 10, 3);

		//Enable language support (i18n).
		load_plugin_textdomain('plugin-update-checker', false, plugin_basename(dirname(__FILE__)) . '/languages');

		//Allow HTTP requests to the metadata URL even if it's on a local host.
		$this->metadataHost = @parse_url($this->metadataUrl, PHP_URL_HOST);
		add_filter('http_request_host_is_external', array($this, 'allowMetadataHost'), 10, 2);
	}
	
	/**
	 * Explicitly allow HTTP requests to the metadata URL.
	 *
	 * WordPress has a security feature where the HTTP API will reject all requests that are sent to
	 * another site hosted on the same server as the current site (IP match), a local host, or a local
	 * IP, unless the host exactly matches the current site.
	 *
	 * This feature is opt-in (at least in WP 4.4). Apparently some people enable it.
	 *
	 * That can be a problem when you're developing your plugin and you decide to host the update information
	 * on the same server as your test site. Update requests will mysteriously fail.
	 *
	 * We fix that by adding an exception for the metadata host.
	 *
	 * @param bool $allow
	 * @param string $host
	 * @return bool
	 */
	public function allowMetadataHost($allow, $host) {
		if ( strtolower($host) === strtolower($this->metadataHost) ) {
			return true;
		}
		return $allow;
	}

	/**
	 * Retrieve plugin info from the configured API endpoint.
	 * 
	 * @uses wp_remote_get()
	 * 
	 * @param array $queryArgs Additional query arguments to append to the request. Optional.
	 * @return SoftaculousProInfo_3_2
	 */
	public function requestInfo($queryArgs = array()){
		//Query args to append to the URL. Plugins can add their own by using a filter callback (see addQueryArgFilter()).
		$installedVersion = $this->getInstalledVersion();
		$queryArgs['installed_version'] = ($installedVersion !== null) ? $installedVersion : '';
		$queryArgs = apply_filters('puc_request_info_query_args-'.$this->slug, $queryArgs);
		
		//Various options for the wp_remote_get() call. Plugins can filter these, too.
		$options = array(
			'timeout' => 10, //seconds
			'headers' => array(
				'Accept' => 'application/json'
			),
		);
		$options = apply_filters('puc_request_info_options-'.$this->slug, $options);
		
		//The plugin info should be at 'http://your-api.com/url/here/$slug/info.json'
		$url = $this->metadataUrl; 
		if ( !empty($queryArgs) ){
			$url = add_query_arg($queryArgs, $url);
		}
		
		$result = wp_remote_get(
			$url,
			$options
		);

		//Try to parse the response
		$status = $this->validateApiResponse($result);
		$pluginInfo = null;
		if ( !is_wp_error($status) ){
			$pluginInfo = SoftaculousProInfo_3_2::fromJson($result['body']);
			if ( $pluginInfo !== null ) {
				$pluginInfo->filename = $this->pluginFile;
				$pluginInfo->slug = $this->slug;
			}
		} else {
			$this->triggerError(
				sprintf('The URL %s does not point to a valid plugin metadata file. ', $url)
					. $status->get_error_message(),
				E_USER_WARNING
			);
		}

		$pluginInfo = apply_filters('puc_request_info_result-'.$this->slug, $pluginInfo, $result);
		return $pluginInfo;
	}

	/**
	 * Check if $result is a successful update API response.
	 *
	 * @param array|WP_Error $result
	 * @return true|WP_Error
	 */
	private function validateApiResponse($result) {
		if ( is_wp_error($result) ) { /** @var WP_Error $result */
			return new WP_Error($result->get_error_code(), 'WP HTTP Error: ' . $result->get_error_message());
		}

		if ( !isset($result['response']['code']) ) {
			return new WP_Error('puc_no_response_code', 'wp_remote_get() returned an unexpected result.');
		}

		if ( $result['response']['code'] !== 200 ) {
			return new WP_Error(
				'puc_unexpected_response_code',
				'HTTP response code is ' . $result['response']['code'] . ' (expected: 200)'
			);
		}

		if ( empty($result['body']) ) {
			return new WP_Error('puc_empty_response', 'The metadata file appears to be empty.');
		}

		return true;
	}

	/**
	 * Retrieve the latest update (if any) from the configured API endpoint.
	 *
	 * @uses SoftaculousProUpdateChecker::requestInfo()
	 *
	 * @return SoftaculousProUpdate_3_2 An instance of SoftaculousProUpdate, or NULL when no updates are available.
	 */
	public function requestUpdate(){
		//For the sake of simplicity, this function just calls requestInfo() 
		//and transforms the result accordingly.
		$pluginInfo = $this->requestInfo(array('checking_for_updates' => '1'));
		if ( $pluginInfo == null ){
			return null;
		}
		$update = SoftaculousProUpdate_3_2::fromSoftaculousProInfo($pluginInfo);

		//Keep only those translation updates that apply to this site.
		$update->translations = $this->filterApplicableTranslations($update->translations);

		return $update;
	}

	/**
	 * Filter a list of translation updates and return a new list that contains only updates
	 * that apply to the current site.
	 *
	 * @param array $translations
	 * @return array
	 */
	private function filterApplicableTranslations($translations) {
		$languages = array_flip(array_values(get_available_languages()));
		$installedTranslations = wp_get_installed_translations('plugins');
		if ( isset($installedTranslations[$this->slug]) ) {
			$installedTranslations = $installedTranslations[$this->slug];
		} else {
			$installedTranslations = array();
		}

		$applicableTranslations = array();
		foreach($translations as $translation) {
			//Does it match one of the available core languages?
			$isApplicable = array_key_exists($translation->language, $languages);
			//Is it more recent than an already-installed translation?
			if ( isset($installedTranslations[$translation->language]) ) {
				$updateTimestamp = strtotime($translation->updated);
				$installedTimestamp = strtotime($installedTranslations[$translation->language]['PO-Revision-Date']);
				$isApplicable = $updateTimestamp > $installedTimestamp;
			}

			if ( $isApplicable ) {
				$applicableTranslations[] = $translation;
			}
		}

		return $applicableTranslations;
	}
	
	/**
	 * Get the currently installed version of the plugin.
	 * 
	 * @return string Version number.
	 */
	public function getInstalledVersion(){
		if ( isset($this->cachedInstalledVersion) ) {
			return $this->cachedInstalledVersion;
		}

		$pluginHeader = $this->getPluginHeader();
		if ( isset($pluginHeader['Version']) ) {
			$this->cachedInstalledVersion = $pluginHeader['Version'];
			return $pluginHeader['Version'];
		} else {
			//This can happen if the filename points to something that is not a plugin.
			$this->triggerError(
				sprintf(
					"Can't to read the Version header for '%s'. The filename is incorrect or is not a plugin.",
					$this->pluginFile
				),
				E_USER_WARNING
			);
			return null;
		}
	}

	/**
	 * Get plugin's metadata from its file header.
	 *
	 * @return array
	 */
	protected function getPluginHeader() {
		if ( !is_file($this->pluginAbsolutePath) ) {
			//This can happen if the plugin filename is wrong.
			$this->triggerError(
				sprintf(
					"Can't to read the plugin header for '%s'. The file does not exist.",
					$this->pluginFile
				),
				E_USER_WARNING
			);
			return array();
		}

		if ( !function_exists('get_plugin_data') ){
			/** @noinspection PhpIncludeInspection */
			require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
		}
		return get_plugin_data($this->pluginAbsolutePath, false, false);
	}

	/**
	 * Check for plugin updates.
	 * The results are stored in the DB option specified in $optionName.
	 *
	 * @return SoftaculousProUpdate_3_2|null
	 */
	public function checkForUpdates(){
		$installedVersion = $this->getInstalledVersion();
		//Fail silently if we can't find the plugin or read its header.
		if ( $installedVersion === null ) {
			$this->triggerError(
				sprintf('Skipping update check for %s - installed version unknown.', $this->pluginFile),
				E_USER_WARNING
			);
			return null;
		}

		$state = $this->getUpdateState();
		if ( empty($state) ){
			$state = new stdClass;
			$state->lastCheck = 0;
			$state->checkedVersion = '';
			$state->update = null;
		}
		
		$state->lastCheck = time();
		$state->checkedVersion = $installedVersion;
		$this->setUpdateState($state); //Save before checking in case something goes wrong 
		
		$state->update = $this->requestUpdate();
		$this->setUpdateState($state);

		return $this->getUpdate();
	}
	
	/**
	 * Load the update checker state from the DB.
	 *  
	 * @return stdClass|null
	 */
	public function getUpdateState() {
		$state = get_site_option($this->optionName, null);
		if ( empty($state) || !is_object($state)) {
			$state = null;
		}

		if ( isset($state, $state->update) && is_object($state->update) ) {
			$state->update = SoftaculousProUpdate_3_2::fromObject($state->update);
		}
		return $state;
	}
	
	
	/**
	 * Persist the update checker state to the DB.
	 * 
	 * @param StdClass $state
	 * @return void
	 */
	private function setUpdateState($state) {
		if ( isset($state->update) && is_object($state->update) && method_exists($state->update, 'toStdClass') ) {
			$update = $state->update; /** @var SoftaculousProUpdate_3_2 $update */
			$state->update = $update->toStdClass();
		}
		update_site_option($this->optionName, $state);
	}

	/**
	 * Reset update checker state - i.e. last check time, cached update data and so on.
	 *
	 * Call this when your plugin is being uninstalled, or if you want to
	 * clear the update cache.
	 */
	public function resetUpdateState() {
		delete_site_option($this->optionName);
	}
	
	/**
	 * Intercept plugins_api() calls that request information about our plugin and 
	 * use the configured API endpoint to satisfy them. 
	 * 
	 * @see plugins_api()
	 * 
	 * @param mixed $result
	 * @param string $action
	 * @param array|object $args
	 * @return mixed
	 */
	public function injectInfo($result, $action = null, $args = null){
    	$relevant = ($action == 'plugin_information') && isset($args->slug) && (
			($args->slug == $this->slug) || ($args->slug == dirname($this->pluginFile))
		);
		if ( !$relevant ) {
			return $result;
		}
		
		$pluginInfo = $this->requestInfo();
		$pluginInfo = apply_filters('puc_pre_inject_info-' . $this->slug, $pluginInfo);
		if ( $pluginInfo ) {
			return $pluginInfo->toWpFormat();
		}
				
		return $result;
	}
	
	/**
	 * Insert the latest update (if any) into the update list maintained by WP.
	 * 
	 * @param StdClass $updates Update list.
	 * @return StdClass Modified update list.
	 */
	public function injectUpdate($updates){
		//Is there an update to insert?
		$update = $this->getUpdate();

		//No update notifications for mu-plugins unless explicitly enabled. The MU plugin file
		//is usually different from the main plugin file so the update wouldn't show up properly anyway.
		if ( $this->isUnknownMuPlugin() ) {
			$update = null;
		}

		if ( !empty($update) ) {
			//Let plugins filter the update info before it's passed on to WordPress.
			$update = apply_filters('puc_pre_inject_update-' . $this->slug, $update);
			$updates = $this->addUpdateToList($updates, $update);
		} else {
			//Clean up any stale update info.
			$updates = $this->removeUpdateFromList($updates);
		}

		return $updates;
	}

	/**
	 * @param StdClass|null $updates
	 * @param SoftaculousProUpdate_3_2 $updateToAdd
	 * @return StdClass
	 */
	private function addUpdateToList($updates, $updateToAdd) {
		if ( !is_object($updates) ) {
			$updates = new stdClass();
			$updates->response = array();
		}

		$wpUpdate = $updateToAdd->toWpFormat();
		$pluginFile = $this->pluginFile;

		if ( $this->isMuPlugin() ) {
			//WP does not support automatic update installation for mu-plugins, but we can still display a notice.
			$wpUpdate->package = null;
			$pluginFile = $this->muPluginFile;
		}
		$updates->response[$pluginFile] = $wpUpdate;
		return $updates;
	}

	/**
	 * @param stdClass|null $updates
	 * @return stdClass|null
	 */
	private function removeUpdateFromList($updates) {
		if ( isset($updates, $updates->response) ) {
			unset($updates->response[$this->pluginFile]);
			if ( !empty($this->muPluginFile) ) {
				unset($updates->response[$this->muPluginFile]);
			}
		}
		return $updates;
	}

	/**
	 * Insert translation updates into the list maintained by WordPress.
	 *
	 * @param stdClass $updates
	 * @return stdClass
	 */
	public function injectTranslationUpdates($updates) {
		$translationUpdates = $this->getTranslationUpdates();
		if ( empty($translationUpdates) ) {
			return $updates;
		}

		//Being defensive.
		if ( !is_object($updates) ) {
			$updates = new stdClass();
		}
		if ( !isset($updates->translations) ) {
			$updates->translations = array();
		}

		//In case there's a name collision with a plugin hosted on wordpress.org,
		//remove any preexisting updates that match our plugin.
		$translationType = 'plugin';
		$filteredTranslations = array();
		foreach($updates->translations as $translation) {
			if ( ($translation['type'] === $translationType) && ($translation['slug'] === $this->slug) ) {
				continue;
			}
			$filteredTranslations[] = $translation;
		}
		$updates->translations = $filteredTranslations;

		//Add our updates to the list.
		foreach($translationUpdates as $update) {
			$convertedUpdate = array_merge(
				array(
					'type' => $translationType,
					'slug' => $this->slug,
					'autoupdate' => 0,
					//AFAICT, WordPress doesn't actually use the "version" field for anything.
					//But lets make sure it's there, just in case.
					'version' => isset($update->version) ? $update->version : ('1.' . strtotime($update->updated)),
				),
				(array)$update
			);

			$updates->translations[] = $convertedUpdate;
		}

		return $updates;
	}

	/**
	 * Rename the update directory to match the existing plugin directory.
	 *
	 * When WordPress installs a plugin or theme update, it assumes that the ZIP file will contain
	 * exactly one directory, and that the directory name will be the same as the directory where
	 * the plugin/theme is currently installed.
	 *
	 * GitHub and other repositories provide ZIP downloads, but they often use directory names like
	 * "project-branch" or "project-tag-hash". We need to change the name to the actual plugin folder.
	 *
	 * This is a hook callback. Don't call it from a plugin.
	 *
	 * @param string $source The directory to copy to /wp-content/plugins. Usually a subdirectory of $remoteSource.
	 * @param string $remoteSource WordPress has extracted the update to this directory.
	 * @param WP_Upgrader $upgrader
	 * @return string|WP_Error
	 */
	public function fixDirectoryName($source, $remoteSource, $upgrader) {
		global $wp_filesystem; /** @var WP_Filesystem_Base $wp_filesystem */

		//Basic sanity checks.
		if ( !isset($source, $remoteSource, $upgrader, $upgrader->skin, $wp_filesystem) ) {
			return $source;
		}

		//If WordPress is upgrading anything other than our plugin, leave the directory name unchanged.
		if ( !$this->isPluginBeingUpgraded($upgrader) ) {
			return $source;
		}

		//Rename the source to match the existing plugin directory.
		$pluginDirectoryName = dirname($this->pluginFile);
		if ( $pluginDirectoryName === '.' ) {
			return $source;
		}
		$correctedSource = trailingslashit($remoteSource) . $pluginDirectoryName . '/';
		if ( $source !== $correctedSource ) {
			//The update archive should contain a single directory that contains the rest of plugin files. Otherwise,
			//WordPress will try to copy the entire working directory ($source == $remoteSource). We can't rename
			//$remoteSource because that would break WordPress code that cleans up temporary files after update.
			if ( $this->isBadDirectoryStructure($remoteSource) ) {
				return new WP_Error(
					'puc-incorrect-directory-structure',
					sprintf(
						'The directory structure of the update is incorrect. All plugin files should be inside ' .
						'a directory named <span class="code">%s</span>, not at the root of the ZIP file.',
						htmlentities($this->slug)
					)
				);
			}

			/** @var WP_Upgrader_Skin $upgrader->skin */
			$upgrader->skin->feedback(sprintf(
				'Renaming %s to %s&#8230;',
				'<span class="code">' . basename($source) . '</span>',
				'<span class="code">' . $pluginDirectoryName . '</span>'
			));

			if ( $wp_filesystem->move($source, $correctedSource, true) ) {
				$upgrader->skin->feedback('Plugin directory successfully renamed.');
				return $correctedSource;
			} else {
				return new WP_Error(
					'puc-rename-failed',
					'Unable to rename the update to match the existing plugin directory.'
				);
			}
		}

		return $source;
	}

	/**
	 * Check for incorrect update directory structure. An update must contain a single directory,
	 * all other files should be inside that directory.
	 *
	 * @param string $remoteSource Directory path.
	 * @return bool
	 */
	private function isBadDirectoryStructure($remoteSource) {
		global $wp_filesystem; /** @var WP_Filesystem_Base $wp_filesystem */

		$sourceFiles = $wp_filesystem->dirlist($remoteSource);
		if ( is_array($sourceFiles) ) {
			$sourceFiles = array_keys($sourceFiles);
			$firstFilePath = trailingslashit($remoteSource) . $sourceFiles[0];
			return (count($sourceFiles) > 1) || (!$wp_filesystem->is_dir($firstFilePath));
		}

		//Assume it's fine.
		return false;
	}

	/**
	 * Is there and update being installed RIGHT NOW, for this specific plugin?
	 *
	 * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
	 * @return bool
	 */
	public function isPluginBeingUpgraded($upgrader = null) {
		return $this->upgraderStatus->isPluginBeingUpgraded($this->pluginFile, $upgrader);
	}

	/**
	 * Get the details of the currently available update, if any.
	 *
	 * If no updates are available, or if the last known update version is below or equal
	 * to the currently installed version, this method will return NULL.
	 *
	 * Uses cached update data. To retrieve update information straight from
	 * the metadata URL, call requestUpdate() instead.
	 *
	 * @return SoftaculousProUpdate_3_2|null
	 */
	public function getUpdate() {
		$state = $this->getUpdateState(); /** @var StdClass $state */

		//Is there an update available?
		if ( isset($state, $state->update) ) {
			$update = $state->update;
			//Check if the update is actually newer than the currently installed version.
			$installedVersion = $this->getInstalledVersion();
			if ( ($installedVersion !== null) && version_compare($update->version, $installedVersion, '>') ){
				$update->filename = $this->pluginFile;
				return $update;
			}
		}
		return null;
	}

	/**
	 * Get a list of available translation updates.
	 *
	 * This method will return an empty array if there are no updates.
	 * Uses cached update data.
	 *
	 * @return array
	 */
	public function getTranslationUpdates() {
		$state = $this->getUpdateState();
		if ( isset($state, $state->update, $state->update->translations) ) {
			return $state->update->translations;
		}
		return array();
	}

	/**
	 * Remove all cached translation updates.
	 *
	 * @see wp_clean_update_cache
	 */
	public function clearCachedTranslationUpdates() {
		$state = $this->getUpdateState();
		if ( isset($state, $state->update, $state->update->translations) ) {
			$state->update->translations = array();
			$this->setUpdateState($state);
		}
	}

	/**
	 * Add a "Check for updates" link to the plugin row in the "Plugins" page. By default,
	 * the new link will appear after the "Visit plugin site" link.
	 *
	 * You can change the link text by using the "puc_manual_check_link-$slug" filter.
	 * Returning an empty string from the filter will disable the link.
	 *
	 * @param array $pluginMeta Array of meta links.
	 * @param string $pluginFile
	 * @return array
	 */
	public function addCheckForUpdatesLink($pluginMeta, $pluginFile) {
		$isRelevant = ($pluginFile == $this->pluginFile)
		              || (!empty($this->muPluginFile) && $pluginFile == $this->muPluginFile);

		if ( $isRelevant && current_user_can('update_plugins') ) {
			$linkUrl = wp_nonce_url(
				add_query_arg(
					array(
						'puc_check_for_updates' => 1,
						'puc_slug' => $this->slug,
					),
					self_admin_url('plugins.php')
				),
				'puc_check_for_updates'
			);

			$linkText = apply_filters('puc_manual_check_link-' . $this->slug, __('Check for updates', 'plugin-update-checker'));
			if ( !empty($linkText) ) {
				$final_link = sprintf('<a href="%s">%s</a>', esc_attr($linkUrl), $linkText);
				$pluginMeta[] = apply_filters('puc_manual_final_check_link-' . $this->slug, $final_link);
			}
		}
		return $pluginMeta;
	}

	/**
	 * Check for updates when the user clicks the "Check for updates" link.
	 * @see self::addCheckForUpdatesLink()
	 *
	 * @return void
	 */
	public function handleManualCheck() {
		$shouldCheck =
			   isset($_GET['puc_check_for_updates'], $_GET['puc_slug'])
			&& $_GET['puc_slug'] == $this->slug
			&& current_user_can('update_plugins')
			&& check_admin_referer('puc_check_for_updates');

		if ( $shouldCheck ) {
			$update = $this->checkForUpdates();
			$status = ($update === null) ? 'no_update' : 'update_available';
			wp_redirect(add_query_arg(
				array(
					'puc_update_check_result' => $status,
					'puc_slug' => $this->slug,
				),
				self_admin_url('plugins.php')
			));
		}
	}

	/**
	 * Display the results of a manual update check.
	 * @see self::handleManualCheck()
	 *
	 * You can change the result message by using the "puc_manual_check_message-$slug" filter.
	 */
	public function displayManualCheckResult() {
		if ( isset($_GET['puc_update_check_result'], $_GET['puc_slug']) && ($_GET['puc_slug'] == $this->slug) ) {
			$status = strval($_GET['puc_update_check_result']);
			if ( $status == 'no_update' ) {
				$message = __('This plugin is up to date.', 'plugin-update-checker');
			} else if ( $status == 'update_available' ) {
				$message = __('A new version of this plugin is available.', 'plugin-update-checker');
			} else {
				$message = sprintf(__('Unknown update checker status "%s"', 'plugin-update-checker'), htmlentities($status));
			}
			printf(
				'<div class="updated notice is-dismissible"><p>%s</p></div>',
				apply_filters('puc_manual_check_message-' . $this->slug, $message, $status)
			);
		}
	}

	/**
	 * Check if the plugin file is inside the mu-plugins directory.
	 *
	 * @return bool
	 */
	protected function isMuPlugin() {
		static $cachedResult = null;

		if ( $cachedResult === null ) {
			//Convert both paths to the canonical form before comparison.
			$muPluginDir = realpath(WPMU_PLUGIN_DIR);
			$pluginPath  = realpath($this->pluginAbsolutePath);
			
			if(!empty($muPluginDir)){
				$cachedResult = (strpos($pluginPath, $muPluginDir) === 0);
			}else{
				$cachedResult = false;
			}
		}

		return $cachedResult;
	}

	/**
	 * MU plugins are partially supported, but only when we know which file in mu-plugins
	 * corresponds to this plugin.
	 *
	 * @return bool
	 */
	protected function isUnknownMuPlugin() {
		return empty($this->muPluginFile) && $this->isMuPlugin();
	}

	/**
	 * Clear the cached plugin version. This method can be set up as a filter (hook) and will
	 * return the filter argument unmodified.
	 *
	 * @param mixed $filterArgument
	 * @return mixed
	 */
	public function clearCachedVersion($filterArgument = null) {
		$this->cachedInstalledVersion = null;
		return $filterArgument;
	}

	/**
	 * Get absolute path to the main plugin file.
	 *
	 * @return string
	 */
	public function getAbsolutePath() {
		return $this->pluginAbsolutePath;
	}

	/**
	 * Register a callback for filtering query arguments. 
	 * 
	 * The callback function should take one argument - an associative array of query arguments.
	 * It should return a modified array of query arguments.
	 * 
	 * @uses add_filter() This method is a convenience wrapper for add_filter().
	 * 
	 * @param callable $callback
	 * @return void
	 */
	public function addQueryArgFilter($callback){
		add_filter('puc_request_info_query_args-'.$this->slug, $callback);
	}
	
	/**
	 * Register a callback for filtering arguments passed to wp_remote_get().
	 * 
	 * The callback function should take one argument - an associative array of arguments -
	 * and return a modified array or arguments. See the WP documentation on wp_remote_get()
	 * for details on what arguments are available and how they work. 
	 * 
	 * @uses add_filter() This method is a convenience wrapper for add_filter().
	 * 
	 * @param callable $callback
	 * @return void
	 */
	public function addHttpRequestArgFilter($callback){
		add_filter('puc_request_info_options-'.$this->slug, $callback);
	}
	
	/**
	 * Register a callback for filtering the plugin info retrieved from the external API.
	 * 
	 * The callback function should take two arguments. If the plugin info was retrieved 
	 * successfully, the first argument passed will be an instance of  SoftaculousProInfo. Otherwise, 
	 * it will be NULL. The second argument will be the corresponding return value of 
	 * wp_remote_get (see WP docs for details).
	 *  
	 * The callback function should return a new or modified instance of SoftaculousProInfo or NULL.
	 * 
	 * @uses add_filter() This method is a convenience wrapper for add_filter().
	 * 
	 * @param callable $callback
	 * @return void
	 */
	public function addResultFilter($callback){
		add_filter('puc_request_info_result-'.$this->slug, $callback, 10, 2);
	}

	/**
	 * Register a callback for one of the update checker filters.
	 *
	 * Identical to add_filter(), except it automatically adds the "puc_" prefix
	 * and the "-$plugin_slug" suffix to the filter name. For example, "request_info_result"
	 * becomes "puc_request_info_result-your_plugin_slug".
	 *
	 * @param string $tag
	 * @param callable $callback
	 * @param int $priority
	 * @param int $acceptedArgs
	 */
	public function addFilter($tag, $callback, $priority = 10, $acceptedArgs = 1) {
		add_filter('puc_' . $tag . '-' . $this->slug, $callback, $priority, $acceptedArgs);
	}

	/**
	 * Initialize the update checker Debug Bar plugin/add-on thingy.
	 */
	public function initDebugBarPanel() {
		$debugBarPlugin = dirname(__FILE__) . '/debug-bar-plugin.php';
		if ( class_exists('Debug_Bar', false) && file_exists($debugBarPlugin) ) {
			/** @noinspection PhpIncludeInspection */
			require_once $debugBarPlugin;
			$this->debugBarPlugin = new SoftaculousPro_PucDebugBarPlugin_3_2($this);
		}
	}

	/**
	 * Trigger a PHP error, but only when $debugMode is enabled.
	 *
	 * @param string $message
	 * @param int $errorType
	 */
	protected function triggerError($message, $errorType) {
		if ( $this->debugMode ) {
			trigger_error($message, $errorType);
		}
	}
}

endif;

if ( !class_exists('SoftaculousProInfo_3_2', false) ):

/**
 * A container class for holding and transforming various plugin metadata.
 * 
 * @author Janis Elsts
 * @copyright 2016
 * @version 3.2
 * @access public
 */
class SoftaculousProInfo_3_2 {
	//Most fields map directly to the contents of the plugin's info.json file.
	//See the relevant docs for a description of their meaning.  
	public $name;
	public $slug;
	public $version;
	public $homepage;
	public $sections = array();
	public $banners;
	public $translations = array();
	public $download_url;

	public $author;
	public $author_homepage;
	
	public $requires;
	public $tested;
	public $upgrade_notice;
	
	public $rating;
	public $num_ratings;
	public $downloaded;
	public $active_installs;
	public $last_updated;
	
	public $id = 0; //The native WP.org API returns numeric plugin IDs, but they're not used for anything.

	public $filename; //Plugin filename relative to the plugins directory.
		
	/**
	 * Create a new instance of SoftaculousProInfo from JSON-encoded plugin info 
	 * returned by an external update API.
	 * 
	 * @param string $json Valid JSON string representing plugin info.
	 * @return SoftaculousProInfo_3_2|null New instance of SoftaculousProInfo, or NULL on error.
	 */
	public static function fromJson($json){
		/** @var StdClass $apiResponse */
		$apiResponse = json_decode($json);
		if ( empty($apiResponse) || !is_object($apiResponse) ){
			trigger_error(
				"Failed to parse plugin metadata. Try validating your .json file with http://jsonlint.com/",
				E_USER_NOTICE
			);
			return null;
		}
		
		$valid = self::validateMetadata($apiResponse);
		if ( is_wp_error($valid) ){
			trigger_error($valid->get_error_message(), E_USER_NOTICE);
			return null;
		}
		
		$info = new self();
		foreach(get_object_vars($apiResponse) as $key => $value){
			$info->$key = $value;
		}

		//json_decode decodes assoc. arrays as objects. We want it as an array.
		$info->sections = (array)$info->sections;
		
		return $info;		
	}

	/**
	 * Very, very basic validation.
	 *
	 * @param StdClass $apiResponse
	 * @return bool|WP_Error
	 */
	protected static function validateMetadata($apiResponse) {
		if (
			!isset($apiResponse->name, $apiResponse->version)
			|| empty($apiResponse->name)
			|| empty($apiResponse->version)
		) {
			return new WP_Error(
				'puc-invalid-metadata',
				"The plugin metadata file does not contain the required 'name' and/or 'version' keys."
			);
		}
		return true;
	}

	
	/**
	 * Transform plugin info into the format used by the native WordPress.org API
	 * 
	 * @return object
	 */
	public function toWpFormat(){
		$info = new stdClass;
		
		//The custom update API is built so that many fields have the same name and format
		//as those returned by the native WordPress.org API. These can be assigned directly. 
		$sameFormat = array(
			'name', 'slug', 'version', 'requires', 'tested', 'rating', 'upgrade_notice',
			'num_ratings', 'downloaded', 'active_installs', 'homepage', 'last_updated',
		);
		foreach($sameFormat as $field){
			if ( isset($this->$field) ) {
				$info->$field = $this->$field;
			} else {
				$info->$field = null;
			}
		}

		//Other fields need to be renamed and/or transformed.
		$info->download_link = $this->download_url;
		$info->author = $this->getFormattedAuthor();
		$info->sections = array_merge(array('description' => ''), $this->sections);

		if ( !empty($this->banners) ) {
			//WP expects an array with two keys: "high" and "low". Both are optional.
			//Docs: https://wordpress.org/plugins/about/faq/#banners
			$info->banners = is_object($this->banners) ? get_object_vars($this->banners) : $this->banners;
			$info->banners = array_intersect_key($info->banners, array('high' => true, 'low' => true));
		}

		return $info;
	}

	protected function getFormattedAuthor() {
		if ( !empty($this->author_homepage) ){
			return sprintf('<a href="%s">%s</a>', $this->author_homepage, $this->author);
		}
		return $this->author;
	}
}
	
endif;

if ( !class_exists('SoftaculousProUpdate_3_2', false) ):

/**
 * A simple container class for holding information about an available update.
 * 
 * @author Janis Elsts
 * @copyright 2016
 * @version 3.2
 * @access public
 */
class SoftaculousProUpdate_3_2 {
	public $id = 0;
	public $slug;
	public $version;
	public $homepage;
	public $download_url;
	public $upgrade_notice;
	public $tested;
	public $translations = array();
	public $filename; //Plugin filename relative to the plugins directory.

	private static $fields = array(
		'id', 'slug', 'version', 'homepage', 'tested',
		'download_url', 'upgrade_notice', 'filename',
		'translations'
	);
	
	/**
	 * Create a new instance of SoftaculousProUpdate from its JSON-encoded representation.
	 * 
	 * @param string $json
	 * @return SoftaculousProUpdate_3_2|null
	 */
	public static function fromJson($json){
		//Since update-related information is simply a subset of the full plugin info,
		//we can parse the update JSON as if it was a plugin info string, then copy over
		//the parts that we care about.
		$pluginInfo = SoftaculousProInfo_3_2::fromJson($json);
		if ( $pluginInfo != null ) {
			return self::fromSoftaculousProInfo($pluginInfo);
		} else {
			return null;
		}
	}

	/**
	 * Create a new instance of SoftaculousProUpdate based on an instance of SoftaculousProInfo.
	 * Basically, this just copies a subset of fields from one object to another.
	 * 
	 * @param SoftaculousProInfo_3_2 $info
	 * @return SoftaculousProUpdate_3_2
	 */
	public static function fromSoftaculousProInfo($info){
		return self::fromObject($info);
	}
	
	/**
	 * Create a new instance of SoftaculousProUpdate by copying the necessary fields from 
	 * another object.
	 *  
	 * @param StdClass|SoftaculousProInfo_3_2|SoftaculousProUpdate_3_2 $object The source object.
	 * @return SoftaculousProUpdate_3_2 The new copy.
	 */
	public static function fromObject($object) {
		$update = new self();
		$fields = self::$fields;
		if ( !empty($object->slug) ) {
			$fields = apply_filters('puc_retain_fields-' . $object->slug, $fields);
		}
		foreach($fields as $field){
			if (property_exists($object, $field)) {
				$update->$field = $object->$field;
			}
		}
		return $update;
	}
	
	/**
	 * Create an instance of StdClass that can later be converted back to 
	 * a SoftaculousProUpdate. Useful for serialization and caching, as it avoids
	 * the "incomplete object" problem if the cached value is loaded before
	 * this class.
	 * 
	 * @return StdClass
	 */
	public function toStdClass() {
		$object = new stdClass();
		$fields = self::$fields;
		if ( !empty($this->slug) ) {
			$fields = apply_filters('puc_retain_fields-' . $this->slug, $fields);
		}
		foreach($fields as $field){
			if (property_exists($this, $field)) {
				$object->$field = $this->$field;
			}
		}
		return $object;
	}
	
	
	/**
	 * Transform the update into the format used by WordPress native plugin API.
	 * 
	 * @return object
	 */
	public function toWpFormat(){
		$update = new stdClass;

		$update->id = $this->id;
		$update->slug = $this->slug;
		$update->new_version = $this->version;
		$update->url = $this->homepage;
		$update->package = $this->download_url;
		$update->tested = $this->tested;
		$update->plugin = $this->filename;

		if ( !empty($this->upgrade_notice) ){
			$update->upgrade_notice = $this->upgrade_notice;
		}
		
		return $update;
	}
}
	
endif;

if ( !class_exists('SoftaculousPro_PucScheduler_3_2', false) ):

/**
 * The scheduler decides when and how often to check for updates.
 * It calls @see SoftaculousProUpdateChecker::checkForUpdates() to perform the actual checks.
 *
 * @version 3.2
 */
class SoftaculousPro_PucScheduler_3_2 {
	public $checkPeriod = 12; //How often to check for updates (in hours).
	public $throttleRedundantChecks = false; //Check less often if we already know that an update is available.
	public $throttledCheckPeriod = 72;

	/**
	 * @var SoftaculousProUpdateChecker_3_2
	 */
	protected $updateChecker;

	private $cronHook = null;

	/**
	 * Scheduler constructor.
	 *
	 * @param SoftaculousProUpdateChecker_3_2 $updateChecker
	 * @param int $checkPeriod How often to check for updates (in hours).
	 */
	public function __construct($updateChecker, $checkPeriod) {
		$this->updateChecker = $updateChecker;
		$this->checkPeriod = $checkPeriod;

		//Set up the periodic update checks
		$this->cronHook = 'check_plugin_updates-' . $this->updateChecker->slug;
		if ( $this->checkPeriod > 0 ){

			//Trigger the check via Cron.
			//Try to use one of the default schedules if possible as it's less likely to conflict
			//with other plugins and their custom schedules.
			$defaultSchedules = array(
				1  => 'hourly',
				12 => 'twicedaily',
				24 => 'daily',
			);
			if ( array_key_exists($this->checkPeriod, $defaultSchedules) ) {
				$scheduleName = $defaultSchedules[$this->checkPeriod];
			} else {
				//Use a custom cron schedule.
				$scheduleName = 'every' . $this->checkPeriod . 'hours';
				add_filter('cron_schedules', array($this, '_addCustomSchedule'));
			}

			if ( !wp_next_scheduled($this->cronHook) && !defined('WP_INSTALLING') ) {
				wp_schedule_event(time(), $scheduleName, $this->cronHook);
			}
			add_action($this->cronHook, array($this, 'maybeCheckForUpdates'));

			register_deactivation_hook($this->updateChecker->pluginFile, array($this, '_removeUpdaterCron'));

			//In case Cron is disabled or unreliable, we also manually trigger
			//the periodic checks while the user is browsing the Dashboard.
			add_action( 'admin_init', array($this, 'maybeCheckForUpdates') );

			//Like WordPress itself, we check more often on certain pages.
			/** @see wp_update_plugins */
			add_action('load-update-core.php', array($this, 'maybeCheckForUpdates'));
			add_action('load-plugins.php', array($this, 'maybeCheckForUpdates'));
			add_action('load-update.php', array($this, 'maybeCheckForUpdates'));
			//This hook fires after a bulk update is complete.
			add_action('upgrader_process_complete', array($this, 'maybeCheckForUpdates'), 11, 0);

		} else {
			//Periodic checks are disabled.
			wp_clear_scheduled_hook($this->cronHook);
		}
	}

	/**
	 * Check for updates if the configured check interval has already elapsed.
	 * Will use a shorter check interval on certain admin pages like "Dashboard -> Updates" or when doing cron.
	 *
	 * You can override the default behaviour by using the "puc_check_now-$slug" filter.
	 * The filter callback will be passed three parameters:
	 *     - Current decision. TRUE = check updates now, FALSE = don't check now.
	 *     - Last check time as a Unix timestamp.
	 *     - Configured check period in hours.
	 * Return TRUE to check for updates immediately, or FALSE to cancel.
	 *
	 * This method is declared public because it's a hook callback. Calling it directly is not recommended.
	 */
	public function maybeCheckForUpdates(){
		if ( empty($this->checkPeriod) ){
			return;
		}

		$state = $this->updateChecker->getUpdateState();
		$shouldCheck =
			empty($state) ||
			!isset($state->lastCheck) ||
			( (time() - $state->lastCheck) >= $this->getEffectiveCheckPeriod() );

		//Let plugin authors substitute their own algorithm.
		$shouldCheck = apply_filters(
			'puc_check_now-' . $this->updateChecker->slug,
			$shouldCheck,
			(!empty($state) && isset($state->lastCheck)) ? $state->lastCheck : 0,
			$this->checkPeriod
		);

		if ( $shouldCheck ) {
			$this->updateChecker->checkForUpdates();
		}
	}

	/**
	 * Calculate the actual check period based on the current status and environment.
	 *
	 * @return int Check period in seconds.
	 */
	protected function getEffectiveCheckPeriod() {
		$currentFilter = current_filter();
		if ( in_array($currentFilter, array('load-update-core.php', 'upgrader_process_complete')) ) {
			//Check more often when the user visits "Dashboard -> Updates" or does a bulk update.
			$period = 60;
		} else if ( in_array($currentFilter, array('load-plugins.php', 'load-update.php')) ) {
			//Also check more often on the "Plugins" page and /wp-admin/update.php.
			$period = 3600;
		} else if ( $this->throttleRedundantChecks && ($this->updateChecker->getUpdate() !== null) ) {
			//Check less frequently if it's already known that an update is available.
			$period = $this->throttledCheckPeriod * 3600;
		} else if ( defined('DOING_CRON') && constant('DOING_CRON') ) {
			//WordPress cron schedules are not exact, so lets do an update check even
			//if slightly less than $checkPeriod hours have elapsed since the last check.
			$cronFuzziness = 20 * 60;
			$period = $this->checkPeriod * 3600 - $cronFuzziness;
		} else {
			$period = $this->checkPeriod * 3600;
		}

		return $period;
	}

	/**
	 * Add our custom schedule to the array of Cron schedules used by WP.
	 *
	 * @param array $schedules
	 * @return array
	 */
	public function _addCustomSchedule($schedules){
		if ( $this->checkPeriod && ($this->checkPeriod > 0) ){
			$scheduleName = 'every' . $this->checkPeriod . 'hours';
			$schedules[$scheduleName] = array(
				'interval' => $this->checkPeriod * 3600,
				'display' => sprintf('Every %d hours', $this->checkPeriod),
			);
		}
		return $schedules;
	}

	/**
	 * Remove the scheduled cron event that the library uses to check for updates.
	 *
	 * @return void
	 */
	public function _removeUpdaterCron(){
		wp_clear_scheduled_hook($this->cronHook);
	}

	/**
	 * Get the name of the update checker's WP-cron hook. Mostly useful for debugging.
	 *
	 * @return string
	 */
	public function getCronHookName() {
		return $this->cronHook;
	}
}

endif;


if ( !class_exists('SoftaculousPro_PucUpgraderStatus_3_2', false) ):

/**
 * A utility class that helps figure out which plugin WordPress is upgrading.
 *
 * It may seem strange to have an separate class just for that, but the task is surprisingly complicated.
 * Core classes like Plugin_Upgrader don't expose the plugin file name during an in-progress update (AFAICT).
 * This class uses a few workarounds and heuristics to get the file name.
 */
class SoftaculousPro_PucUpgraderStatus_3_2 {
	private $upgradedPluginFile = null; //The plugin that is currently being upgraded by WordPress.

	public function __construct() {
		//Keep track of which plugin WordPress is currently upgrading.
		add_filter('upgrader_pre_install', array($this, 'setUpgradedPlugin'), 10, 2);
		add_filter('upgrader_package_options', array($this, 'setUpgradedPluginFromOptions'), 10, 1);
		add_filter('upgrader_post_install', array($this, 'clearUpgradedPlugin'), 10, 1);
		add_action('upgrader_process_complete', array($this, 'clearUpgradedPlugin'), 10, 1);
	}

	/**
	 * Is there and update being installed RIGHT NOW, for a specific plugin?
	 *
	 * Caution: This method is unreliable. WordPress doesn't make it easy to figure out what it is upgrading,
	 * and upgrader implementations are liable to change without notice.
	 *
	 * @param string $pluginFile The plugin to check.
	 * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
	 * @return bool True if the plugin identified by $pluginFile is being upgraded.
	 */
	public function isPluginBeingUpgraded($pluginFile, $upgrader = null) {
		if ( isset($upgrader) ) {
			$upgradedPluginFile = $this->getPluginBeingUpgradedBy($upgrader);
			if ( !empty($upgradedPluginFile) ) {
				$this->upgradedPluginFile = $upgradedPluginFile;
			}
		}
		return ( !empty($this->upgradedPluginFile) && ($this->upgradedPluginFile === $pluginFile) );
	}

	/**
	 * Get the file name of the plugin that's currently being upgraded.
	 *
	 * @param Plugin_Upgrader|WP_Upgrader $upgrader
	 * @return string|null
	 */
	private function getPluginBeingUpgradedBy($upgrader) {
		if ( !isset($upgrader, $upgrader->skin) ) {
			return null;
		}

		//Figure out which plugin is being upgraded.
		$pluginFile = null;
		$skin = $upgrader->skin;
		if ( $skin instanceof Plugin_Upgrader_Skin ) {
			if ( isset($skin->plugin) && is_string($skin->plugin) && ($skin->plugin !== '') ) {
				$pluginFile = $skin->plugin;
			}
		} elseif ( isset($skin->plugin_info) && is_array($skin->plugin_info) ) {
			//This case is tricky because Bulk_Plugin_Upgrader_Skin (etc) doesn't actually store the plugin
			//filename anywhere. Instead, it has the plugin headers in $plugin_info. So the best we can
			//do is compare those headers to the headers of installed plugins.
			$pluginFile = $this->identifyPluginByHeaders($skin->plugin_info);
		}

		return $pluginFile;
	}

	/**
	 * Identify an installed plugin based on its headers.
	 *
	 * @param array $searchHeaders The plugin file header to look for.
	 * @return string|null Plugin basename ("foo/bar.php"), or NULL if we can't identify the plugin.
	 */
	private function identifyPluginByHeaders($searchHeaders) {
		if ( !function_exists('get_plugins') ){
			/** @noinspection PhpIncludeInspection */
			require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
		}

		$installedPlugins = get_plugins();
		$matches = array();
		foreach($installedPlugins as $pluginBasename => $headers) {
			$diff1 = array_diff_assoc($headers, $searchHeaders);
			$diff2 = array_diff_assoc($searchHeaders, $headers);
			if ( empty($diff1) && empty($diff2) ) {
				$matches[] = $pluginBasename;
			}
		}

		//It's possible (though very unlikely) that there could be two plugins with identical
		//headers. In that case, we can't unambiguously identify the plugin that's being upgraded.
		if ( count($matches) !== 1 ) {
			return null;
		}

		return reset($matches);
	}

	/**
	 * @access private
	 *
	 * @param mixed $input
	 * @param array $hookExtra
	 * @return mixed Returns $input unaltered.
	 */
	public function setUpgradedPlugin($input, $hookExtra) {
		if (!empty($hookExtra['plugin']) && is_string($hookExtra['plugin'])) {
			$this->upgradedPluginFile = $hookExtra['plugin'];
		} else {
			$this->upgradedPluginFile = null;
		}
		return $input;
	}

	/**
	 * @access private
	 *
	 * @param array $options
	 * @return array
	 */
	public function setUpgradedPluginFromOptions($options) {
		if (isset($options['hook_extra']['plugin']) && is_string($options['hook_extra']['plugin'])) {
			$this->upgradedPluginFile = $options['hook_extra']['plugin'];
		} else {
			$this->upgradedPluginFile = null;
		}
		return $options;
	}

	/**
	 * @access private
	 *
	 * @param mixed $input
	 * @return mixed Returns $input unaltered.
	 */
	public function clearUpgradedPlugin($input = null) {
		$this->upgradedPluginFile = null;
		return $input;
	}
}

endif;


if ( !class_exists('SoftaculousPro_PucFactory', false) ):

/**
 * A factory that builds instances of other classes from this library.
 *
 * When multiple versions of the same class have been loaded (e.g. SoftaculousProUpdateChecker 1.2
 * and 1.3), this factory will always use the latest available version. Register class
 * versions by calling {@link SoftaculousPro_PucFactory::addVersion()}.
 *
 * At the moment it can only build instances of the SoftaculousProUpdateChecker class. Other classes
 * are intended mainly for internal use and refer directly to specific implementations. If you
 * want to instantiate one of them anyway, you can use {@link SoftaculousPro_PucFactory::getLatestClassVersion()}
 * to get the class name and then create it with <code>new $class(...)</code>.
 */
class SoftaculousPro_PucFactory {
	protected static $classVersions = array();
	protected static $sorted = false;

	/**
	 * Create a new instance of SoftaculousProUpdateChecker.
	 *
	 * @see SoftaculousProUpdateChecker::__construct()
	 *
	 * @param $metadataUrl
	 * @param $pluginFile
	 * @param string $slug
	 * @param int $checkPeriod
	 * @param string $optionName
	 * @param string $muPluginFile
	 * @return SoftaculousProUpdateChecker_3_2
	 */
	public static function buildUpdateChecker($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') {
		$class = self::getLatestClassVersion('SoftaculousProUpdateChecker');
		return new $class($metadataUrl, $pluginFile, $slug, $checkPeriod, $optionName, $muPluginFile);
	}

	/**
	 * Get the specific class name for the latest available version of a class.
	 *
	 * @param string $class
	 * @return string|null
	 */
	public static function getLatestClassVersion($class) {
		if ( !self::$sorted ) {
			self::sortVersions();
		}

		if ( isset(self::$classVersions[$class]) ) {
			return reset(self::$classVersions[$class]);
		} else {
			return null;
		}
	}

	/**
	 * Sort available class versions in descending order (i.e. newest first).
	 */
	protected static function sortVersions() {
		foreach ( self::$classVersions as $class => $versions ) {
			uksort($versions, array(__CLASS__, 'compareVersions'));
			self::$classVersions[$class] = $versions;
		}
		self::$sorted = true;
	}

	protected static function compareVersions($a, $b) {
		return -version_compare($a, $b);
	}

	/**
	 * Register a version of a class.
	 *
	 * @access private This method is only for internal use by the library.
	 *
	 * @param string $generalClass Class name without version numbers, e.g. 'SoftaculousProUpdateChecker'.
	 * @param string $versionedClass Actual class name, e.g. 'SoftaculousProUpdateChecker_1_2'.
	 * @param string $version Version number, e.g. '1.2'.
	 */
	public static function addVersion($generalClass, $versionedClass, $version) {
		if ( !isset(self::$classVersions[$generalClass]) ) {
			self::$classVersions[$generalClass] = array();
		}
		self::$classVersions[$generalClass][$version] = $versionedClass;
		self::$sorted = false;
	}
}

endif;

//Register classes defined in this file with the factory.
SoftaculousPro_PucFactory::addVersion('SoftaculousProUpdateChecker', 'SoftaculousProUpdateChecker_3_2', '3.2');
SoftaculousPro_PucFactory::addVersion('SoftaculousProUpdate', 'SoftaculousProUpdate_3_2', '3.2');
SoftaculousPro_PucFactory::addVersion('SoftaculousProInfo', 'SoftaculousProInfo_3_2', '3.2');
SoftaculousPro_PucFactory::addVersion('SoftaculousPro_PucGitHubChecker', 'SoftaculousPro_PucGitHubChecker_3_2', '3.2');
pquery/gan_parser_html.php000064400000061014151526522240011755 0ustar00<?php
/**
 * @author Niels A.D.
 * @author Todd Burry <todd@vanillaforums.com>
 * @copyright 2010 Niels A.D., 2014 Todd Burry
 * @license http://opensource.org/licenses/LGPL-2.1 LGPL-2.1
 * @package pQuery
 */

namespace pagelayerQuery;

/**
 * Parses a HTML document
 *
 * Functionality can be extended by overriding functions or adjusting the tag map.
 * Document may contain small errors, the parser will try to recover and resume parsing.
 */
class HtmlParserBase extends TokenizerBase {

	/**
	 * Tag open token, used for "<"
	 */
	const TOK_TAG_OPEN = 100;
	/**
	 * Tag close token, used for ">"
	 */
	const TOK_TAG_CLOSE = 101;
	/**
	 * Forward slash token, used for "/"
	 */
	const TOK_SLASH_FORWARD = 103;
	/**
	 * Backslash token, used for "\"
	 */
	const TOK_SLASH_BACKWARD = 104;
	/**
	 * String token, used for attribute values (" and ')
	 */
	const TOK_STRING = 104;
	/**
	 * Equals token, used for "="
	 */
	const TOK_EQUALS = 105;

	/**
	 * Sets HTML identifiers, tags/attributes are considered identifiers
	 * @see TokenizerBase::$identifiers
	 * @access private
	 */
	var $identifiers = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890:-_!?%';

	/**
	 * Status of the parser (tagname, closing tag, etc)
	 * @var array
	 */
	var $status = array();

	/**
	 * Map characters to match their tokens
	 * @see TokenizerBase::$custom_char_map
	 * @access private
	 */
	var $custom_char_map = array(
		'<' => self::TOK_TAG_OPEN,
		'>' => self::TOK_TAG_CLOSE,
		"'" => 'parse_string',
		'"' => 'parse_string',
		'/' => self::TOK_SLASH_FORWARD,
		'\\' => self::TOK_SLASH_BACKWARD,
		'=' => self::TOK_EQUALS
	);

	function __construct($doc = '', $pos = 0) {
		parent::__construct($doc, $pos);
		$this->parse_all();
	}

	#php4 PHP4 class constructor compatibility
	#function HtmlParserBase($doc = '', $pos = 0) {return $this->__construct($doc, $pos);}
	#php4e

	/**
	 Callback functions for certain tags
	 @var array (TAG_NAME => FUNCTION_NAME)
	 @internal Function should be a method in the class
	 @internal Tagname should be lowercase and is everything after <, e.g. "?php" or "!doctype"
	 @access private
	 */
	var $tag_map = array(
		'!doctype' => 'parse_doctype',
		'?' => 'parse_php',
		'?php' => 'parse_php',
		'%' => 'parse_asp',
		'style' => 'parse_style',
		'script' => 'parse_script'
	);

	/**
	 * Parse a HTML string (attributes)
	 * @internal Gets called with ' and "
	 * @return int
	 */
	protected function parse_string() {
		if ($this->next_pos($this->doc[$this->pos], false) !== self::TOK_UNKNOWN) {
			--$this->pos;
		}
		return self::TOK_STRING;
	}

	/**
	 * Parse text between tags
	 * @internal Gets called between tags, uses {@link $status}[last_pos]
	 * @internal Stores text in {@link $status}[text]
	 */
	function parse_text() {
		$len = $this->pos - 1 - $this->status['last_pos'];
		$this->status['text'] = (($len > 0) ? substr($this->doc, $this->status['last_pos'] + 1, $len) : '');
	}

	/**
	 * Parse comment tags
	 * @internal Gets called with HTML comments ("<!--")
	 * @internal Stores text in {@link $status}[comment]
	 * @return bool
	 */
	function parse_comment() {
		$this->pos += 3;
		if ($this->next_pos('-->', false) !== self::TOK_UNKNOWN) {
			$this->status['comment'] = $this->getTokenString(1, -1);
			--$this->pos;
		} else {
			$this->status['comment'] = $this->getTokenString(1, -1);
			$this->pos += 2;
		}
		$this->status['last_pos'] = $this->pos;

		return true;
	}

	/**
	 * Parse doctype tag
	 * @internal Gets called with doctype ("<!doctype")
	 * @internal Stores text in {@link $status}[dtd]
	 * @return bool
	 */
	function parse_doctype() {
		$start = $this->pos;
		if ($this->next_search('[>', false) === self::TOK_UNKNOWN)  {
			if ($this->doc[$this->pos] === '[') {
				if (($this->next_pos(']', false) !== self::TOK_UNKNOWN) || ($this->next_pos('>', false) !== self::TOK_UNKNOWN)) {
					$this->addError('Invalid doctype');
					return false;
				}
			}

			$this->token_start = $start;
			$this->status['dtd'] = $this->getTokenString(2, -1);
			$this->status['last_pos'] = $this->pos;
			return true;
		} else {
			$this->addError('Invalid doctype');
			return false;
		}
	}

	/**
	 * Parse cdata tag
	 * @internal Gets called with cdata ("<![cdata")
	 * @internal Stores text in {@link $status}[cdata]
	 * @return bool
	 */
	function parse_cdata() {
		if ($this->next_pos(']]>', false) === self::TOK_UNKNOWN) {
			$this->status['cdata'] = $this->getTokenString(9, -1);
			$this->status['last_pos'] = $this->pos + 2;
			return true;
		} else {
			$this->addError('Invalid cdata tag');
			return false;
		}
	}

	/**
	 * Parse php tags
	 * @internal Gets called with php tags ("<?php")
	 * @return bool
	 */
	function parse_php() {
		$start = $this->pos;
		if ($this->next_pos('?>', false) !== self::TOK_UNKNOWN) {
			$this->pos -= 2; //End of file
		}

		$len = $this->pos - 1 - $start;
		$this->status['text'] = (($len > 0) ? substr($this->doc, $start + 1, $len) : '');
		$this->status['last_pos'] = ++$this->pos;
		return true;
	}

	/**
	 * Parse asp tags
	 * @internal Gets called with asp tags ("<%")
	 * @return bool
	 */
	function parse_asp() {
		$start = $this->pos;
		if ($this->next_pos('%>', false) !== self::TOK_UNKNOWN) {
			$this->pos -= 2; //End of file
		}

		$len = $this->pos - 1 - $start;
		$this->status['text'] = (($len > 0) ? substr($this->doc, $start + 1, $len) : '');
		$this->status['last_pos'] = ++$this->pos;
		return true;
	}

	/**
	 * Parse style tags
	 * @internal Gets called with php tags ("<style>")
	 * @return bool
	 */
	function parse_style() {
		if ($this->parse_attributes() && ($this->token === self::TOK_TAG_CLOSE) && ($start = $this->pos) && ($this->next_pos('</style>', false) === self::TOK_UNKNOWN)) {
			$len = $this->pos - 1 - $start;
			$this->status['text'] = (($len > 0) ? substr($this->doc, $start + 1, $len) : '');

			$this->pos += 7;
			$this->status['last_pos'] = $this->pos;
			return true;
		} else {
			$this->addError('No end for style tag found');
			return false;
		}
	}

	/**
	 * Parse script tags
	 * @internal Gets called with php tags ("<script>")
	 * @return bool
	 */
	function parse_script() {
		if ($this->parse_attributes() && ($this->token === self::TOK_TAG_CLOSE) && ($start = $this->pos) && ($this->next_pos('</script>', false) === self::TOK_UNKNOWN)) {
			$len = $this->pos - 1 - $start;
			$this->status['text'] = (($len > 0) ? substr($this->doc, $start + 1, $len) : '');

			$this->pos += 8;
			$this->status['last_pos'] = $this->pos;
			return true;
		} else {
			$this->addError('No end for script tag found');
			return false;
		}
	}

	/**
	 * Parse conditional tags (+ all conditional tags inside)
	 * @internal Gets called with IE conditionals ("<![if]" and "<!--[if]")
	 * @internal Stores condition in {@link $status}[tag_condition]
	 * @return bool
	 */
	function parse_conditional() {
		if ($this->status['closing_tag']) {
			$this->pos += 8;
		} else {
			$this->pos += (($this->status['comment']) ? 5 : 3);
			if ($this->next_pos(']', false) !== self::TOK_UNKNOWN) {
				$this->addError('"]" not found in conditional tag');
				return false;
			}
			$this->status['tag_condition'] = $this->getTokenString(0, -1);
		}

		if ($this->next_no_whitespace() !== self::TOK_TAG_CLOSE) {
			$this->addError('No ">" tag found 2 for conditional tag');
			return false;
		}

		if ($this->status['comment']) {
			$this->status['last_pos'] = $this->pos;
			if ($this->next_pos('-->', false) !== self::TOK_UNKNOWN) {
				$this->addError('No ending tag found for conditional tag');
				$this->pos = $this->size - 1;

				$len = $this->pos - 1 - $this->status['last_pos'];
				$this->status['text'] = (($len > 0) ? substr($this->doc, $this->status['last_pos'] + 1, $len) : '');
			} else {
				$len = $this->pos - 10 - $this->status['last_pos'];
				$this->status['text'] = (($len > 0) ? substr($this->doc, $this->status['last_pos'] + 1, $len) : '');
				$this->pos += 2;
			}
		}

		$this->status['last_pos'] = $this->pos;
		return true;
	}

	/**
	 * Parse attributes (names + value)
	 * @internal Stores attributes in {@link $status}[attributes] (array(ATTR => VAL))
	 * @return bool
	 */
	function parse_attributes() {
		$this->status['attributes'] = array();

		while ($this->next_no_whitespace() === self::TOK_IDENTIFIER) {
			$attr = $this->getTokenString();
			if (($attr === '?') || ($attr === '%')) {
				//Probably closing tags
				break;
			}

			if ($this->next_no_whitespace() === self::TOK_EQUALS) {
				if ($this->next_no_whitespace() === self::TOK_STRING) {
					$val = $this->getTokenString(1, -1);
				} else {
					$this->token_start = $this->pos;
					if (!isset($stop)) {
						$stop = $this->whitespace;
						$stop['<'] = true;
						$stop['>'] = true;
					}

					while ((++$this->pos < $this->size) && (!isset($stop[$this->doc[$this->pos]]))) {
						// Do nothing.
					}
					--$this->pos;

					$val = $this->getTokenString();

					if (trim($val) === '') {
						$this->addError('Invalid attribute value');
						return false;
					}
				}
			} else {
				$val = $attr;
				$this->pos = (($this->token_start) ? $this->token_start : $this->pos) - 1;
			}

			$this->status['attributes'][$attr] = $val;
		}

		return true;
	}

	/**
	 * Default callback for tags
	 * @internal Gets called after the tagname (<html*ENTERS_HERE* attribute="value">)
	 * @return bool
	 */
	function parse_tag_default() {
		if ($this->status['closing_tag']) {
			$this->status['attributes'] = array();
			$this->next_no_whitespace();
		} else {
			if (!$this->parse_attributes()) {
				return false;
			}
		}

		if ($this->token !== self::TOK_TAG_CLOSE) {
			if ($this->token === self::TOK_SLASH_FORWARD) {
				$this->status['self_close'] = true;
				$this->next();
			} elseif ((($this->status['tag_name'][0] === '?') && ($this->doc[$this->pos] === '?')) || (($this->status['tag_name'][0] === '%') && ($this->doc[$this->pos] === '%'))) {
				$this->status['self_close'] = true;
				$this->pos++;

				if (isset($this->char_map[$this->doc[$this->pos]]) && (!is_string($this->char_map[$this->doc[$this->pos]]))) {
					$this->token = $this->char_map[$this->doc[$this->pos]];
				} else {
					$this->token = self::TOK_UNKNOWN;
				}
			}/* else {
				$this->status['self_close'] = false;
			}*/
		}

		if ($this->token !== self::TOK_TAG_CLOSE) {
			$this->addError('Expected ">", but found "'.$this->getTokenString().'"');
			if ($this->next_pos('>', false) !== self::TOK_UNKNOWN) {
				$this->addError('No ">" tag found for "'.$this->status['tag_name'].'" tag');
				return false;
			}
		}

		return true;
	}

	/**
	 * Parse tag
	 * @internal Gets called after opening tag (<*ENTERS_HERE*html attribute="value">)
	 * @internal Stores information about the tag in {@link $status} (comment, closing_tag, tag_name)
	 * @return bool
	 */
	function parse_tag() {
		$start = $this->pos;
		$this->status['self_close'] = false;
		$this->parse_text();

		$next = (($this->pos + 1) < $this->size) ? $this->doc[$this->pos + 1] : '';
		if ($next === '!') {
			$this->status['closing_tag'] = false;

			if (substr($this->doc, $this->pos + 2, 2) === '--') {
				$this->status['comment'] = true;

				if (($this->doc[$this->pos + 4] === '[') && (strcasecmp(substr($this->doc, $this->pos + 5, 2), 'if') === 0)) {
					return $this->parse_comment();
				} else {
					return $this->parse_comment();
				}
			} else {
				$this->status['comment'] = false;

				if ($this->doc[$this->pos + 2] === '[') {
					if (strcasecmp(substr($this->doc, $this->pos + 3, 2), 'if') === 0) {
						return $this->parse_conditional();
					} elseif (strcasecmp(substr($this->doc, $this->pos + 3, 5), 'endif') === 0) {
						$this->status['closing_tag'] = true;
						return $this->parse_conditional();
					} elseif (strcasecmp(substr($this->doc, $this->pos + 3, 5), 'cdata') === 0) {
						return $this->parse_cdata();
					}
				}
			}
		} elseif ($next === '/') {
			$this->status['closing_tag'] = true;
			++$this->pos;
		} else {
			$this->status['closing_tag'] = false;
		}

		if ($this->next() !== self::TOK_IDENTIFIER) {
			$this->addError('Tagname expected');
			//if ($this->next_pos('>', false) === self::TOK_UNKNOWN) {
				$this->status['last_pos'] = $start - 1;
				return true;
			//} else {
			//	return false;
			//}
		}

		$tag = $this->getTokenString();
		$this->status['tag_name'] = $tag;
		$tag = strtolower($tag);

		if (isset($this->tag_map[$tag])) {
			$res = $this->{$this->tag_map[$tag]}();
		} else {
			$res = $this->parse_tag_default();
		}

		$this->status['last_pos'] = $this->pos;
		return $res;
	}

	/**
	 * Parse full document
	 * @return bool
	 */
	function parse_all() {
		$this->errors = array();
		$this->status['last_pos'] = -1;

		if (($this->token === self::TOK_TAG_OPEN) || ($this->next_pos('<', false) === self::TOK_UNKNOWN)) {
			do {
				if (!$this->parse_tag()) {
					return false;
				}
			} while ($this->next_pos('<') !== self::TOK_NULL);
		}

		$this->pos = $this->size;
		$this->parse_text();

		return true;
	}
}

/**
 * Parses a HTML document into a HTML DOM
 */
class HtmlParser extends HtmlParserBase {

	/**
	 * Root object
	 * @internal If string, then it will create a new instance as root
	 * @var DomNode
	 */
	var $root = 'pagelayerQuery\\DomNode';

	/**
	 * Current parsing hierarchy
	 * @internal Root is always at index 0, current tag is at the end of the array
	 * @var array
	 * @access private
	 */
	var $hierarchy = array();

	/**
	 * Tags that don't need closing tags
	 * @var array
	 * @access private
	 */
	var	$tags_selfclose = array(
		'area'		=> true,
		'base'		=> true,
		'basefont'	=> true,
		'br'		=> true,
		'col'		=> true,
		'command'	=> true,
		'embed'		=> true,
		'frame'		=> true,
		'hr'		=> true,
		'img'		=> true,
		'input'		=> true,
		'ins'		=> true,
		'keygen'	=> true,
		'link'		=> true,
		'meta'		=> true,
		'param'		=> true,
		'source'	=> true,
		'track'		=> true,
		'wbr'		=> true
	);

	/**
	 * Class constructor
	 * @param string $doc Document to be tokenized
	 * @param int $pos Position to start parsing
	 * @param DomNode $root Root node, null to auto create
	 */
	function __construct($doc = '', $pos = 0, $root = null) {
		if ($root === null) {
			$root = new $this->root('~root~', null);
		}
		$this->root =& $root;

		parent::__construct($doc, $pos);
	}

	#php4 PHP4 class constructor compatibility
	#function HtmlParser($doc = '', $pos = 0, $root = null) {return $this->__construct($doc, $pos, $root);}
	#php4e

	/**
	 * Class magic invoke method, performs {@link select()}
	 * @return array
	 * @access private
	 */
	function __invoke($query = '*') {
		return $this->select($query);
	}

	/**
	 * Class magic toString method, performs {@link DomNode::toString()}
	 * @return string
	 * @access private
	 */
	function __toString() {
		return $this->root->getInnerText();
	}

	/**
	 * Performs a css select query on the root node
	 * @see DomNode::select()
	 * @return array
	 */
	function select($query = '*', $index = false, $recursive = true, $check_self = false) {
		return $this->root->select($query, $index, $recursive, $check_self);
	}

	/**
	 * Updates the current hierarchy status and checks for
	 * correct opening/closing of tags
	 * @param bool $self_close Is current tag self closing? Null to use {@link tags_selfclose}
	 * @internal This is were most of the nodes get added
	 * @access private
	 */
	protected function parse_hierarchy($self_close = null) {
		if ($self_close === null) {
			$this->status['self_close'] = ($self_close = isset($this->tags_selfclose[strtolower($this->status['tag_name'])]));
		}

		if ($self_close) {
			if ($this->status['closing_tag']) {

				//$c = end($this->hierarchy)->children
				$c = $this->hierarchy[count($this->hierarchy) - 1]->children;
				$found = false;
				for ($count = count($c), $i = $count - 1; $i >= 0; $i--) {
					if (strcasecmp($c[$i]->tag, $this->status['tag_name']) === 0) {
						for($ii = $i + 1; $ii < $count; $ii++) {
							$index = null; //Needs to be passed by ref
							$c[$i + 1]->changeParent($c[$i], $index);
						}
						$c[$i]->self_close = false;

						$found = true;
						break;
					}
				}

				if (!$found) {
					$this->addError('Closing tag "'.$this->status['tag_name'].'" which is not open');
				}

			} elseif ($this->status['tag_name'][0] === '?') {
				//end($this->hierarchy)->addXML($this->status['tag_name'], '', $this->status['attributes']);
				$index = null; //Needs to be passed by ref
				$this->hierarchy[count($this->hierarchy) - 1]->addXML($this->status['tag_name'], '', $this->status['attributes'], $index);
			} elseif ($this->status['tag_name'][0] === '%') {
				//end($this->hierarchy)->addASP($this->status['tag_name'], '', $this->status['attributes']);
				$index = null; //Needs to be passed by ref
				$this->hierarchy[count($this->hierarchy) - 1]->addASP($this->status['tag_name'], '', $this->status['attributes'], $index);
			} else {
				//end($this->hierarchy)->addChild($this->status);
				$index = null; //Needs to be passed by ref
				$this->hierarchy[count($this->hierarchy) - 1]->addChild($this->status, $index);
			}
		} elseif ($this->status['closing_tag']) {
			$found = false;
			for ($count = count($this->hierarchy), $i = $count - 1; $i >= 0; $i--) {
				if (strcasecmp($this->hierarchy[$i]->tag, $this->status['tag_name']) === 0) {

					for($ii = ($count - $i - 1); $ii >= 0; $ii--) {
						$e = array_pop($this->hierarchy);
						if ($ii > 0) {
							$this->addError('Closing tag "'.$this->status['tag_name'].'" while "'.$e->tag.'" is not closed yet');
						}
					}

					$found = true;
					break;
				}
			}

			if (!$found) {
				$this->addError('Closing tag "'.$this->status['tag_name'].'" which is not open');
			}

		} else {
			//$this->hierarchy[] = end($this->hierarchy)->addChild($this->status);
			$index = null; //Needs to be passed by ref
			$this->hierarchy[] = $this->hierarchy[count($this->hierarchy) - 1]->addChild($this->status, $index);
		}
	}

	function parse_cdata() {
		if (!parent::parse_cdata()) {return false;}

		//end($this->hierarchy)->addCDATA($this->status['cdata']);
		$index = null; //Needs to be passed by ref
		$this->hierarchy[count($this->hierarchy) - 1]->addCDATA($this->status['cdata'], $index);
		return true;
	}

	function parse_comment() {
		if (!parent::parse_comment()) {return false;}

		//end($this->hierarchy)->addComment($this->status['comment']);
		$index = null; //Needs to be passed by ref
		$this->hierarchy[count($this->hierarchy) - 1]->addComment($this->status['comment'], $index);
		return true;
	}

	function parse_conditional() {
		if (!parent::parse_conditional()) {return false;}

		if ($this->status['comment']) {
			//$e = end($this->hierarchy)->addConditional($this->status['tag_condition'], true);
			$index = null; //Needs to be passed by ref
			$e = $this->hierarchy[count($this->hierarchy) - 1]->addConditional($this->status['tag_condition'], true, $index);
			if ($this->status['text'] !== '') {
				$index = null; //Needs to be passed by ref
				$e->addText($this->status['text'], $index);
			}
		} else {
			if ($this->status['closing_tag']) {
				$this->parse_hierarchy(false);
			} else {
				//$this->hierarchy[] = end($this->hierarchy)->addConditional($this->status['tag_condition'], false);
				$index = null; //Needs to be passed by ref
				$this->hierarchy[] = $this->hierarchy[count($this->hierarchy) - 1]->addConditional($this->status['tag_condition'], false, $index);
			}
		}

		return true;
	}

	function parse_doctype() {
		if (!parent::parse_doctype()) {return false;}

		//end($this->hierarchy)->addDoctype($this->status['dtd']);
		$index = null; //Needs to be passed by ref
		$this->hierarchy[count($this->hierarchy) - 1]->addDoctype($this->status['dtd'], $index);
		return true;
	}

	function parse_php() {
		if (!parent::parse_php()) {return false;}

		//end($this->hierarchy)->addXML('php', $this->status['text']);
		$index = null; //Needs to be passed by ref
		$this->hierarchy[count($this->hierarchy) - 1]->addXML('php', $this->status['text'], $index);
		return true;
	}

	function parse_asp() {
		if (!parent::parse_asp()) {return false;}

		//end($this->hierarchy)->addASP('', $this->status['text']);
		$index = null; //Needs to be passed by ref
		$this->hierarchy[count($this->hierarchy) - 1]->addASP('', $this->status['text'], $index);
		return true;
	}

	function parse_script() {
		if (!parent::parse_script()) {return false;}

		//$e = end($this->hierarchy)->addChild($this->status);
		$index = null; //Needs to be passed by ref
		$e = $this->hierarchy[count($this->hierarchy) - 1]->addChild($this->status, $index);
		if ($this->status['text'] !== '') {
			$index = null; //Needs to be passed by ref
			$e->addText($this->status['text'], $index);
		}
		return true;
	}

	function parse_style() {
		if (!parent::parse_style()) {return false;}

		//$e = end($this->hierarchy)->addChild($this->status);
		$index = null; //Needs to be passed by ref
		$e = $this->hierarchy[count($this->hierarchy) - 1]->addChild($this->status, $index);
		if ($this->status['text'] !== '') {
			$index = null; //Needs to be passed by ref
			$e->addText($this->status['text'], $index);
		}
		return true;
	}

	function parse_tag_default() {
		if (!parent::parse_tag_default()) {return false;}

		$this->parse_hierarchy(($this->status['self_close']) ? true : null);
		return true;
	}

	function parse_text() {
		parent::parse_text();
		if ($this->status['text'] !== '') {
			//end($this->hierarchy)->addText($this->status['text']);
			$index = null; //Needs to be passed by ref
			$this->hierarchy[count($this->hierarchy) - 1]->addText($this->status['text'], $index);
		}
	}

	function parse_all() {
		$this->hierarchy = array(&$this->root);
		return ((parent::parse_all()) ? $this->root : false);
	}
}

/**
 * HTML5 specific parser (adds support for omittable closing tags)
 */
class Html5Parser extends HtmlParser {

	/**
	 * Tags with ommitable closing tags
	 * @var array array('tag2' => 'tag1') will close tag1 if following (not child) tag is tag2
	 * @access private
	 */
	var $tags_optional_close = array(
		//Current tag	=> Previous tag
		'li' 			=> array('li' => true),
		'dt' 			=> array('dt' => true, 'dd' => true),
		'dd' 			=> array('dt' => true, 'dd' => true),
		'address' 		=> array('p' => true),
		'article' 		=> array('p' => true),
		'aside' 		=> array('p' => true),
		'blockquote' 	=> array('p' => true),
		'dir' 			=> array('p' => true),
		'div' 			=> array('p' => true),
		'dl' 			=> array('p' => true),
		'fieldset' 		=> array('p' => true),
		'footer' 		=> array('p' => true),
		'form' 			=> array('p' => true),
		'h1' 			=> array('p' => true),
		'h2' 			=> array('p' => true),
		'h3' 			=> array('p' => true),
		'h4' 			=> array('p' => true),
		'h5' 			=> array('p' => true),
		'h6' 			=> array('p' => true),
		'header' 		=> array('p' => true),
		'hgroup' 		=> array('p' => true),
		'hr' 			=> array('p' => true),
		'menu' 			=> array('p' => true),
		'nav' 			=> array('p' => true),
		'ol' 			=> array('p' => true),
		'p' 			=> array('p' => true),
		'pre' 			=> array('p' => true),
		'section' 		=> array('p' => true),
		'table' 		=> array('p' => true),
		'ul' 			=> array('p' => true),
		'rt'			=> array('rt' => true, 'rp' => true),
		'rp'			=> array('rt' => true, 'rp' => true),
		'optgroup'		=> array('optgroup' => true, 'option' => true),
		'option'		=> array('option'),
		'tbody'			=> array('thread' => true, 'tbody' => true, 'tfoot' => true),
		'tfoot'			=> array('thread' => true, 'tbody' => true),
		'tr'			=> array('tr' => true),
		'td'			=> array('td' => true, 'th' => true),
		'th'			=> array('td' => true, 'th' => true),
		'body'			=> array('head' => true)
	);

	protected function parse_hierarchy($self_close = null) {
		$tag_curr = strtolower($this->status['tag_name']);
		if ($self_close === null) {
			$this->status['self_close'] = ($self_close = isset($this->tags_selfclose[$tag_curr]));
		}

		if (! ($self_close || $this->status['closing_tag'])) {
			//$tag_prev = strtolower(end($this->hierarchy)->tag);
			$tag_prev = strtolower($this->hierarchy[count($this->hierarchy) - 1]->tag);
			if (isset($this->tags_optional_close[$tag_curr]) && isset($this->tags_optional_close[$tag_curr][$tag_prev])) {
				array_pop($this->hierarchy);
			}
		}

		return parent::parse_hierarchy($self_close);
	}
}

?>pquery/IQuery.php000064400000012430151526522360010027 0ustar00<?php

namespace pagelayerQuery;

interface IQuery extends \Countable {
   /// Methods ///

   /**
    * Adds the specified class(es) to each of the set of matched elements.
    * @param string $classname The name of the class to add. You can add multiple classes by separating them with spaces.
    * @return IQuery
    */
   function addClass($classname);

   /**
    * Insert content, specified by the parameter, after each element in the set of matched elements.
    * @param string $content The content to add.
    * @return IQuery
    */
   function after($content);

   /**
    * Insert content, specified by the parameter, to the end of each element in the set of matched elements.
    * @param string $content The content to append.
    * @return IQuery
    */
   function append($content);

   /**
    * Get the value of an attribute for the first element in the set of matched elements or set one
    * or more attributes for every matched element.
    * @param string $name The name of the attribute.
    * @param null|string $value The value to set or null to get the current attribute value.
    * @return string|IQuery
    */
   function attr($name, $value = null);

   /**
    * Insert content, specified by the parameter, before each element in the set of matched elements.
    * @param string $content The content to add.
    * @return IQuery
    */
   function before($content);

   /**
    * Remove all child nodes of the set of matched elements from the DOM.
    * @return IQuery;
    */
   function clear();

   /**
    * Get the value of a style property for the first element in the set of matched elements or
    * set one or more CSS properties for every matched element.
    */
//   function css($name, $value = null);

   /**
    * Determine whether any of the matched elements are assigned the given class.
    * @param string $classname The name of the class to check.
    */
   function hasClass($classname);

   /**
    * Get the HTML contents of the first element in the set of matched elements
    * or set the HTML contents of every matched element.
    * @param string|null $value The value to set.
    */
   function html($value = null);

   /**
    * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
    * @param string $content The content to add.
    */
   function prepend($content);

   /**
    * Get the value of a property for the first element in the set of matched elements
    * or set one or more properties for every matched element.
    * @param string $name The name of the property.
    * The currently supported properties are `tagname`, `selected`, and `checked`.
    * @param null|string $value The value to set or null to get the current property value.
    */
   function prop($name, $value = null);

   /**
    * Remove the set of matched elements from the DOM.
    * @param null|string $selector A css query to filter the set of removed nodes.
    */
   function remove($selector = null);

   /**
    * Remove an attribute from each element in the set of matched elements.
    * @param string $name The name of the attribute to remove.
    */
   function removeAttr($name);

   /**
    * Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
    * @param string $classname The name of the class to remove.
    */
   function removeClass($classname);

   /**
    * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.
    * @param string $content The content that will replace the nodes.
    */
   function replaceWith($content);

   /**
    * Returns the name of the element.
    * @param null|string $tagName A new tag name or null to return the current tag name.
    */
   function tagName($value = null);

   /**
    * Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.
    * @param null|string $value A string to set the text or null to return the current text.
    */
   function text($value = null);

   /**
    * Add or remove one or more classes from each element in the set of matched elements,
    * depending on either the class’s presence or the value of the switch argument.
    * @param string $classname
    * @param bool|null
    */
   function toggleClass($classname, $switch = null);

   /**
    * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.
    */
   function unwrap();

   /**
    * Get the current value of the first element in the set of matched elements or set the value of every matched element.
    * @param string|null $value The new value of the element or null to return the current value.
    */
   function val($value = null);

   /**
    * Wrap an HTML structure around each element in the set of matched elements.
    * @param string A tag name or html string specifying the structure to wrap around the matched elements.
    */
   function wrap($wrapping_element);

   /**
    * Wrap an HTML structure around the content of each element in the set of matched elements.
    * @param string A tag name or html string specifying the structure to wrap around the content of the matched elements.
    */
   function wrapInner($wrapping_element);
}

pquery/gan_xml2array.php000064400000004745151526522430011367 0ustar00<?php
/**
 * @author Niels A.D.
 * @author Todd Burry <todd@vanillaforums.com>
 * @copyright 2010 Niels A.D., 2014 Todd Burry
 * @license http://opensource.org/licenses/LGPL-2.1 LGPL-2.1
 * @package pQuery
 */

namespace pagelayerQuery;

/**
 * Converts a XML document to an array
 */
class XML2ArrayParser extends HtmlParserBase {

	/**
	 * Holds the document structure
	 * @var array array('name' => 'tag', 'attrs' => array('attr' => 'val'), 'childen' => array())
	 */
	var $root = array(
		'name' => '',
		'attrs' => array(),
		'children' => array()
	);

	/**
	 * Current parsing hierarchy
	 * @var array
	 * @access private
	 */
	var $hierarchy = array();

	protected function parse_hierarchy($self_close) {
		if ($this->status['closing_tag']) {
			$found = false;
			for ($count = count($this->hierarchy), $i = $count - 1; $i >= 0; $i--) {
				if (strcasecmp($this->hierarchy[$i]['name'], $this->status['tag_name']) === 0) {

					for($ii = ($count - $i - 1); $ii >= 0; $ii--) {
						$e = array_pop($this->hierarchy);
						if ($ii > 0) {
							$this->addError('Closing tag "'.$this->status['tag_name'].'" while "'.$e['name'].'" is not closed yet');
						}
					}

					$found = true;
					break;
				}
			}

			if (!$found) {
				$this->addError('Closing tag "'.$this->status['tag_name'].'" which is not open');
			}
		} else {
			$tag = array(
				'name' => $this->status['tag_name'],
				'attrs' => $this->status['attributes'],
				'children' => array()
			);
			if ($this->hierarchy) {
				$current =& $this->hierarchy[count($this->hierarchy) - 1];
				$current['children'][] = $tag;
				$tag =& $current['children'][count($current['children']) - 1];
				unset($current['tagData']);
			} else {
				$this->root = $tag;
				$tag =& $this->root;
				$self_close = false;
			}
			if (!$self_close) {
				$this->hierarchy[] =& $tag;
			}
		}
	}

	function parse_tag_default() {
		if (!parent::parse_tag_default()) {return false;}

		if ($this->status['tag_name'][0] !== '?') {
			$this->parse_hierarchy(($this->status['self_close']) ? true : null);
		}
		return true;
	}

	function parse_text() {
		parent::parse_text();
		if (($this->status['text'] !== '') && $this->hierarchy) {
			$current =& $this->hierarchy[count($this->hierarchy) - 1];
			if (!$current['children']) {
				$current['tagData'] = $this->status['text'];
			}
		}
	}

	function parse_all() {
		return ((parent::parse_all()) ? $this->root : false);
	}
}

?>pquery/pQuery.php000064400000016435151526522430010105 0ustar00<?php
/**
 * @author Niels A.D.
 * @author Todd Burry <todd@vanillaforums.com>
 * @copyright 2010 Niels A.D., 2014 Todd Burry
 * @license http://opensource.org/licenses/LGPL-2.1 LGPL-2.1
 * @package pQuery
 */

use pagelayerQuery\IQuery;

/**
 * A jQuery-like object for php.
 */
class pagelayerQuery implements ArrayAccess, IteratorAggregate, IQuery {
    /// Properties ///

    /**
     * @var IQuery[]
     */
    protected $nodes = array();

    /// Methods ///

    public function __construct($nodes = array()) {
        $this->nodes = $nodes;
    }

    public function addClass($classname) {
        foreach ($this->nodes as $node) {
            $node->addClass($classname);
        }
        return $this;
    }

    public function after($content) {
        foreach ($this->nodes as $node) {
            $node->after($content);
        }
        return $this;
    }

    public function append($content) {
        foreach ($this->nodes as $node) {
            $node->append($content);
        }
        return $this;
    }

    public function attr($name, $value = null) {
        if (empty($this->nodes) && $value === null)
            return '';

        foreach ($this->nodes as $node) {
            if ($value === null)
                return $node->attr($name);
            $value = str_replace('<', '&lt;', $value);
            $value = str_replace('>', '&gt;', $value);
            $node->attr($name, $value);
        }
        return $this;
    }

    public function before($content) {
        foreach ($this->nodes as $node) {
            $node->before($content);
        }
        return $this;
    }

    public function clear() {
        foreach ($this->nodes as $node) {
            $node->clear();
        }
        return $this;
    }

    /**
     * Get the count of matched elements.
     *
     * @return int Returns the count of matched elements.
     */
     
    #[\ReturnTypeWillChange]
    public function count() {
        return count($this->nodes);
    }

    /**
     * Format/beautify a DOM.
     *
     * @param pagelayerQuery\DomNode $dom The dom to format.
     * @param array $options Extra formatting options. See {@link pagelayerQuery\HtmlFormatter::$options}.
     * @return bool Returns `true` on sucess and `false` on failure.
     */
//    public static function format($dom, $options = array()) {
//        $formatter = new pagelayerQuery\HtmlFormatter($options);
//        return $formatter->format($dom);
//    }

    #[\ReturnTypeWillChange]
    public function getIterator() {
        return new ArrayIterator($this->nodes);
    }

    public function hasClass($classname) {
        foreach ($this->nodes as $node) {
            if ($node->hasClass($classname))
                return true;
        }
        return false;
    }

    public function html($value = null) {
        if (empty($this->nodes) && $value === null)
            return '';

        foreach ($this->nodes as $node) {
            if ($value === null)
                return $node->html();
            $node->html($value);
        }
        return $this;
    }
    
    #[\ReturnTypeWillChange]
    public function offsetExists($offset){
        return isset($this->nodes[$offset]);
    }
	
    #[\ReturnTypeWillChange]
    public function offsetGet($offset) {
        return isset($this->nodes[$offset]) ? $this->nodes[$offset] : null;
    }
	
    #[\ReturnTypeWillChange]
    public function offsetSet($offset, $value) {

        if (is_null($offset) || !isset($this->nodes[$offset])) {
            throw new \BadMethodCallException("You are not allowed to add new nodes to the pQuery object.");
        } else {
            $this->nodes[$offset]->replaceWith($value);
        }
    }
	
    #[\ReturnTypeWillChange]
    public function offsetUnset($offset) {
        if (isset($this->nodes[$offset])) {
            $this->nodes[$offset]->remove();
            unset($this->nodes[$offset]);
        }
    }

    /**
     * Query a file or url.
     *
     * @param string $path The path to the url.
     * @param resource $context A context suitable to be passed into {@link file_get_contents}
     * @return pagelayerQuery\DomNode Returns the root dom node for the html file.
     */
    public static function parseFile($path, $context = null) {
        $html_str = file_get_contents($path, false, $context);
        return static::parseStr($html_str);
    }

    /**
     * Query a string of html.
     *
     * @param string $html
     * @return pagelayerQuery\DomNode Returns the root dom node for the html string.
     */
    public static function parseStr($html) {
        $parser = new pagelayerQuery\Html5Parser($html);
        return $parser->root;
    }

    public function prepend($content = null) {
        foreach ($this->nodes as $node) {
            $node->prepend($content);
        }
        return $this;
    }

    public function prop($name, $value = null) {
        if (empty($this->nodes) && $value === null)
            return '';

        foreach ($this->nodes as $node) {
            if ($value === null)
                return $node->prop($name);
            $node->prop($name, $value);
        }
        return $this;
    }

    public function remove($selector = null) {
        foreach ($this->nodes as $node) {
            $node->remove($selector);
        }
        if ($selector === null)
            $this->nodes = array();

        return $this;
    }

    public function removeAttr($name) {
        foreach ($this->nodes as $node) {
            $node->removeAttr($name);
        }
        return $this;
    }

    public function removeClass($classname) {
        foreach ($this->nodes as $node) {
            $node->removeClass($classname);
        }
        return $this;
    }

    public function replaceWith($content) {
        foreach ($this->nodes as &$node) {
            $node = $node->replaceWith($content);
        }
        return $this;
    }

    public function tagName($value = null) {
        foreach ($this->nodes as $node) {
            if ($value === null)
                return $node->tagName();
            $node->tagName($value);
        }
        return $this;
    }

    public function text($value = null) {
        if (empty($this->nodes) && $value === null)
            return '';

        foreach ($this->nodes as $node) {
            if ($value === null)
                return $node->text();
            $node->text($value);
        }
        return $this;
    }

    public function toggleClass($classname, $switch = null) {
        foreach ($this->nodes as $node) {
            $node->toggleClass($classname, $switch);
        }

        return $this;
    }

    public function unwrap() {
        foreach ($this->nodes as $node) {
            $node->unwrap();
        }
        return $this;
    }

    public function val($value = null) {
        if (empty($this->nodes) && $value === null)
            return '';

        foreach ($this->nodes as $node) {
            if ($value === null)
                return $node->val();
            $node->val($value);
        }
        return $this;
    }

    public function wrap($wrapping_element) {
        foreach ($this->nodes as $node) {
            $node->wrap($wrapping_element);
        }
        return $this;
    }

    public function wrapInner($wrapping_element) {
        foreach ($this->nodes as $node) {
            $node->wrapInner($wrapping_element);
        }
        return $this;
    }
}
pquery/gan_selector_html.php000064400000057574151526522430012322 0ustar00<?php
/**
 * @author Niels A.D.
 * @author Todd Burry <todd@vanillaforums.com>
 * @copyright 2010 Niels A.D., 2014 Todd Burry
 * @license http://opensource.org/licenses/LGPL-2.1 LGPL-2.1
 * @package pQuery
 */

namespace pagelayerQuery;

/**
 * Tokenizes a css selector query
 */
class CSSQueryTokenizer extends TokenizerBase {

	/**
	 * Opening bracket token, used for "["
	 */
	const TOK_BRACKET_OPEN = 100;
	/**
	 * Closing bracket token, used for "]"
	 */
	const TOK_BRACKET_CLOSE = 101;
	/**
	 * Opening brace token, used for "("
	 */
	const TOK_BRACE_OPEN = 102;
	/**
	 * Closing brace token, used for ")"
	 */
	const TOK_BRACE_CLOSE = 103;
	/**
	 * String token
	 */
	const TOK_STRING = 104;
	/**
	 * Colon token, used for ":"
	 */
	const TOK_COLON = 105;
	/**
	 * Comma token, used for ","
	 */
	const TOK_COMMA = 106;
	/**
	 * "Not" token, used for "!"
	 */
	const TOK_NOT = 107;

	/**
	 * "All" token, used for "*" in query
	 */
	const TOK_ALL = 108;
	/**
	 * Pipe token, used for "|"
	 */
	const TOK_PIPE = 109;
	/**
	 * Plus token, used for "+"
	 */
	const TOK_PLUS = 110;
	/**
	 * "Sibling" token, used for "~" in query
	 */
	const TOK_SIBLING = 111;
	/**
	 * Class token, used for "." in query
	 */
	const TOK_CLASS = 112;
	/**
	 * ID token, used for "#" in query
	 */
	const TOK_ID = 113;
	/**
	 * Child token, used for ">" in query
	 */
	const TOK_CHILD = 114;

	/**
	 * Attribute compare prefix token, used for "|="
	 */
	const TOK_COMPARE_PREFIX = 115;
	/**
	 * Attribute contains token, used for "*="
	 */
	const TOK_COMPARE_CONTAINS = 116;
	/**
	 * Attribute contains word token, used for "~="
	 */
	const TOK_COMPARE_CONTAINS_WORD = 117;
	/**
	 * Attribute compare end token, used for "$="
	 */
	const TOK_COMPARE_ENDS = 118;
	/**
	 * Attribute equals token, used for "="
	 */
	const TOK_COMPARE_EQUALS = 119;
	/**
	 * Attribute not equal token, used for "!="
	 */
	const TOK_COMPARE_NOT_EQUAL = 120;
	/**
	 * Attribute compare bigger than token, used for ">="
	 */
	const TOK_COMPARE_BIGGER_THAN = 121;
	/**
	 * Attribute compare smaller than token, used for "<="
	 */
	const TOK_COMPARE_SMALLER_THAN = 122;
	/**
	 * Attribute compare with regex, used for "%="
	 */
	const TOK_COMPARE_REGEX = 123;
	/**
	 * Attribute compare start token, used for "^="
	 */
	const TOK_COMPARE_STARTS = 124;

	/**
	 * Sets query identifiers
	 * @see TokenizerBase::$identifiers
	 * @access private
	 */
	var $identifiers = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_-?';

	/**
	 * Map characters to match their tokens
	 * @see TokenizerBase::$custom_char_map
	 * @access private
	 */
	var $custom_char_map = array(
		'.' => self::TOK_CLASS,
		'#' => self::TOK_ID,
		',' => self::TOK_COMMA,
		'>' => 'parse_gt',//self::TOK_CHILD,

		'+' => self::TOK_PLUS,
		'~' => 'parse_sibling',

		'|' => 'parse_pipe',
		'*' => 'parse_star',
		'$' => 'parse_compare',
		'=' => self::TOK_COMPARE_EQUALS,
		'!' => 'parse_not',
		'%' => 'parse_compare',
		'^' => 'parse_compare',
		'<' => 'parse_compare',

		'"' => 'parse_string',
		"'" => 'parse_string',
		'(' => self::TOK_BRACE_OPEN,
		')' => self::TOK_BRACE_CLOSE,
		'[' => self::TOK_BRACKET_OPEN,
		']' => self::TOK_BRACKET_CLOSE,
		':' => self::TOK_COLON
	);

	/**
	 * Parse ">" character
	 * @internal Could be {@link TOK_CHILD} or {@link TOK_COMPARE_BIGGER_THAN}
	 * @return int
	 */
	protected function parse_gt() {
		if ((($this->pos + 1) < $this->size) && ($this->doc[$this->pos + 1] === '=')) {
			++$this->pos;
			return ($this->token = self::TOK_COMPARE_BIGGER_THAN);
		} else {
			return ($this->token = self::TOK_CHILD);
		}
	}

	/**
	 * Parse "~" character
	 * @internal Could be {@link TOK_SIBLING} or {@link TOK_COMPARE_CONTAINS_WORD}
	 * @return int
	 */
	protected function parse_sibling() {
		if ((($this->pos + 1) < $this->size) && ($this->doc[$this->pos + 1] === '=')) {
			++$this->pos;
			return ($this->token = self::TOK_COMPARE_CONTAINS_WORD);
		} else {
			return ($this->token = self::TOK_SIBLING);
		}
	}

	/**
	 * Parse "|" character
	 * @internal Could be {@link TOK_PIPE} or {@link TOK_COMPARE_PREFIX}
	 * @return int
	 */
	protected function parse_pipe() {
		if ((($this->pos + 1) < $this->size) && ($this->doc[$this->pos + 1] === '=')) {
			++$this->pos;
			return ($this->token = self::TOK_COMPARE_PREFIX);
		} else {
			return ($this->token = self::TOK_PIPE);
		}
	}

	/**
	 * Parse "*" character
	 * @internal Could be {@link TOK_ALL} or {@link TOK_COMPARE_CONTAINS}
	 * @return int
	 */
	protected function parse_star() {
		if ((($this->pos + 1) < $this->size) && ($this->doc[$this->pos + 1] === '=')) {
			++$this->pos;
			return ($this->token = self::TOK_COMPARE_CONTAINS);
		} else {
			return ($this->token = self::TOK_ALL);
		}
	}

	/**
	 * Parse "!" character
	 * @internal Could be {@link TOK_NOT} or {@link TOK_COMPARE_NOT_EQUAL}
	 * @return int
	 */
	protected function parse_not() {
		if ((($this->pos + 1) < $this->size) && ($this->doc[$this->pos + 1] === '=')) {
			++$this->pos;
			return ($this->token = self::TOK_COMPARE_NOT_EQUAL);
		} else {
			return ($this->token = self::TOK_NOT);
		}
	}

	/**
	 * Parse several compare characters
	 * @return int
	 */
	protected function parse_compare() {
		if ((($this->pos + 1) < $this->size) && ($this->doc[$this->pos + 1] === '=')) {
			switch($this->doc[$this->pos++]) {
				case '$':
					return ($this->token = self::TOK_COMPARE_ENDS);
				case '%':
					return ($this->token = self::TOK_COMPARE_REGEX);
				case '^':
					return ($this->token = self::TOK_COMPARE_STARTS);
				case '<':
					return ($this->token = self::TOK_COMPARE_SMALLER_THAN);
			}
		}
		return false;
	}

	/**
	 * Parse strings (" and ')
	 * @return int
	 */
	protected function parse_string() {
		$char = $this->doc[$this->pos];

		while (true) {
			if ($this->next_search($char.'\\', false) !== self::TOK_NULL) {
				if($this->doc[$this->pos] === $char) {
					break;
				} else {
					++$this->pos;
				}
			} else {
				$this->pos = $this->size - 1;
				break;
			}
		}

		return ($this->token = self::TOK_STRING);
	}

}

/**
 * Performs a css select query on HTML nodes
 */
class HtmlSelector {

	/**
	 * Parser object
	 * @internal If string, then it will create a new instance as parser
	 * @var CSSQueryTokenizer
	 */
	var $parser = 'pagelayerQuery\\CSSQueryTokenizer';

	/**
	 * Target of queries
	 * @var DomNode
	 */
	var $root = null;

	/**
	 * Last performed query, result in {@link $result}
	 * @var string
	 */
	var $query = '';

	/**
	 * Array of matching nodes
	 * @var array
	 */
	var $result = array();

	/**
	 * Include root in search, if false the only child nodes are evaluated
	 * @var bool
	 */
	var $search_root = false;

	/**
	 * Search recursively
	 * @var bool
	 */
	var $search_recursive = true;

	/**
	 * Extra function map for custom filters
	 * @var array
	 * @internal array('root' => 'filter_root') will cause the
	 * selector to call $this->filter_root at :root
	 * @see DomNode::$filter_map
	 */
	var $custom_filter_map = array();

	/**
	 * Class constructor
	 * @param DomNode $root {@link $root}
	 * @param string $query
	 * @param bool $search_root {@link $search_root}
	 * @param bool $search_recursive {@link $search_recursive}
	 * @param CSSQueryTokenizer $parser If null, then default class will be used
	 */
	function __construct($root, $query = '*', $search_root = false, $search_recursive = true, $parser = null) {
		if ($parser === null) {
			$parser = new $this->parser();
		}
		$this->parser = $parser;
		$this->root =& $root;

		$this->search_root = $search_root;
		$this->search_recursive = $search_recursive;

		$this->select($query);
	}

	#php4 PHP4 class constructor compatibility
	#function HtmlSelector($root, $query = '*', $search_root = false, $search_recursive = true, $parser = null) {return $this->__construct($root, $query, $search_root, $search_recursive, $parser);}
	#php4e

	/**
	 * toString method, returns {@link $query}
	 * @return string
	 * @access private
	 */
	function __toString() {
		return $this->query;
	}

	/**
	 * Class magic invoke method, performs {@link select()}
	 * @return array
	 * @access private
	 */
	function __invoke($query = '*') {
		return $this->select($query);
	}

	/**
	 * Perform query
	 * @param string $query
	 * @return array False on failure
	 */
	function select($query = '*') {
		$this->parser->setDoc($query);
		$this->query = $query;
		return (($this->parse()) ? $this->result : false);
	}

	/**
	 * Trigger error
	 * @param string $error
	 * @internal %pos% and %tok% will be replace in string with position and token(string)
	 * @access private
	 */
	protected function error($error) {
		$error = htmlentities(str_replace(
			array('%tok%', '%pos%'),
			array($this->parser->getTokenString(), (int) $this->parser->getPos()),
			$error
		));

		trigger_error($error);
	}

	/**
	 * Get identifier (parse identifier or string)
	 * @param bool $do_error Error on failure
	 * @return string False on failure
	 * @access private
	 */
	protected function parse_getIdentifier($do_error = true) {
		$p =& $this->parser;
		$tok = $p->token;

		if ($tok === CSSQueryTokenizer::TOK_IDENTIFIER) {
			return $p->getTokenString();
		} elseif($tok === CSSQueryTokenizer::TOK_STRING) {
			return str_replace(array('\\\'', '\\"', '\\\\'), array('\'', '"', '\\'), $p->getTokenString(1, -1));
		} elseif ($do_error) {
			$this->error('Expected identifier at %pos%!');
		}
		return false;
	}

	/**
	 * Get query conditions (tag, attribute and filter conditions)
	 * @return array False on failure
	 * @see DomNode::match()
	 * @access private
	 */
	protected function parse_conditions() {
		$p =& $this->parser;
		$tok = $p->token;

		if ($tok === CSSQueryTokenizer::TOK_NULL) {
			$this->error('Invalid search pattern(1): Empty string!');
			return false;
		}
		$conditions_all = array();

		//Tags
		while ($tok !== CSSQueryTokenizer::TOK_NULL) {
			$conditions = array('tags' => array(), 'attributes' => array());

			if ($tok === CSSQueryTokenizer::TOK_ALL) {
				$tok = $p->next();
				if (($tok === CSSQueryTokenizer::TOK_PIPE) && ($tok = $p->next()) && ($tok !== CSSQueryTokenizer::TOK_ALL)) {
					if (($tag = $this->parse_getIdentifier()) === false) {
						return false;
					}
					$conditions['tags'][] = array(
						'tag' => $tag,
						'compare' => 'name'
					);
					$tok = $p->next_no_whitespace();
				} else {
					$conditions['tags'][''] = array(
						'tag' => '',
						'match' => false
					);
					if ($tok === CSSQueryTokenizer::TOK_ALL) {
						$tok = $p->next_no_whitespace();
					}
				}
			} elseif ($tok === CSSQueryTokenizer::TOK_PIPE) {
				$tok = $p->next();
				if ($tok === CSSQueryTokenizer::TOK_ALL) {
					$conditions['tags'][] = array(
						'tag' => '',
						'compare' => 'namespace',
					);
				} elseif (($tag = $this->parse_getIdentifier()) !== false) {
					$conditions['tags'][] = array(
						'tag' => $tag,
						'compare' => 'total',
					);
				} else {
					return false;
				}
				$tok = $p->next_no_whitespace();
			} elseif ($tok === CSSQueryTokenizer::TOK_BRACE_OPEN) {
				$tok = $p->next_no_whitespace();
				$last_mode = 'or';

				while (true) {
					$match = true;
					$compare = 'total';

					if ($tok === CSSQueryTokenizer::TOK_NOT) {
						$match = false;
						$tok = $p->next_no_whitespace();
					}

					if ($tok === CSSQueryTokenizer::TOK_ALL) {
						$tok = $p->next();
						if ($tok === CSSQueryTokenizer::TOK_PIPE) {
							$this->next();
							$compare = 'name';
							if (($tag = $this->parse_getIdentifier()) === false) {
								return false;
							}
						}
					} elseif ($tok === CSSQueryTokenizer::TOK_PIPE) {
						$tok = $p->next();
						if ($tok === CSSQueryTokenizer::TOK_ALL) {
							$tag = '';
							$compare = 'namespace';
						} elseif (($tag = $this->parse_getIdentifier()) === false) {
							return false;
						}
						$tok = $p->next_no_whitespace();
					} else {
						if (($tag = $this->parse_getIdentifier()) === false) {
							return false;
						}
						$tok = $p->next();
						if ($tok === CSSQueryTokenizer::TOK_PIPE) {
							$tok = $p->next();

							if ($tok === CSSQueryTokenizer::TOK_ALL) {
								$compare = 'namespace';
							} elseif (($tag_name = $this->parse_getIdentifier()) !== false) {
								$tag = $tag.':'.$tag_name;
							} else {
								return false;
							}

							$tok = $p->next_no_whitespace();
						}
					}
					if ($tok === CSSQueryTokenizer::TOK_WHITESPACE) {
						$tok = $p->next_no_whitespace();
					}

					$conditions['tags'][] = array(
						'tag' => $tag,
						'match' => $match,
						'operator' => $last_mode,
						'compare' => $compare
					);
					switch($tok) {
						case CSSQueryTokenizer::TOK_COMMA:
							$tok = $p->next_no_whitespace();
							$last_mode = 'or';
							continue 2;
						case CSSQueryTokenizer::TOK_PLUS:
							$tok = $p->next_no_whitespace();
							$last_mode = 'and';
							continue 2;
						case CSSQueryTokenizer::TOK_BRACE_CLOSE:
							$tok = $p->next();
							break 2;
						default:
							$this->error('Expected closing brace or comma at pos %pos%!');
							return false;
					}
				}
			} elseif (($tag = $this->parse_getIdentifier(false)) !== false) {
				$tok = $p->next();
				if ($tok === CSSQueryTokenizer::TOK_PIPE) {
					$tok = $p->next();

					if ($tok === CSSQueryTokenizer::TOK_ALL) {
						$conditions['tags'][] = array(
							'tag' => $tag,
							'compare' => 'namespace'
						);
					} elseif (($tag_name = $this->parse_getIdentifier()) !== false) {
						$tag = $tag.':'.$tag_name;
						$conditions['tags'][] = array(
							'tag' => $tag,
							'match' => true
						);
					} else {
						return false;
					}

					$tok = $p->next();
                } elseif ($tag === 'text' && $tok === CSSQueryTokenizer::TOK_BRACE_OPEN) {
                    $pos = $p->getPos();
                    $tok = $p->next();
                    if ($tok === CSSQueryTokenizer::TOK_BRACE_CLOSE) {
                        $conditions['tags'][] = array(
                            'tag' => '~text~',
                            'match' => true
                        );
                        $p->next();
                    } else {
                        $p->setPos($pos);
                    }
				} else {
					$conditions['tags'][] = array(
						'tag' => $tag,
						'match' => true
					);
				}
			} else {
				unset($conditions['tags']);
			}

			//Class
			$last_mode = 'or';
			if ($tok === CSSQueryTokenizer::TOK_CLASS) {
				$p->next();
				if (($class = $this->parse_getIdentifier()) === false) {
					return false;
				}

				$conditions['attributes'][] = array(
					'attribute' => 'class',
					'operator_value' => 'contains_word',
					'value' => $class,
					'operator_result' => $last_mode
				);
				$last_mode = 'and';
				$tok = $p->next();
			}

			//ID
			if ($tok === CSSQueryTokenizer::TOK_ID) {
				$p->next();
				if (($id = $this->parse_getIdentifier()) === false) {
					return false;
				}

				$conditions['attributes'][] = array(
					'attribute' => 'id',
					'operator_value' => 'equals',
					'value' => $id,
					'operator_result' => $last_mode
				);
				$last_mode = 'and';
				$tok = $p->next();
			}

			//Attributes
			if ($tok === CSSQueryTokenizer::TOK_BRACKET_OPEN) {
				$tok = $p->next_no_whitespace();

				while (true) {
					$match = true;
					$compare = 'total';
					if ($tok === CSSQueryTokenizer::TOK_NOT) {
						$match = false;
						$tok = $p->next_no_whitespace();
					}

					if ($tok === CSSQueryTokenizer::TOK_ALL) {
						$tok = $p->next();
						if ($tok === CSSQueryTokenizer::TOK_PIPE) {
							$tok = $p->next();
							if (($attribute = $this->parse_getIdentifier()) === false) {
								return false;
							}
							$compare = 'name';
							$tok = $p->next();
						} else {
							$this->error('Expected pipe at pos %pos%!');
							return false;
						}
					} elseif ($tok === CSSQueryTokenizer::TOK_PIPE) {
						$tok = $p->next();
						if (($tag = $this->parse_getIdentifier()) === false) {
							return false;
						}
						$tok = $p->next_no_whitespace();
					} elseif (($attribute = $this->parse_getIdentifier()) !== false) {
						$tok = $p->next();
						if ($tok === CSSQueryTokenizer::TOK_PIPE) {
							$tok = $p->next();

							if (($attribute_name = $this->parse_getIdentifier()) !== false) {
								$attribute = $attribute.':'.$attribute_name;
							} else {
								return false;
							}

							$tok = $p->next();
						}
					} else {
						return false;
					}
					if ($tok === CSSQueryTokenizer::TOK_WHITESPACE) {
						$tok = $p->next_no_whitespace();
					}

					$operator_value = '';
					$val = '';
					switch($tok) {
						case CSSQueryTokenizer::TOK_COMPARE_PREFIX:
						case CSSQueryTokenizer::TOK_COMPARE_CONTAINS:
						case CSSQueryTokenizer::TOK_COMPARE_CONTAINS_WORD:
						case CSSQueryTokenizer::TOK_COMPARE_ENDS:
						case CSSQueryTokenizer::TOK_COMPARE_EQUALS:
						case CSSQueryTokenizer::TOK_COMPARE_NOT_EQUAL:
						case CSSQueryTokenizer::TOK_COMPARE_REGEX:
						case CSSQueryTokenizer::TOK_COMPARE_STARTS:
						case CSSQueryTokenizer::TOK_COMPARE_BIGGER_THAN:
						case CSSQueryTokenizer::TOK_COMPARE_SMALLER_THAN:
							$operator_value = $p->getTokenString(($tok === CSSQueryTokenizer::TOK_COMPARE_EQUALS) ? 0 : -1);
							$p->next_no_whitespace();

							if (($val = $this->parse_getIdentifier()) === false) {
								return false;
							}

							$tok = $p->next_no_whitespace();
							break;
					}

					if ($operator_value && $val) {
						$conditions['attributes'][] = array(
							'attribute' => $attribute,
							'operator_value' => $operator_value,
							'value' => $val,
							'match' => $match,
							'operator_result' => $last_mode,
							'compare' => $compare
						);
					} else {
						$conditions['attributes'][] = array(
							'attribute' => $attribute,
							'value' => $match,
							'operator_result' => $last_mode,
							'compare' => $compare
						);
					}

					switch($tok) {
						case CSSQueryTokenizer::TOK_COMMA:
							$tok = $p->next_no_whitespace();
							$last_mode = 'or';
							continue 2;
						case CSSQueryTokenizer::TOK_PLUS:
							$tok = $p->next_no_whitespace();
							$last_mode = 'and';
							continue 2;
						case CSSQueryTokenizer::TOK_BRACKET_CLOSE:
							$tok = $p->next();
							break 2;
						default:
							$this->error('Expected closing bracket or comma at pos %pos%!');
							return false;
					}
				}
			}

			if (count($conditions['attributes']) < 1) {
				unset($conditions['attributes']);
			}

			while($tok === CSSQueryTokenizer::TOK_COLON) {
				if (count($conditions) < 1) {
					$conditions['tags'] = array(array(
						'tag' => '',
						'match' => false
					));
				}

				$tok = $p->next();
				if (($filter = $this->parse_getIdentifier()) === false) {
					return false;
				}

				if (($tok = $p->next()) === CSSQueryTokenizer::TOK_BRACE_OPEN) {
					$start = $p->pos;
					$count = 1;
					while ((($tok = $p->next()) !== CSSQueryTokenizer::TOK_NULL) && !(($tok === CSSQueryTokenizer::TOK_BRACE_CLOSE) && (--$count === 0))) {
						if ($tok === CSSQueryTokenizer::TOK_BRACE_OPEN) {
							++$count;
						}
					}


					if ($tok !== CSSQueryTokenizer::TOK_BRACE_CLOSE) {
						$this->error('Expected closing brace at pos %pos%!');
						return false;
					}
					$len = $p->pos - 1 - $start;
					$params = (($len > 0) ? substr($p->doc, $start + 1, $len) : '');
					$tok = $p->next();
				} else {
					$params = '';
				}

				$conditions['filters'][] = array('filter' => $filter, 'params' => $params);
			}
			if (count($conditions) < 1) {
				$this->error('Invalid search pattern(2): No conditions found!');
				return false;
			}
			$conditions_all[] = $conditions;

			if ($tok === CSSQueryTokenizer::TOK_WHITESPACE) {
				$tok = $p->next_no_whitespace();
			}

			if ($tok === CSSQueryTokenizer::TOK_COMMA) {
				$tok = $p->next_no_whitespace();
				continue;
			} else {
				break;
			}
		}

		return $conditions_all;
	}


	/**
	 * Evaluate root node using custom callback
	 * @param array $conditions {@link parse_conditions()}
	 * @param bool|int $recursive
	 * @param bool $check_root
	 * @return array
	 * @access private
	 */
	protected function parse_callback($conditions, $recursive = true, $check_root = false) {
		return ($this->result = $this->root->getChildrenByMatch(
			$conditions,
			$recursive,
			$check_root,
			$this->custom_filter_map
		));
	}

	/**
	 * Parse first bit of query, only root node has to be evaluated now
	 * @param bool|int $recursive
	 * @return bool
	 * @internal Result of query is set in {@link $result}
	 * @access private
	 */
	protected function parse_single($recursive = true) {
		if (($c = $this->parse_conditions()) === false) {
			return false;
		}

		$this->parse_callback($c, $recursive, $this->search_root);
		return true;
	}

	/**
	 * Evaluate sibling nodes
	 * @return bool
	 * @internal Result of query is set in {@link $result}
	 * @access private
	 */
	protected function parse_adjacent() {
		$tmp = $this->result;
		$this->result = array();
		if (($c = $this->parse_conditions()) === false) {
			return false;
		}

		foreach($tmp as $t) {
			if (($sibling = $t->getNextSibling()) !== false) {
				if ($sibling->match($c, true, $this->custom_filter_map)) {
					$this->result[] = $sibling;
				}
			}
		}

		return true;
	}

	/**
	 * Evaluate {@link $result}
	 * @param bool $parent Evaluate parent nodes
	 * @param bool|int $recursive
	 * @return bool
	 * @internal Result of query is set in {@link $result}
	 * @access private
	 */
	protected function parse_result($parent = false, $recursive = true) {
		$tmp = $this->result;
		$tmp_res = array();
		if (($c = $this->parse_conditions()) === false) {
			return false;
		}

		foreach(array_keys($tmp) as $t) {
			$this->root = (($parent) ? $tmp[$t]->parent : $tmp[$t]);
			$this->parse_callback($c, $recursive);
			foreach(array_keys($this->result) as $r) {
				if (!in_array($this->result[$r], $tmp_res, true)) {
					$tmp_res[] = $this->result[$r];
				}
			}
		}
		$this->result = $tmp_res;
		return true;
	}

	/**
	 * Parse full query
	 * @return bool
	 * @internal Result of query is set in {@link $result}
	 * @access private
	 */
	protected function parse() {
		$p =& $this->parser;
		$p->setPos(0);
		$this->result = array();

		if (!$this->parse_single()) {
			return false;
		}

		while (count($this->result) > 0) {
			switch($p->token) {
				case CSSQueryTokenizer::TOK_CHILD:
					$this->parser->next_no_whitespace();
					if (!$this->parse_result(false, 1)) {
						return false;
					}
					break;

				case CSSQueryTokenizer::TOK_SIBLING:
					$this->parser->next_no_whitespace();
					if (!$this->parse_result(true, 1)) {
						return false;
					}
					break;

				case CSSQueryTokenizer::TOK_PLUS:
					$this->parser->next_no_whitespace();
					if (!$this->parse_adjacent()) {
						return false;
					}
					break;

				case CSSQueryTokenizer::TOK_ALL:
				case CSSQueryTokenizer::TOK_IDENTIFIER:
				case CSSQueryTokenizer::TOK_STRING:
				case CSSQueryTokenizer::TOK_BRACE_OPEN:
				case CSSQueryTokenizer::TOK_BRACKET_OPEN:
				case CSSQueryTokenizer::TOK_ID:
				case CSSQueryTokenizer::TOK_CLASS:
				case CSSQueryTokenizer::TOK_COLON:
					if (!$this->parse_result()) {
						return false;
					}
					break;

				case CSSQueryTokenizer::TOK_NULL:
					break 2;

				default:
					$this->error('Invalid search pattern(3): No result modifier found!');
					return false;
			}
		}

		return true;
	}
}

?>
pquery/gan_node_html.php000064400000224041151526522430011410 0ustar00<?php
/**
 * @author Niels A.D.
 * @author Todd Burry <todd@vanillaforums.com>
 * @copyright 2010 Niels A.D., 2014 Todd Burry
 * @license http://opensource.org/licenses/LGPL-2.1 LGPL-2.1
 * @package pQuery
 */

namespace pagelayerQuery;

/**
 * Holds (x)html/xml tag information like tag name, attributes,
 * parent, children, self close, etc.
 *
 */
class DomNode implements IQuery {

	/**
	 * Element Node, used for regular elements
	 */
	const NODE_ELEMENT = 0;
	/**
	 * Text Node
	 */
	const NODE_TEXT = 1;
	/**
	 * Comment Node
	 */
	const NODE_COMMENT = 2;
	/**
	 * Conditional Node (<![if]> <![endif])
	 */
	const NODE_CONDITIONAL = 3;
	/**
	 * CDATA Node (<![CDATA[]]>
	 */
	const NODE_CDATA = 4;
	/**
	 * Doctype Node
	 */
	const NODE_DOCTYPE = 5;
	/**
	 * XML Node, used for tags that start with ?, like <?xml and <?php
	 */
	const NODE_XML = 6;
	/**
	 * ASP Node
	 */
	const NODE_ASP = 7;

	#php4 Compatibility with PHP4, this gets changed to a regular var in release tool
	#static $NODE_TYPE = self::NODE_ELEMENT;
	#php4e
	#php5
	/**
	 * Node type of class
	 */
	const NODE_TYPE = self::NODE_ELEMENT;
	#php5e


	/**
	 * Name of the selector class
	 * @var string
	 * @see select()
	 */
	var $selectClass = 'pagelayerQuery\\HtmlSelector';
	/**
	 * Name of the parser class
	 * @var string
	 * @see setOuterText()
	 * @see setInnerText()
	 */
	var $parserClass = 'pagelayerQuery\\Html5Parser';

	/**
	 * Name of the class used for {@link addChild()}
	 * @var string
	 */
	var $childClass = __CLASS__;
	/**
	 * Name of the class used for {@link addText()}
	 * @var string
	 */
	var $childClass_Text = 'pagelayerQuery\\TextNode';
	/**
	 * Name of the class used for {@link addComment()}
	 * @var string
	 */
	var $childClass_Comment = 'pagelayerQuery\\CommentNode';
	/**
	 * Name of the class used for {@link addContional()}
	 * @var string
	 */
	var $childClass_Conditional = 'pagelayerQuery\\ConditionalTagNode';
	/**
	 * Name of the class used for {@link addCDATA()}
	 * @var string
	 */
	var $childClass_CDATA = 'pagelayerQuery\\CdataNode';
	/**
	 * Name of the class used for {@link addDoctype()}
	 * @var string
	 */
	var $childClass_Doctype = 'pagelayerQuery\\DoctypeNode';
	/**
	 * Name of the class used for {@link addXML()}
	 * @var string
	 */
	var $childClass_XML = 'pagelayerQuery\\XmlNode';
	/**
	 * Name of the class used for {@link addASP()}
	 * @var string
	 */
	var $childClass_ASP = 'pagelayerQuery\\AspEmbeddedNode';

	/**
	 * Parent node, null if none
	 * @var DomNode
	 * @see changeParent()
	 */
	var $parent = null;

	/**
	 * Attributes of node
	 * @var array
	 * @internal array('attribute' => 'value')
	 * @internal Public for faster access!
	 * @see getAttribute()
	 * @see setAttribute()
	 * @access private
	 */
	var $attributes = array();

	/**
	 * Namespace info for attributes
	 * @var array
	 * @internal array('tag' => array(array('ns', 'tag', 'ns:tag', index)))
	 * @internal Public for easy outside modifications!
	 * @see findAttribute()
	 * @access private
	 */
	var $attributes_ns = null;

	/**
	 * Array of child nodes
	 * @var array
	 * @internal Public for faster access!
	 * @see childCount()
	 * @see getChild()
	 * @see addChild()
	 * @see deleteChild()
	 * @access private
	 */
	var $children = array();

	/**
	 * Full tag name (including namespace)
	 * @var string
	 * @see getTagName()
	 * @see getNamespace()
	 */
	var $tag = '';

	/**
	 * Namespace info for tag
	 * @var array
	 * @internal array('namespace', 'tag')
	 * @internal Public for easy outside modifications!
	 * @access private
	 */
	var $tag_ns = null;

	/**
	 * Is node a self closing node? No closing tag if true.
	 * @var bool
	 */
	var $self_close = false;

	/**
	 * If self close, then this will be used to close the tag
	 * @var string
	 * @see $self_close
	 */
	var $self_close_str = ' /';

	/**
	 * Use short tags for attributes? If true, then attributes
	 * with values equal to the attribute name will not output
	 * the value, e.g. selected="selected" will be selected.
	 * @var bool
	 */
	var $attribute_shorttag = false;

	/**
	 * Function map used for the selector filter
	 * @var array
	 * @internal array('root' => 'filter_root') will cause the
	 * selector to call $this->filter_root at :root
	 * @access private
	 */
	var $filter_map = array(
		'root' => 'filter_root',
		'nth-child' => 'filter_nchild',
		'eq' => 'filter_nchild', //jquery (naming) compatibility
		'gt' => 'filter_gt',
		'lt' => 'filter_lt',
		'nth-last-child' => 'filter_nlastchild',
		'nth-of-type' => 'filter_ntype',
		'nth-last-of-type' => 'filter_nlastype',
		'odd' => 'filter_odd',
		'even' => 'filter_even',
		'every' => 'filter_every',
		'first-child' => 'filter_first',
		'last-child' => 'filter_last',
		'first-of-type' => 'filter_firsttype',
		'last-of-type' => 'filter_lasttype',
		'only-child' => 'filter_onlychild',
		'only-of-type' => 'filter_onlytype',
		'empty' => 'filter_empty',
		'not-empty' => 'filter_notempty',
		'has-text' => 'filter_hastext',
		'no-text' => 'filter_notext',
		'lang' => 'filter_lang',
		'contains' => 'filter_contains',
		'has' => 'filter_has',
		'not' => 'filter_not',
		'element' => 'filter_element',
		'text' => 'filter_text',
		'comment' => 'filter_comment',
        'checked' => 'filter_checked',
        'selected' => 'filter_selected',
	);

	/**
	 * Class constructor
	 * @param string|array $tag Name of the tag, or array with taginfo (array(
	 *	'tag_name' => 'tag',
	 *	'self_close' => false,
	 *	'attributes' => array('attribute' => 'value')))
	 * @param DomNode $parent Parent of node, null if none
	 */
	function __construct($tag, $parent) {
		$this->parent = $parent;

		if (is_string($tag)) {
			$this->tag = $tag;
		} else {
			$this->tag = $tag['tag_name'];
			$this->self_close = $tag['self_close'];
			$this->attributes = $tag['attributes'];
		}
	}

	#php4 PHP4 class constructor compatibility
	#function DomNode($tag, $parent) {return $this->__construct($tag, $parent);}
	#php4e

	/**
	 * Class destructor
	 * @access private
	 */
	function __destruct() {
		$this->delete();
	}

	/**
	 * Class toString, outputs {@link $tag}
	 * @return string
	 * @access private
	 */
	function __toString() {
		return (($this->tag === '~root~') ? $this->toString(true, true, 1) : $this->tag);
	}

	/**
	 * Class magic get method, outputs {@link getAttribute()}
	 * @return string
	 * @access private
	 */
	function __get($attribute) {
		return $this->getAttribute($attribute);
	}

	/**
	 * Class magic set method, performs {@link setAttribute()}
	 * @access private
	 */
	function __set($attribute, $value) {
		$this->setAttribute($attribute, $value);
	}

	/**
	 * Class magic isset method, returns {@link hasAttribute()}
	 * @return bool
	 * @access private
	 */
	function __isset($attribute) {
		return $this->hasAttribute($attribute);
	}

	/**
	 * Class magic unset method, performs {@link deleteAttribute()}
	 * @access private
	 */
	function __unset($attribute) {
		return $this->deleteAttribute($attribute);
	}

	/**
	 * Class magic invoke method, performs {@link query()}.
     * @param string $query The css query to run on the nodes.
	 * @return \pQuery
	 */
	function __invoke($query = '*') {
		return $this->query($query);
	}

	/**
	 * Returns place in document
	 * @return string
	 */
	 function dumpLocation() {
		return (($this->parent) ? (($p = $this->parent->dumpLocation()) ? $p.' > ' : '').$this->tag.'('.$this->typeIndex().')' : '');
	 }

	/**
	 * Returns all the attributes and their values
	 * @return string
	 * @access private
	 */
	protected function toString_attributes() {
		$s = '';
		foreach($this->attributes as $a => $v) {
			$s .= ' '.$a;
			if ((!$this->attribute_shorttag) || ($v !== $a)) {
				$quote = '"';//(strpos($v, '"') === false) ? '"' : "'";
				$v = str_replace('"', '&quot;', $v);
				$s .= '='.$quote.$v.$quote;
			}
		}
		return $s;
	}

	/**
	 * Returns the content of the node (child tags and text)
	 * @param bool $attributes Print attributes of child tags
	 * @param bool|int $recursive How many sublevels of childtags to print. True for all.
	 * @param bool $content_only Only print text, false will print tags too.
	 * @return string
	 * @access private
	 */
	protected function toString_content($attributes = true, $recursive = true, $content_only = false) {
		$s = '';
		foreach($this->children as $c) {
			$s .= $c->toString($attributes, $recursive, $content_only);
		}
		return $s;
	}

	/**
	 * Returns the node as string
	 * @param bool $attributes Print attributes (of child tags)
	 * @param bool|int $recursive How many sub-levels of child tags to print. True for all.
	 * @param bool|int $content_only Only print text, false will print tags too.
	 * @return string
	 */
	function toString($attributes = true, $recursive = true, $content_only = false) {
		if ($content_only) {
			if (is_int($content_only)) {
				--$content_only;
			}
			return $this->toString_content($attributes, $recursive, $content_only);
		}

		$s = '<'.$this->tag;
		if ($attributes) {
			$s .= $this->toString_attributes();
		}
		if ($this->self_close) {
			$s .= $this->self_close_str.'>';
		} else {
			$s .= '>';
			if($recursive) {
				$s .= $this->toString_content($attributes);
			}
			$s .= '</'.$this->tag.'>';
		}
		return $s;
	}

	/**
	 * Similar to JavaScript outerText, will return full (html formatted) node
	 * @return string
	 */
	function getOuterText() {
		return $this->toString();
	}

	/**
	 * Similar to JavaScript outerText, will replace node (and child nodes) with new text
	 * @param string $text
	 * @param HtmlParserBase $parser Null to auto create instance
	 * @return bool|array True on succeed, array with errors on failure
	 */
	function setOuterText($text, $parser = null) {
		if (trim($text)) {
			$index = $this->index();
			if ($parser === null) {
				$parser = new $this->parserClass();
			}
			$parser->setDoc($text);
			$parser->parse_all();
			$parser->root->moveChildren($this->parent, $index);
		}
		$this->delete();
		return (($parser && $parser->errors) ? $parser->errors : true);
	}

	/**
	 * Return html code of node
	 * @internal jquery (naming) compatibility
     * @param string|null $value The value to set or null to get the value.
	 * @see toString()
	 * @return string
	 */
	function html($value = null) {
      if ($value !== null) {
         $this->setInnerText($value);
      }
		return $this->getInnerText();
	}

	/**
	 * Similar to JavaScript innerText, will return (html formatted) content
	 * @return string
	 */
	function getInnerText() {
		return $this->toString(true, true, 1);
	}

	/**
	 * Similar to JavaScript innerText, will replace child nodes with new text
	 * @param string $text
	 * @param HtmlParserBase $parser Null to auto create instance
	 * @return bool|array True on succeed, array with errors on failure
	 */
	function setInnerText($text, $parser = null) {
		$this->clear();
		if (trim($text)) {
			if ($parser === null) {
				$parser = new $this->parserClass();
			}
			$parser->root =& $this;
			$parser->setDoc($text);
			$parser->parse_all();
		}
		return (($parser && $parser->errors) ? $parser->errors : true);
	}

	/**
	 * Similar to JavaScript plainText, will return text in node (and subnodes)
	 * @return string
	 */
	function getPlainText() {
		return preg_replace('`\s+`', ' ', $this->toString(true, true, true));
	}

	/**
	 * Return plaintext taking document encoding into account
	 * @return string
	 */
	function getPlainTextUTF8() {
		$txt = $this->toString(true, true, true);
		$enc = $this->getEncoding();
		if ($enc !== false) {
			$txt = mb_convert_encoding($txt, 'UTF-8', $enc);
		}
		return preg_replace('`\s+`', ' ', $txt);
	}

	/**
	 * Similar to JavaScript plainText, will replace child nodes with new text (literal)
	 * @param string $text
	 */
	function setPlainText($text) {
		$this->clear();
		if (trim($text)) {
			$this->addText($text);
		}
	}

	/**
	 * Delete node from parent and clear node
	 */
	function delete() {
		if (($p = $this->parent) !== null) {
			$this->parent = null;
			$p->deleteChild($this);
		} else {
			$this->clear();
		}
	}

	/**
	 * Detach node from parent
	 * @param bool $move_children_up Only detach current node and replace it with child nodes
	 * @internal jquery (naming) compatibility
	 * @see delete()
	 */
	function detach($move_children_up = false) {
		if (($p = $this->parent) !== null) {
			$index = $this->index();
			$this->parent = null;

			if ($move_children_up) {
				$this->moveChildren($p, $index);
			}
			$p->deleteChild($this, true);
		}
	}

	/**
	 * Deletes all child nodes from node
	 */
	function clear() {
		foreach($this->children as $c) {
			$c->parent = null;
			$c->delete();
		}
		$this->children = array();
	}

	/**
	 * Get top parent
	 * @return DomNode Root, null if node has no parent
	 */
	function getRoot() {
		$r = $this->parent;
		$n = ($r === null) ? null : $r->parent;
		while ($n !== null) {
			$r = $n;
			$n = $r->parent;
		}

		return $r;
	}

	/**
	 * Change parent
	 * @param null|DomNode $to New parent, null if none
	 * @param false|int $index Add child to parent if not present at index, false to not add, negative to count from end, null to append
	 */
	#php4
	#function changeParent($to, &$index) {
	#php4e
	#php5
	function changeParent($to, &$index = null) {
	#php5e
		if ($this->parent !== null) {
			$this->parent->deleteChild($this, true);
		}
		$this->parent = $to;
		if ($index !== false) {
			$new_index = $this->index();
			if (!(is_int($new_index) && ($new_index >= 0))) {
				$this->parent->addChild($this, $index);
			}
		}
	}

	/**
	 * Find out if node has (a certain) parent
	 * @param DomNode|string $tag Match against parent, string to match tag, object to fully match node, null to return if node has parent
	 * @param bool $recursive
	 * @return bool
	 */
	function hasParent($tag = null, $recursive = false) {
		if ($this->parent !== null) {
			if ($tag === null) {
				return true;
			} elseif (is_string($tag)) {
				return (($this->parent->tag === $tag) || ($recursive && $this->parent->hasParent($tag)));
			} elseif (is_object($tag)) {
				return (($this->parent === $tag) || ($recursive && $this->parent->hasParent($tag)));
			}
		}

		return false;
	}

	/**
	 * Find out if node is parent of a certain tag
	 * @param DomNode|string $tag Match against parent, string to match tag, object to fully match node
	 * @param bool $recursive
	 * @return bool
	 * @see hasParent()
	 */
	function isParent($tag, $recursive = false) {
		return ($this->hasParent($tag, $recursive) === ($tag !== null));
	}

	/**
	 * Find out if node is text
	 * @return bool
	 */
	function isText() {
		return false;
	}

	/**
	 * Find out if node is comment
	 * @return bool
	 */
	function isComment() {
		return false;
	}

	/**
	 * Find out if node is text or comment node
	 * @return bool
	 */
	function isTextOrComment() {
		return false;
	}

	/**
	 * Move node to other node
	 * @param DomNode $to New parent, null if none
	 * @param int $new_index Add child to parent at index if not present, null to not add, negative to count from end
	 * @internal Performs {@link changeParent()}
	 */
	#php4
	#function move($to, &$new_index) {
	#php4e
	#php5
	function move($to, &$new_index = -1) {
	#php5e
		$this->changeParent($to, $new_index);
	}

	/**
	 * Move child nodes to other node
	 * @param DomNode $to New parent, null if none
	 * @param int $new_index Add child to new node at index if not present, null to not add, negative to count from end
	 * @param int $start Index from child node where to start wrapping, 0 for first element
	 * @param int $end Index from child node where to end wrapping, -1 for last element
	 */
	#php4
	#function moveChildren($to, &$new_index, $start = 0, $end = -1) {
	#php4e
	#php5
	function moveChildren($to, &$new_index = -1, $start = 0, $end = -1) {
	#php5e
		if ($end < 0) {
			$end += count($this->children);
		}
		for ($i = $start; $i <= $end; $i++) {
			$this->children[$start]->changeParent($to, $new_index);
		}
	}

	/**
	 * Index of node in parent
	 * @param bool $count_all True to count all tags, false to ignore text and comments
	 * @return int -1 if not found
	 */
	function index($count_all = true) {
		if (!$this->parent) {
			return -1;
		} elseif ($count_all) {
			return $this->parent->findChild($this);
		} else{
			$index = -1;
			//foreach($this->parent->children as &$c) {
			//	if (!$c->isTextOrComment()) {
			//		++$index;
			//	}
			//	if ($c === $this) {
			//		return $index;
			//	}
			//}

			foreach(array_keys($this->parent->children) as $k) {
				if (!$this->parent->children[$k]->isTextOrComment()) {
					++$index;
				}
				if ($this->parent->children[$k] === $this) {
					return $index;
				}
			}
			return -1;
		}
	}

	/**
	 * Change index of node in parent
	 * @param int $index New index
	 */
	function setIndex($index) {
		if ($this->parent) {
			if ($index > $this->index()) {
				--$index;
			}
			$this->delete();
			$this->parent->addChild($this, $index);
		}
	}

	/**
	 * Index of all similar nodes in parent
	 * @return int -1 if not found
	 */
	function typeIndex() {
		if (!$this->parent) {
			return -1;
		} else {
			$index = -1;
			//foreach($this->parent->children as &$c) {
			//	if (strcasecmp($this->tag, $c->tag) === 0) {
			//		++$index;
			//	}
			//	if ($c === $this) {
			//		return $index;
			//	}
			//}

			foreach(array_keys($this->parent->children) as $k) {
				if (strcasecmp($this->tag, $this->parent->children[$k]->tag) === 0) {
					++$index;
				}
				if ($this->parent->children[$k] === $this) {
					return $index;
				}
			}
			return -1;
		}
	}

	/**
	 * Calculate indent of node (number of parent tags - 1)
	 * @return int
	 */
	function indent() {
		return (($this->parent) ? $this->parent->indent() + 1 : -1);
	}

	/**
	 * Get sibling node
	 * @param int $offset Offset from current node
	 * @return DomNode Null if not found
	 */
	function getSibling($offset = 1) {
		$index = $this->index() + $offset;
		if (($index >= 0) && ($index < $this->parent->childCount())) {
			return $this->parent->getChild($index);
		} else {
			return null;
		}
	}

	/**
	 * Get node next to current
	 * @param bool $skip_text_comments
	 * @return DomNode Null if not found
	 * @see getSibling()
	 * @see getPreviousSibling()
	 */
	function getNextSibling($skip_text_comments = true) {
		$offset = 1;
		while (($n = $this->getSibling($offset)) !== null) {
			if ($skip_text_comments && ($n->tag[0] === '~')) {
				++$offset;
			} else {
				break;
			}
		}

		return $n;
	}

	/**
	 * Get node previous to current
	 * @param bool $skip_text_comments
	 * @return DomNode Null if not found
	 * @see getSibling()
	 * @see getNextSibling()
	 */
	function getPreviousSibling($skip_text_comments = true) {
		$offset = -1;
		while (($n = $this->getSibling($offset)) !== null) {
			if ($skip_text_comments && ($n->tag[0] === '~')) {
				--$offset;
			} else {
				break;
			}
		}

		return $n;
	}

	/**
	 * Get namespace of node
	 * @return string
	 * @see setNamespace()
	 */
	function getNamespace() {
		if ($this->tag_ns === null) {
			$a = explode(':', $this->tag, 2);
			if (empty($a[1])) {
				$this->tag_ns = array('', $a[0]);
			} else {
				$this->tag_ns = array($a[0], $a[1]);
			}
		}

		return $this->tag_ns[0];
	}

	/**
	 * Set namespace of node
	 * @param string $ns
	 * @see getNamespace()
	 */
	function setNamespace($ns) {
		if ($this->getNamespace() !== $ns) {
			$this->tag_ns[0] = $ns;
			$this->tag = $ns.':'.$this->tag_ns[1];
		}
	}

	/**
	 * Get tagname of node (without namespace)
	 * @return string
	 * @see setTag()
	 */
	function getTag() {
		if ($this->tag_ns === null) {
			$this->getNamespace();
		}

		return $this->tag_ns[1];
	}

	/**
	 * Set tag (with or without namespace)
	 * @param string $tag
	 * @param bool $with_ns Does $tag include namespace?
	 * @see getTag()
	 */
	function setTag($tag, $with_ns = false) {
		$with_ns = $with_ns || (strpos($tag, ':') !== false);
		if ($with_ns) {
			$this->tag = $tag;
			$this->tag_ns = null;
		} elseif ($this->getTag() !== $tag) {
			$this->tag_ns[1] = $tag;
			$this->tag = (($this->tag_ns[0]) ? $this->tag_ns[0].':' : '').$tag;
		}
	}

	/**
	 * Try to determine the encoding of the current tag
	 * @return string|bool False if encoding could not be found
	 */
	function getEncoding() {
		$root = $this->getRoot();
		if ($root !== null) {
			if ($enc = $root->select('meta[charset]', 0, true, true)) {
				return $enc->getAttribute("charset");
			} elseif ($enc = $root->select('"?xml"[encoding]', 0, true, true)) {
				return $enc->getAttribute("encoding");
			} elseif ($enc = $root->select('meta[content*="charset="]', 0, true, true)) {
				$enc = $enc->getAttribute("content");
				return substr($enc, strpos($enc, "charset=")+8);
			}
		}

		return false;
	}

	/**
	 * Number of children in node
	 * @param bool $ignore_text_comments Ignore text/comments with calculation
	 * @return int
	 */
	function childCount($ignore_text_comments = false) {
		if (!$ignore_text_comments) {
			return count($this->children);
		} else{
			$count = 0;
			//foreach($this->children as &$c) {
			//	if (!$c->isTextOrComment()) {
			//		++$count;
			//	}
			//}

			foreach(array_keys($this->children) as $k) {
				if (!$this->children[$k]->isTextOrComment()) {
					++$count;
				}
			}
			return $count;
		}
	}

	/**
	 * Find node in children
	 * @param DomNode $child
	 * @return int False if not found
	 */
	function findChild($child) {
		return array_search($child, $this->children, true);
	}

	/**
	 * Checks if node has another node as child
	 * @param DomNode $child
	 * @return bool
	 */
	function hasChild($child) {
		return ((bool) findChild($child));
	}

	/**
	 * Get childnode
	 * @param int|DomNode $child Index, negative to count from end
	 * @param bool $ignore_text_comments Ignore text/comments with index calculation
	 * @return DomNode
	 */
	function &getChild($child, $ignore_text_comments = false) {
		if (!is_int($child)) {
			$child = $this->findChild($child);
		} elseif ($child < 0) {
			$child += $this->childCount($ignore_text_comments);
		}

		if ($ignore_text_comments) {
			$count = 0;
			$last = null;
			//foreach($this->children as &$c) {
			//	if (!$c->isTextOrComment()) {
			//		if ($count++ === $child) {
			//			return $c;
			//		}
			//		$last = $c;
			//	}
			//}

			foreach(array_keys($this->children) as $k) {
				if (!$this->children[$k]->isTextOrComment()) {
					if ($count++ === $child) {
						return $this->children[$k];
					}
					$last = $this->children[$k];
				}
			}
			return (($child > $count) ? $last : null);
		} else {
			return $this->children[$child];
		}
	}

	/**
	 * Add child node
	 * @param string|DomNode $tag Tag name or object
	 * @param int $offset Position to insert node, negative to count from end, null to append
	 * @return DomNode Added node
	 */
	#php4
	#function &addChild($tag, &$offset) {
	#php4e
	#php5
	function &addChild($tag, &$offset = null) {
	#php5e
        if (is_array($tag)) {
            $tag = new $this->childClass($tag, $this);
        } elseif (is_string($tag)) {
            $nodes = $this->createNodes($tag);
            $tag = array_shift($nodes);

            if ($tag && $tag->parent !== $this) {
                $index = false;
                $tag->changeParent($this, $index);
            }
		} elseif (is_object($tag) && $tag->parent !== $this) {
			$index = false; //Needs to be passed by ref
			$tag->changeParent($this, $index);
		}

		if (is_int($offset) && ($offset < count($this->children)) && ($offset !== -1)) {
			if ($offset < 0) {
				$offset += count($this->children);
			}
			array_splice($this->children, $offset++, 0, array(&$tag));
		} else {
			$this->children[] =& $tag;
		}

		return $tag;
	}

	/**
	 * First child node
	 * @param bool $ignore_text_comments Ignore text/comments with index calculation
	 * @return DomNode
	 */
	function &firstChild($ignore_text_comments = false) {
		return $this->getChild(0, $ignore_text_comments);
	}

	/**
	 * Last child node
	 * @param bool $ignore_text_comments Ignore text/comments with index calculation
	 * @return DomNode
	 */
	function &lastChild($ignore_text_comments = false) {
		return $this->getChild(-1, $ignore_text_comments);
	}

	/**
	 * Insert childnode
	 * @param string|DomNode $tag Tagname or object
	 * @param int $offset Position to insert node, negative to count from end, null to append
	 * @return DomNode Added node
	 * @see addChild();
	 */
	function &insertChild($tag, $index) {
		return $this->addChild($tag, $index);
	}

	/**
	 * Add text node
	 * @param string $text
	 * @param int $offset Position to insert node, negative to count from end, null to append
	 * @return DomNode Added node
	 * @see addChild();
	 */
	#php4
	#function &addText($text, &$offset) {
	#php4e
	#php5
	function &addText($text, &$offset = null) {
	#php5e
		return $this->addChild(new $this->childClass_Text($this, $text), $offset);
	}

	/**
	 * Add comment node
	 * @param string $text
	 * @param int $offset Position to insert node, negative to count from end, null to append
	 * @return DomNode Added node
	 * @see addChild();
	 */
	#php4
	#function &addComment($text, &$offset) {
	#php4e
	#php5
	function &addComment($text, &$offset = null) {
	#php5e
		return $this->addChild(new $this->childClass_Comment($this, $text), $offset);
	}

	/**
	 * Add conditional node
	 * @param string $condition
	 * @param bool True for <!--[if, false for <![if
	 * @param int $offset Position to insert node, negative to count from end, null to append
	 * @return DomNode Added node
	 * @see addChild();
	 */
	#php4
	#function &addConditional($condition, $hidden = true, &$offset) {
	#php4e
	#php5
	function &addConditional($condition, $hidden = true, &$offset = null) {
	#php5e
		return $this->addChild(new $this->childClass_Conditional($this, $condition, $hidden), $offset);
	}

	/**
	 * Add CDATA node
	 * @param string $text
	 * @param int $offset Position to insert node, negative to count from end, null to append
	 * @return DomNode Added node
	 * @see addChild();
	 */
	#php4
	#function &addCDATA($text, &$offset) {
	#php4e
	#php5
	function &addCDATA($text, &$offset = null) {
	#php5e
		return $this->addChild(new $this->childClass_CDATA($this, $text), $offset);
	}

	/**
	 * Add doctype node
	 * @param string $dtd
	 * @param int $offset Position to insert node, negative to count from end, null to append
	 * @return DomNode Added node
	 * @see addChild();
	 */
	#php4
	#function &addDoctype($dtd, &$offset) {
	#php4e
	#php5
	function &addDoctype($dtd, &$offset = null) {
	#php5e
		return $this->addChild(new $this->childClass_Doctype($this, $dtd), $offset);
	}

	/**
	 * Add xml node
	 * @param string $tag Tag name after "?", e.g. "php" or "xml"
	 * @param string $text
	 * @param array $attributes Array of attributes (array('attribute' => 'value'))
	 * @param int $offset Position to insert node, negative to count from end, null to append
	 * @return DomNode Added node
	 * @see addChild();
	 */
	#php4
	#function &addXML($tag = 'xml', $text = '', $attributes = array(), &$offset) {
	#php4e
	#php5
	function &addXML($tag = 'xml', $text = '', $attributes = array(), &$offset = null) {
	#php5e
		return $this->addChild(new $this->childClass_XML($this, $tag, $text, $attributes), $offset);
	}

	/**
	 * Add ASP node
	 * @param string $tag Tag name after "%"
	 * @param string $text
	 * @param array $attributes Array of attributes (array('attribute' => 'value'))
	 * @param int $offset Position to insert node, negative to count from end, null to append
	 * @return DomNode Added node
	 * @see addChild();
	 */
	#php4
	#function &addASP($tag = '', $text = '', $attributes = array(), &$offset) {
	#php4e
	#php5
	function &addASP($tag = '', $text = '', $attributes = array(), &$offset = null) {
	#php5e
		return $this->addChild(new $this->childClass_ASP($this, $tag, $text, $attributes), $offset);
	}

	/**
	 * Delete a child node
	 * @param int|DomNode $child Child(index) to delete, negative to count from end
	 * @param bool $soft_delete False to call {@link delete()} from child
	 */
	function deleteChild($child, $soft_delete = false) {
		if (is_object($child)) {
			$child = $this->findChild($child);
		} elseif ($child < 0) {
			$child += count($this->children);
		}

		if (!$soft_delete) {
			$this->children[$child]->delete();
		}
		unset($this->children[$child]);

		//Rebuild indices
		$tmp = array();

		//foreach($this->children as &$c) {
		//	$tmp[] =& $c;
		//}
		foreach(array_keys($this->children) as $k) {
			$tmp[] =& $this->children[$k];
		}
		$this->children = $tmp;
	}

	/**
	 * Wrap node
	 * @param string|DomNode $node Wrapping node, string to create new element node
	 * @param int $wrap_index Index to insert current node in wrapping node, -1 to append
	 * @param int $node_index Index to insert wrapping node, null to keep at same position
	 * @return DomNode Wrapping node
	 */
	function wrap($node, $wrap_index = -1, $node_index = null) {
		if ($node_index === null) {
			$node_index = $this->index();
		}

		if (!is_object($node)) {
			$node = $this->parent->addChild($node, $node_index);
		} elseif ($node->parent !== $this->parent) {
			$node->changeParent($this->parent, $node_index);
		}

		$this->changeParent($node, $wrap_index);
		return $node;
	}

	/**
	 * Wrap child nodes
	 * @param string|DomNode $node Wrapping node, string to create new element node
	 * @param int $start Index from child node where to start wrapping, 0 for first element
	 * @param int $end Index from child node where to end wrapping, -1 for last element
	 * @param int $wrap_index Index to insert in wrapping node, -1 to append
	 * @param int $node_index Index to insert current node, null to keep at same position
	 * @return DomNode Wrapping node
	 */
	function wrapInner($node, $start = 0, $end = -1, $wrap_index = -1, $node_index = null) {
		if ($end < 0) {
			$end += count($this->children);
		}
		if ($node_index === null) {
			$node_index = $end + 1;
		}

		if (!is_object($node)) {
			$node = $this->addChild($node, $node_index);
		} elseif ($node->parent !== $this) {
			$node->changeParent($this->parent, $node_index);
		}

		$this->moveChildren($node, $wrap_index, $start, $end);
		return $node;
	}

	/**
	 * Number of attributes
	 * @return int
	 */
	function attributeCount() {
		return count($this->attributes);
	}

	/**
	 * Find attribute using namespace, name or both
	 * @param string|int $attr Negative int to count from end
	 * @param string $compare "namespace", "name" or "total"
	 * @param bool $case_sensitive Compare with case sensitivity
	 * @return array array('ns', 'attr', 'ns:attr', index)
	 * @access private
	 */
	protected function findAttribute($attr, $compare = 'total', $case_sensitive = false) {
		if (is_int($attr)) {
			if ($attr < 0) {
				$attr += count($this->attributes);
			}
			$keys = array_keys($this->attributes);
			return $this->findAttribute($keys[$attr], 'total', true);
		} else if ($compare === 'total') {
			$b = explode(':', $attr, 2);
			if ($case_sensitive) {
				$t =& $this->attributes;
			} else {
				$t = array_change_key_case($this->attributes);
				$attr = strtolower($attr);
			}

			if (isset($t[$attr])) {
				$index = 0;
				foreach($this->attributes as $a => $v) {
					if (($v === $t[$attr]) && (strcasecmp($a, $attr) === 0)) {
						$attr = $a;
						$b = explode(':', $attr, 2);
						break;
					}
					++$index;
				}

				if (empty($b[1])) {
					return array(array('', $b[0], $attr, $index));
				} else {
					return array(array($b[0], $b[1], $attr, $index));
				}
			} else {
				return false;
			}
		} else {
			if ($this->attributes_ns === null) {
				$index = 0;
				foreach($this->attributes as $a => $v) {
					$b = explode(':', $a, 2);
					if (empty($b[1])) {
						$this->attributes_ns[$b[0]][] = array('', $b[0], $a, $index);
					} else {
						$this->attributes_ns[$b[1]][] = array($b[0], $b[1], $a, $index);
					}
					++$index;
				}
			}

			if ($case_sensitive) {
				$t =& $this->attributes_ns;
			} else {
				$t = array_change_key_case($this->attributes_ns);
				$attr = strtolower($attr);
			}

			if ($compare === 'namespace') {
				$res = array();
				foreach($t as $ar) {
					foreach($ar as $a) {
						if ($a[0] === $attr) {
							$res[] = $a;
						}
					}
				}
				return $res;
			} elseif ($compare === 'name') {
				return ((isset($t[$attr])) ? $t[$attr] : false);
			} else {
				trigger_error('Unknown comparison mode');
			}
		}
	}

	/**
	 * Checks if node has attribute
	 * @param string|int$attr Negative int to count from end
	 * @param string $compare Find node using "namespace", "name" or "total"
	 * @param bool $case_sensitive Compare with case sensitivity
	 * @return bool
	 */
	function hasAttribute($attr, $compare = 'total', $case_sensitive = false) {
		return ((bool) $this->findAttribute($attr, $compare, $case_sensitive));
	}

	/**
	 * Gets namespace of attribute(s)
	 * @param string|int $attr Negative int to count from end
	 * @param string $compare Find node using "namespace", "name" or "total"
	 * @param bool $case_sensitive Compare with case sensitivity
	 * @return string|array False if not found
	 */
	function getAttributeNS($attr, $compare = 'name', $case_sensitive = false) {
		$f = $this->findAttribute($attr, $compare, $case_sensitive);
		if (is_array($f) && $f) {
			if (count($f) === 1) {
				return $this->attributes[$f[0][0]];
			} else {
				$res = array();
				foreach($f as $a) {
					$res[] = $a[0];
				}
				return $res;
			}
		} else {
			return false;
		}
	}

	/**
	 * Sets namespace of attribute(s)
	 * @param string|int $attr Negative int to count from end
	 * @param string $namespace
	 * @param string $compare Find node using "namespace", "name" or "total"
	 * @param bool $case_sensitive Compare with case sensitivity
	 * @return bool
	 */
	function setAttributeNS($attr, $namespace, $compare = 'name', $case_sensitive = false) {
		$f = $this->findAttribute($attr, $compare, $case_sensitive);
		if (is_array($f) && $f) {
			if ($namespace) {
				$namespace .= ':';
			}
			foreach($f as $a) {
				$val = $this->attributes[$a[2]];
				unset($this->attributes[$a[2]]);
				$this->attributes[$namespace.$a[1]] = $val;
			}
			$this->attributes_ns = null;
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Gets value(s) of attribute(s)
	 * @param string|int $attr Negative int to count from end
	 * @param string $compare Find node using "namespace", "name" or "total"
	 * @param bool $case_sensitive Compare with case sensitivity
	 * @return string|array
	 */
	function getAttribute($attr, $compare = 'total', $case_sensitive = false) {
		$f = $this->findAttribute($attr, $compare, $case_sensitive);
		if (is_array($f) && $f){
			if (count($f) === 1) {
				return $this->attributes[$f[0][2]];
			} else {
				$res = array();
				foreach($f as $a) {
					$res[] = $this->attributes[$a[2]];
				}
				return $res;
			}
		} else {
			return null;
		}
	}

	/**
	 * Sets value(s) of attribute(s)
	 * @param string|int $attr Negative int to count from end
	 * @param string $compare Find node using "namespace", "name" or "total"
	 * @param bool $case_sensitive Compare with case sensitivity
	 */
	function setAttribute($attr, $val, $compare = 'total', $case_sensitive = false) {
		if ($val === null) {
			return $this->deleteAttribute($attr, $compare, $case_sensitive);
		}

		$f = $this->findAttribute($attr, $compare, $case_sensitive);
		if (is_array($f) && $f) {
			foreach($f as $a) {
				$this->attributes[$a[2]] = (string) $val;
			}
		} else {
			$this->attributes[$attr] = (string) $val;
		}
	}

	/**
	 * Add new attribute
	 * @param string $attr
	 * @param string $val
	 */
	function addAttribute($attr, $val) {
		$this->setAttribute($attr, $val, 'total', true);
	}

	/**
	 * Delete attribute(s)
	 * @param string|int $attr Negative int to count from end
	 * @param string $compare Find node using "namespace", "name" or "total"
	 * @param bool $case_sensitive Compare with case sensitivity
	 */
	function deleteAttribute($attr, $compare = 'total', $case_sensitive = false) {
		$f = $this->findAttribute($attr, $compare, $case_sensitive);
		if (is_array($f) && $f) {
			foreach($f as $a) {
				unset($this->attributes[$a[2]]);
				if ($this->attributes_ns !== null) {
					unset($this->attributes_ns[$a[1]]);
				}
			}
		}
	}

	/**
	 * Determine if node has a certain class
	 * @param string $className
	 * @return bool
	 */
	function hasClass($className) {
		return ($className && preg_match('`\b'.preg_quote($className).'\b`si', $this->class));
	}

	/**
	 * Add new class(es)
	 * @param string|array $className
	 */
	function addClass($className) {
		if (!is_array($className)) {
			$className = array($className);
		}
		$class = isset($this->class) ? $this->class : '';
		foreach ($className as $c) {
			if (!(preg_match('`\b'.preg_quote($c).'\b`si', $class) > 0)) {
				$class .= ' '.$c;
			}
		}
		 $this->class = trim($class);
	}

	/**
	 * Remove clas(ses)
	 * @param string|array $className
	 */
	function removeClass($className) {
		if (!is_array($className)) {
			$className = array($className);
		}
		$class = $this->class;
		foreach ($className as $c) {
			$class = preg_replace('`\b'.preg_quote($c).'\b`si', '', $class);
		}
		if ($class) {
			$this->class = $class;
		} else {
			unset($this->class);
		}
	}

	/**
	 * Finds children using a callback function
	 * @param callable $callback Function($node) that returns a bool
	 * @param bool|int $recursive Check recursively
	 * @param bool $check_self Include this node in search?
	 * @return array
	 */
	function getChildrenByCallback($callback, $recursive = true, $check_self = false) {
		$count = $this->childCount();
		if ($check_self && $callback($this)) {
			$res = array($this);
		} else {
			$res = array();
		}

		if ($count > 0) {
			if (is_int($recursive)) {
				$recursive = (($recursive > 1) ? $recursive - 1 : false);
			}

			for ($i = 0; $i < $count; $i++) {
				if ($callback($this->children[$i])) {
					$res[] = $this->children[$i];
				}
				if ($recursive) {
					$res = array_merge($res, $this->children[$i]->getChildrenByCallback($callback, $recursive));
				}
			}
		}

		return $res;
	}

	/**
	 * Finds children using the {$link match()} function
	 * @param $conditions See {$link match()}
	 * @param $custom_filters See {$link match()}
	 * @param bool|int $recursive Check recursively
	 * @param bool $check_self Include this node in search?
	 * @return array
	 */
	function getChildrenByMatch($conditions, $recursive = true, $check_self = false, $custom_filters = array()) {
		$count = $this->childCount();
		if ($check_self && $this->match($conditions, true, $custom_filters)) {
			$res = array($this);
		} else {
			$res = array();
		}

		if ($count > 0) {
			if (is_int($recursive)) {
				$recursive = (($recursive > 1) ? $recursive - 1 : false);
			}

			for ($i = 0; $i < $count; $i++) {
				if ($this->children[$i]->match($conditions, true, $custom_filters)) {
					$res[] = $this->children[$i];
				}
				if ($recursive) {
					$res = array_merge($res, $this->children[$i]->getChildrenByMatch($conditions, $recursive, false, $custom_filters));
				}
			}
		}

		return $res;
	}

	/**
	 * Checks if tag matches certain conditions
	 * @param array $tags array('tag1', 'tag2') or array(array(
	 *	'tag' => 'tag1',
	 *	'operator' => 'or'/'and',
	 *	'compare' => 'total'/'namespace'/'name',
	 * 	'case_sensitive' => true))
	 * @return bool
	 * @internal Used by selector class
	 * @see match()
	 * @access private
	 */
	protected function match_tags($tags) {
		$res = false;

		foreach($tags as $tag => $match) {
			if (!is_array($match)) {
				$match = array(
					'match' => $match,
					'operator' => 'or',
					'compare' => 'total',
					'case_sensitive' => false
				);
			} else {
				if (is_int($tag)) {
					$tag = $match['tag'];
				}
				if (!isset($match['match'])) {
					$match['match'] = true;
				}
				if (!isset($match['operator'])) {
					$match['operator'] = 'or';
				}
				if (!isset($match['compare'])) {
					$match['compare'] = 'total';
				}
				if (!isset($match['case_sensitive'])) {
					$match['case_sensitive'] = false;
				}
			}

			if (($match['operator'] === 'and') && (!$res)) {
				return false;
			} elseif (!($res && ($match['operator'] === 'or'))) {
				if ($match['compare'] === 'total') {
					$a = $this->tag;
				} elseif ($match['compare'] === 'namespace') {
					$a = $this->getNamespace();
				} elseif ($match['compare'] === 'name') {
					$a = $this->getTag();
				}

				if ($match['case_sensitive']) {
					$res = (($a === $tag) === $match['match']);
				} else {
					$res = ((strcasecmp($a, $tag) === 0) === $match['match']);
				}
			}
		}

		return $res;
	}

	/**
	 * Checks if attributes match certain conditions
	 * @param array $attributes array('attr' => 'val') or array(array(
	 *	'operator_value' => 'equals'/'='/'contains_regex'/etc
	 *	'attribute' => 'attr',
	 *	'value' => 'val',
	 *	'match' => true,
	 *	'operator_result' => 'or'/'and',
	 *	'compare' => 'total'/'namespace'/'name',
	 *	'case_sensitive' => true))
	 * @return bool
	 * @internal Used by selector class
	 * @see match()
	 * @access private
	 */
	protected function match_attributes($attributes) {
		$res = false;

		foreach($attributes as $attribute => $match) {
			if (!is_array($match)) {
				$match = array(
					'operator_value' => 'equals',
					'value' => $match,
					'match' => true,
					'operator_result' => 'or',
					'compare' => 'total',
					'case_sensitive' => false
				);
			} else {
				if (is_int($attribute)) {
					$attribute = $match['attribute'];
				}
				if (!isset($match['match'])) {
					$match['match'] = true;
				}
				if (!isset($match['operator_result'])) {
					$match['operator_result'] = 'or';
				}
				if (!isset($match['compare'])) {
					$match['compare'] = 'total';
				}
				if (!isset($match['case_sensitive'])) {
					$match['case_sensitive'] = false;
				}
			}

			if (is_string($match['value']) && (!$match['case_sensitive'])) {
				$match['value'] = strtolower($match['value']);
			}

			if (($match['operator_result'] === 'and') && (!$res)) {
				return false;
			} elseif (!($res && ($match['operator_result'] === 'or'))) {
				$possibles = $this->findAttribute($attribute, $match['compare'], $match['case_sensitive']);

				$has = (is_array($possibles) && $possibles);
				$res = (($match['value'] === $has) || (($match['match'] === false) && ($has === $match['match'])));

				if ((!$res) && $has && is_string($match['value'])) {
					foreach($possibles as $a) {
						$val = $this->attributes[$a[2]];
						if (is_string($val) && (!$match['case_sensitive'])) {
							$val = strtolower($val);
						}

						switch($match['operator_value']) {
							case '%=':
							case 'contains_regex':
								$res = ((preg_match('`'.$match['value'].'`s', $val) > 0) === $match['match']);
								if ($res) break 1; else break 2;

							case '|=':
							case 'contains_prefix':
								$res = ((preg_match('`\b'.preg_quote($match['value']).'[\-\s]`s', $val) > 0) === $match['match']);
								if ($res) break 1; else break 2;

							case '~=':
							case 'contains_word':
								$res = ((preg_match('`\s'.preg_quote($match['value']).'\s`s', " $val ") > 0) === $match['match']);
								if ($res) break 1; else break 2;

							case '*=':
							case 'contains':
								$res = ((strpos($val, $match['value']) !== false) === $match['match']);
								if ($res) break 1; else break 2;

							case '$=':
							case 'ends_with':
								$res = ((substr($val, -strlen($match['value'])) === $match['value']) === $match['match']);
								if ($res) break 1; else break 2;

							case '^=':
							case 'starts_with':
								$res = ((substr($val, 0, strlen($match['value'])) === $match['value']) === $match['match']);
								if ($res) break 1; else break 2;

							case '!=':
							case 'not_equal':
								$res = (($val !== $match['value']) === $match['match']);
								if ($res) break 1; else break 2;

							case '=':
							case 'equals':
								$res = (($val === $match['value']) === $match['match']);
								if ($res) break 1; else break 2;

							case '>=':
							case 'bigger_than':
								$res = (($val >= $match['value']) === $match['match']);
								if ($res) break 1; else break 2;

							case '<=':
							case 'smaller_than':
								$res = (($val >= $match['value']) === $match['match']);
								if ($res) break 1; else break 2;

							default:
								trigger_error('Unknown operator "'.$match['operator_value'].'" to match attributes!');
								return false;
						}
					}
				}
			}
		}

		return $res;
	}

	/**
	 * Checks if node matches certain filters
	 * @param array $tags array(array(
	 *	'filter' => 'last-child',
	 *	'params' => '123'))
	 * @param array $custom_filters Custom map next to {@link $filter_map}
	 * @return bool
	 * @internal Used by selector class
	 * @see match()
	 * @access private
	 */
	protected function match_filters($conditions, $custom_filters = array()) {
		foreach($conditions as $c) {
			$c['filter'] = strtolower($c['filter']);
			if (isset($this->filter_map[$c['filter']])) {
				if (!$this->{$this->filter_map[$c['filter']]}($c['params'])) {
					return false;
				}
			} elseif (isset($custom_filters[$c['filter']])) {
				if (!call_user_func($custom_filters[$c['filter']], $this, $c['params'])) {
					return false;
				}
			} else {
				trigger_error('Unknown filter "'.$c['filter'].'"!');
				return false;
			}
		}

		return true;
	}

	/**
	 * Checks if node matches certain conditions
	 * @param array $tags array('tags' => array(tag_conditions), 'attributes' => array(attr_conditions), 'filters' => array(filter_conditions))
	 * @param array $match Should conditions evaluate to true?
	 * @param array $custom_filters Custom map next to {@link $filter_map}
	 * @return bool
	 * @internal Used by selector class
	 * @see match_tags();
	 * @see match_attributes();
	 * @see match_filters();
	 * @access private
	 */
	function match($conditions, $match = true, $custom_filters = array()) {
		$t = isset($conditions['tags']);
		$a = isset($conditions['attributes']);
		$f = isset($conditions['filters']);

		if (!($t || $a || $f)) {
			if (is_array($conditions) && $conditions) {
				foreach($conditions as $c) {
					if ($this->match($c, $match)) {
						return true;
					}
				}
			}

			return false;
		} else {
			if (($t && (!$this->match_tags($conditions['tags']))) === $match) {
				return false;
			}

			if (($a && (!$this->match_attributes($conditions['attributes']))) === $match) {
				return false;
			}

			if (($f && (!$this->match_filters($conditions['filters'], $custom_filters))) === $match) {
				return false;
			}

			return true;
		}
	}

	/**
	 * Finds children that match a certain attribute
	 * @param string $attribute
	 * @param string $value
	 * @param string $mode Compare mode, "equals", "|=", "contains_regex", etc.
	 * @param string $compare "total"/"namespace"/"name"
	 * @param bool|int $recursive
	 * @return array
	 */
	function getChildrenByAttribute($attribute, $value, $mode = 'equals', $compare = 'total', $recursive = true) {
		if ($this->childCount() < 1) {
			return array();
		}

		$mode = explode(' ', strtolower($mode));
		$match = ((isset($mode[1]) && ($mode[1] === 'not')) ? 'false' : 'true');

		return $this->getChildrenByMatch(
			array(
				'attributes' => array(
					$attribute => array(
						'operator_value' => $mode[0],
						'value' => $value,
						'match' => $match,
						'compare' => $compare
					)
				)
			),
			$recursive
		);
	}

	/**
	 * Finds children that match a certain tag
	 * @param string $tag
	 * @param string $compare "total"/"namespace"/"name"
	 * @param bool|int $recursive
	 * @return array
	 */
	function getChildrenByTag($tag, $compare = 'total', $recursive = true) {
		if ($this->childCount() < 1) {
			return array();
		}

		$tag = explode(' ', strtolower($tag));
		$match = ((isset($tag[1]) && ($tag[1] === 'not')) ? 'false' : 'true');

		return $this->getChildrenByMatch(
			array(
				'tags' => array(
					$tag[0] => array(
						'match' => $match,
						'compare' => $compare
					)
				)
			),
			$recursive
		);
	}

	/**
	 * Finds all children using ID attribute
	 * @param string $id
	 * @param bool|int $recursive
	 * @return array
	 */
	function getChildrenByID($id, $recursive = true) {
		return $this->getChildrenByAttribute('id', $id, 'equals', 'total', $recursive);
	}

	/**
	 * Finds all children using class attribute
	 * @param string $class
	 * @param bool|int $recursive
	 * @return array
	 */
	function getChildrenByClass($class, $recursive = true) {
		return $this->getChildrenByAttribute('class', $class, 'equals', 'total', $recursive);
	}

	/**
	 * Finds all children using name attribute
	 * @param string $name
	 * @param bool|int $recursive
	 * @return array
	 */
	function getChildrenByName($name, $recursive = true) {
		return $this->getChildrenByAttribute('name', $name, 'equals', 'total', $recursive);
	}

    /**
     * Performs a css query on the node.
     * @param string $query
     * @return IQuery Returns the matching nodes from the query.
     */
    public function query($query = '*') {
        $select = $this->select($query);
        $result = new \pagelayerQuery((array)$select);
        return $result;
    }

	/**
	 * Performs css query on node
	 * @param string $query
	 * @param int|bool $index True to return node instead of array if only 1 match,
	 * false to return array, int to return match at index, negative int to count from end
	 * @param bool|int $recursive
	 * @param bool $check_self Include this node in search or only search child nodes
	 * @return DomNode[]|DomNode Returns an array of matching {@link DomNode} objects
     *  or a single {@link DomNode} if `$index` is not false.
	 */
	function select($query = '*', $index = false, $recursive = true, $check_self = false) {
		$s = new $this->selectClass($this, $query, $check_self, $recursive);
		$res = $s->result;
		unset($s);
		if (is_array($res) && ($index === true) && (count($res) === 1)) {
			return $res[0];
		} elseif (is_int($index) && is_array($res)) {
			if ($index < 0) {
				$index += count($res);
			}
			return ($index < count($res)) ? $res[$index] : null;
        } else {
			return $res;
		}
	}

	/**
	 * Checks if node matches css query filter ":root"
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_root() {
		return (strtolower($this->tag) === 'html');
	}

	/**
	 * Checks if node matches css query filter ":nth-child(n)"
	 * @param string $n 1-based index
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_nchild($n) {
		return ($this->index(false)+1 === (int) $n);
	}

	/**
	 * Checks if node matches css query filter ":gt(n)"
	 * @param string $n 0-based index
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_gt($n) {
		return ($this->index(false) > (int) $n);
	}

	/**
	 * Checks if node matches css query filter ":lt(n)"
	 * @param string $n 0-based index
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_lt($n) {
		return ($this->index(false) < (int) $n);
	}

	/**
	 * Checks if node matches css query filter ":nth-last-child(n)"
	 * @param string $n 1-based index
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_nlastchild($n) {
		if ($this->parent === null) {
			return false;
		} else {
			return ($this->parent->childCount(true) - $this->index(false) === (int) $n);
		}
	}

	/**
	 * Checks if node matches css query filter ":nth-of-type(n)"
	 * @param string $n 1-based index
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_ntype($n) {
		return ($this->typeIndex()+1 === (int) $n);
	}

	/**
	 * Checks if node matches css query filter ":nth-last-of-type(n)"
	 * @param string $n 1-based index
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_nlastype($n) {
		if ($this->parent === null) {
			return false;
		} else {
			return (count($this->parent->getChildrenByTag($this->tag, 'total', false)) - $this->typeIndex() === (int) $n);
		}
	}

	/**
	 * Checks if node matches css query filter ":odd"
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_odd() {
		return (($this->index(false) & 1) === 1);
	}

	/**
	 * Checks if node matches css query filter ":even"
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_even() {
		return (($this->index(false) & 1) === 0);
	}

	/**
	 * Checks if node matches css query filter ":every(n)"
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_every($n) {
		return (($this->index(false) % (int) $n) === 0);
	}

	/**
	 * Checks if node matches css query filter ":first"
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_first() {
		return ($this->index(false) === 0);
	}

	/**
	 * Checks if node matches css query filter ":last"
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_last() {
		if ($this->parent === null) {
			return false;
		} else {
			return ($this->parent->childCount(true) - 1 === $this->index(false));
		}
	}

	/**
	 * Checks if node matches css query filter ":first-of-type"
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_firsttype() {
		return ($this->typeIndex() === 0);
	}

	/**
	 * Checks if node matches css query filter ":last-of-type"
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_lasttype() {
		if ($this->parent === null) {
			return false;
		} else {
			return (count($this->parent->getChildrenByTag($this->tag, 'total', false)) - 1 === $this->typeIndex());
		}
	}

	/**
	 * Checks if node matches css query filter ":only-child"
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_onlychild() {
		if ($this->parent === null) {
			return false;
		} else {
			return ($this->parent->childCount(true) === 1);
		}
	}

	/**
	 * Checks if node matches css query filter ":only-of-type"
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_onlytype() {
		if ($this->parent === null) {
			return false;
		} else {
			return (count($this->parent->getChildrenByTag($this->tag, 'total', false)) === 1);
		}
	}

	/**
	 * Checks if node matches css query filter ":empty"
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_empty() {
		return ($this->childCount() === 0);
	}

	/**
	 * Checks if node matches css query filter ":not-empty"
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_notempty() {
		return ($this->childCount() !== 0);
	}

	/**
	 * Checks if node matches css query filter ":has-text"
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_hastext() {
		return ($this->getPlainText() !== '');
	}

	/**
	 * Checks if node matches css query filter ":no-text"
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_notext() {
		return ($this->getPlainText() === '');
	}

	/**
	 * Checks if node matches css query filter ":lang(s)"
	 * @param string $lang
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_lang($lang) {
		return ($this->lang === $lang);
	}

	/**
	 * Checks if node matches css query filter ":contains(s)"
	 * @param string $text
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_contains($text) {
		return (strpos($this->getPlainTextUTF8(), $text) !== false);
	}

	/**
	 * Checks if node matches css query filter ":has(s)"
	 * @param string $selector
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_has($selector) {
		$s = $this->select((string) $selector, false);
		return (is_array($s) && (count($s) > 0));
	}

	/**
	 * Checks if node matches css query filter ":not(s)"
	 * @param string $selector
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_not($selector) {
		$s = $this->select((string) $selector, false, true, true);
		return ((!is_array($s)) || (array_search($this, $s, true) === false));
	}

	/**
	 * Checks if node matches css query filter ":element"
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_element() {
		return true;
	}

	/**
	 * Checks if node matches css query filter ":text"
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_text() {
		return false;
	}

    /**
     * Checks if a node matches css query filter ":checked"
     * @return bool
     * @see match()
     */
    protected function filter_checked() {
        $attr = $this->getAttribute('checked');
        if (is_array($attr))
            $attr = reset($attr);
        return strcasecmp($attr, 'checked') === 0;
    }

	/**
	 * Checks if node matches css query filter ":comment"
	 * @return bool
	 * @see match()
	 * @access private
	 */
	protected function filter_comment() {
		return false;
	}

    /**
     * Checks if a node matches css query filter ":selected"
     * @return bool
     * @see match()
     */
    protected function filter_selected() {
        $attr = $this->getAttribute('selected');
        if (is_array($attr))
            $attr = reset($attr);

        return strcasecmp($attr, 'selected') === 0;
    }

    public function after($content) {
        $offset = $this->index() + 1;
        $parent = $this->parent;
        $nodes = $this->createNodes($content);

        foreach ($nodes as $node) {
            $node->changeParent($parent, $offset);
        }
        return $this;
    }


    /**
     * Create a {@link DomNode} from its string representation.
     * @param string|DomNode $content
     * @return DomNode
     */
    protected function createNode($content) {
        $nodes = $this->createNodes($content);
        return reset($nodes);
    }

    /**
     * Create an array of {@link DomNode} objects from their string representation.
     * @param string|DomNode $content
     * @return DomNode[]
     */
    protected function createNodes($content) {
        if (is_string($content)) {
            if (strpos($content, ' ') === false) {
                $nodes = array(new $this->childClass($content, $this));
            } else {
                $node = new $this->parserClass($content);
                $nodes = $node->root->children;
            }
        } else {
            $nodes = (array)$content;
        }
        return $nodes;
    }

    public function append($content) {
        $nodes = $this->createNodes($content);
        foreach ($nodes as $node) {
            $node->changeParent($this);
        }
        return $this;
    }

    public function attr($name, $value = null) {
        if ($value === null)
            return $this->getAttribute($name);

        $this->setAttribute($name, $value);
        return $this;
    }

   public function before($content) {
      $offset = $this->index();
      $parent = $this->parent;
      $nodes = $this->createNodes($content);

      foreach ($nodes as $node) {
          $node->changeParent($parent, $offset);
      }

      return $this;
   }

   #[\ReturnTypeWillChange]
   public function count() {
       return 1;
   }

//   public function css($name, $value = null) {
//
//   }

   public function prepend($content = null) {
      $offset = 0;
      $parent = $this;
      $nodes = $this->createNodes($content);

      foreach ($nodes as $node) {
          $node->changeParent($parent, $offset);
      }

      return $this;
   }

    public function prop($name, $value = null) {
        switch (strtolower($name)) {
            case 'checked':
            case 'disabled':
            case 'selected':
                if ($value !== null) {
                    if ($value) {
                        $this->attr($name, $name);
                    } else {
                        $this->removeAttr($name);
                    }
                    return $this;
                }
                return $this->attr($name) == $name;
            case 'tagname':
                return $this->tagName($value);
        }
        // The property is not supported, degrade gracefully
        if ($value === null)
            return $this;
        else
            return null;
    }

   public function remove($selector = null) {
      if ($selector == null) {
         $this->delete();
      } else {
         $nodes = (array)$this->select($selector);
         foreach ($nodes as $node) {
            $node->delete();
         }
      }
   }

   public function removeAttr($name) {
      $this->deleteAttribute($name);

      return $this;
   }

   function replaceWith($content) {
        $node_index = $this->index();

        // Add the new node.
        $node = $this->createNode($content);
        $node->changeParent($this->parent, $node_index);

        // Remove this node.
        $this->remove();

		return $node;
	}

    /**
     * @param type $value
     * @return string|DomNode
     */
    public function tagName($value = null) {
        if ($value !== null) {
            $this->setTag($value);
            return $this;
        }
        return $this->getTag();
    }

   public function text($value = null) {
      if ($value === null)
         return $this->getPlainText();

      $this->setPlainText($value);
      return $this;
   }

   public function toggleClass($classname, $switch = null) {
      if ($switch === true) {
         $this->addClass($classname);
      } elseif ($switch === false) {
         $this->removeClass($classname);
      } else {
         if ($this->hasClass($classname))
            $this->removeClass($classname);
         else
            $this->addClass($classname);
      }
      return $this;
   }

   public function unwrap() {
      $this->parent->detach(true);
      return $this;
   }

    public function val($value = null) {
        switch (strtolower($this->tag)) {
            case 'select':
                if ($value === null) {
                    // Return the value of a selected child.
                    return $this->query('option:selected')->attr('value');
                } else {
                    // Select the option with the right value and deselect the others.
                    foreach ($this->query('option') as $option) {
                        if ($option->attr('value') == $value) {
                            $option->attr('selected', 'selected');
                        } else {
                            $option->removeAttr('selected');
                        }
                    }
                    return $this;
                }
            case 'textarea':
                if ($value === null) {
                    // Return the contents of the textarea.
                    return $this->getInnerText();
                } else {
                    // Set the contents of the textarea.
                    $this->setInnerText($value);
                    return $this;
                }
            case 'input':
                switch (strtolower($this->getAttribute('type'))) {
                    case 'checkbox':
                        if ($value === null)
                            return $this->prop('checked') ? $this->getAttribute('value') : null;
                        else {
                            if (!$value) {
                                $this->deleteAttribute('checked');
                            } else {
                                $this->setAttribute('value', $value);
                                $this->setAttribute('checked', 'checked');
                            }
                            return $this;
                        }
                }
        }

        // Other node types can just get/set the value attribute.
        if ($value !== null) {
           $this->setAttribute('value', $value);
           return $this;
        }
        return $this->getAttribute('value');
    }

}

/**
 * Node subclass for text
 */
class TextNode extends DomNode {
	#php4 Compatibility with PHP4, this gets changed to a regular var in release tool
	#static $NODE_TYPE = self::NODE_TEXT;
	#php4e
	#php5
	const NODE_TYPE = self::NODE_TEXT;
	#php5e
	var $tag = '~text~';

	/**
	 * @var string
	 */
	var $text = '';

	/**
	 * Class constructor
	 * @param DomNode $parent
	 * @param string $text
	 */
	function __construct($parent, $text = '') {
		$this->parent = $parent;
		$this->text = $text;
	}

	#php4 PHP4 class constructor compatibility
	#function TextNode($parent, $text = '') {return $this->__construct($parent, $text);}
	#php4e

	function isText() {return true;}
	function isTextOrComment() {return true;}
	protected function filter_element() {return false;}
	protected function filter_text() {return true;}
	function toString_attributes() {return '';}
	function toString_content($attributes = true, $recursive = true, $content_only = false) {return $this->text;}
	function toString($attributes = true, $recursive = true, $content_only = false) {return $this->text;}

    /**
     * {@inheritdoc}
     */
    public function text($value = null) {
        if ($value !== null) {
            $this->text = $value;
            return $this;
        }
        return $this->text;
    }

    /**
     * {@inheritdoc}
     */
    public function html($value = null) {
        if ($value !== null) {
            $this->text = $value;
            return $this;
        }
        return $this->text;
    }
}

/**
 * Node subclass for comments
 */
class CommentNode extends DomNode {
	#php4 Compatibility with PHP4, this gets changed to a regular var in release tool
	#static $NODE_TYPE = self::NODE_COMMENT;
	#php4e
	#php5
	const NODE_TYPE = self::NODE_COMMENT;
	#php5e
	var $tag = '~comment~';

	/**
	 * @var string
	 */
	var $text = '';

	/**
	 * Class constructor
	 * @param DomNode $parent
	 * @param string $text
	 */
	function __construct($parent, $text = '') {
		$this->parent = $parent;
		$this->text = $text;
	}

	#php4 PHP4 class constructor compatibility
	#function CommentNode($parent, $text = '') {return $this->__construct($parent, $text);}
	#php4e

	function isComment() {return true;}
	function isTextOrComment() {return true;}
	protected function filter_element() {return false;}
	protected function filter_comment() {return true;}
	function toString_attributes() {return '';}
	function toString_content($attributes = true, $recursive = true, $content_only = false) {return $this->text;}
	function toString($attributes = true, $recursive = true, $content_only = false) {return '<!--'.$this->text.'-->';}
}

/**
 * Node subclass for conditional tags
 */
class ConditionalTagNode extends DomNode {
	#php4 Compatibility with PHP4, this gets changed to a regular var in release tool
	#static $NODE_TYPE = self::NODE_CONDITIONAL;
	#php4e
	#php5
	const NODE_TYPE = self::NODE_CONDITIONAL;
	#php5e
	var $tag = '~conditional~';

	/**
	 * @var string
	 */
	var $condition = '';

	/**
	 * Class constructor
	 * @param DomNode $parent
	 * @param string $condition e.g. "if IE"
	 * @param bool $hidden <!--[if if true, <![if if false
	 */
	function __construct($parent, $condition = '', $hidden = true) {
		$this->parent = $parent;
		$this->hidden = $hidden;
		$this->condition = $condition;
	}

	#php4 PHP4 class constructor compatibility
	#function ConditionalTagNode($parent, $condition = '', $hidden = true) {return $this->__construct($parent, $condition, $hidden);}
	#php4e

	protected function filter_element() {return false;}
	function toString_attributes() {return '';}
	function toString($attributes = true, $recursive = true, $content_only = false) {
		if ($content_only) {
			if (is_int($content_only)) {
				--$content_only;
			}
			return $this->toString_content($attributes, $recursive, $content_only);
		}

		$s = '<!'.(($this->hidden) ? '--' : '').'['.$this->condition.']>';
		if($recursive) {
			$s .= $this->toString_content($attributes);
		}
		$s .= '<![endif]'.(($this->hidden) ? '--' : '').'>';
		return $s;
	}
}

/**
 * Node subclass for CDATA tags
 */
class CdataNode extends DomNode {
	#php4 Compatibility with PHP4, this gets changed to a regular var in release tool
	#static $NODE_TYPE = self::NODE_CDATA;
	#php4e
	#php5
	const NODE_TYPE = self::NODE_CDATA;
	#php5e
	var $tag = '~cdata~';

	/**
	 * @var string
	 */
	var $text = '';

	/**
	 * Class constructor
	 * @param DomNode $parent
	 * @param string $text
	 */
	function __construct($parent, $text = '') {
		$this->parent = $parent;
		$this->text = $text;
	}

	#php4 PHP4 class constructor compatibility
	#function CdataNode($parent, $text = '') {return $this->__construct($parent, $text);}
	#php4e

	protected function filter_element() {return false;}
	function toString_attributes() {return '';}
	function toString_content($attributes = true, $recursive = true, $content_only = false) {return $this->text;}
	function toString($attributes = true, $recursive = true, $content_only = false) {return '<![CDATA['.$this->text.']]>';}
}

/**
 * Node subclass for doctype tags
 */
class DoctypeNode extends DomNode {
	#php4 Compatibility with PHP4, this gets changed to a regular var in release tool
	#static $NODE_TYPE = self::NODE_DOCTYPE;
	#php4e
	#php5
	const NODE_TYPE = self::NODE_DOCTYPE;
	#php5e
	var $tag = '!DOCTYPE';

	/**
	 * @var string
	 */
	var $dtd = '';

	/**
	 * Class constructor
	 * @param DomNode $parent
	 * @param string $dtd
	 */
	function __construct($parent, $dtd = '') {
		$this->parent = $parent;
		$this->dtd = $dtd;
	}

	#php4 PHP4 class constructor compatibility
	#function DoctypeNode($parent, $dtd = '') {return $this->__construct($parent, $dtd);}
	#php4e

	protected function filter_element() {return false;}
	function toString_attributes() {return '';}
	function toString_content($attributes = true, $recursive = true, $content_only = false) {return $this->text;}
	function toString($attributes = true, $recursive = true, $content_only = false) {return '<'.$this->tag.' '.$this->dtd.'>';}
}

/**
 * Node subclass for embedded tags like xml, php and asp
 */
class EmbeddedNode extends DomNode {

	/**
	 * @var string
	 * @internal specific char for tags, like ? for php and % for asp
	 * @access private
	 */
	var $tag_char = '';

	/**
	 * @var string
	 */
	var $text = '';

	/**
	 * Class constructor
	 * @param DomNode $parent
	 * @param string $tag_char {@link $tag_char}
	 * @param string $tag {@link $tag}
	 * @param string $text
	 * @param array $attributes array('attr' => 'val')
	 */
	function __construct($parent, $tag_char = '', $tag = '', $text = '', $attributes = array()) {
		$this->parent = $parent;
		$this->tag_char = $tag_char;
		if ($tag[0] !== $this->tag_char) {
			$tag = $this->tag_char.$tag;
		}
		$this->tag = $tag;
		$this->text = $text;
		$this->attributes = $attributes;
		$this->self_close_str = $tag_char;
	}

	#php4 PHP4 class constructor compatibility
	#function EmbeddedNode($parent, $tag_char = '', $tag = '', $text = '', $attributes = array()) {return $this->__construct($parent, $tag_char, $tag, $text, $attributes);}
	#php4e

	protected function filter_element() {return false;}
	function toString($attributes = true, $recursive = true, $content_only = false) {
		$s = '<'.$this->tag;
		if ($attributes) {
			$s .= $this->toString_attributes();
		}
		$s .= $this->text.$this->self_close_str.'>';
		return $s;
	}
}

/**
 * Node subclass for "?" tags, like php and xml
 */
class XmlNode extends EmbeddedNode {
	#php4 Compatibility with PHP4, this gets changed to a regular var in release tool
	#static $NODE_TYPE = self::NODE_XML;
	#php4e
	#php5
	const NODE_TYPE = self::NODE_XML;
	#php5e

	/**
	 * Class constructor
	 * @param DomNode $parent
	 * @param string $tag {@link $tag}
	 * @param string $text
	 * @param array $attributes array('attr' => 'val')
	 */
	function __construct($parent, $tag = 'xml', $text = '', $attributes = array()) {
		return parent::__construct($parent, '?', $tag, $text, $attributes);
	}

	#php4 PHP4 class constructor compatibility
	#function XmlNode($parent, $tag = 'xml', $text = '', $attributes = array()) {return $this->__construct($parent, $tag, $text, $attributes);}
	#php4e
}

/**
 * Node subclass for asp tags
 */
class AspEmbeddedNode extends EmbeddedNode {
	#php4 Compatibility with PHP4, this gets changed to a regular var in release tool
	#static $NODE_TYPE = self::NODE_ASP;
	#php4e
	#php5
	const NODE_TYPE = self::NODE_ASP;
	#php5e

	/**
	 * Class constructor
	 * @param DomNode $parent
	 * @param string $tag {@link $tag}
	 * @param string $text
	 * @param array $attributes array('attr' => 'val')
	 */
	function __construct($parent, $tag = '', $text = '', $attributes = array()) {
		return parent::__construct($parent, '%', $tag, $text, $attributes);
	}

	#php4 PHP4 class constructor compatibility
	#function AspEmbeddedNode($parent, $tag = '', $text = '', $attributes = array()) {return $this->__construct($parent, $tag, $text, $attributes);}
	#php4e
}

?>pquery/README.md000064400000003746151526522430007367 0ustar00# pQuery

[![Build Status](https://img.shields.io/travis/tburry/pquery.svg?style=flat)](https://travis-ci.org/tburry/pquery)
[![Coverage](https://img.shields.io/scrutinizer/coverage/g/tburry/pquery.svg?style=flat)](https://scrutinizer-ci.com/g/tburry/pquery/)
[![Latest Stable Version](http://img.shields.io/packagist/v/tburry/pquery.svg?style=flat)](https://packagist.org/packages/tburry/pquery)

pQuery is a jQuery like html dom parser written in php. It is a fork of the [ganon dom parser](https://code.google.com/p/ganon/).

## Basic usage

To get started using pQuery do the following.

1. Require the pQuery library into your project using [composer](http://getcomposer.org/doc/01-basic-usage.md#the-require-key).
2. Parse a snippet of html using `pQuery::parseStr()` or `pQuery::parseFile()` to return a document object model (DOM).
3. Run jQuery like functions on the DOM.

## Example

The following example parses an html string and does some manipulation on it.

```php
$html = '<div class="container">
  <div class="inner verb">Hello</div>
  <div class="inner adj">Cruel</div>
  <div class="inner obj">World</div>
</div>';

$dom = pQuery::parseStr($html);

$dom->query('.inner')
    ->tagName('span');

$dom->query('.adj')
    ->html('Beautiful')
    ->tagName('i');

echo $dom->html();
```

## Differences between pQuery and ganon

pQuery is a fork of the [ganon php processor](https://code.google.com/p/ganon/). Most of the functionality is identical to ganon with the following exceptions.

* pQuery is a composer package.
* pQuery renames ganon's classes and puts them into a namespace.
* pQuery is used only with objects rather than functions so that it can be autoloaded.
* pQuery Adds the `IQuery` interface and the `pQuery` object that define the jQuery-like interface for querying the dom.
* pQuery implements more of jQuery's methods. See the `IQuery` interface for a list of methods.
* pQuery supports adding tags to the dom using the `<div class="something"></div>` notation rather than just `div`.
pquery/composer.json000064400000001274151526522430010624 0ustar00{
   "name": "tburry/pquery",
   "type": "library",
   "description": "A jQuery like html dom parser written in php.",
   "keywords": ["php", "dom", "ganon"],
   "license": "LGPL-2.1",
   "authors": [
       { "name": "Todd Burry", "email": "todd@vanillaforums.com", "role": "Developer" }
   ],
   "autoload": {
      "classmap": [
          "IQuery.php", 
          "gan_formatter.php", 
          "gan_node_html.php",
          "gan_parser_html.php",
          "gan_selector_html.php",
          "gan_tokenizer.php",
          "gan_xml2array.php",
          "pQuery.php"
      ]
   },
   "require": {
       "php": ">=5.3.0"
   },
   "require-dev": {
       "htmlawed/htmlawed": "dev-master"
   }
}pquery/gan_tokenizer.php000064400000037466151526522440011467 0ustar00<?php
/**
 * @author Niels A.D.
 * @author Todd Burry <todd@vanillaforums.com>
 * @copyright 2010 Niels A.D., 2014 Todd Burry
 * @license http://opensource.org/licenses/LGPL-2.1 LGPL-2.1
 * @package pQuery
 */

namespace pagelayerQuery;

/**
 * Converts a document into tokens
 *
 * Can convert any string into tokens. The base class only supports
 * identifier/whitespace tokens. For more tokens, the class can be
 * easily extended.
 *
 * Use like:
 * <code>
 * <?php
 *  $a = new TokenizerBase('hello word');
 *  while ($a->next() !== $a::TOK_NULL) {
 *    echo $a->token, ': ',$a->getTokenString(), "<br>\n";
 *  }
 * ?>
 * </code>
 *
 * @internal The tokenizer works with a character map that connects a certain
 * character to a certain function/token. This class is build with speed in mind.
 */
class TokenizerBase {

	/**
	 * NULL Token, used at end of document (parsing should stop after this token)
	 */
	const TOK_NULL = 0;
	/**
	 * Unknown token, used at unidentified character
	 */
	const TOK_UNKNOWN = 1;
	/**
	 * Whitespace token, used with whitespace
	 */
	const TOK_WHITESPACE = 2;
	/**
	 * Identifier token, used with identifiers
	 */
	const TOK_IDENTIFIER = 3;

	/**
	 * The document that is being tokenized
	 * @var string
	 * @internal Public for faster access!
	 * @see setDoc()
	 * @see getDoc()
	 * @access private
	 */
	var $doc = '';

	/**
	 * The size of the document (length of string)
	 * @var int
	 * @internal Public for faster access!
	 * @see $doc
	 * @access private
	 */
	var $size = 0;

	/**
	 * Current (character) position in the document
	 * @var int
	 * @internal Public for faster access!
	 * @see setPos()
	 * @see getPos()
	 * @access private
	 */
	var $pos = 0;

	/**
	 * Current (Line/Column) position in document
	 * @var array (Current_Line, Line_Starting_Pos)
	 * @internal Public for faster access!
	 * @see getLinePos()
	 * @access private
	 */
	var $line_pos = array(0, 0);

	/**
	 * Current token
	 * @var int
	 * @internal Public for faster access!
	 * @see getToken()
	 * @access private
	 */
	var $token = self::TOK_NULL;

	/**
	 * Start position of token. If NULL, then current position is used.
	 * @var int
	 * @internal Public for faster access!
	 * @see getTokenString()
	 * @access private
	 */
	var $token_start = null;

	/**
	 * List with all the character that can be considered as whitespace
	 * @var array|string
	 * @internal Variable is public + associated array for faster access!
	 * @internal array(' ' => true) will recognize space (' ') as whitespace
	 * @internal String will be converted to array in constructor
	 * @internal Result token will be {@link self::TOK_WHITESPACE};
	 * @see setWhitespace()
	 * @see getWhitespace()
	 * @access private
	 */
	var $whitespace = " \t\n\r\0\x0B";

	/**
	 * List with all the character that can be considered as identifier
	 * @var array|string
	 * @internal Variable is public + associated array for faster access!
	 * @internal array('a' => true) will recognize 'a' as identifier
	 * @internal String will be converted to array in constructor
	 * @internal Result token will be {@link self::TOK_IDENTIFIER};
	 * @see setIdentifiers()
	 * @see getIdentifiers()
	 * @access private
	 */
	var $identifiers = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_';

	/**
	 * All characters that should be mapped to a token/function that cannot be considered as whitespace or identifier
	 * @var array
	 * @internal Variable is public + associated array for faster access!
	 * @internal array('a' => 'parse_a') will call $this->parse_a() if it matches the character 'a'
	 * @internal array('a' => self::TOK_A) will set token to TOK_A if it matches the character 'a'
	 * @see mapChar()
	 * @see unmapChar()
	 * @access private
	 */
	var $custom_char_map = array();

	/**
	 * Automatically built character map. Built using {@link $identifiers}, {@link $whitespace} and {@link $custom_char_map}
	 * @var array
	 * @internal Public for faster access!
	 * @access private
	 */
	var $char_map = array();

	/**
	 * All errors found while parsing the document
	 * @var array
	 * @see addError()
	 */
	var $errors = array();

	/**
	 * Class constructor
	 * @param string $doc Document to be tokenized
	 * @param int $pos Position to start parsing
	 * @see setDoc()
	 * @see setPos()
	 */
	function __construct($doc = '', $pos = 0) {
		$this->setWhitespace($this->whitespace);
		$this->setIdentifiers($this->identifiers);

		$this->setDoc($doc, $pos);
	}

	#php4 PHP4 class constructor compatibility
	#function TokenizerBase($doc = '', $pos = 0) {return $this->__construct($doc, $pos);}
	#php4e

	/**
	 * Sets target document
	 * @param string $doc Document to be tokenized
	 * @param int $pos Position to start parsing
	 * @see getDoc()
	 * @see setPos()
	 */
	function setDoc($doc, $pos = 0) {
		$this->doc = $doc;
		$this->size = strlen($doc);
		$this->setPos($pos);
	}

	/**
	 * Returns target document
	 * @return string
	 * @see setDoc()
	 */
	function getDoc() {
		return $this->doc;
	}

	/**
	 * Sets position in document
	 * @param int $pos
	 * @see getPos()
	 */
	function setPos($pos = 0) {
		$this->pos = $pos - 1;
		$this->line_pos = array(0, 0);
		$this->next();
	}

	/**
	 * Returns current position in document (Index)
	 * @return int
	 * @see setPos()
	 */
	function getPos() {
		return $this->pos;
	}

	/**
	 * Returns current position in document (Line/Char)
	 * @return array array(Line, Column)
	 */
	function getLinePos() {
		return array($this->line_pos[0], $this->pos - $this->line_pos[1]);
	}

	/**
	 * Returns current token
	 * @return int
	 * @see $token
	 */
	function getToken() {
		return $this->token;
	}

	/**
	 * Returns current token as string
	 * @param int $start_offset Offset from token start
	 * @param int $end_offset Offset from token end
	 * @return string
	 */
	function getTokenString($start_offset = 0, $end_offset = 0) {
		$token_start = ((is_int($this->token_start)) ? $this->token_start : $this->pos) + $start_offset;
		$len = $this->pos - $token_start + 1 + $end_offset;
		return (($len > 0) ? substr($this->doc, $token_start, $len) : '');
	}

	/**
	 * Sets characters to be recognized as whitespace
	 *
	 * Used like: setWhitespace('ab') or setWhitespace(array('a' => true, 'b', 'c'));
	 * @param string|array $ws
	 * @see getWhitespace();
	 */
	function setWhitespace($ws) {
		if (is_array($ws)) {
			$this->whitespace = array_fill_keys(array_values($ws), true);
			$this->buildCharMap();
		} else {
			$this->setWhiteSpace(str_split($ws));
		}
	}

	/**
	 * Returns whitespace characters as string/array
	 * @param bool $as_string Should the result be a string or an array?
	 * @return string|array
	 * @see setWhitespace()
	 */
	function getWhitespace($as_string = true) {
		$ws = array_keys($this->whitespace);
		return (($as_string) ? implode('', $ws) : $ws);
	}

	/**
	 * Sets characters to be recognized as identifier
	 *
	 * Used like: setIdentifiers('ab') or setIdentifiers(array('a' => true, 'b', 'c'));
	 * @param string|array $ident
	 * @see getIdentifiers();
	 */
	function setIdentifiers($ident) {
		if (is_array($ident)) {
			$this->identifiers = array_fill_keys(array_values($ident), true);
			$this->buildCharMap();
		} else {
			$this->setIdentifiers(str_split($ident));
		}
	}

	/**
	 * Returns identifier characters as string/array
	 * @param bool $as_string Should the result be a string or an array?
	 * @return string|array
	 * @see setIdentifiers()
	 */
	function getIdentifiers($as_string = true) {
		$ident = array_keys($this->identifiers);
		return (($as_string) ? implode('', $ident) : $ident);
	}

	/**
	 * Maps a custom character to a token/function
	 *
	 * Used like: mapChar('a', self::{@link TOK_IDENTIFIER}) or mapChar('a', 'parse_identifier');
	 * @param string $char Character that should be mapped. If set, it will be overridden
	 * @param int|string $map If function name, then $this->function will be called, otherwise token is set to $map
	 * @see unmapChar()
	 */
	function mapChar($char, $map) {
		$this->custom_char_map[$char] = $map;
		$this->buildCharMap();
	}

	/**
	 * Removes a char mapped with {@link mapChar()}
	 * @param string $char Character that should be unmapped
	 * @see mapChar()
	 */
	function unmapChar($char) {
		unset($this->custom_char_map[$char]);
		$this->buildCharMap();
	}

	/**
	 * Builds the {@link $map_char} array
	 * @internal Builds single array that maps all characters. Gets called if {@link $whitespace}, {@link $identifiers} or {@link $custom_char_map} get modified
	 */
	protected function buildCharMap() {
		$this->char_map = $this->custom_char_map;
		if (is_array($this->whitespace)) {
			foreach($this->whitespace as $w => $v) {
				$this->char_map[$w] = 'parse_whitespace';
			}
		}
		if (is_array($this->identifiers)) {
			foreach($this->identifiers as $i => $v) {
				$this->char_map[$i] = 'parse_identifier';
			}
		}
	}

	/**
	 * Add error to the array and appends current position
	 * @param string $error
	 */
	function addError($error) {
		$this->errors[] = htmlentities($error.' at '.($this->line_pos[0] + 1).', '.($this->pos - $this->line_pos[1] + 1).'!');
	}

	/**
	 * Parse line breaks and increase line number
	 * @internal Gets called to process line breaks
	 */
	protected function parse_linebreak() {
		if($this->doc[$this->pos] === "\r") {
			++$this->line_pos[0];
			if ((($this->pos + 1) < $this->size) && ($this->doc[$this->pos + 1] === "\n")) {
				++$this->pos;
			}
			$this->line_pos[1] = $this->pos;
		} elseif($this->doc[$this->pos] === "\n") {
			++$this->line_pos[0];
			$this->line_pos[1] = $this->pos;
		}
	}

	/**
	 * Parse whitespace
	 * @return int Token
	 * @internal Gets called with {@link $whitespace} characters
	 */
	protected function parse_whitespace() {
		$this->token_start = $this->pos;

		while(++$this->pos < $this->size) {
			if (!isset($this->whitespace[$this->doc[$this->pos]])) {
				break;
			} else {
				$this->parse_linebreak();
			}
		}

		--$this->pos;
		return self::TOK_WHITESPACE;
	}

	/**
	 * Parse identifiers
	 * @return int Token
	 * @internal Gets called with {@link $identifiers} characters
	 */
	protected function parse_identifier() {
		$this->token_start = $this->pos;

		while((++$this->pos < $this->size) && isset($this->identifiers[$this->doc[$this->pos]])) {}

		--$this->pos;
		return self::TOK_IDENTIFIER;
	}

	/**
	 * Continues to the next token
	 * @return int Next token ({@link TOK_NULL} if none)
	 */
	function next() {
		$this->token_start = null;

		if (++$this->pos < $this->size) {
			if (isset($this->char_map[$this->doc[$this->pos]])) {
				if (is_string($this->char_map[$this->doc[$this->pos]])) {
					return ($this->token = $this->{$this->char_map[$this->doc[$this->pos]]}());
				} else {
					return ($this->token = $this->char_map[$this->doc[$this->pos]]);
				}
			} else {
				return ($this->token = self::TOK_UNKNOWN);
			}
		} else {
			return ($this->token = self::TOK_NULL);
		}
	}

	/**
	 * Finds the next token, but skips whitespace
	 * @return int Next token ({@link TOK_NULL} if none)
	 */
	function next_no_whitespace() {
		$this->token_start = null;

		while (++$this->pos < $this->size) {
			if (!isset($this->whitespace[$this->doc[$this->pos]])) {
				if (isset($this->char_map[$this->doc[$this->pos]])) {
					if (is_string($this->char_map[$this->doc[$this->pos]])) {
						return ($this->token = $this->{$this->char_map[$this->doc[$this->pos]]}());
					} else {
						return ($this->token = $this->char_map[$this->doc[$this->pos]]);
					}
				} else {
					return ($this->token = self::TOK_UNKNOWN);
				}
			} else {
				$this->parse_linebreak();
			}
		}

		return ($this->token = self::TOK_NULL);
	}

	/**
	 * Finds the next token using stop characters.
	 *
	 * Used like: next_search('abc') or next_search(array('a' => true, 'b' => true, 'c' => true));
	 * @param string|array $characters Characters to search for
	 * @param bool $callback Should the function check the charmap after finding a character?
	 * @return int Next token ({@link TOK_NULL} if none)
	 */
	function next_search($characters, $callback = true) {
		$this->token_start = $this->pos;
		if (!is_array($characters)) {
			$characters = array_fill_keys(str_split($characters), true);
		}

		while(++$this->pos < $this->size) {
			if (isset($characters[$this->doc[$this->pos]])) {
				if ($callback && isset($this->char_map[$this->doc[$this->pos]])) {
					if (is_string($this->char_map[$this->doc[$this->pos]])) {
						return ($this->token = $this->{$this->char_map[$this->doc[$this->pos]]}());
					} else {
						return ($this->token = $this->char_map[$this->doc[$this->pos]]);
					}
				} else {
					return ($this->token = self::TOK_UNKNOWN);
				}
			} else {
				$this->parse_linebreak();
			}
		}

		return ($this->token = self::TOK_NULL);
	}

	/**
	 * Finds the next token by searching for a string
	 * @param string $needle The needle that's being searched for
	 * @param bool $callback Should the function check the charmap after finding the needle?
	 * @return int Next token ({@link TOK_NULL} if none)
	 */
	function next_pos($needle, $callback = true) {
		$this->token_start = $this->pos;
		if (($this->pos < $this->size) && (($p = stripos($this->doc, $needle, $this->pos + 1)) !== false)) {

			$len = $p - $this->pos - 1;
			if ($len > 0) {
				$str = substr($this->doc, $this->pos + 1, $len);

				if (($l = strrpos($str, "\n")) !== false) {
					++$this->line_pos[0];
					$this->line_pos[1] = $l + $this->pos + 1;

					$len -= $l;
					if ($len > 0) {
						$str = substr($str, 0, -$len);
						$this->line_pos[0] += substr_count($str, "\n");
					}
				}
			}

			$this->pos = $p;
			if ($callback && isset($this->char_map[$this->doc[$this->pos]])) {
				if (is_string($this->char_map[$this->doc[$this->pos]])) {
					return ($this->token = $this->{$this->char_map[$this->doc[$this->pos]]}());
				} else {
					return ($this->token = $this->char_map[$this->doc[$this->pos]]);
				}
			} else {
				return ($this->token = self::TOK_UNKNOWN);
			}
		} else {
			$this->pos = $this->size;
			return ($this->token = self::TOK_NULL);
		}
	}

	/**
	 * Expect a specific token or character. Adds error if token doesn't match.
	 * @param string|int $token Character or token to expect
	 * @param bool|int $do_next Go to next character before evaluating. 1 for next char, true to ignore whitespace
	 * @param bool|int $try_next Try next character if current doesn't match. 1 for next char, true to ignore whitespace
	 * @param bool|int $next_on_match Go to next character after evaluating. 1 for next char, true to ignore whitespace
	 * @return bool
	 */
	protected function expect($token, $do_next = true, $try_next = false, $next_on_match = 1) {
		if ($do_next) {
			if ($do_next === 1) {
				$this->next();
			} else {
				$this->next_no_whitespace();
			}
		}

		if (is_int($token)) {
			if (($this->token !== $token) && ((!$try_next) || ((($try_next === 1) && ($this->next() !== $token)) || (($try_next === true) && ($this->next_no_whitespace() !== $token))))) {
				$this->addError('Unexpected "'.$this->getTokenString().'"');
				return false;
			}
		} else {
			if (($this->doc[$this->pos] !== $token) && ((!$try_next) || (((($try_next === 1) && ($this->next() !== self::TOK_NULL)) || (($try_next === true) && ($this->next_no_whitespace() !== self::TOK_NULL))) && ($this->doc[$this->pos] !== $token)))) {
				$this->addError('Expected "'.$token.'", but found "'.$this->getTokenString().'"');
				return false;
			}
		}

		if ($next_on_match) {
			if ($next_on_match === 1) {
				$this->next();
			} else {
				$this->next_no_whitespace();
			}
		}
		return true;
	}
}

?>pquery/LICENSE000064400000063641151526522440007116 0ustar00                  GNU LESSER GENERAL PUBLIC LICENSE
                       Version 2.1, February 1999

 Copyright (C) 1991, 1999 Free Software Foundation, Inc.
 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

[This is the first released version of the Lesser GPL.  It also counts
 as the successor of the GNU Library Public License, version 2, hence
 the version number 2.1.]

                            Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.

  This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it.  You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.

  When we speak of free software, we are referring to freedom of use,
not price.  Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.

  To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights.  These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.

  For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you.  You must make sure that they, too, receive or can get the source
code.  If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it.  And you must show them these terms so they know their rights.

  We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.

  To protect each distributor, we want to make it very clear that
there is no warranty for the free library.  Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.

  Finally, software patents pose a constant threat to the existence of
any free program.  We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder.  Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.

  Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License.  This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License.  We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.

  When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library.  The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom.  The Lesser General
Public License permits more lax criteria for linking other code with
the library.

  We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License.  It also provides other free software developers Less
of an advantage over competing non-free programs.  These disadvantages
are the reason we use the ordinary General Public License for many
libraries.  However, the Lesser license provides advantages in certain
special circumstances.

  For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard.  To achieve this, non-free programs must be
allowed to use the library.  A more frequent case is that a free
library does the same job as widely used non-free libraries.  In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.

  In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software.  For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.

  Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.

  The precise terms and conditions for copying, distribution and
modification follow.  Pay close attention to the difference between a
"work based on the library" and a "work that uses the library".  The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.

                  GNU LESSER GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".

  A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.

  The "Library", below, refers to any such software library or work
which has been distributed under these terms.  A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language.  (Hereinafter, translation is
included without limitation in the term "modification".)

  "Source code" for a work means the preferred form of the work for
making modifications to it.  For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.

  Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it).  Whether that is true depends on what the Library does
and what the program that uses the Library does.

  1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.

  You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.

  2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) The modified work must itself be a software library.

    b) You must cause the files modified to carry prominent notices
    stating that you changed the files and the date of any change.

    c) You must cause the whole of the work to be licensed at no
    charge to all third parties under the terms of this License.

    d) If a facility in the modified Library refers to a function or a
    table of data to be supplied by an application program that uses
    the facility, other than as an argument passed when the facility
    is invoked, then you must make a good faith effort to ensure that,
    in the event an application does not supply such function or
    table, the facility still operates, and performs whatever part of
    its purpose remains meaningful.

    (For example, a function in a library to compute square roots has
    a purpose that is entirely well-defined independent of the
    application.  Therefore, Subsection 2d requires that any
    application-supplied function or table used by this function must
    be optional: if the application does not supply it, the square
    root function must still compute square roots.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.

In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library.  To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License.  (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.)  Do not make any other change in
these notices.

  Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.

  This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.

  4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.

  If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.

  5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library".  Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.

  However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library".  The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.

  When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library.  The
threshold for this to be true is not precisely defined by law.

  If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work.  (Executables containing this object code plus portions of the
Library will still fall under Section 6.)

  Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.

  6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.

  You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License.  You must supply a copy of this License.  If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License.  Also, you must do one
of these things:

    a) Accompany the work with the complete corresponding
    machine-readable source code for the Library including whatever
    changes were used in the work (which must be distributed under
    Sections 1 and 2 above); and, if the work is an executable linked
    with the Library, with the complete machine-readable "work that
    uses the Library", as object code and/or source code, so that the
    user can modify the Library and then relink to produce a modified
    executable containing the modified Library.  (It is understood
    that the user who changes the contents of definitions files in the
    Library will not necessarily be able to recompile the application
    to use the modified definitions.)

    b) Use a suitable shared library mechanism for linking with the
    Library.  A suitable mechanism is one that (1) uses at run time a
    copy of the library already present on the user's computer system,
    rather than copying library functions into the executable, and (2)
    will operate properly with a modified version of the library, if
    the user installs one, as long as the modified version is
    interface-compatible with the version that the work was made with.

    c) Accompany the work with a written offer, valid for at
    least three years, to give the same user the materials
    specified in Subsection 6a, above, for a charge no more
    than the cost of performing this distribution.

    d) If distribution of the work is made by offering access to copy
    from a designated place, offer equivalent access to copy the above
    specified materials from the same place.

    e) Verify that the user has already received a copy of these
    materials or that you have already sent this user a copy.

  For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it.  However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.

  It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system.  Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.

  7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:

    a) Accompany the combined library with a copy of the same work
    based on the Library, uncombined with any other library
    facilities.  This must be distributed under the terms of the
    Sections above.

    b) Give prominent notice with the combined library of the fact
    that part of it is a work based on the Library, and explaining
    where to find the accompanying uncombined form of the same work.

  8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License.  Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License.  However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.

  9. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Library or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.

  10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.

  11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all.  For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.

If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded.  In such case, this License incorporates the limitation as if
written in the body of this License.

  13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.

Each version is given a distinguishing version number.  If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation.  If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.

  14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission.  For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this.  Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.

                            NO WARRANTY

  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.

                     END OF TERMS AND CONDITIONS

           How to Apply These Terms to Your New Libraries

  If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change.  You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).

  To apply these terms, attach the following notices to the library.  It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.

    <one line to give the library's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Also add information on how to contact you by electronic and paper mail.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the
  library `Frob' (a library for tweaking knobs) written by James Random Hacker.

  <signature of Ty Coon>, 1 April 1990
  Ty Coon, President of Vice

That's all there is to it!pquery/ganon.php000064400000005233151526522440007715 0ustar00<?php
/**
 * @author Niels A.D.
 * @author Todd Burry <todd@vanillaforums.com>
 * @copyright 2010 Niels A.D., 2014 Todd Burry
 * @license http://opensource.org/licenses/LGPL-2.1 LGPL-2.1
 * @package pQuery
 */

use pagelayerQuery\Html5Parser;
use pagelayerQuery\HtmlFormatter;

/**
 * Returns HTML DOM from string
 * @param string $str
 * @param bool $return_root Return root node or return parser object
 * @return Html5Parser|DomNode
 */
function str_get_dom($str, $return_root = true) {
	$a = new Html5Parser($str);
	return (($return_root) ? $a->root : $a);
}

/**
 * Returns HTML DOM from file/website
 * @param string $str
 * @param bool $return_root Return root node or return parser object
 * @param bool $use_include_path Use include path search in file_get_contents
 * @param resource $context Context resource used in file_get_contents (PHP >= 5.0.0)
 * @return Html5Parser|DomNode
 */
function file_get_dom($file, $return_root = true, $use_include_path = false, $context = null) {
	if (version_compare(PHP_VERSION, '5.0.0', '>='))
		$f = file_get_contents($file, $use_include_path, $context);
	else {
		if ($context !== null)
			trigger_error('Context parameter not supported in this PHP version');
		$f = file_get_contents($file, $use_include_path);
	}

	return (($f === false) ? false : str_get_dom($f, $return_root));
}

/**
 * Format/beautify DOM
 * @param DomNode $root
 * @param array $options Extra formatting options {@link Formatter::$options}
 * @return bool
 */
function dom_format(&$root, $options = array()) {
	$formatter = new HtmlFormatter($options);
	return $formatter->format($root);
}

if (version_compare(PHP_VERSION, '5.0.0', '<')) {
	/**
	 * PHP alternative to str_split, for backwards compatibility
	 * @param string $string
	 * @return string
	 */
	function str_split($string) {
		$res = array();
		$size = strlen($string);
		for ($i = 0; $i < $size; $i++) {
			$res[] = $string[$i];
		}

		return $res;
	}
}

if (version_compare(PHP_VERSION, '5.2.0', '<')) {
	/**
	 * PHP alternative to array_fill_keys, for backwards compatibility
	 * @param array $keys
	 * @param mixed $value
	 * @return array
	 */
	function array_fill_keys($keys, $value) {
		$res = array();
		foreach($keys as $k) {
			$res[$k] = $value;
		}

		return $res;
	}
}

#!! <- Ignore when converting to single file
if (!defined('GANON_NO_INCLUDES')) {
	define('GANON_NO_INCLUDES', true);
    include_once('IQuery.php');
	include_once('gan_tokenizer.php');
	include_once('gan_parser_html.php');
	include_once('gan_node_html.php');
	include_once('gan_selector_html.php');
	include_once('gan_formatter.php');
}
#!

?>pquery/gan_formatter.php000064400000032273151526522440011447 0ustar00<?php
/**
 * @author Niels A.D.
 * @author Todd Burry <todd@vanillaforums.com>
 * @copyright 2010 Niels A.D., 2014 Todd Burry
 * @license http://opensource.org/licenses/LGPL-2.1 LGPL-2.1
 * @package pQuery
 */

namespace pagelayerQuery;

/**
 * Indents text
 * @param string $text
 * @param int $indent
 * @param string $indent_string
 * @return string
 */
function indent_text($text, $indent, $indent_string = '  ') {
	if ($indent && $indent_string) {
		return str_replace("\n", "\n".str_repeat($indent_string, $indent), $text);
	} else {
		return $text;
	}
}

/**
 * Class used to format/minify HTML nodes
 *
 * Used like:
 * <code>
 * <?php
 *   $formatter = new HtmlFormatter();
 *   $formatter->format($root);
 * ?>
 * </code>
 */
class HtmlFormatter {

	/**
	 * Determines which elements start on a new line and which function as block
	 * @var array('element' => array('new_line' => true, 'as_block' => true, 'format_inside' => true))
	 */
	var $block_elements = array(
		'p' =>			array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'h1' => 		array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'h2' =>  		array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'h3' =>  		array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'h4' =>  		array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'h5' =>  		array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'h6' =>  		array('new_line' => true,  'as_block' => true,  'format_inside' => true),

		'form' =>  		array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'fieldset' =>  	array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'legend' =>  	array('new_line' => true,  'as_block' => false, 'format_inside' => true),
		'dl' =>  		array('new_line' => true,  'as_block' => false, 'format_inside' => true),
		'dt' =>  		array('new_line' => true,  'as_block' => false, 'format_inside' => true),
		'dd' =>  		array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'ol' =>  		array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'ul' =>  		array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'li' =>  		array('new_line' => true,  'as_block' => false, 'format_inside' => true),

		'table' =>  	array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'tr' =>  		array('new_line' => true,  'as_block' => true,  'format_inside' => true),

		'dir' =>  		array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'menu' =>  		array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'address' =>  	array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'blockquote' => array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'center' =>  	array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'del' =>  		array('new_line' => true,  'as_block' => false, 'format_inside' => true),
		//'div' =>  	array('new_line' => false, 'as_block' => true,  'format_inside' => true),
		'hr' =>  		array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'ins' =>  		array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'noscript' =>  	array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'pre' =>  		array('new_line' => true,  'as_block' => true,  'format_inside' => false),
		'script' =>  	array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'style' =>  	array('new_line' => true,  'as_block' => true,  'format_inside' => true),

		'html' => 		array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'head' => 		array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'body' => 		array('new_line' => true,  'as_block' => true,  'format_inside' => true),
		'title' => 		array('new_line' => true,  'as_block' => false, 'format_inside' => false)
	);

	/**
	 * Determines which characters are considered whitespace
	 * @var array("\t" => true) True to recognize as new line
	 */
	var $whitespace = array(
		' ' => false,
		"\t" => false,
		"\x0B" => false,
		"\0" => false,
		"\n" => true,
		"\r" => true
	);

	/**
	 * String that is used to generate correct indenting
	 * @var string
	 */
	var $indent_string = ' ';

	/**
	 * String that is used to break lines
	 * @var string
	 */
	var $linebreak_string = "\n";

	/**
	 * Other formatting options
	 * @var array
	 */
	public $options = array(
		'img_alt' => '',
		'self_close_str' => null,
		'attribute_shorttag' => false,
		'sort_attributes' => false,
		'attributes_case' => CASE_LOWER,
		'minify_script' => true
	);

	/**
	 * Errors found during formatting
	 * @var array
	 */
	var $errors = array();


	/**
	 * Class constructor
	 * @param array $options {@link $options}
	 */
	function __construct($options = array()) {
		$this->options = array_merge($this->options, $options);

      if (isset($options['indent_str']))
         $this->indent_string = $options['indent_str'];

      if (isset($options['linebreak_str']))
         $this->linebreak_string = $options['linebreak_str'];
	}

	#php4 PHP4 class constructor compatibility
	#function HtmlFormatter($options = array()) {return $this->__construct($options);}
	#php4e

	/**
	 * Class magic invoke method, performs {@link format()}
	 * @access private
	 */
	function __invoke(&$node) {
		return $this->format($node);
	}

	/**
	 * Minifies HTML / removes unneeded whitespace
	 * @param DomNode $root
	 * @param bool $strip_comments
	 * @param bool $recursive
	 */
	static function minify_html(&$root, $strip_comments = true, $recursive = true) {
		if ($strip_comments) {
			foreach($root->select(':comment', false, $recursive, true) as $c) {
				$prev = $c->getSibling(-1);
				$next = $c->getSibling(1);
				$c->delete();
				if ($prev && $next && ($prev->isText()) && ($next->isText())) {
					$prev->text .= $next->text;
					$next->delete();
				}
			}
		}
		foreach($root->select('(!pre + !xmp + !style + !script + !"?php" + !"~text~" + !"~comment~"):not-empty > "~text~"', false, $recursive, true) as $c) {
			$c->text = preg_replace('`\s+`', ' ', $c->text);
		}
	}

	/**
	 * Minifies javascript using JSMin+
	 * @param DomNode $root
	 * @param string $indent_string
	 * @param bool $wrap_comment Wrap javascript in HTML comments (<!-- ~text~ //-->)
	 * @param bool $recursive
	 * @return bool|array Array of errors on failure, true on succes
	 */
	static function minify_javascript(&$root, $indent_string = ' ', $wrap_comment = true, $recursive = true) {
	#php4 JSMin+ doesn't support PHP4
	#return true;
	#php4e
	#php5
		include_once('third party/jsminplus.php');

		$errors = array();
		foreach($root->select('script:not-empty > "~text~"', false, $recursive, true) as $c) {
			try {
				$text = $c->text;
				while ($text) {
					$text = trim($text);
					//Remove comment/CDATA tags at begin and end
					if (substr($text, 0, 4) === '<!--') {
						$text = substr($text, 5);
						continue;
					} elseif (strtolower(substr($text, 0, 9)) === '<![cdata[') {
						$text = substr($text, 10);
						continue;
					}

					if (($end = substr($text, -3)) && (($end === '-->') || ($end === ']]>'))) {
						$text = substr($text, 0, -3);
						continue;
					}

					break;
				}

				if (trim($text)) {
					$text = \JSMinPlus::minify($text);
					if ($wrap_comment) {
						$text = "<!--\n".$text."\n//-->";
					}
					if ($indent_string && ($wrap_comment || (strpos($text, "\n") !== false))) {
						$text = indent_text("\n".$text, $c->indent(), $indent_string);
					}
				}
				$c->text = $text;
			} catch (\Exception $e) {
				$errors[] = array($e, $c->parent->dumpLocation());
			}
		}

		return (($errors) ? $errors : true);
	#php5e
	}

	/**
	 * Formats HTML
	 * @param DomNode $root
	 * @param bool $recursive
	 * @access private
	 */
	function format_html(&$root, $recursive = null) {
		if ($recursive === null) {
			$recursive = true;
			self::minify_html($root);
		} elseif (is_int($recursive)) {
			$recursive = (($recursive > 1) ? $recursive - 1 : false);
		}

		$root_tag = strtolower($root->tag);
		$in_block = isset($this->block_elements[$root_tag]) && $this->block_elements[$root_tag]['as_block'];
		$child_count = count($root->children);

		if (isset($this->options['attributes_case']) && $this->options['attributes_case']) {
			$root->attributes = array_change_key_case($root->attributes, $this->options['attributes_case']);
			$root->attributes_ns = null;
		}

		if (isset($this->options['sort_attributes']) && $this->options['sort_attributes']) {
			if ($this->options['sort_attributes'] === 'reverse') {
				krsort($root->attributes);
			} else {
				ksort($root->attributes);
			}
		}

		if ($root->select(':element', true, false, true)) {
			$root->setTag(strtolower($root->tag), true);
			if (($this->options['img_alt'] !== null) && ($root_tag === 'img') && (!isset($root->alt))) {
                $root->setAttribute('alt', $this->options['img_alt']);
			}
		}
		if ($this->options['self_close_str'] !== null) {
			$root->self_close_str = $this->options['self_close_str'];
		}
		if ($this->options['attribute_shorttag'] !== null) {
			$root->attribute_shorttag = $this->options['attribute_shorttag'];
		}

		$prev = null;
		$n_tag = '';
//		$prev_tag = '';
		$as_block = false;
		$prev_asblock = false;
		for($i = 0; $i < $child_count; $i++) {
			$n =& $root->children[$i];
			$indent = $n->indent();

			if (!$n->isText()) {
				$n_tag = strtolower($n->tag);
				$new_line = isset($this->block_elements[$n_tag]) && $this->block_elements[$n_tag]['new_line'];
				$as_block = isset($this->block_elements[$n_tag]) && $this->block_elements[$n_tag]['as_block'];
				$format_inside = ((!isset($this->block_elements[$n_tag])) || $this->block_elements[$n_tag]['format_inside']);

				if ($prev && ($prev->isText()) && $prev->text && ($char = $prev->text[strlen($prev->text) - 1]) && isset($this->whitespace[$char])) {
					if ($this->whitespace[$char]) {
						$prev->text .= str_repeat($this->indent_string, $indent);
					} else {
						$prev->text = substr_replace($prev->text, $this->linebreak_string.str_repeat($this->indent_string, $indent), -1, 1);
					}
				} elseif (($new_line || $prev_asblock || ($in_block && ($i === 0)))){
					if ($prev && ($prev->isText())) {
						$prev->text .= $this->linebreak_string.str_repeat($this->indent_string, $indent);
					} else {
						$root->addText($this->linebreak_string.str_repeat($this->indent_string, $indent), $i);
						++$child_count;
					}
				}

				if ($format_inside && count($n->children)) {
					//$last = end($n->children);
					$last = $n->children[count($n->children) - 1];
					$last_tag = ($last) ? strtolower($last->tag) : '';
					$last_asblock = ($last_tag && isset($this->block_elements[$last_tag]) && $this->block_elements[$last_tag]['as_block']);

					if (($n->childCount(true) > 0) || (trim($n->getPlainText()))) {
						if ($last && ($last->isText()) && $last->text && ($char = $last->text[strlen($last->text) - 1]) && isset($this->whitespace[$char])) {
							if ($as_block || ($last->index() > 0) || isset($this->whitespace[$last->text[0]])) {
								if ($this->whitespace[$char]) {
									$last->text .= str_repeat($this->indent_string, $indent);
								} else {
									$last->text = substr_replace($last->text, $this->linebreak_string.str_repeat($this->indent_string, $indent), -1, 1);
								}
							}
						} elseif (($as_block || $last_asblock || ($in_block && ($i === 0))) && $last) {
							if ($last && ($last->isText())) {
								$last->text .= $this->linebreak_string.str_repeat($this->indent_string, $indent);
							} else {
								$n->addText($this->linebreak_string.str_repeat($this->indent_string, $indent));
							}
						}
					} elseif (!trim($n->getInnerText())) {
						$n->clear();
					}

					if ($recursive) {
						$this->format_html($n, $recursive);
					}
				}

			} elseif (trim($n->text) && ((($i - 1 < $child_count) && ($char = $n->text[0]) && isset($this->whitespace[$char])) || ($in_block && ($i === 0)))) {
				if (isset($this->whitespace[$char])) {
					if ($this->whitespace[$char]) {
						$n->text = str_repeat($this->indent_string, $indent).$n->text;
					} else {
						$n->text = substr_replace($n->text, $this->linebreak_string.str_repeat($this->indent_string, $indent), 0, 1);
					}
				} else {
					$n->text = $this->linebreak_string.str_repeat($this->indent_string, $indent).$n->text;
				}
			}

			$prev = $n;
//			$prev_tag = $n_tag;
			$prev_asblock = $as_block;
		}

		return true;
	}

	/**
	 * Formats HTML/Javascript
	 * @param DomNode $root
	 * @see format_html()
	 */
	function format(&$node) {
		$this->errors = array();
		if ($this->options['minify_script']) {
			$a = self::minify_javascript($node, $this->indent_string, true, true);
			if (is_array($a)) {
				foreach($a as $error) {
					$this->errors[] = $error[0]->getMessage().' >>> '.$error[1];
				}
			}
		}
		return $this->format_html($node);
	}
}

?>