cleaning and fixing

This commit is contained in:
Usuario Moodle 2013-05-07 17:01:22 -03:00
parent a89f4b7fa1
commit 91a657ae57
13 changed files with 919 additions and 951 deletions

View File

@ -17,244 +17,242 @@ require_once('xml_creater.php');
* The protected member functions are the backbone functions which can be used for creating any ANDS RIF-CS records. * The protected member functions are the backbone functions which can be used for creating any ANDS RIF-CS records.
* *
*/ */
class ANDS_RIFCS { class ANDS_RIFCS {
/** /**
* \var $oai_pmh * \var $oai_pmh
* Type: ANDS_Response_XML. Assigned by constructor. \see __construct * Type: ANDS_Response_XML. Assigned by constructor. \see __construct
*/ */
protected $oai_pmh; protected $oai_pmh;
/** \var $working_node /** \var $working_node
* Type: DOMElement. Assigned by constructor. \see __construct * Type: DOMElement. Assigned by constructor. \see __construct
*/ */
protected $working_node; protected $working_node;
/** /**
* Constructor * Constructor
* *
* \param $ands_response_doc ANDS_Response_XML. A XML Doc acts as the parent node. * \param $ands_response_doc ANDS_Response_XML. A XML Doc acts as the parent node.
* \param $metadata_node DOMElement. The meta node which all subsequent nodes will be added to. * \param $metadata_node DOMElement. The meta node which all subsequent nodes will be added to.
*/ */
function __construct($ands_response_doc, $metadata_node) { function __construct($ands_response_doc, $metadata_node) {
$this->oai_pmh = $ands_response_doc; $this->oai_pmh = $ands_response_doc;
$this->working_node = $metadata_node; $this->working_node = $metadata_node;
$this->create_regObjects(); $this->create_regObjects();
} }
/** /**
* A worker function for easily adding a newly created node to current XML Doc. * A worker function for easily adding a newly created node to current XML Doc.
* @param $mom_node Type: DOMElement. Node the new child will be attached to. * @param $mom_node Type: DOMElement. Node the new child will be attached to.
* @param $name Type: sting. The name of the child node is being added. * @param $name Type: sting. The name of the child node is being added.
* @param $value Type: sting. The text content of the child node is being added. The default is ''. * @param $value Type: sting. The text content of the child node is being added. The default is ''.
* @return DOMElement. The added child node * @return DOMElement. The added child node
*/ */
protected function addChild($mom_node,$name, $value='') { protected function addChild($mom_node,$name, $value='') {
return $this->oai_pmh->addChild($mom_node,$name, $value); return $this->oai_pmh->addChild($mom_node,$name, $value);
} }
/** Create a registryObjects node to hold individual registryObject's. /** Create a registryObjects node to hold individual registryObject's.
* This is only a holder node. * This is only a holder node.
*/ */
protected function create_regObjects() { protected function create_regObjects() {
$this->working_node = $this->oai_pmh->addChild($this->working_node,'registryObjects'); $this->working_node = $this->oai_pmh->addChild($this->working_node,'registryObjects');
$this->working_node->setAttribute('xmlns',"http://ands.org.au/standards/rif-cs/registryObjects"); $this->working_node->setAttribute('xmlns',"http://ands.org.au/standards/rif-cs/registryObjects");
$this->working_node->setAttribute('xmlns:xsi',"http://www.w3.org/2001/XMLSchema-instance"); $this->working_node->setAttribute('xmlns:xsi',"http://www.w3.org/2001/XMLSchema-instance");
$this->working_node->setAttribute('xsi:schemaLocation','http://ands.org.au/standards/rif-cs/registryObjects http://services.ands.org.au/documentation/rifcs/1.2.0/schema/registryObjects.xsd'); $this->working_node->setAttribute('xsi:schemaLocation','http://ands.org.au/standards/rif-cs/registryObjects http://services.ands.org.au/documentation/rifcs/1.2.0/schema/registryObjects.xsd');
} }
/** Create a single registryObject node. Each set has its own structure but they all have an attribute of group, a key node and an originatingSource node. The newly created node will be used as the working node.
*
* \param $group string, group attribute of the new registryObject node .
* \param $key string, key node, used as an identifier.
* \param $originatingSource string, an url of the data provider.
*/
protected function create_regObject($group, $key, $originatingSource) {
$regObj_node = $this->addChild($this->working_node,'registryObject');
$regObj_node->setAttribute('group',$group);
$this->addChild($regObj_node,'key',$key);
$this->addChild($regObj_node,'originatingSource',$originatingSource);
$this->working_node = $regObj_node;
}
/** RIF-CS node is the content node of RIF-CS metadata node which starts from regObjects.
* Each set supportted in RIF-CS has its own content model. The created node will be used as the
* root node of this record for following nodes will be created.
*
* \param $set_name string, the name of set. For ANDS, they are Activity, Party and Collection
* \param $set_type string, the type of set. For example, Activity can have project as a type.
*/
protected function create_rifcs_node($set_name, $set_type) {
$this->working_node = $this->addChild($this->working_node, $set_name);
$this->working_node->setAttribute('type', $set_type);
}
/** /** Create a single registryObject node. Each set has its own structure but they all have an attribute of group, a key node and an originatingSource node. The newly created node will be used as the working node.
* Create a top level name node. *
* @param $name_type string. Text for the types, can be either primary or abbreviated. Default: primary * \param $group string, group attribute of the new registryObject node .
* * \param $key string, key node, used as an identifier.
* @return DOMElement $added_name_node. * \param $originatingSource string, an url of the data provider.
* The newly created node, it will be used for further expansion by adding namePart. */
*/ protected function create_regObject($group, $key, $originatingSource) {
protected function create_name_node($name_type = 'primary') { $regObj_node = $this->addChild($this->working_node,'registryObject');
$c = $this->addChild($this->working_node, 'name'); $regObj_node->setAttribute('group',$group);
$c->setAttribute('type', $name_type); $this->addChild($regObj_node,'key',$key);
return $c; $this->addChild($regObj_node,'originatingSource',$originatingSource);
} $this->working_node = $regObj_node;
}
/**
* Create a namePart of a name node.
* @param $name_node
* Type: DOMElement. Node of name_node created previously
*
* @param $value
* Type: string. Text fror this namePart
*
* @param $part_type Type: string, used for group:person record. Types can be: titile, given, family
*
*/
protected function create_namePart($name_node, $value, $part_type = '') {
$c = $this->addChild($name_node, 'namePart', $value);
if (!empty($part_type)) {
$c->setAttribute('type', $part_type);
}
}
/** Create related object. One RIF-CS can have more than one related object nodes,
* each object is described by one node.
* \param $key
* Type: string. The identifier of the related object.
* \param $relation_type
* Type: string. Type of relationship.
*
*/
protected function create_relatedObject($key,$relation_type) {
$c = $this->addChild($this->working_node, 'relatedObject');
$this->addChild($c,'key',$key);
$c = $this->addChild($c, 'relation');
// Mimick ANDS with enpty value to get both tags for relation. Only for better display
// $c = $this->addChild($c, 'relation',' ');
$c->setAttribute('type', $relation_type);
}
/** Create description node. One RIF-CS can have more than one description nodes.
* Each description node has only one description.
* \param $value Type: string. The content of the description.
* \param $des_type Type: string. Type of the description. Types can be brief, full, acessRights and note. Default is 'brief'.
*/
protected function create_description_node($value, $des_type='brief') {
$c = $this->addChild($this->working_node, 'description', $value);
$c->setAttribute('type', $des_type);
}
/** Create local or other type of identifier inside of RIF-CS metadata node /** RIF-CS node is the content node of RIF-CS metadata node which starts from regObjects.
* \param $key * Each set supportted in RIF-CS has its own content model. The created node will be used as the
* Type string. The indentifier itself. * root node of this record for following nodes will be created.
* \param $i_type *
* Type string. Type of identifier. Can be abn, uri, local, etc.. Default is local. * \param $set_name string, the name of set. For ANDS, they are Activity, Party and Collection
*/ * \param $set_type string, the type of set. For example, Activity can have project as a type.
protected function create_identifier_node($key, $i_type='local') { */
$c = $this->addChild($this->working_node, 'identifier',$key); protected function create_rifcs_node($set_name, $set_type) {
$c->setAttribute('type', $i_type); $this->working_node = $this->addChild($this->working_node, $set_name);
} $this->working_node->setAttribute('type', $set_type);
}
/** Location node is a holder node for either address or spatial nodes
* \return DOMElement node, for adding address or spatial nodes.
*/
protected function create_location_node() {
return $this->addChild($this->working_node, 'location');
}
/** Address node is a holder node for phiscal or electrical nodes.
* \param $location_node Type: DOMElement. Location node created previously.
* \return DOMElement
*/
protected function create_address_node($location_node) {
return $this->addChild($location_node, 'address');
}
/** Electrical address node. Used for email, url, etc
* \param $addr_node Type: DOMElement. Previously created address node.
* \param $e_node Type: string. The content of the adding node.
* \param $e_type Type: string. Default is email.
*/
protected function create_e_node($addr_node, $e_node, $e_type = 'email') {
$c = $this->addChild($addr_node, 'electronic');
$c->setAttribute('type', $e_type);
$this->addChild($c,'value',$e_node);
}
/** Physical node is a holder node for phone or fax nodes. /**
* \param $addr_node Type: DOMelement. Address node created before to which the new phiscial->addressPart will be attached. * Create a top level name node.
* \param $number Type: string. Telephone or fax number as a string. * @param $name_type string. Text for the types, can be either primary or abbreviated. Default: primary
* \param $fone_fax Type: string. Either telehoneNumber or faxNumber. *
*/ * @return DOMElement $added_name_node.
protected function create_physcial_fone_fax($addr_node, $number,$fone_fax='telephoneNumber') { * The newly created node, it will be used for further expansion by adding namePart.
$c = $this->addChild($addr_node, 'physical'); */
$c = $this->addChild($c, 'addressPart', $number); protected function create_name_node($name_type = 'primary') {
$c->setAttribute('type', $fone_fax); $c = $this->addChild($this->working_node, 'name');
} $c->setAttribute('type', $name_type);
return $c;
}
/** create address node under location node, either streetAddress or postalAddress. /**
* But they are in text (one block) format. * Create a namePart of a name node.
* \param $addr_node Type: DOMelement. Address node created before to which the new phiscial->addressPart will be attached. * @param $name_node
* \param $txt_addr string, full street address in text block format * Type: DOMElement. Node of name_node created previously
* \param $phys_type string, default is 'streetAddress', can be 'postalAddress' *
*/ * @param $value
protected function create_physcial_addr_txt($addr_node, $txt_addr,$phys_type='streetAddress') { * Type: string. Text fror this namePart
$c = $this->addChild($addr_node, 'physical'); *
$c->setAttribute('type', $phys_type); * @param $part_type Type: string, used for group:person record. Types can be: titile, given, family
$c = $this->addChild($c, 'addressPart', $txt_addr); *
$c->setAttribute('type', 'text'); */
} protected function create_namePart($name_node, $value, $part_type = '') {
$c = $this->addChild($name_node, 'namePart', $value);
if (!empty($part_type)) {
$c->setAttribute('type', $part_type);
}
}
/** Create spatial node under a location node. /** Create related object. One RIF-CS can have more than one related object nodes,
* \param $location_node Type: DOMElement. Location node where spatial node is being added to. * each object is described by one node.
* \param $value Type: string. The value of spatial information. Default is local latitude and longitude. * \param $key
* \param $sp_type Type: string. Type of spaitial informaion. Default is kmlPolyCoords. * Type: string. The identifier of the related object.
*/ * \param $relation_type
protected function create_spatial_node($location_node, $value = '138.6396,-34.97063', $sp_type = 'kmlPolyCoords') { * Type: string. Type of relationship.
$c = $this->addChild($location_node, 'spatial',$value); *
$c->setAttribute('type',$sp_type); */
} protected function create_relatedObject($key,$relation_type) {
$c = $this->addChild($this->working_node, 'relatedObject');
$this->addChild($c,'key',$key);
$c = $this->addChild($c, 'relation');
// Mimick ANDS with enpty value to get both tags for relation. Only for better display
// $c = $this->addChild($c, 'relation',' ');
$c->setAttribute('type', $relation_type);
}
/** Create temporal coverage node for collection or activity records. /** Create description node. One RIF-CS can have more than one description nodes.
* \param $values Type: 2-D array. The values of temporal coverage. It can has maximal two elements: one from 'dateFrom' and another for 'dateTo'. * Each description node has only one description.
* Either can be ommited according to RIF-CS schema. Each element of $values is an array and has keys: date, type and format. * \param $value Type: string. The content of the description.
* ['date'] is a string represents date. It has to be in W3CDTF or UTC format. * \param $des_type Type: string. Type of the description. Types can be brief, full, acessRights and note. Default is 'brief'.
* ['type'] has to be either 'dateFrom' or 'dateTo'. */
* ['format'] is optional and its default is 'W3CDTF'. UTC format requires date has to be in UTC: dateTtimeZ. protected function create_description_node($value, $des_type='brief') {
* It throws an exception if the input parameter is not an array. $c = $this->addChild($this->working_node, 'description', $value);
*/ $c->setAttribute('type', $des_type);
protected function create_coverage_tempo($values) { }
// Non array is not acceptable.
if (!is_array($values)) { throw new Exception('The input of temporal coverage has to be an array of arraies with keys.');}
$c = $this->addChild($this->working_node,'coverage');
$t = $this->addChild($c,'temporal');
foreach($values as $value) $this->create_coverage_tempo_date($t, $value);
}
/** Create temporal coverage node for collection or activity records. /** Create local or other type of identifier inside of RIF-CS metadata node
* \param $t Type: DOMElement. The \<coverage\>\<temporal/\>\</coverage\> node to which \<date\> nodes will be attached to. * \param $key
* \param $value Type: array. The value of temporal coverage. It has maxmimal three elements with keys: type, date and format. * Type string. The indentifier itself.
* It throws an exception if the input parameter is not an array. * \param $i_type
* \see create_coverage_tempo * Type string. Type of identifier. Can be abn, uri, local, etc.. Default is local.
*/ */
private function create_coverage_tempo_date($t, $value) { protected function create_identifier_node($key, $i_type='local') {
if (!is_array($value)) { throw new Exception('The input of temporal coverage has to be an array with keys.');} $c = $this->addChild($this->working_node, 'identifier',$key);
$d = $this->addChild($t,'date',$value['date']); $c->setAttribute('type', $i_type);
$d->setAttribute('type',$value['type']); }
if (isset($value['format'])) $d->setAttribute('dateFormat',$value['format']);
else $d->setAttribute('dateFormat','W3CDTF'); /** Location node is a holder node for either address or spatial nodes
} * \return DOMElement node, for adding address or spatial nodes.
*/
/** Create a subject node for a researcher, project, project, etc protected function create_location_node() {
* \param $value Type: string. A string representing the new namePart. return $this->addChild($this->working_node, 'location');
* \param $subject_type Type: string. A string representing the type of subject. The default value is anzsrc-for. }
*/
protected function create_subject_node($value, $subject_type = 'anzsrc-for') { /** Address node is a holder node for phiscal or electrical nodes.
if (empty($value)) return; * \param $location_node Type: DOMElement. Location node created previously.
$c = $this->addChild($this->working_node,'subject',$value); * \return DOMElement
$c->setAttribute('type',$subject_type); */
} protected function create_address_node($location_node) {
return $this->addChild($location_node, 'address');
}
/** Electrical address node. Used for email, url, etc
* \param $addr_node Type: DOMElement. Previously created address node.
* \param $e_node Type: string. The content of the adding node.
* \param $e_type Type: string. Default is email.
*/
protected function create_e_node($addr_node, $e_node, $e_type = 'email') {
$c = $this->addChild($addr_node, 'electronic');
$c->setAttribute('type', $e_type);
$this->addChild($c,'value',$e_node);
}
/** Physical node is a holder node for phone or fax nodes.
* \param $addr_node Type: DOMelement. Address node created before to which the new phiscial->addressPart will be attached.
* \param $number Type: string. Telephone or fax number as a string.
* \param $fone_fax Type: string. Either telehoneNumber or faxNumber.
*/
protected function create_physcial_fone_fax($addr_node, $number,$fone_fax='telephoneNumber') {
$c = $this->addChild($addr_node, 'physical');
$c = $this->addChild($c, 'addressPart', $number);
$c->setAttribute('type', $fone_fax);
}
/** create address node under location node, either streetAddress or postalAddress.
* But they are in text (one block) format.
* \param $addr_node Type: DOMelement. Address node created before to which the new phiscial->addressPart will be attached.
* \param $txt_addr string, full street address in text block format
* \param $phys_type string, default is 'streetAddress', can be 'postalAddress'
*/
protected function create_physcial_addr_txt($addr_node, $txt_addr,$phys_type='streetAddress') {
$c = $this->addChild($addr_node, 'physical');
$c->setAttribute('type', $phys_type);
$c = $this->addChild($c, 'addressPart', $txt_addr);
$c->setAttribute('type', 'text');
}
/** Create spatial node under a location node.
* \param $location_node Type: DOMElement. Location node where spatial node is being added to.
* \param $value Type: string. The value of spatial information. Default is local latitude and longitude.
* \param $sp_type Type: string. Type of spaitial informaion. Default is kmlPolyCoords.
*/
protected function create_spatial_node($location_node, $value = '138.6396,-34.97063', $sp_type = 'kmlPolyCoords') {
$c = $this->addChild($location_node, 'spatial',$value);
$c->setAttribute('type',$sp_type);
}
/** Create temporal coverage node for collection or activity records.
* \param $values Type: 2-D array. The values of temporal coverage. It can has maximal two elements: one from 'dateFrom' and another for 'dateTo'.
* Either can be ommited according to RIF-CS schema. Each element of $values is an array and has keys: date, type and format.
* ['date'] is a string represents date. It has to be in W3CDTF or UTC format.
* ['type'] has to be either 'dateFrom' or 'dateTo'.
* ['format'] is optional and its default is 'W3CDTF'. UTC format requires date has to be in UTC: dateTtimeZ.
* It throws an exception if the input parameter is not an array.
*/
protected function create_coverage_tempo($values) {
// Non array is not acceptable.
if (!is_array($values)) { throw new Exception('The input of temporal coverage has to be an array of arraies with keys.');}
$c = $this->addChild($this->working_node,'coverage');
$t = $this->addChild($c,'temporal');
foreach($values as $value) $this->create_coverage_tempo_date($t, $value);
}
/** Create temporal coverage node for collection or activity records.
* \param $t Type: DOMElement. The \<coverage\>\<temporal/\>\</coverage\> node to which \<date\> nodes will be attached to.
* \param $value Type: array. The value of temporal coverage. It has maxmimal three elements with keys: type, date and format.
* It throws an exception if the input parameter is not an array.
* \see create_coverage_tempo
*/
private function create_coverage_tempo_date($t, $value) {
if (!is_array($value)) { throw new Exception('The input of temporal coverage has to be an array with keys.');}
$d = $this->addChild($t,'date',$value['date']);
$d->setAttribute('type',$value['type']);
if (isset($value['format'])) $d->setAttribute('dateFormat',$value['format']);
else $d->setAttribute('dateFormat','W3CDTF');
}
/** Create a subject node for a researcher, project, project, etc
* \param $value Type: string. A string representing the new namePart.
* \param $subject_type Type: string. A string representing the type of subject. The default value is anzsrc-for.
*/
protected function create_subject_node($value, $subject_type = 'anzsrc-for') {
if (empty($value)) return;
$c = $this->addChild($this->working_node,'subject',$value);
$c->setAttribute('type',$subject_type);
}
} // end of class ANDS_RIFCS } // end of class ANDS_RIFCS

View File

@ -31,319 +31,318 @@ require_once('ands_rifcs.php');
*/ */
class ANDS_TPA extends ANDS_RIFCS { class ANDS_TPA extends ANDS_RIFCS {
//! Type: PDO. The database connection of the data source. //! Type: PDO. The database connection of the data source.
//! \see __construct. //! \see __construct.
private $db; private $db;
/** /**
* Constructor * Constructor
* The first two parameters are used by its parent class ANDS_RIFCS. The third is its own private property. * The first two parameters are used by its parent class ANDS_RIFCS. The third is its own private property.
* *
* \param $ands_response_doc ANDS_Response_XML. A XML Doc acts as the parent node. * \param $ands_response_doc ANDS_Response_XML. A XML Doc acts as the parent node.
* \param $metadata_node DOMElement. The meta node which all subsequent nodes will be added to. * \param $metadata_node DOMElement. The meta node which all subsequent nodes will be added to.
* \param $db Type: PDO. The database connection of the data source. * \param $db Type: PDO. The database connection of the data source.
*/ */
function __construct($ands_response_doc, $metadata_node, $db) { function __construct($ands_response_doc, $metadata_node, $db) {
parent::__construct($ands_response_doc, $metadata_node); parent::__construct($ands_response_doc, $metadata_node);
$this->db = $db; $this->db = $db;
} }
/**
* This is the general entrence of creating actual content. It calls different functions for different type of RIF-CS model.
* When anything goes wrong, e.g. found no record, or $set_name is not recognised, an exception will be thrown.
* And for this implementation, data are stored in a database therefore a PDO is needed. But the source can be any.
*
* \param $set_name Type: string. The name of set is going to be created. Can be one of activity, collection or party.
* \param $key Type: string. The main identifier used in ANDS system. There can be other identifier.
*
* \see create_activity, create_collection, create_party
*/
function create_obj_node($set_name, $key) {
$db = $this->db;
$set_name = strtolower($set_name);
if (in_array($set_name,prepare_set_names())) {
try {
// Get ori_id and which the original table is:
$query = "select ori_table_name, ori_id from oai_headers where oai_identifier = '".$key."'";
$res = exec_pdo_query($db, $query);
$record = $res->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo "$key returned no record.\n";
echo $e->getMessage();
}
$processor = 'create_'.substr($set_name,6); /**
$this->create_regObject(REG_OBJ_GROUP, $key, MY_URI); * This is the general entrence of creating actual content. It calls different functions for different type of RIF-CS model.
$this->$processor($record['ori_table_name'],$record['ori_id']); * When anything goes wrong, e.g. found no record, or $set_name is not recognised, an exception will be thrown.
$this->create_identifier_node($key); * And for this implementation, data are stored in a database therefore a PDO is needed. But the source can be any.
$this->create_identifier_node('table='.$record['ori_table_name'].'+id='.$record['ori_id']); *
} else { * \param $set_name Type: string. The name of set is going to be created. Can be one of activity, collection or party.
throw new Exception('Wrong set name was used: '.$set_name); * \param $key Type: string. The main identifier used in ANDS system. There can be other identifier.
} *
} * \see create_activity, create_collection, create_party
*/
/** The processor for creating metadata node of Activity. Called from create_obj_node. function create_obj_node($set_name, $key) {
* \param $table_name Type: string. The table name will be used to retrieve data from. $db = $this->db;
* \param $id_project Type: integer. Internal project id associated to this activity-project. $set_name = strtolower($set_name);
* \see Function create_obj_node. if (in_array($set_name,prepare_set_names())) {
*/ try {
private function create_activity($table_name, $id_project) { // Get ori_id and which the original table is:
$db = $this->db; $query = "select ori_table_name, ori_id from oai_headers where oai_identifier = '".$key."'";
$res = exec_pdo_query($db, $query);
$record = $res->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo "$key returned no record.\n";
echo $e->getMessage();
}
$processor = 'create_'.substr($set_name,6);
$this->create_regObject(REG_OBJ_GROUP, $key, MY_URI);
$this->$processor($record['ori_table_name'],$record['ori_id']);
$this->create_identifier_node($key);
$this->create_identifier_node('table='.$record['ori_table_name'].'+id='.$record['ori_id']);
} else {
throw new Exception('Wrong set name was used: '.$set_name);
}
}
/** The processor for creating metadata node of Activity. Called from create_obj_node.
* \param $table_name Type: string. The table name will be used to retrieve data from.
* \param $id_project Type: integer. Internal project id associated to this activity-project.
* \see Function create_obj_node.
*/
private function create_activity($table_name, $id_project) {
$db = $this->db;
# // Get ori_id and which the original table is: # // Get ori_id and which the original table is:
# $query = "select ori_table_name, ori_id from oai_headers where oai_identifier = '".$key."'"; # $query = "select ori_table_name, ori_id from oai_headers where oai_identifier = '".$key."'";
# $res = exec_pdo_query($db, $query); # $res = exec_pdo_query($db, $query);
# $record = $res->fetch(PDO::FETCH_ASSOC); # $record = $res->fetch(PDO::FETCH_ASSOC);
# // $id_project will e used later, so save it: # // $id_project will e used later, so save it:
# $id_project = $record['ori_id']; # $id_project = $record['ori_id'];
// Get the content using the previously obtained infor: // Get the content using the previously obtained infor:
$query = sprintf("select inter_no,start_date, end_date,pub_descrip from %s where id_project = %s",$table_name,$id_project); $query = sprintf("select inter_no,start_date, end_date,pub_descrip from %s where id_project = %s",$table_name,$id_project);
try { try {
$res = exec_pdo_query($db,$query); $res = exec_pdo_query($db,$query);
$record = $res->fetch(PDO::FETCH_ASSOC); $record = $res->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) { } catch (Exception $e) {
echo $e->getMessage(); echo $e->getMessage();
} }
$this->create_rifcs_node('activity','project'); $this->create_rifcs_node('activity','project');
$c = $this->create_name_node(); $c = $this->create_name_node();
$this->create_namePart($c,'The Plant Accelerator Project '.$record['inter_no']); $this->create_namePart($c,'The Plant Accelerator Project '.$record['inter_no']);
// Test codes for rich format. // Test codes for rich format.
# // \n works # // \n works
# $this->create_description_node(sprintf("Line one:%s,\nLine two:%s.\nThird",'a','b')); # $this->create_description_node(sprintf("Line one:%s,\nLine two:%s.\nThird",'a','b'));
$this->create_description_node(str_replace("\r\n","\n",$record['pub_descrip'])); $this->create_description_node(str_replace("\r\n","\n",$record['pub_descrip']));
$this->create_description_node('The experiment was carried out between '.$record['start_date'].' and '.$record['end_date'],'note'); $this->create_description_node('The experiment was carried out between '.$record['start_date'].' and '.$record['end_date'],'note');
$query = sprintf("select idr,stype from list_prj_ids_v2(%d) where stype in ('dataset','person')",$id_project); $query = sprintf("select idr,stype from list_prj_ids_v2 where stype in ('dataset','person')",$id_project);
// echo $query; // echo $query;
try { try {
$res = $db->query($query,PDO::FETCH_ASSOC); $res = $db->query($query,PDO::FETCH_ASSOC);
if ($res==false) { if ($res==false) {
throw new Exception($query."\nIt found nothing.\n"); throw new Exception($query."\nIt found nothing.\n");
} }
foreach ($res as $record) { foreach ($res as $record) {
switch ($record['stype']) { switch ($record['stype']) {
case 'dataset': case 'dataset':
$this->create_relatedObject($record['idr'],'hasOutput'); $this->create_relatedObject($record['idr'],'hasOutput');
break; break;
case 'person': case 'person':
$this->create_relatedObject($record['idr'],'isManagedBy'); $this->create_relatedObject($record['idr'],'isManagedBy');
break; break;
} }
} }
// The Plant Accelerator always participates in Activity // The Plant Accelerator always participates in Activity
$this->create_relatedObject('0874ad60-ab4d-11df-aebd-0002a5d5c51b','hasParticipant'); $this->create_relatedObject('0874ad60-ab4d-11df-aebd-0002a5d5c51b','hasParticipant');
} catch (PDOException $e) { } catch (PDOException $e) {
process_pdo_error($query, $e); process_pdo_error($query, $e);
}// end of try-catch block }// end of try-catch block
} // end of function create_activity($key, $id_project) } // end of function create_activity($key, $id_project)
/** The processor for creating metadata node of Collection. Called from create_obj_node.
* \param $table_name Type: string. The table name will be used to retrieve data from.
* \param $id_collect Type: integer. Internal collection id associated to this collection-dataset.
* \see Function create_obj_node.
*/
private function create_collection($table_name, $id_collect) {
$db = $this->db;
try {
$query = sprintf("select plant,variety,start_date,end_date,img_freq,anzsrc from %s where id_collect = %s",$table_name,$id_collect);
$res = exec_pdo_query($db, $query);
$dataset = $res->fetch(PDO::FETCH_ASSOC);
$res = exec_pdo_query($db, $query); /** The processor for creating metadata node of Collection. Called from create_obj_node.
$record = $res->fetch(PDO::FETCH_ASSOC); * \param $table_name Type: string. The table name will be used to retrieve data from.
* \param $id_collect Type: integer. Internal collection id associated to this collection-dataset.
$query = 'select id_rep, inter_no, id_project from tpa_project_ids where id_collect = '.$id_collect; * \see Function create_obj_node.
$res = exec_pdo_query($db, $query); */
$prj_info = $res->fetch(PDO::FETCH_ASSOC); private function create_collection($table_name, $id_collect) {
$db = $this->db;
$query = 'select email from tpa_person where id_rep = '.$prj_info['id_rep']; try {
$res = exec_pdo_query($db, $query); $query = sprintf("select plant,variety,start_date,end_date,img_freq,anzsrc from %s where id_collect = %s",$table_name,$id_collect);
$email = $res->fetch(PDO::FETCH_ASSOC); $res = exec_pdo_query($db, $query);
} catch (PDOException $e) { $dataset = $res->fetch(PDO::FETCH_ASSOC);
echo $query.' was failed\n';
echo $e->getMessage();
}
$this->create_rifcs_node('collection','dataset');
// Get the project inter_no as the name of this dataset
$c = $this->create_name_node();
$this->create_namePart($c,'Data set of Plant Accelerator Project '.$prj_info['inter_no']);
// locatin node: contact person
$l_node = $this->create_location_node();
$a_node = $this->create_address_node($l_node);
$this->create_e_node($a_node, $email['email']);
// location node: TPA's physical address
$l_node = $this->create_location_node();
$a_node = $this->create_address_node($l_node);
$this->create_physcial_addr_txt($a_node, 'The Plant Accelerator, Hartley Grove, Urrbrae, SA 5064') ;
// Temporal coverage of colletion
$dates = array(array('date'=>$dataset['start_date'],'type'=>'dateFrom'),array('date'=>$dataset['end_date'],'type'=>'dateTo'));
$this->create_coverage_tempo($dates);
// subject
$this->create_subject_node($dataset['aznsrc']);
// relatedOjbects
$query = sprintf("select idr,stype from list_prj_ids_v2(%d) where stype in ('project','person')",$prj_info['id_project']);
try {
$res = $db->query($query,PDO::FETCH_ASSOC);
if ($res==false) {
throw new Exception($query."\nIt found nothing.\n");
}
foreach ($res as $record) {
switch ($record['stype']) {
case 'project':
$this->create_relatedObject($record['idr'],'isOutputOf');
break;
case 'person':
$this->create_relatedObject($record['idr'],'isOwnedBy');
break;
}
}
} catch (PDOException $e) {
process_pdo_error($query, $e);
}// end of try-catch block
// right of accessing
$this->create_description_node('For information on rights and access to this dataset, please contact the owner.','accessRights');
// image data: $res = exec_pdo_query($db, $query);
$imgs = ''; $ex_conf = ''; $record = $res->fetch(PDO::FETCH_ASSOC);
$dic = array('im_type_rgb'=>'RGB','im_type_nir'=>'NIR','im_type_fir'=>'FIR','im_type_nir_roots'=>'NIR Roots','im_type_fluo'=>'Fluorescence');
$query = 'select im_type_rgb,im_type_nir,im_type_fir,im_type_nir_roots,im_type_fluo, lines, treatments, replicates, total from ands_collection where id_collect = '. $id_collect;
$res = $db->query($query,PDO::FETCH_ASSOC);
if ($res==false) {
throw new Exception($query."\nIt found nothing.\n");
}
$info = $res->fetch();
foreach ($info as $item => $v) {
switch ($item) {
case 'im_type_rgb':
case 'im_type_nir':
case 'im_type_fir':
case 'im_type_nir_roots':
case 'im_type_fluo':
if (!empty($v)) { $imgs .= $dic[$item].', '; }
break;
default:
if (!empty($v)) { $ex_conf .= ' '.$item.' = '.$v.', '; }
break;
}
}
if (empty($imgs)) $imgs = "Images data of RGB, FIR, NIR, NIR Roots and Fluorescence cameras., ";
$imgs = substr($imgs,0,-2);
if (!empty($ex_conf)) $imgs = $imgs."\n".substr($ex_conf,0,-2);
$this->create_description_node($imgs);
// imaging frequency
$this->create_description_node('Imaging frequency: '.$dataset['img_freq'],'note');
} // end of function create_collection($key,$id_collect)
/** The processor for creating metadata node of Party. Called from create_obj_node. As party-person is different to party-group, there are two sub-functions are called accordingly.
* \param $table_name Type: string. The table name will be used to retrieve data from.
* \param $id_party Type: integer. Internal party id associated to this party.
* \see Function create_obj_node.
*/
private function create_party($table_name, $id_party) {
$db = $this->db;
$query = sprintf("SELECT set_type FROM oai_headers WHERE ori_table_name = '%s' AND ori_id = %s",$table_name,$id_party);
$res = exec_pdo_query($db, $query);
$party_type = $res->fetch(PDO::FETCH_ASSOC);
if (in_array($party_type['set_type'],array('person','group'))) {
$this->create_rifcs_node('party',$party_type['set_type']);
if ($party_type['set_type']=='person') { $query = 'select id_rep, inter_no, id_project from tpa_project_ids where id_collect = '.$id_collect;
$this->create_person($table_name, $id_party); $res = exec_pdo_query($db, $query);
} elseif ($party_type['set_type']=='group') { $prj_info = $res->fetch(PDO::FETCH_ASSOC);
$this->create_group($table_name, $id_party); }
} else {
throw new Exception('Unsupported set_type: '.$party_type['set_type']);
}
} // end of function create_part($key,$id_party)
/** The processor for creating metadata node of Party. Called from create_obj_node. As party-person is different to party-group, there are two sub-functions are called accordingly. $query = 'select email from tpa_person where id_rep = '.$prj_info['id_rep'];
* \param $table_name Type: string. The table name will be used to retrieve data from. $res = exec_pdo_query($db, $query);
* \param $id_party Type: integer. Internal party id associated to this party-person. $email = $res->fetch(PDO::FETCH_ASSOC);
* \see Function create_party. } catch (PDOException $e) {
*/ echo $query.' was failed\n';
private function create_person($table_name, $id_party) { echo $e->getMessage();
$db = $this->db; }
$query = sprintf("SELECT id_org, title, first_name, family_name, tel, fax, email, www, address, post_code, city,state,country,duty FROM %s WHERE id_rep = %s",$table_name, $id_party);
$res = exec_pdo_query($db, $query);
$info = $res->fetch(PDO::FETCH_ASSOC);
$c = $this->create_name_node();
if (!empty($info['title'])) $this->create_namePart($c,$info['title'],'title');
$this->create_namePart($c,$info['family_name'],'family');
$this->create_namePart($c,$info['first_name'],'given');
// locatin node: contact person
$l_node = $this->create_location_node();
$a_node = $this->create_address_node($l_node);
$this->create_e_node($a_node, $info['email']);
if (!empty($info['www'])) $this->create_e_node($a_node, $info['www'],'url');
$this->create_physcial_fone_fax($a_node, $info['tel'],'telephoneNumber');
if (!empty($info['fax'])) $this->create_physcial_fone_fax($a_node, $info['fax'],'faxNumber');
$add_txt = trim($info['address']).', '.$info['city'].' '.$info['state'].' '.$info['post_code'].', '.$info['country'];
// the strlength of ', , ' is 6
if (strlen($add_txt)>6) $this->create_physcial_addr_txt($a_node,$add_txt);
// related objects:
// their group: id_customer is a foreign key of tpa_organisation
$query = sprintf("SELECT get_identifier('tpa_organisation',%s)",$info['id_org']);
$res = exec_pdo_query($db, $query);
$info = $res->fetch(PDO::FETCH_NUM);
$this->create_relatedObject($info[0],'isMemberOf');
// their activities
$query = "SELECT list_persons_objs($id_party,'project')";
$res = exec_pdo_query($db, $query);
$info = $res->fetch(PDO::FETCH_NUM);
foreach ($info as $item) {
$this->create_relatedObject($item,'isManagerOf');
}
// their collections
$query = "SELECT list_persons_objs($id_party,'dataset')";
$res = exec_pdo_query($db, $query);
$info = $res->fetch(PDO::FETCH_NUM);
foreach ($info as $item) {
$this->create_relatedObject($item,'isOwnerOf');
}
}
/** The processor for creating metadata node of Party. Called from create_obj_node. As party-person is different to party-group, there are two sub-functions are called accordingly.
* \param $table_name Type: string. The table name will be used to retrieve data from.
* \param $id_party Type: integer. Internal party id associated to this party-group.
* \see Function create_party.
*/
private function create_group($table_name, $id_party) {
$db = $this->db;
// echo 'table: ',$table_name,' party: ',$id_party,"\n";
$query = sprintf("SELECT customer_name, abn, post_code, address, city, state, country, tel, fax, email, www, description FROM %s WHERE id_org = %s",$table_name, $id_party);
//echo $query;
$res = exec_pdo_query($db, $query);
$info = $res->fetch(PDO::FETCH_ASSOC);
$c = $this->create_name_node();
$this->create_namePart($c,$info['customer_name']);
if (!empty($info['abn'])) $this->create_identifier_node($info['abn'],'abn');
if (!empty($info['description'])) $this->create_description_node($info['description']); $this->create_rifcs_node('collection','dataset');
// Get the project inter_no as the name of this dataset
$l_node = $this->create_location_node(); $c = $this->create_name_node();
$a_node = $this->create_address_node($l_node); $this->create_namePart($c,'Data set of Plant Accelerator Project '.$prj_info['inter_no']);
$this->create_physcial_fone_fax($a_node, $info['tel'],'telephoneNumber');
$this->create_physcial_fone_fax($a_node, $info['fax'],'faxNumber'); // locatin node: contact person
$add_txt = trim($info['address']).', '.$info['city'].' '.$info['state'].' '.$info['post_code'].', '.$info['country']; $l_node = $this->create_location_node();
$this->create_physcial_addr_txt($a_node,$add_txt); $a_node = $this->create_address_node($l_node);
$this->create_e_node($a_node, $email['email']);
// related objects: // location node: TPA's physical address
// their members: $l_node = $this->create_location_node();
$query = "SELECT list_pub_members($id_party)"; $a_node = $this->create_address_node($l_node);
$res = exec_pdo_query($db, $query); $this->create_physcial_addr_txt($a_node, 'The Plant Accelerator, Hartley Grove, Urrbrae, SA 5064') ;
$info = $res->fetch(PDO::FETCH_NUM); // Temporal coverage of colletion
foreach ($info as $item) { $dates = array(array('date'=>$dataset['start_date'],'type'=>'dateFrom'),array('date'=>$dataset['end_date'],'type'=>'dateTo'));
$this->create_relatedObject($item,'hasMember'); $this->create_coverage_tempo($dates);
} // subject
} $this->create_subject_node($dataset['aznsrc']);
// relatedOjbects
$query = sprintf("select idr,stype from list_prj_ids_v2(%d) where stype in ('project','person')",$prj_info['id_project']);
try {
$res = $db->query($query,PDO::FETCH_ASSOC);
if ($res==false) {
throw new Exception($query."\nIt found nothing.\n");
}
foreach ($res as $record) {
switch ($record['stype']) {
case 'project':
$this->create_relatedObject($record['idr'],'isOutputOf');
break;
case 'person':
$this->create_relatedObject($record['idr'],'isOwnedBy');
break;
}
}
} catch (PDOException $e) {
process_pdo_error($query, $e);
}// end of try-catch block
// right of accessing
$this->create_description_node('For information on rights and access to this dataset, please contact the owner.','accessRights');
// image data:
$imgs = ''; $ex_conf = '';
$dic = array('im_type_rgb'=>'RGB','im_type_nir'=>'NIR','im_type_fir'=>'FIR','im_type_nir_roots'=>'NIR Roots','im_type_fluo'=>'Fluorescence');
$query = 'select im_type_rgb,im_type_nir,im_type_fir,im_type_nir_roots,im_type_fluo, lines, treatments, replicates, total from ands_collection where id_collect = '. $id_collect;
$res = $db->query($query,PDO::FETCH_ASSOC);
if ($res==false) {
throw new Exception($query."\nIt found nothing.\n");
}
$info = $res->fetch();
foreach ($info as $item => $v) {
switch ($item) {
case 'im_type_rgb':
case 'im_type_nir':
case 'im_type_fir':
case 'im_type_nir_roots':
case 'im_type_fluo':
if (!empty($v)) { $imgs .= $dic[$item].', '; }
break;
default:
if (!empty($v)) { $ex_conf .= ' '.$item.' = '.$v.', '; }
break;
}
}
if (empty($imgs)) $imgs = "Images data of RGB, FIR, NIR, NIR Roots and Fluorescence cameras., ";
$imgs = substr($imgs,0,-2);
if (!empty($ex_conf)) $imgs = $imgs."\n".substr($ex_conf,0,-2);
$this->create_description_node($imgs);
// imaging frequency
$this->create_description_node('Imaging frequency: '.$dataset['img_freq'],'note');
} // end of function create_collection($key,$id_collect)
/** The processor for creating metadata node of Party. Called from create_obj_node. As party-person is different to party-group, there are two sub-functions are called accordingly.
* \param $table_name Type: string. The table name will be used to retrieve data from.
* \param $id_party Type: integer. Internal party id associated to this party.
* \see Function create_obj_node.
*/
private function create_party($table_name, $id_party) {
$db = $this->db;
$query = sprintf("SELECT set_type FROM oai_headers WHERE ori_table_name = '%s' AND ori_id = %s",$table_name,$id_party);
$res = exec_pdo_query($db, $query);
$party_type = $res->fetch(PDO::FETCH_ASSOC);
if (in_array($party_type['set_type'],array('person','group'))) {
$this->create_rifcs_node('party',$party_type['set_type']);
if ($party_type['set_type']=='person') {
$this->create_person($table_name, $id_party);
} elseif ($party_type['set_type']=='group') {
$this->create_group($table_name, $id_party); }
} else {
throw new Exception('Unsupported set_type: '.$party_type['set_type']);
}
} // end of function create_part($key,$id_party)
/** The processor for creating metadata node of Party. Called from create_obj_node. As party-person is different to party-group, there are two sub-functions are called accordingly.
* \param $table_name Type: string. The table name will be used to retrieve data from.
* \param $id_party Type: integer. Internal party id associated to this party-person.
* \see Function create_party.
*/
private function create_person($table_name, $id_party) {
$db = $this->db;
$query = sprintf("SELECT id_org, title, first_name, family_name, tel, fax, email, www, address, post_code, city,state,country,duty FROM %s WHERE id_rep = %s",$table_name, $id_party);
$res = exec_pdo_query($db, $query);
$info = $res->fetch(PDO::FETCH_ASSOC);
$c = $this->create_name_node();
if (!empty($info['title'])) $this->create_namePart($c,$info['title'],'title');
$this->create_namePart($c,$info['family_name'],'family');
$this->create_namePart($c,$info['first_name'],'given');
// locatin node: contact person
$l_node = $this->create_location_node();
$a_node = $this->create_address_node($l_node);
$this->create_e_node($a_node, $info['email']);
if (!empty($info['www'])) $this->create_e_node($a_node, $info['www'],'url');
$this->create_physcial_fone_fax($a_node, $info['tel'],'telephoneNumber');
if (!empty($info['fax'])) $this->create_physcial_fone_fax($a_node, $info['fax'],'faxNumber');
$add_txt = trim($info['address']).', '.$info['city'].' '.$info['state'].' '.$info['post_code'].', '.$info['country'];
// the strlength of ', , ' is 6
if (strlen($add_txt)>6) $this->create_physcial_addr_txt($a_node,$add_txt);
// related objects:
// their group: id_customer is a foreign key of tpa_organisation
$query = sprintf("SELECT get_identifier('tpa_organisation',%s)",$info['id_org']);
$res = exec_pdo_query($db, $query);
$info = $res->fetch(PDO::FETCH_NUM);
$this->create_relatedObject($info[0],'isMemberOf');
// their activities
$query = "SELECT list_persons_objs($id_party,'project')";
$res = exec_pdo_query($db, $query);
$info = $res->fetch(PDO::FETCH_NUM);
foreach ($info as $item) {
$this->create_relatedObject($item,'isManagerOf');
}
// their collections
$query = "SELECT list_persons_objs($id_party,'dataset')";
$res = exec_pdo_query($db, $query);
$info = $res->fetch(PDO::FETCH_NUM);
foreach ($info as $item) {
$this->create_relatedObject($item,'isOwnerOf');
}
}
/** The processor for creating metadata node of Party. Called from create_obj_node. As party-person is different to party-group, there are two sub-functions are called accordingly.
* \param $table_name Type: string. The table name will be used to retrieve data from.
* \param $id_party Type: integer. Internal party id associated to this party-group.
* \see Function create_party.
*/
private function create_group($table_name, $id_party) {
$db = $this->db;
// echo 'table: ',$table_name,' party: ',$id_party,"\n";
$query = sprintf("SELECT customer_name, abn, post_code, address, city, state, country, tel, fax, email, www, description FROM %s WHERE id_org = %s",$table_name, $id_party);
//echo $query;
$res = exec_pdo_query($db, $query);
$info = $res->fetch(PDO::FETCH_ASSOC);
$c = $this->create_name_node();
$this->create_namePart($c,$info['customer_name']);
if (!empty($info['abn'])) $this->create_identifier_node($info['abn'],'abn');
if (!empty($info['description'])) $this->create_description_node($info['description']);
$l_node = $this->create_location_node();
$a_node = $this->create_address_node($l_node);
$this->create_physcial_fone_fax($a_node, $info['tel'],'telephoneNumber');
$this->create_physcial_fone_fax($a_node, $info['fax'],'faxNumber');
$add_txt = trim($info['address']).', '.$info['city'].' '.$info['state'].' '.$info['post_code'].', '.$info['country'];
$this->create_physcial_addr_txt($a_node,$add_txt);
// related objects:
// their members:
$query = "SELECT list_pub_members($id_party)";
$res = exec_pdo_query($db, $query);
$info = $res->fetch(PDO::FETCH_NUM);
foreach ($info as $item) {
$this->create_relatedObject($item,'hasMember');
}
}
} // end of class ANDS_TPA } // end of class ANDS_TPA

View File

@ -16,11 +16,10 @@ $metadataPrefix = $args['metadataPrefix'];
// myhandler is a php file which will be included to generate metadata node. // myhandler is a php file which will be included to generate metadata node.
// $inc_record = $METADATAFORMATS[$metadataPrefix]['myhandler']; // $inc_record = $METADATAFORMATS[$metadataPrefix]['myhandler'];
if (is_array($METADATAFORMATS[$metadataPrefix]) if (is_array($METADATAFORMATS[$metadataPrefix]) && isset($METADATAFORMATS[$metadataPrefix]['myhandler'])) {
&& isset($METADATAFORMATS[$metadataPrefix]['myhandler'])) { $inc_record = $METADATAFORMATS[$metadataPrefix]['myhandler'];
$inc_record = $METADATAFORMATS[$metadataPrefix]['myhandler'];
} else { } else {
$errors[] = oai_error('cannotDisseminateFormat', 'metadataPrefix', $metadataPrefix); $errors[] = oai_error('cannotDisseminateFormat', 'metadataPrefix', $metadataPrefix);
} }
$identifier = $args['identifier']; $identifier = $args['identifier'];
@ -31,50 +30,44 @@ debug_message("Query: $query") ;
$res = $db->query($query); $res = $db->query($query);
if ($res===false) { if ($res===false) {
if (SHOW_QUERY_ERROR) { if (SHOW_QUERY_ERROR) {
echo __FILE__.','.__LINE__."<br />"; echo __FILE__.','.__LINE__."<br />";
echo "Query: $query<br />\n"; echo "Query: $query<br />\n";
die($db->errorInfo()); die($db->errorInfo());
} else { } else {
$errors[] = oai_error('idDoesNotExist', '', $identifier); $errors[] = oai_error('idDoesNotExist', '', $identifier);
} }
} elseif (!$res->rowCount()) { // based on PHP manual, it might only work for some DBs } elseif (!$res->rowCount()) { // based on PHP manual, it might only work for some DBs
$errors[] = oai_error('idDoesNotExist', '', $identifier); $errors[] = oai_error('idDoesNotExist', '', $identifier);
} }
if (!empty($errors)) { if (!empty($errors)) {
oai_exit(); oai_exit();
} }
$record = $res->fetch(PDO::FETCH_ASSOC); $record = $res->fetch(PDO::FETCH_ASSOC);
if ($record===false) { if ($record===false) {
if (SHOW_QUERY_ERROR) { if (SHOW_QUERY_ERROR) {
echo __FILE__.','.__LINE__."<br />"; echo __FILE__.','.__LINE__."<br />";
echo "Query: $query<br />\n"; echo "Query: $query<br />\n";
} }
$errors[] = oai_error('idDoesNotExist', '', $identifier); $errors[] = oai_error('idDoesNotExist', '', $identifier);
} }
$identifier = $record[$SQL['identifier']];; $identifier = $record[$SQL['identifier']];;
$datestamp = formatDatestamp($record[$SQL['datestamp']]); $datestamp = formatDatestamp($record[$SQL['datestamp']]);
if (isset($record[$SQL['deleted']]) && ($record[$SQL['deleted']] == 'true') && $status_deleted = (isset($record[$SQL['deleted']]) && ($record[$SQL['deleted']] == 'true') &&
($deletedRecord == 'transient' || $deletedRecord == 'persistent')) { ($deletedRecord == 'transient' || $deletedRecord == 'persistent'));
$status_deleted = TRUE;
} else {
$status_deleted = FALSE;
}
$outputObj = new ANDS_Response_XML($args); $outputObj = new ANDS_Response_XML($args);
$cur_record = $outputObj->create_record(); $cur_record = $outputObj->create_record();
$cur_header = $outputObj->create_header($identifier, $datestamp,$record[$SQL['set']],$cur_record); $cur_header = $outputObj->create_header($identifier, $datestamp,$record[$SQL['set']],$cur_record);
// return the metadata record itself // return the metadata record itself
if (!$status_deleted) { if (!$status_deleted) {
include($inc_record); // where the metadata node is generated. include($inc_record); // where the metadata node is generated.
create_metadata($outputObj, $cur_record, $identifier, $record[$SQL['set']], $db); create_metadata($outputObj, $cur_record, $identifier, $record[$SQL['set']], $db);
} else { } else {
$cur_header->setAttribute("status","deleted"); $cur_header->setAttribute("status","deleted");
} }
?>

View File

@ -10,23 +10,24 @@
// The response to Identify is fixed // The response to Identify is fixed
if (SHOW_QUERY_ERROR) { if (SHOW_QUERY_ERROR) {
echo "Here are some settings in raw format:\n"; echo "Here are some settings in raw format:\n";
print_r($identifyResponse); print_r($identifyResponse);
echo 'MAXRECORDS ',MAXRECORDS, ', MAXIDS ', MAXIDS,"\n"; echo 'MAXRECORDS ',MAXRECORDS, ', MAXIDS ', MAXIDS,"\n";
echo 'Token is valid for ',TOKEN_VALID," seconds\n"; echo 'Token is valid for ',TOKEN_VALID," seconds\n";
echo 'Tokens have prefix: ',TOKEN_PREFIX,"\n"; echo 'Tokens have prefix: ',TOKEN_PREFIX,"\n";
echo 'XMLSCHEMA: ',XMLSCHEMA,"\n"; echo 'XMLSCHEMA: ',XMLSCHEMA,"\n";
echo "\n"; echo "\n";
} }
$outputObj = new ANDS_Response_XML($args); $outputObj = new ANDS_Response_XML($args);
foreach($identifyResponse as $key => $val) { foreach($identifyResponse as $key => $val) {
$outputObj->add2_verbNode($key, $val); $outputObj->add2_verbNode($key, $val);
} }
if(isset($compression)) { if(isset($compression)) {
foreach($compression as $val) { foreach($compression as $val) {
$outputObj->add2_verbNode("compression", $val); $outputObj->add2_verbNode("compression", $val);
} }
} }
// A description MAY be included. // A description MAY be included.
@ -132,4 +133,3 @@ if(strlen($output)>10) {
$des->appendXML($output); $des->appendXML($output);
$outputObj->verbNode->appendChild($des); $outputObj->verbNode->appendChild($des);
} }
?>

View File

@ -136,6 +136,3 @@ University of Adelaide
</p> </p>
</body> </body>
</html> </html>

View File

@ -18,32 +18,32 @@
* *
*/ */
function addMetedataFormat(&$outputObj,$key,$val) { function addMetedataFormat(&$outputObj,$key,$val) {
$cmf = $outputObj->add2_verbNode("metadataFormat"); $cmf = $outputObj->add2_verbNode("metadataFormat");
$outputObj->addChild($cmf,'metadataPrefix',$key); $outputObj->addChild($cmf,'metadataPrefix',$key);
$outputObj->addChild($cmf,'schema',$val['schema']); $outputObj->addChild($cmf,'schema',$val['schema']);
$outputObj->addChild($cmf,'metadataNamespace',$val['metadataNamespace']); $outputObj->addChild($cmf,'metadataNamespace',$val['metadataNamespace']);
} }
if (isset($args['identifier'])) { if (isset($args['identifier'])) {
$identifier = $args['identifier']; $identifier = $args['identifier'];
$query = idFormatQuery($identifier); $query = idFormatQuery($identifier);
$res = $db->query($query); $res = $db->query($query);
if ($res==false) { if ($res==false) {
if (SHOW_QUERY_ERROR) { if (SHOW_QUERY_ERROR) {
echo __FILE__.','.__LINE__."<br />"; echo __FILE__.','.__LINE__."<br />";
echo "Query: $query<br />\n"; echo "Query: $query<br />\n";
die($db->errorInfo()); die($db->errorInfo());
} else { } else {
$errors[] = oai_error('idDoesNotExist','', $identifier); $errors[] = oai_error('idDoesNotExist','', $identifier);
} }
} else { } else {
$record = $res->fetch(); $record = $res->fetch();
if($record===false) { if($record===false) {
$errors[] = oai_error('idDoesNotExist', '', $identifier); $errors[] = oai_error('idDoesNotExist', '', $identifier);
} else { } else {
$mf = explode(",",$record[$SQL['metadataPrefix']]); $mf = explode(",",$record[$SQL['metadataPrefix']]);
} }
} }
} }
//break and clean up on error //break and clean up on error
@ -51,17 +51,15 @@ if (!empty($errors)) oai_exit();
$outputObj = new ANDS_Response_XML($args); $outputObj = new ANDS_Response_XML($args);
if (isset($mf)) { if (isset($mf)) {
foreach($mf as $key) { foreach($mf as $key) {
$val = $METADATAFORMATS[$key]; $val = $METADATAFORMATS[$key];
addMetedataFormat($outputObj,$key, $val); addMetedataFormat($outputObj,$key, $val);
} }
} elseif (is_array($METADATAFORMATS)) { } elseif (is_array($METADATAFORMATS)) {
foreach($METADATAFORMATS as $key=>$val) { foreach($METADATAFORMATS as $key=>$val) {
addMetedataFormat($outputObj,$key, $val); addMetedataFormat($outputObj,$key, $val);
} }
} else { // a very unlikely event
$errors[] = oai_error('noMetadataFormats');
oai_exit();
} }
else { // a very unlikely event
$errors[] = oai_error('noMetadataFormats');
oai_exit();
}
?>

View File

@ -13,116 +13,117 @@ debug_message("\nI am debuging". __FILE__) ;
// Resume previous session? // Resume previous session?
if (isset($args['resumptionToken'])) { if (isset($args['resumptionToken'])) {
if (!file_exists(TOKEN_PREFIX.$args['resumptionToken'])) { if (!file_exists(TOKEN_PREFIX.$args['resumptionToken'])) {
$errors[] = oai_error('badResumptionToken', '', $args['resumptionToken']); $errors[] = oai_error('badResumptionToken', '', $args['resumptionToken']);
} else { } else {
$readings = readResumToken(TOKEN_PREFIX.$args['resumptionToken']); $readings = readResumToken(TOKEN_PREFIX.$args['resumptionToken']);
if ($readings == false) { if ($readings == false) {
$errors[] = oai_error('badResumptionToken', '', $args['resumptionToken']); $errors[] = oai_error('badResumptionToken', '', $args['resumptionToken']);
} else { } else {
debug_var_dump('readings',$readings); debug_var_dump('readings',$readings);
list($deliveredrecords, $extquery, $metadataPrefix) = $readings; list($deliveredrecords, $extquery, $metadataPrefix) = $readings;
} }
} }
} else { // no, we start a new session } else { // no, we start a new session
$deliveredrecords = 0; $deliveredrecords = 0;
$extquery = ''; $extquery = '';
$metadataPrefix = $args['metadataPrefix']; $metadataPrefix = $args['metadataPrefix'];
if (isset($args['from'])) { if (isset($args['from'])) {
$from = checkDateFormat($args['from']); $from = checkDateFormat($args['from']);
$extquery .= fromQuery($from); $extquery .= fromQuery($from);
} }
if (isset($args['until'])) { if (isset($args['until'])) {
$until = checkDateFormat($args['until']); $until = checkDateFormat($args['until']);
$extquery .= untilQuery($until); $extquery .= untilQuery($until);
} }
if (isset($args['set'])) { if (isset($args['set'])) {
if (is_array($SETS)) { if (is_array($SETS)) {
$extquery .= setQuery($args['set']); $extquery .= setQuery($args['set']);
} else { } else {
$errors[] = oai_error('noSetHierarchy'); $errors[] = oai_error('noSetHierarchy');
} }
} }
} }
if (!empty($errors)) { if (!empty($errors)) {
oai_exit(); oai_exit();
} }
// Load the handler // Load the handler
if (is_array($METADATAFORMATS[$metadataPrefix]) if (is_array($METADATAFORMATS[$metadataPrefix]) && isset($METADATAFORMATS[$metadataPrefix]['myhandler'])) {
&& isset($METADATAFORMATS[$metadataPrefix]['myhandler'])) { $inc_record = $METADATAFORMATS[$metadataPrefix]['myhandler'];
$inc_record = $METADATAFORMATS[$metadataPrefix]['myhandler']; include($inc_record);
include($inc_record);
} else { } else {
$errors[] = oai_error('cannotDisseminateFormat', 'metadataPrefix', $metadataPrefix); $errors[] = oai_error('cannotDisseminateFormat', 'metadataPrefix', $metadataPrefix);
} }
if (!empty($errors)) { if (!empty($errors)) {
oai_exit(); oai_exit();
} }
if (empty($errors)) { if (empty($errors)) {
$query = selectallQuery($metadataPrefix) . $extquery; $query = selectallQuery($metadataPrefix) . $extquery;
debug_message("Query: $query") ; debug_message("Query: $query") ;
$res = $db->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL)); $res = $db->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$r = $res->execute(); $r = $res->execute();
if ($r===false) { if (($r===false) ) {
if (SHOW_QUERY_ERROR) { if ( (SHOW_QUERY_ERROR)) {
echo __FILE__.','.__LINE__."<br />"; echo __FILE__.','.__LINE__."<br />";
echo "Query: $query<br />\n"; echo "Query: $query<br />\n";
print_r($db->errorInfo()); print_r($db->errorInfo());
exit(); exit();
} else { } else {
$errors[] = oai_error('noRecordsMatch'); $errors[] = oai_error('noRecordsMatch');
} }
} else { } else {
$r = $res->setFetchMode(PDO::FETCH_ASSOC); $r = $res->setFetchMode(PDO::FETCH_ASSOC);
if ($r===false) { if ($r===false) {
exit("FetchMode is not supported"); exit("FetchMode is not supported");
} }
$num_rows = rowCount($metadataPrefix, $extquery, $db); $num_rows = rowCount($metadataPrefix, $extquery, $db);
if ($num_rows==0) { if ($num_rows==0) {
echo "Cannot find records: $query\n"; if (SHOW_QUERY_ERROR) {
$errors[] = oai_error('noRecordsMatch'); echo "Cannot find records: $query\n";
} }
} $errors[] = oai_error('noRecordsMatch');
}
}
} }
if (!empty($errors)) { if (!empty($errors)) {
oai_exit(); oai_exit();
} }
// Will we need a new ResumptionToken? // Will we need a new ResumptionToken?
if($args['verb']=='ListRecords') { if($args['verb']=='ListRecords') {
$maxItems = MAXRECORDS; $maxItems = MAXRECORDS;
} elseif($args['verb']=='ListIdentifiers') { } elseif($args['verb']=='ListIdentifiers') {
$maxItems = MAXIDS; $maxItems = MAXIDS;
} else { } else {
exit("Check ".__FILE__." ".__LINE__.", there is something wrong."); exit("Check ".__FILE__." ".__LINE__.", there is something wrong.");
} }
$maxrec = min($num_rows - $deliveredrecords, $maxItems); $maxrec = min($num_rows - $deliveredrecords, $maxItems);
if ($num_rows - $deliveredrecords > $maxItems) { if ($num_rows - $deliveredrecords > $maxItems) {
$cursor = (int)$deliveredrecords + $maxItems; $cursor = (int)$deliveredrecords + $maxItems;
$restoken = createResumToken($cursor, $extquery, $metadataPrefix); $restoken = createResumToken($cursor, $extquery, $metadataPrefix);
$expirationdatetime = gmstrftime('%Y-%m-%dT%TZ', time()+TOKEN_VALID); $expirationdatetime = gmstrftime('%Y-%m-%dT%TZ', time()+TOKEN_VALID);
} }
// Last delivery, return empty ResumptionToken // Last delivery, return empty ResumptionToken
elseif (isset($args['resumptionToken'])) { elseif (isset($args['resumptionToken'])) {
$restoken = $args['resumptionToken']; // just used as an indicator $restoken = $args['resumptionToken']; // just used as an indicator
unset($expirationdatetime); unset($expirationdatetime);
} }
if (isset($args['resumptionToken'])) { if (isset($args['resumptionToken'])) {
debug_message("Try to resume because a resumptionToken supplied.") ; debug_message("Try to resume because a resumptionToken supplied.") ;
$record = $res->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, $deliveredrecords); $record = $res->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, $deliveredrecords);
} }
// Record counter // Record counter
$countrec = 0; $countrec = 0;
@ -130,53 +131,48 @@ $countrec = 0;
// Publish a batch to $maxrec number of records // Publish a batch to $maxrec number of records
$outputObj = new ANDS_Response_XML($args); $outputObj = new ANDS_Response_XML($args);
while ($countrec++ < $maxrec) { while ($countrec++ < $maxrec) {
$record = $res->fetch(PDO::FETCH_ASSOC); $record = $res->fetch(PDO::FETCH_ASSOC);
if ($record===false) { if ($record===false) {
if (SHOW_QUERY_ERROR) { if (SHOW_QUERY_ERROR) {
echo __FILE__.",". __LINE__."<br />"; echo __FILE__.",". __LINE__."<br />";
print_r($db->errorInfo()); print_r($db->errorInfo());
exit(); exit();
} }
} }
$identifier = $oaiprefix.$record[$SQL['identifier']]; $identifier = $oaiprefix.$record[$SQL['identifier']];
$datestamp = formatDatestamp($record[$SQL['datestamp']]); $datestamp = formatDatestamp($record[$SQL['datestamp']]);
$setspec = $record[$SQL['set']]; $setspec = $record[$SQL['set']];
// debug_var_dump('record', $record); // debug_var_dump('record', $record);
if (isset($record[$SQL['deleted']]) && ($record[$SQL['deleted']] === true) && $status_deleted = (isset($record[$SQL['deleted']]) && ($record[$SQL['deleted']] === true) &&
($deletedRecord == 'transient' || $deletedRecord == 'persistent')) { ($deletedRecord == 'transient' || $deletedRecord == 'persistent'));
$status_deleted = TRUE;
} else { //debug_var_dump('status_deleted', $status_deleted);
$status_deleted = FALSE; if($args['verb']=='ListRecords') {
} $cur_record = $outputObj->create_record();
$cur_header = $outputObj->create_header($identifier, $datestamp,$setspec,$cur_record);
//debug_var_dump('status_deleted', $status_deleted); // return the metadata record itself
if($args['verb']=='ListRecords') { if (!$status_deleted) {
$cur_record = $outputObj->create_record(); debug_var_dump('inc_record',$inc_record);
$cur_header = $outputObj->create_header($identifier, $datestamp,$setspec,$cur_record); create_metadata($outputObj, $cur_record, $identifier, $setspec, $db);
// return the metadata record itself }
if (!$status_deleted) { } else { // for ListIdentifiers, only identifiers will be returned.
debug_var_dump('inc_record',$inc_record); $cur_header = $outputObj->create_header($identifier, $datestamp,$setspec);
create_metadata($outputObj, $cur_record, $identifier, $setspec, $db); }
} if ($status_deleted) {
} else { // for ListIdentifiers, only identifiers will be returned. $cur_header->setAttribute("status","deleted");
$cur_header = $outputObj->create_header($identifier, $datestamp,$setspec); }
}
if ($status_deleted) {
$cur_header->setAttribute("status","deleted");
}
} }
// ResumptionToken // ResumptionToken
if (isset($restoken)) { if (isset($restoken)) {
if(isset($expirationdatetime)) { if(isset($expirationdatetime)) {
$outputObj->create_resumpToken($restoken,$expirationdatetime,$num_rows,$cursor); $outputObj->create_resumpToken($restoken,$expirationdatetime,$num_rows,$cursor);
} else { } else {
$outputObj->create_resumpToken('',null,$num_rows,$deliveredrecords); $outputObj->create_resumpToken('',null,$num_rows,$deliveredrecords);
} }
} }
// end ListRecords // end ListRecords
if (SHOW_QUERY_ERROR) {echo "Debug listrecord.php reached to the end.\n\n";} if (SHOW_QUERY_ERROR) {echo "Debug listrecord.php reached to the end.\n\n";}
?>

View File

@ -1,30 +1,28 @@
<?php <?php
/** /**
* \file * \file
* \brief Response to Verb ListSets * \brief Response to Verb ListSets
* *
* Lists what sets are available to records in the system. * Lists what sets are available to records in the system.
*/ */
// Here the size of sets is small, no resumptionToken is taken care. // Here the size of sets is small, no resumptionToken is taken care.
if (is_array($SETS)) { if (is_array($SETS)) {
$outputObj = new ANDS_Response_XML($args); $outputObj = new ANDS_Response_XML($args);
foreach($SETS as $set) { foreach($SETS as $set) {
$setNode = $outputObj->add2_verbNode("set"); $setNode = $outputObj->add2_verbNode("set");
foreach($set as $key => $val) { foreach($set as $key => $val) {
if($key=='setDescription') { if($key=='setDescription') {
$desNode = $outputObj->addChild($setNode,$key); $desNode = $outputObj->addChild($setNode,$key);
$des = $outputObj->doc->createDocumentFragment(); $des = $outputObj->doc->createDocumentFragment();
$des->appendXML($val); $des->appendXML($val);
$desNode->appendChild($des); $desNode->appendChild($des);
} else { } else {
$outputObj->addChild($setNode,$key,$val); $outputObj->addChild($setNode,$key,$val);
} }
} }
} }
} else { } else {
$errors[] = oai_error('noSetHierarchy'); $errors[] = oai_error('noSetHierarchy');
oai_exit(); oai_exit();
} }
?>

View File

@ -152,7 +152,9 @@ if (isset($args['verb'])) {
$errors[] = oai_error('noVerb'); $errors[] = oai_error('noVerb');
} }
if (!empty($errors)) { oai_exit(); } if (!empty($errors)) {
oai_exit();
}
if ($compress) { if ($compress) {
ob_start('ob_gzhandler'); ob_start('ob_gzhandler');
@ -160,7 +162,7 @@ if ($compress) {
header(CONTENT_TYPE); header(CONTENT_TYPE);
if(isset($outputObj)) { if (isset($outputObj)) {
$outputObj->display(); $outputObj->display();
} else { } else {
exit("There is a bug in codes"); exit("There is a bug in codes");
@ -169,5 +171,3 @@ if(isset($outputObj)) {
if ($compress) { if ($compress) {
ob_end_flush(); ob_end_flush();
} }
?>

View File

@ -119,12 +119,12 @@ $deletedRecord = $identifyResponse["deletedRecord"]; // a shorthand for checking
//granularity is days //granularity is days
//$granularity = 'YYYY-MM-DD'; //$granularity = 'YYYY-MM-DD';
// granularity is seconds // granularity is seconds
$identifyResponse["granularity"] = 'YYYY-MM-DD'; $identifyResponse["granularity"] = 'YYYY-MM-DDThh:mm:ssZ';
// this is appended if your granularity is seconds. // this is appended if your granularity is seconds.
// do not change // do not change
if (strcmp($identifyResponse["granularity"],'YYYY-MM-DDThh:mm:ssZ')==0) { if (strcmp($identifyResponse["granularity"],'YYYY-MM-DDThh:mm:ssZ')==0) {
$identifyResponse["earliestDatestamp"] = $identifyResponse["earliestDatestamp"].'T00:00:00Z'; // $identifyResponse["earliestDatestamp"] = $identifyResponse["earliestDatestamp"].'T00:00:00Z';
} }
/** Compression methods supported. Optional (multiple). Default: null. /** Compression methods supported. Optional (multiple). Default: null.

View File

@ -13,10 +13,10 @@
* \see SHOW_QUERY_ERROR in oaidp-config.php * \see SHOW_QUERY_ERROR in oaidp-config.php
*/ */
function debug_var_dump($var_name, $var) { function debug_var_dump($var_name, $var) {
if (SHOW_QUERY_ERROR) { if (SHOW_QUERY_ERROR) {
echo "Dumping \${$var_name}: \n"; echo "Dumping \${$var_name}: \n";
var_dump($var)."\n"; var_dump($var)."\n";
} }
} }
/** Prints human-readable information about a variable for debugging, /** Prints human-readable information about a variable for debugging,
@ -26,10 +26,10 @@ function debug_var_dump($var_name, $var) {
* \see SHOW_QUERY_ERROR in oaidp-config.php * \see SHOW_QUERY_ERROR in oaidp-config.php
*/ */
function debug_print_r($var_name, $var) { function debug_print_r($var_name, $var) {
if (SHOW_QUERY_ERROR) { if (SHOW_QUERY_ERROR) {
echo "Printing \${$var_name}: \n"; echo "Printing \${$var_name}: \n";
print_r($var)."\n"; print_r($var)."\n";
} }
} }
/** Prints a message for debugging, /** Prints a message for debugging,
@ -39,8 +39,9 @@ function debug_print_r($var_name, $var) {
* \see SHOW_QUERY_ERROR in oaidp-config.php * \see SHOW_QUERY_ERROR in oaidp-config.php
*/ */
function debug_message($msg) { function debug_message($msg) {
if (!SHOW_QUERY_ERROR) return; if (SHOW_QUERY_ERROR) {
echo $msg,"\n"; echo $msg,"\n";
}
} }
/** Check if provided correct arguments for a request. /** Check if provided correct arguments for a request.
@ -53,63 +54,63 @@ function debug_message($msg) {
* is needed. * is needed.
*/ */
function checkArgs($args, $checkList) { function checkArgs($args, $checkList) {
// global $errors, $TOKEN_VALID, $METADATAFORMATS; // global $errors, $TOKEN_VALID, $METADATAFORMATS;
global $errors, $METADATAFORMATS; global $errors, $METADATAFORMATS;
// $verb = $args['verb']; // $verb = $args['verb'];
unset($args["verb"]); unset($args["verb"]);
debug_print_r('checkList',$checkList); debug_print_r('checkList',$checkList);
debug_print_r('args',$args); debug_print_r('args',$args);
// "verb" has been checked before, no further check is needed
if(isset($checkList['required'])) {
for($i = 0; $i < count($checkList["required"]); $i++) {
debug_message("Checking: par$i: ". $checkList['required'][$i] . " in ");
debug_var_dump("isset(\$args[\$checkList['required'][\$i]])",isset($args[$checkList['required'][$i]]));
// echo "key exists". array_key_exists($checkList["required"][$i],$args)."\n";
if(isset($args[$checkList['required'][$i]])==false) {
// echo "caught\n";
$errors[] = oai_error('missingArgument', $checkList["required"][$i]);
} else {
// if metadataPrefix is set, it is in required section
if(isset($args['metadataPrefix'])) {
$metadataPrefix = $args['metadataPrefix'];
// Check if the format is supported, it has enough infor (an array), last if a handle has been defined.
if (!array_key_exists ($metadataPrefix, $METADATAFORMATS) || !(is_array($METADATAFORMATS[$metadataPrefix])
|| !isset($METADATAFORMATS[$metadataPrefix]['myhandler']))) {
$errors[] = oai_error('cannotDisseminateFormat', 'metadataPrefix', $metadataPrefix);
}
}
unset($args[$checkList["required"][$i]]);
}
}
}
debug_message('Before return');
debug_print_r('errors',$errors);
if (!empty($errors)) return;
// check to see if there is unwanted // "verb" has been checked before, no further check is needed
foreach($args as $key => $val) { if(isset($checkList['required'])) {
debug_message("checkArgs: $key"); for($i = 0; $i < count($checkList["required"]); $i++) {
if(!in_array($key, $checkList["ops"])) { debug_message("Checking: par$i: ". $checkList['required'][$i] . " in ");
debug_message("Wrong\n".print_r($checkList['ops'],true)); debug_var_dump("isset(\$args[\$checkList['required'][\$i]])",isset($args[$checkList['required'][$i]]));
$errors[] = oai_error('badArgument', $key, $val); // echo "key exists". array_key_exists($checkList["required"][$i],$args)."\n";
} if(isset($args[$checkList['required'][$i]])==false) {
switch ($key) { // echo "caught\n";
case 'from': $errors[] = oai_error('missingArgument', $checkList["required"][$i]);
case 'until': } else {
if(!checkDateFormat($val)) { // if metadataPrefix is set, it is in required section
$errors[] = oai_error('badGranularity', $key, $val); if(isset($args['metadataPrefix'])) {
} $metadataPrefix = $args['metadataPrefix'];
break; // Check if the format is supported, it has enough infor (an array), last if a handle has been defined.
if (!array_key_exists ($metadataPrefix, $METADATAFORMATS) || !(is_array($METADATAFORMATS[$metadataPrefix])
case 'resumptionToken': || !isset($METADATAFORMATS[$metadataPrefix]['myhandler']))) {
// only check for expairation $errors[] = oai_error('cannotDisseminateFormat', 'metadataPrefix', $metadataPrefix);
if((int)$val+TOKEN_VALID < time()) }
$errors[] = oai_error('badResumptionToken'); }
break; unset($args[$checkList["required"][$i]]);
} }
} }
}
debug_message('Before return');
debug_print_r('errors',$errors);
if (!empty($errors)) return;
// check to see if there is unwanted
foreach($args as $key => $val) {
debug_message("checkArgs: $key");
if(!in_array($key, $checkList["ops"])) {
debug_message("Wrong\n".print_r($checkList['ops'],true));
$errors[] = oai_error('badArgument', $key, $val);
}
switch ($key) {
case 'from':
case 'until':
if(!checkDateFormat($val)) {
$errors[] = oai_error('badGranularity', $key, $val);
}
break;
case 'resumptionToken':
// only check for expairation
if((int)$val+TOKEN_VALID < time())
$errors[] = oai_error('badResumptionToken');
break;
}
}
} }
/** Validates an identifier. The pattern is: '/^[-a-z\.0-9]+$/i' which means /** Validates an identifier. The pattern is: '/^[-a-z\.0-9]+$/i' which means
@ -117,9 +118,8 @@ function checkArgs($args, $checkList) {
* Used only by function <B>oai_error</B> code idDoesNotExist. * Used only by function <B>oai_error</B> code idDoesNotExist.
* \param $url Type: string * \param $url Type: string
*/ */
function is_valid_uri($url) function is_valid_uri($url) {
{ return((bool)preg_match('/^[-a-z\.0-9]+$/i', $url));
return((bool)preg_match('/^[-a-z\.0-9]+$/i', $url));
} }
/** Validates attributes come with the query. /** Validates attributes come with the query.
@ -127,72 +127,69 @@ function is_valid_uri($url)
* Here there are few more match patterns than is_valid_uri(): ':_'. * Here there are few more match patterns than is_valid_uri(): ':_'.
* \param $attrb Type: string * \param $attrb Type: string
*/ */
function is_valid_attrb($attrb) { function is_valid_attrb($attrb) {
return preg_match("/^[_a-zA-Z0-9\-\:\.]+$/",$attrb); return preg_match("/^[_a-zA-Z0-9\-\:\.]+$/",$attrb);
} }
/** All datestamps used in this system are GMT even /** All datestamps used in this system are GMT even
* return value from database has no TZ information * return value from database has no TZ information
*/ */
function formatDatestamp($datestamp) function formatDatestamp($datestamp) {
{ return date("Y-m-d\TH:i:s\Z",strtotime($datestamp));
return date("Y-m-d\TH:i:s\Z",strtotime($datestamp));
} }
/** The database uses datastamp without time-zone information. /** The database uses datastamp without time-zone information.
* It needs to clean all time-zone informaion from time string and reformat it * It needs to clean all time-zone informaion from time string and reformat it
*/ */
function checkDateFormat($date) { function checkDateFormat($date) {
$date = str_replace(array("T","Z")," ",$date); $date = str_replace(array("T","Z")," ",$date);
$time_val = strtotime($date); $time_val = strtotime($date);
if (SHOW_QUERY_ERROR) { echo "timeval: $time_val\n"; } if (SHOW_QUERY_ERROR) { echo "timeval: $time_val\n"; }
if(!$time_val) return false; if(!$time_val) return false;
if(strstr($date,":")) { if(strstr($date,":")) {
return date("Y-m-d H:i:s",$time_val); return date("Y-m-d H:i:s",$time_val);
} else { } else {
return date("Y-m-d",$time_val); return date("Y-m-d",$time_val);
} }
} }
/** Retrieve all defined 'setSpec' from configuraiton of $SETS. /** Retrieve all defined 'setSpec' from configuraiton of $SETS.
* It is used by ANDS_TPA::create_obj_node(); * It is used by ANDS_TPA::create_obj_node();
*/ */
function prepare_set_names() { function prepare_set_names() {
global $SETS; global $SETS;
$n = count($SETS); $n = count($SETS);
$a = array_fill(0,$n,''); $a = array_fill(0,$n,'');
for ($i = 0; $i <$n; $i++) { for ($i = 0; $i <$n; $i++) {
$a[$i] = $SETS[$i]['setSpec']; $a[$i] = $SETS[$i]['setSpec'];
} }
return $a; return $a;
} }
/** Finish a request when there is an error: send back errors. */ /** Finish a request when there is an error: send back errors. */
function oai_exit() function oai_exit() {
{
// global $CONTENT_TYPE;
header(CONTENT_TYPE);
global $args,$errors,$compress;
$e = new ANDS_Error_XML($args,$errors);
if ($compress) {
ob_start('ob_gzhandler');
}
$e->display();
if ($compress) { // global $CONTENT_TYPE;
ob_end_flush(); header(CONTENT_TYPE);
} global $args,$errors,$compress;
$e = new ANDS_Error_XML($args,$errors);
exit(); if ($compress) {
ob_start('ob_gzhandler');
}
$e->display();
if ($compress) {
ob_end_flush();
}
exit();
} }
// ResumToken section // ResumToken section
/** Generate a string based on the current Unix timestamp in microseconds for creating resumToken file name. */ /** Generate a string based on the current Unix timestamp in microseconds for creating resumToken file name. */
function get_token() function get_token() {
{ list($usec, $sec) = explode(" ", microtime());
list($usec, $sec) = explode(" ", microtime()); return ((int)($usec*1000) + (int)($sec*1000));
return ((int)($usec*1000) + (int)($sec*1000));
} }
/** Create a token file. /** Create a token file.
@ -200,30 +197,30 @@ function get_token()
* Called by listrecords.php. * Called by listrecords.php.
*/ */
function createResumToken($cursor, $extquery, $metadataPrefix) { function createResumToken($cursor, $extquery, $metadataPrefix) {
$token = get_token(); $token = get_token();
$fp = fopen (TOKEN_PREFIX.$token, 'w'); $fp = fopen (TOKEN_PREFIX.$token, 'w');
if($fp==false) { if($fp==false) {
exit("Cannot write. Writer permission needs to be changed."); exit("Cannot write. Writer permission needs to be changed.");
} }
fputs($fp, "$cursor#"); fputs($fp, "$cursor#");
fputs($fp, "$extquery#"); fputs($fp, "$extquery#");
fputs($fp, "$metadataPrefix#"); fputs($fp, "$metadataPrefix#");
fclose($fp); fclose($fp);
return $token; return $token;
} }
/** Read a saved ResumToken */ /** Read a saved ResumToken */
function readResumToken($resumptionToken) { function readResumToken($resumptionToken) {
$rtVal = false; $rtVal = false;
$fp = fopen($resumptionToken, 'r'); $fp = fopen($resumptionToken, 'r');
if ($fp!=false) { if ($fp!=false) {
$filetext = fgets($fp, 255); $filetext = fgets($fp, 255);
$textparts = explode('#', $filetext); $textparts = explode('#', $filetext);
fclose($fp); fclose($fp);
unlink ($resumptionToken); unlink ($resumptionToken);
$rtVal = array((int)$textparts[0], $textparts[1], $textparts[2]); $rtVal = array((int)$textparts[0], $textparts[1], $textparts[2]);
} }
return $rtVal; return $rtVal;
} }
// Here are a couple of queries which might need to be adjusted to // Here are a couple of queries which might need to be adjusted to
@ -235,86 +232,80 @@ function readResumToken($resumptionToken) {
* the useless condition id_column = id_column is just there to ease * the useless condition id_column = id_column is just there to ease
* further extensions to the query, please leave it as it is. * further extensions to the query, please leave it as it is.
*/ */
function selectallQuery ($metadPrefix = "rif", $id = '') function selectallQuery($metadPrefix = "rif", $id = ''){
{ global $SQL;
global $SQL; $query = "SELECT * FROM ".$SQL['table'] . " WHERE ".$SQL['metadataPrefix']." LIKE '%$metadPrefix%'";
$query = "SELECT * FROM ".$SQL['table'] . " WHERE ".$SQL['metadataPrefix']." LIKE '%$metadPrefix%'"; if ($id != '') {
if ($id != '') { $query .= " AND ".$SQL['identifier']." ='$id'";
$query .= " AND ".$SQL['identifier']." ='$id'"; }
} return $query;
return $query;
} }
/** this function will return metadataFormat of a record */ /** this function will return metadataFormat of a record */
function idFormatQuery($id) function idFormatQuery($id) {
{ global $SQL;
global $SQL; return 'select '.$SQL['metadataPrefix'].' FROM '.$SQL['table']. " WHERE ".$SQL['identifier']." = '".$id."'";
return 'select '.$SQL['metadataPrefix'].' FROM '.$SQL['table']. " WHERE ".$SQL['identifier']." = '".$id."'";
} }
/** this function will return identifier and datestamp for all records /** this function will return identifier and datestamp for all records
* not very useful * not very useful
*/ */
function idQuery ($metadPrefix = "rif", $id = '') function idQuery($metadPrefix = "rif", $id = '') {
{ global $SQL;
global $SQL;
if ($SQL['set'] != '') { if ($SQL['set'] != '') {
$query = 'select '.$SQL['identifier'].','.$SQL['datestamp'].','.$SQL['set'].' FROM '.$SQL['table']. " WHERE ".$SQL['metadataPrefix']." LIKE '%$metadPrefix%'"; $query = 'select '.$SQL['identifier'].','.$SQL['datestamp'].','.$SQL['set'].' FROM '.$SQL['table']. " WHERE ".$SQL['metadataPrefix']." LIKE '%$metadPrefix%'";
} else { } else {
$query = 'select '.$SQL['identifier'].','.$SQL['datestamp'].' FROM '.$SQL['table']. " WHERE ".$SQL['metadataPrefix']." LIKE '%$metadPrefix%'"; $query = 'select '.$SQL['identifier'].','.$SQL['datestamp'].' FROM '.$SQL['table']. " WHERE ".$SQL['metadataPrefix']." LIKE '%$metadPrefix%'";
} }
if ($id != '') {
$query .= " AND ".$SQL['identifier']." = '$id'";
}
return $query; if ($id != '') {
$query .= " AND ".$SQL['identifier']." = '$id'";
}
return $query;
} }
/** filter for until, appends to the end of SQL query */ /** filter for until, appends to the end of SQL query */
function untilQuery($until) function untilQuery($until) {
{ global $SQL;
global $SQL;
return ' AND '.$SQL['datestamp']." <= '$until'"; return ' AND '.$SQL['datestamp']." <= '$until'";
} }
/** filter for from , appends to the end of SQL query */ /** filter for from , appends to the end of SQL query */
function fromQuery($from) function fromQuery($from) {
{ global $SQL;
global $SQL;
return ' AND '.$SQL['datestamp']." >= '$from'"; return ' AND '.$SQL['datestamp']." >= '$from'";
} }
/** filter for sets, appends to the end of SQL query */ /** filter for sets, appends to the end of SQL query */
function setQuery($set) function setQuery($set) {
{ global $SQL;
global $SQL; // strip off "class:" which is not saved in database
// strip off "class:" which is not saved in database if(strstr($set,"class:")) $set = substr($set,6);
if(strstr($set,"class:")) $set = substr($set,6); return ' AND '.$SQL['set']." LIKE '%$set%'";
return ' AND '.$SQL['set']." LIKE '%$set%'";
} }
/** for accurately to assess how many records satisfy conditions for all DBs */ /** for accurately to assess how many records satisfy conditions for all DBs */
function rowCount($metadataPrefix, $extQuery, $db) { function rowCount($metadataPrefix, $extQuery, $db) {
global $SQL; global $SQL;
$n = 0; $n = 0;
$sql = "SELECT COUNT(*) FROM ".$SQL['table'] . " WHERE ".$SQL['metadataPrefix']." LIKE '%$metadataPrefix%'" . $extQuery; $sql = "SELECT COUNT(*) FROM ".$SQL['table'] . " WHERE ".$SQL['metadataPrefix']." LIKE '%$metadataPrefix%'" . $extQuery;
if ($res = $db->query($sql)) { if ($res = $db->query($sql)) {
$n = $res->fetchColumn(); $n = $res->fetchColumn();
} }
return $n; return $n;
} }
/** A worker function for processing an error when a query was executed /** A worker function for processing an error when a query was executed
* \param $query string, original query * \param $query string, original query
* \param $e PDOException, the PDOException object * \param $e PDOException, the PDOException object
*/ */
function process_pdo_error($query, $e) { function process_pdo_error($query, $e) {
echo $query.' was failed\n'; echo $query.' was failed\n';
echo $e->getMessage(); echo $e->getMessage();
} }
/** When query return no result, throw an Exception of Not found. /** When query return no result, throw an Exception of Not found.
@ -322,11 +313,9 @@ function process_pdo_error($query, $e) {
* \param $query string * \param $query string
* \return $res PDOStatement * \return $res PDOStatement
*/ */
function exec_pdo_query($db, $query) function exec_pdo_query($db, $query) {
{ $res = $db->query($query);
$res = $db->query($query); if ($res===false) {
if ($res===false) { throw new Exception($query.":\nIt found nothing.\n");
throw new Exception($query.":\nIt found nothing.\n"); } else return $res;
} else return $res;
} }
?>

View File

@ -12,7 +12,7 @@
* As XML output document and the database connection are the same, it is possible to design otherwise. * As XML output document and the database connection are the same, it is possible to design otherwise.
* *
* \sa oaidp-config.php * \sa oaidp-config.php
*/ */
// This handles RIF-CS records, but can be also used as a sample // This handles RIF-CS records, but can be also used as a sample
// for other formats. // for other formats.
@ -20,15 +20,15 @@
// Create a metadata object and a registryObjects, and its only child registryObject // Create a metadata object and a registryObjects, and its only child registryObject
function create_metadata($outputObj, $cur_record, $identifier, $setspec, $db) { function create_metadata($outputObj, $cur_record, $identifier, $setspec, $db) {
// debug_message('In '.__FILE__.' function '.__FUNCTION__.' was called.'); // debug_message('In '.__FILE__.' function '.__FUNCTION__.' was called.');
// debug_var_dump('metadata_node',$metadata_node); // debug_var_dump('metadata_node',$metadata_node);
$metadata_node = $outputObj->create_metadata($cur_record); $metadata_node = $outputObj->create_metadata($cur_record);
$obj_node = new ANDS_TPA($outputObj, $metadata_node, $db); $obj_node = new ANDS_TPA($outputObj, $metadata_node, $db);
try { try {
$obj_node->create_obj_node($setspec, $identifier); $obj_node->create_obj_node($setspec, $identifier);
} catch (Exception $e) { } catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), " when adding $identifier\n"; echo 'Caught exception: ', $e->getMessage(), " when adding $identifier\n";
} }
} }

View File

@ -60,29 +60,29 @@ function oai_error($code, $argument = '', $value = '')
{ {
switch ($code) { switch ($code) {
case 'badArgument' : case 'badArgument' :
$text = "The argument '$argument' (value='$value') included in the request is not valid."; $text = "Attribute '{$argument}' is not allowed to appear in element 'request'";
break; break;
case 'badGranularity' : case 'badGranularity' :
$text = "The value '$value' of the argument '$argument' is not valid."; $text = "The value '{$value}' of the argument '{$argument}' is not valid.";
$code = 'badArgument'; $code = 'badArgument';
break; break;
case 'badResumptionToken' : case 'badResumptionToken' :
$text = "The resumptionToken '$value' does not exist or has already expired."; $text = "The resumptionToken '{$value}' does not exist or has already expired.";
break; break;
case 'badRequestMethod' : case 'badRequestMethod' :
$text = "The request method '$argument' is unknown."; $text = "The request method '{$argument}' is unknown.";
$code = 'badVerb'; $code = 'badVerb';
break; break;
case 'badVerb' : case 'badVerb' :
$text = "The verb '$argument' provided in the request is illegal."; $text = "The verb '{$argument}' provided in the request is illegal.";
break; break;
case 'cannotDisseminateFormat' : case 'cannotDisseminateFormat' :
$text = "The metadata format '$value' given by $argument is not supported by this repository."; $text = "The metadata format '{$value}' given by {$argument} is not supported by this repository.";
break; break;
case 'exclusiveArgument' : case 'exclusiveArgument' :
@ -91,7 +91,7 @@ function oai_error($code, $argument = '', $value = '')
break; break;
case 'idDoesNotExist' : case 'idDoesNotExist' :
$text = "The value '$value' of the identifier does not exist in this repository."; $text = "The value '{$value}' of the identifier does not exist in this repository.";
if (!is_valid_uri($value)) { if (!is_valid_uri($value)) {
$code = 'badArgument'; $code = 'badArgument';
$text .= ' Invalidated URI has been detected.'; $text .= ' Invalidated URI has been detected.';
@ -99,7 +99,7 @@ function oai_error($code, $argument = '', $value = '')
break; break;
case 'missingArgument' : case 'missingArgument' :
$text = "The required argument '$argument' is missing in the request."; $text = "The required argument '{$argument}' is missing in the request.";
$code = 'badArgument'; $code = 'badArgument';
break; break;
@ -136,7 +136,7 @@ function oai_error($code, $argument = '', $value = '')
break; break;
default: default:
$text = "Unknown error: code: '$code', argument: '$argument', value: '$value'"; $text = "Unknown error: code: '{$code}', argument: '{$argument}', value: '{$value}'";
$code = 'badArgument'; $code = 'badArgument';
} }
return $code."|".$text; return $code."|".$text;