<?php

require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/core/BeanFactory.class.php';
require_once 'Item.class.php';
require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/core/Utils.class.php';
class Xoonips_Metadata {

	private $dirname;
	private $trustDirname;

	/** metadataPrefix */
	private $metadataPrefix;

	/** OAI-PMH Schema List */
	private $schemaList;
	/** OAI-PMH Schema Selectable Value List */
	private $valueSetList;

	/** OAIp-PMH Schema and Item Type Link Table */
	private $linkBean;

	/**
     * Constructor
     * 
     * @param string $dirname module dirname
     */
    public function Xoonips_Metadata($dirname, $trustDirname, $metadataPrefix) {
    	$this->dirname = $dirname;
    	$this->trustDirname = $trustDirname;
    	$this->metadataPrefix = $metadataPrefix;
		$oaipmhSchemaBean = Xoonips_BeanFactory::getBean('OaipmhSchemaBean', $this->dirname, $this->trustDirname);
		$this->schemaList = $oaipmhSchemaBean->getSchemaList($this->metadataPrefix);
		$this->valueSetList = $oaipmhSchemaBean->getSchemaValueSetList($this->metadataPrefix);
		$this->linkBean = Xoonips_BeanFactory::getBean('OaipmhSchemaItemtypeLinkBean', $this->dirname, $this->trustDirname);
    }

    public function getMetadata($item_type_id, $item_id) {
		$lines = array();
		// if junii2
		if ($this->metadataPrefix == 'junii2') {
			$lines[] = '<metadata>';
            $lines[] = '<meta xmlns="http://irdb.nii.ac.jp/oai/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://irdb.nii.ac.jp/oai http://irdb.nii.ac.jp/oai/junii2.xsd">';
			$this->getContents($item_type_id, $item_id, $lines);
			$lines[] = '</meta>';
			$lines[] = '</metadata>';
		// if oai_dc
		} else if ($this->metadataPrefix == 'oai_dc') {
			$lines[] = '<metadata>';
			$lines[] = '<oai_dc:dc xmlns:oai_dc="http://www.openarchives.org/OAI/2.0/oai_dc/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd">';
			$this->getContents($item_type_id, $item_id, $lines);
			$lines[] = '</oai_dc:dc>';
			$lines[] = '</metadata>';
		}
		return implode("\n", $lines);
	}
	
	public static function supportMetadataFormat($metadataPrefix) {
		if ($metadataPrefix == 'oai_dc' || $metadataPrefix == 'junii2') {
		    return true;
		}
		return false;
	}
	
	private function getContents($item_type_id, $item_id, &$lines) {
		$links = $this->linkBean->get($this->metadataPrefix, $item_type_id);
		$itemtype = new Xoonips_Item($item_type_id, $this->dirname, $this->trustDirname);
		$itemtype->setId($item_id);
		foreach ($this->schemaList as $schema) {
			$flg = false;
			foreach ($links as $link) {
				if ($schema['schema_id'] == $link['schema_id']) {
					$flg = true;
					$metadata = array();
					$detail_ids = explode(',', $link['item_field_detail_id']);
					foreach ($detail_ids as $detail_id) {
						$valueset = false;
						foreach ($this->valueSetList as $obj) {
							if ($obj['schema_id'] == $schema['schema_id'] && $obj['seq_id'] == $detail_id) {
								$valueset = $obj['value'];
								$metadata[] = $valueset;
								break;
							}
						}
						if ($valueset == false) {
							if ($detail_id == 'http://') {
								$metadata[] = XOOPS_URL . '/modules/' . $this->dirname . "/detail.php?id=$item_id";
							} elseif ($detail_id == 'ID') {
								$itemBean = Xoonips_BeanFactory::getBean('ItemBean', $this->dirname, $this->trustDirname);
								$item = $itemBean->getItemBasicInfo($item_id);
								$doi = $item['doi'];
								$configBean = Xoonips_BeanFactory::getBean('ConfigBean', $this->dirname, $this->trustDirname);
								$database_id = $configBean->getConfig(XOONIPS_CONFIG_REPOSITORY_NIJC_CODE);
								if ($doi == null) {
									$metadata[] = "$database_id/$item_type_id.$item_id";
								} else {
									$metadata[] = "$database_id:" . XOONIPS_CONFIG_DOI_FIELD_PARAM_NAME . "/$doi";
								}
							} elseif ($detail_id == 'meta_author') {
								$moduleHandler =& xoops_gethandler('module');
								$legacyRender =& $moduleHandler->getByDirname('legacyRender');
								$configHandler =& xoops_gethandler('config');
								$configs =& $configHandler->getConfigsByCat(0, $legacyRender->get('mid'));
								$metadata[] = $configs['meta_author'];								
							} elseif ($detail_id == 'itemtype') {
								$itemTypeBean = Xoonips_BeanFactory::getBean('ItemTypeBean', $this->dirname, $this->trustDirname);
								$itemTypeInfo = $itemTypeBean->getItemTypeInfo($item_type_id);
								$metadata[] = $itemTypeInfo['name'];
							} else {
								$temp = $itemtype->getMetadata($detail_id);
								if ($schema['name'] == 'format') {
									if (is_array($temp)) {
										$metadata[] = $temp[1];
									} else {
										$metadata[] = $temp;
									}
								} else {
									if (is_array($temp)) {
										$metadata[] = $temp[0];
									} else {
										$metadata[] = $temp;
									}
								}
							}
						}
					}
					$temp = self::convert($metadata, $link['value']);
                	$temp = Xoonips_Utils::encodeUtf8($temp, _CHARSET);
					$lines[] = '<' . $schema['name'] . '>' . Xoonips_Utils::xmlSpecialChars($temp) . '</' . $schema['name'] . '>' ;
				} elseif ($flg == true) {
					break;
				}
			}
		}
	}
	
	private static function convert($metadata, $convertString) {
		$ret = implode('', $metadata);
		if ($convertString != '') {
			preg_match_all("/\bsprintf\b\(\"([^\"]|(\\\\\"))*\",((\d+,)*\d+)\)/", $convertString, $matches);
			foreach ($matches[0] as $key => $match) {
				$cmd = substr($match, 0, strlen($match) - strlen($matches[3][$key]) - 1);
				$parameters = explode(',', $matches[3][$key]);
				foreach ($parameters as $parameter) {
					$temp[] = "\"" . str_replace("\"", "\\\"", $metadata[$parameter - 1]) . "\"";
				}
				$cmd = $cmd . implode(',', $temp) . ')';
				$convertString = str_replace($match, $cmd, $convertString);
			}
			$tmpfname = tempnam("c:\\tmp\\", 'item_type');
			$handle = fopen($tmpfname, 'w');
			$size = fwrite($handle, '<?php echo ' . $convertString . ';?>'); 
			ob_start();
			include $tmpfname;
			$ret = ob_get_contents(); 
			ob_clean();
			fclose($handle);
			unlink($tmpfname);
		}
		return $ret;
	}
}
?>
