diff --git a/CollectionClass.inc b/CollectionClass.inc index 0e518b6d..fe5528eb 100644 --- a/CollectionClass.inc +++ b/CollectionClass.inc @@ -2,10 +2,10 @@ /** * @file - * + * * Collection Class Class */ - + /** * This CLASS caches the streams so once you call a getstream once it will always return * the same stream as long as you are using the instance of this class. Cached to @@ -34,12 +34,12 @@ class CollectionClass { } public static function getCollectionQuery($pid) { - if ($query = self::getCollectionQueryFromStream($pid)) { - return $query; - } - else { - return self::getDefaultCollectionQuery($pid); + $query = self::getCollectionQueryFromStream($pid); + if (!$query) { + $query = self::getDefaultCollectionQuery($pid); } + drupal_alter("islandora_collection_query", $query, $pid); + return $query; } protected static function getCollectionQueryFromStream($pid) { @@ -54,13 +54,11 @@ class CollectionClass { } protected static function getDefaultCollectionQuery($pid) { - return 'select $object $title $content from <#ri> + return 'select $object $title from <#ri> where ($object $title - and $object $content and ($object or $object ) and $object ) - minus $content order by $title'; } @@ -104,7 +102,7 @@ class CollectionClass { function getRelatedItems($pid, $query_string = NULL, $limit = NULL, $offset = NULL) { module_load_include('inc', 'fedora_repository', 'api/fedora_utils'); module_load_include('inc', 'fedora_repository', 'ObjectHelper'); - if (!fedora_repository_access(OBJECTHELPER :: $OBJECT_HELPER_VIEW_FEDORA, $pid)) { + if (!fedora_repository_check_perm(OBJECTHELPER :: $OBJECT_HELPER_VIEW_FEDORA, $pid)) { drupal_set_message(t("You do not have access to Fedora objects within the attempted namespace or access to Fedora denied."), 'error'); return ' '; } @@ -323,7 +321,7 @@ class CollectionClass { * @return type */ function getAndDoRules($file, $mimetype, $pid, $dsid) { - if (!user_access('ingest new fedora objects')) { + if (!fedora_repository_check_perm('ingest new fedora objects', $pid)) { drupal_set_message(t('You do not have permission to ingest objects.')); return FALSE; } @@ -588,7 +586,7 @@ class CollectionClass { function getIngestInterface() { module_load_include('inc', 'fedora_repository', 'CollectionPolicy'); $collectionPolicyExists = $this->collectionObject->getMimeType($this->pid, CollectionPolicy::getDefaultDSID()); - if (user_access(ObjectHelper :: $INGEST_FEDORA_OBJECTS) && $collectionPolicyExists) { + if (fedora_repository_check_perm(ObjectHelper :: $INGEST_FEDORA_OBJECTS, $this->pid) && $collectionPolicyExists) { if (!empty($collectionPolicyExists)) { $allow = TRUE; if (module_exists('fedora_fesl')) { @@ -606,66 +604,6 @@ class CollectionClass { return $ingestObject; } - /** - * Unfortunate function, I know... - * - * Does just what it says: Hacks the default Drupal pager such that it might - * be rendered, likely with: theme('pager', array(), $per_page, $pager_name) - * (I reccomend seeing the real documentation for more detail, but the first - * array can be a list of the tags to use for first, previous, next and last - * (text in the pager), I don't believe per_page is actually used in the theme - * function, and $pager_name is an integer used to identify the pager (such - * that there can be more than one--that is, tracking different lists of - * content on a single page. You can render the exact same pager multiple - * times, say if you want one at the top and bottom of a list, using the same - * ID/pager_name. - * - * @global $pager_total array - * Numerically indexed array, where keys are the $pager_names and values - * are the number of pages in the given set, based on: ceil($total_items/$per_page); - * @global $pager_page_array array - * Numerically indexed array, where keys are the $pager_names and values - * are the page selected in the relevant set. - * @param $pager_name int - * An integer to identify the pager to affect. Do note that paging in using - * this function will add the 'page' HTTP GET parameter to the URL, with - * the value containing a comma-separated list with max($pager_name + 1) - * values--that is, if you create a single pager named '10', the 'next' - * link will look something like: 0,0,0,0,0,0,0,0,0,0,1 - * @param $per_page int - * An integer representing the number of items per page. - * @param $total_items int - * An integer representing the total number of items in the set. - * @return int - * An integer representing what the current page should be. - */ - protected static function hackPager($pager_name, $per_page = NULL, $total_items = NULL) { - global $pager_total, $pager_page_array; - - if ($per_page !== NULL && $total_items !== NULL) { - $pager_total[$pager_name] = ceil($total_items / $per_page); - } - - //XXX: Don't know that this is neccessary, to try to load all the time, or - // whether Drupal will load it automatically somewhere... Docs seems a - // a little sparse. - $page_info = explode(',', isset($_GET['page']) ? $_GET['page'] : ''); - $page = $page_info[$pager_name]; - if ($page < 0) { - $page = 0; - } - - if (!isset($pager_page_array)) { - $pager_page_array = pager_load_array($page, $pager_name, $page_info); - } - else { - $pager_page_array = pager_load_array($page, $pager_name, $pager_page_array); - } - - $page = $pager_page_array[$pager_name]; - return $page; - } - /** * Assemble results in a somewhat more logical manner... * @@ -684,17 +622,18 @@ class CollectionClass { * An array to be passed to drupal_render, containing a pager, an unordered * list of items, and another pager. */ - public static function assembleCollectionView($sparql_results) { - $per_page = 20; //XXX: Make this configurable. - $pager_name = 0; - $total = count($sparql_results); - $pager_page = self::hackPager($pager_name, $per_page, $total); - $max_title_length = 60; - - $results = array(); - foreach (array_slice($sparql_results, $per_page * $pager_page, $per_page) as $result) { + public static function assembleCollectionView($sparql_results) { + module_load_include('inc', 'fedora_repository', 'PagerSetup'); + $per_page = 20; //XXX: Make this configurable. + $pager_name = 0; + $total = count($sparql_results); + $pager_page = fedora_repository_setup_pager($pager_name, $per_page, $total); + $max_title_length = 60; + + $results = array(); + foreach (array_slice($sparql_results, $per_page * $pager_page, $per_page) as $result) { $title = $result['title']; - $truncated_title = truncate_utf8($title, $max_title_length, TRUE, TRUE, 5); + $truncated_title = truncate_utf8($title, $max_title_length, TRUE, TRUE, 5); $obj_path = "fedora/repository/{$result['object']}"; //Get a thumbnail @@ -703,28 +642,28 @@ class CollectionClass { "$obj_path/TN"); $thumbnail = _fedora_repository_render_image($tn_path); - - $results[] = array( - 'data' => l($thumbnail, $obj_path, array( - 'html' => TRUE, - 'attributes' => array( - 'class' => 'results-image', - ), - )) . l($truncated_title, $obj_path, array('attributes' => array('class' => 'results-text'))), - ); - } - if (!$results) { - drupal_set_message(t("No objects in this collection (or bad query).")); - } - else { - $first = $per_page * $pager_page; - $last = (($total - $first) > $per_page)? - ($first + $per_page): - $total; - $results_range_text = t('Results @first to @last of @total', array( - '@first' => $first + 1, - '@last' => $last, - '@total' => $total, + + $results[] = array( + 'data' => l($thumbnail, $obj_path, array( + 'html' => TRUE, + 'attributes' => array( + 'class' => 'results-image', + ), + )) . l($truncated_title, $obj_path, array('attributes' => array('class' => 'results-text'))), + ); + } + if (!$results) { + drupal_set_message(t("No objects in this collection (or bad query).")); + } + else { + $first = $per_page * $pager_page; + $last = (($total - $first) > $per_page)? + ($first + $per_page): + $total; + $results_range_text = t('Results @first to @last of @total', array( + '@first' => $first + 1, + '@last' => $last, + '@total' => $total, )); return array( @@ -734,15 +673,15 @@ class CollectionClass { ), array( '#type' => 'markup', - '#value' => theme('item_list', $results, $result_range_text, 'ul', array( - 'class' => 'islandora-collection-results-list', + '#value' => theme('item_list', $results, $result_range_text, 'ul', array( + 'class' => 'islandora-collection-results-list', )) ), array( '#type' => 'markup', '#value' => theme('pager', array(), $per_page, $pager_name) ), - ); + ); } } diff --git a/ContentModel.inc b/ContentModel.inc index be362c70..52ebdf09 100644 --- a/ContentModel.inc +++ b/ContentModel.inc @@ -1,11 +1,11 @@ getAttribute('class'); - $methodName = ($method->getAttribute('method')); - if (!class_exists($className)) { - self::$errors[] = 'Execute Form Handler: class \'' . $className . '\' does not exist.'; - } - else { - $class = new $className($pid); - if (!method_exists($class, $methodName)) { - self::$errors[] = 'Execute Form Handler: method \'' . $className . '->' . $methodName . '\' does not exist.'; + + $file_extension = pathinfo($method->getAttribute('file'), PATHINFO_EXTENSION); + $file_path_without_extension = $method->getAttribute('file'); + /* Only in PHP. This is meant to avoid file path + * concatenation issues.*/ + $file_path_without_extension = substr($file_path_without_extension, 0, strlen($file_path_without_extension) - (strlen($file_extension) + 1)); + /* Only try to execute if the module is present, this is + * necessarybecause we go outside of the expected + * 'Drupal Way' and have dynamic dependencies.*/ + if (module_exists(!empty($module) ? $module : 'fedora_repository')) { + module_load_include($file_extension, !empty($module) ? $module : 'fedora_repository', $file_path_without_extension); + $className = $method->getAttribute('class'); + $methodName = ($method->getAttribute('method')); + if (!class_exists($className)) { + self::$errors[] = 'Execute Form Handler: class \'' . $className . '\' does not exist.'; } else { - $output = $class->$methodName($page_number); + $class = new $className($pid); + if (!method_exists($class, $methodName)) { + self::$errors[] = 'Execute Form Handler: method \'' . $className . '->' . $methodName . '\' does not exist.'; + } + else { + $output = $class->$methodName($page_number); + } } } } @@ -1527,8 +1538,8 @@ class ContentModel extends XMLDatastream { } /** - * Adds an allowed mimetype to the model. - * + * Adds an allowed mimetype to the model. + * * @param String $type * @return boolean $success */ @@ -1581,7 +1592,7 @@ class ContentModel extends XMLDatastream { /** * getDisplayMethods ?? * @param type $ds - * @return type + * @return type */ public function getDisplayMethods($ds) { $ret = FALSE; @@ -1603,7 +1614,7 @@ class ContentModel extends XMLDatastream { * addDs ?? * @param type $dsid * @param type $display_in_fieldset - * @return boolean + * @return boolean */ public function addDs($dsid, $display_in_fieldset = FALSE) { $ret = FALSE; @@ -1632,7 +1643,7 @@ class ContentModel extends XMLDatastream { /** * removeDs ?? * @param type $dsid - * @return boolean + * @return boolean */ public function removeDs($dsid) { $ret = FALSE; @@ -1648,7 +1659,7 @@ class ContentModel extends XMLDatastream { /** * displayInFieldset ?? * @param type $dsid - * @return type + * @return type */ public function displayInFieldset($dsid) { $ret = FALSE; @@ -1662,7 +1673,7 @@ class ContentModel extends XMLDatastream { * setDisplayInFieldset ?? * @param type $dsid * @param type $value - * @return boolean + * @return boolean */ public function setDisplayInFieldset($dsid, $value = TRUE) { $ret = FALSE; @@ -1686,7 +1697,7 @@ class ContentModel extends XMLDatastream { * @param type $file * @param type $class * @param type $method - * @return boolean + * @return boolean */ public function setDefaultDispMeth($dsid, $module, $file, $class, $method) { $ret = FALSE; @@ -1725,7 +1736,7 @@ class ContentModel extends XMLDatastream { * @param type $file * @param type $class * @param type $method - * @return boolean + * @return boolean */ public function removeDispMeth($dsid, $module, $file, $class, $method) { $ret = FALSE; @@ -1757,7 +1768,7 @@ class ContentModel extends XMLDatastream { * @param type $class * @param type $method * @param type $default - * @return boolean + * @return boolean */ public function addDispMeth($dsid, $module, $file, $class, $method, $default = FALSE) { $ret = FALSE; @@ -1779,7 +1790,7 @@ class ContentModel extends XMLDatastream { /** * getAddDsMethod ?? * @param type $ds - * @return type + * @return type */ public function getAddDsMethod($ds) { $ret = FALSE; @@ -1801,7 +1812,7 @@ class ContentModel extends XMLDatastream { /** * getIngestRule ?? * @param type $rule_id - * @return type + * @return type */ public function getIngestRule($rule_id) { $ret = FALSE; @@ -1817,7 +1828,7 @@ class ContentModel extends XMLDatastream { * removeAppliesTo ?? * @param type $rule_id * @param type $type - * @return boolean + * @return boolean */ public function removeAppliesTo($rule_id, $type) { $ret = FALSE; @@ -1842,7 +1853,7 @@ class ContentModel extends XMLDatastream { * addAppliesTo ?? * @param type $rule_id * @param type $type - * @return boolean + * @return boolean */ public function addAppliesTo($rule_id, $type) { $ret = FALSE; @@ -1871,7 +1882,7 @@ class ContentModel extends XMLDatastream { * @param type $method * @param type $dsid * @param type $modified_files_ext - * @return boolean + * @return boolean */ public function addIngestMethod($rule_id, $module, $file, $class, $method, $dsid, $modified_files_ext) { $ret = FALSE; @@ -1898,7 +1909,7 @@ class ContentModel extends XMLDatastream { * @param type $file * @param type $class * @param type $method - * @return boolean + * @return boolean */ public function removeIngestMethod($rule_id, $module, $file, $class, $method) { $ret = FALSE; @@ -1929,7 +1940,7 @@ class ContentModel extends XMLDatastream { * @param type $method * @param type $name * @param type $value - * @return boolean + * @return boolean */ public function addIngestMethodParam($rule_id, $module, $file, $class, $method, $name, $value) { $ret = FALSE; @@ -1981,7 +1992,7 @@ class ContentModel extends XMLDatastream { * @param type $class * @param type $method * @param type $name - * @return boolean + * @return boolean */ public function removeIngestMethodParam($rule_id, $module, $file, $class, $method, $name) { $ret = FALSE; @@ -2024,7 +2035,7 @@ class ContentModel extends XMLDatastream { /** * removeIngestRule ?? * @param type $rule_id - * @return type + * @return type */ public function removeIngestRule($rule_id) { $ret = FALSE; @@ -2043,7 +2054,7 @@ class ContentModel extends XMLDatastream { * @param type $method * @param type $dsid * @param type $modified_files_ext - * @return type + * @return type */ public function addIngestRule($applies_to, $module, $file, $class, $method, $dsid, $modified_files_ext) { $ret = FALSE; @@ -2061,7 +2072,7 @@ class ContentModel extends XMLDatastream { /** * getIngestRules ?? - * @return type + * @return type */ public function getIngestRules() { $ret = FALSE; @@ -2105,7 +2116,7 @@ class ContentModel extends XMLDatastream { /** * getIngestFormAttributes ?? - * @return type + * @return type */ public function getIngestFormAttributes() { $ret = FALSE; @@ -2125,7 +2136,7 @@ class ContentModel extends XMLDatastream { * @param type $page * @param type $hide_file_chooser * @param type $redirect - * @return boolean + * @return boolean */ public function editIngestFormAttributes($dsid, $page, $hide_file_chooser = FALSE, $redirect = TRUE) { $ret = FALSE; @@ -2152,7 +2163,7 @@ class ContentModel extends XMLDatastream { /** * getIngestFormBuilderMethod - * @return type + * @return type */ public function getIngestFormBuilderMethod() { $ret = FALSE; @@ -2174,7 +2185,7 @@ class ContentModel extends XMLDatastream { * @param type $class * @param type $method * @param type $handler - * @return boolean + * @return boolean */ public function editIngestFormBuilderMethod($module, $file, $class, $method, $handler) { $ret = FALSE; @@ -2192,7 +2203,7 @@ class ContentModel extends XMLDatastream { /** * Find the form element with name $name. - * + * * @param string $name * The name of the form element to find. * @return DOMElement @@ -2263,7 +2274,7 @@ class ContentModel extends XMLDatastream { * * @param string $name * Name of the form to remove. - * + * * @return boolean * TRUE on success, FALSE otherwise. */ diff --git a/MimeClass.inc b/MimeClass.inc index b2950f6e..d01cd9f8 100644 --- a/MimeClass.inc +++ b/MimeClass.inc @@ -6,26 +6,27 @@ * @file * This class inspired by Chris Jean's work, here: * http://chrisjean.com/2009/02/14/generating-mime-type-in-php-is-not-magic/ - * - * It does some MIME trickery, inspired by the need to to deal with Openoffice - * and MS Office 2007 file formats -- which are often mis-interpreted by + * + * It does some MIME trickery, inspired by the need to to deal with Openoffice + * and MS Office 2007 file formats -- which are often mis-interpreted by * mime-magic, fileinfo, and the *nix `file` command. * - * In Drupal 6, we also make use of file_get_mimetype. See: + * In Drupal 6, we also make use of file_get_mimetype. See: * http://api.drupal.org/api/function/file_get_mimetype/6 * ... however this only provides a uni-directional lookup (ext->mime). * While I don't have a specific use case for a mime->extension lookup, I think * it's good to have in here. - * + * * Drupal 7 will have better mime handlers. See: * http://api.drupal.org/api/function/file_default_mimetype_mapping/7 * */ + class MimeClass { private $private_mime_types = array( - /** - * This is a shortlist of mimetypes which should catch most + /* + * This is a shortlist of mimetypes which should catch most * mimetype<-->extension lookups in the context of Islandora collections. * * It has been cut from a much longer list. @@ -33,26 +34,26 @@ class MimeClass { * Two types of mimetypes should be put in this list: * 1) Special emerging formats which may not yet be expressed in the system * mime.types file. - * 2) Heavily used mimetypes of particular importance to the Islandora - * project, as lookups against this list will be quicker and less + * 2) Heavily used mimetypes of particular importance to the Islandora + * project, as lookups against this list will be quicker and less * resource intensive than other methods. * - * Lookups are first checked against this short list. If no results are found, - * then the lookup function may move on to check other sources, namely the - * system's mime.types file. + * Lookups are first checked against this short list. + * If no results are found, then the lookup function may move + * on to check other sources, namely the system's mime.types file. * * In most cases though, this short list should suffice. - * + * * If modifying this list, please note that for promiscuous mimetypes * (those which map to multiple extensions, such as text/plain) - * The function get_extension will always return the *LAST* extension in this list, - * so you should put your preferred extension *LAST*. + * The function get_extension will always return the *LAST* extension + * in this list, so you should put your preferred extension *LAST*. * - * e.g... + * e.g... * "jpeg" => "image/jpeg", * "jpe" => "image/jpeg", * "jpg" => "image/jpeg", - * + * * $this->get_extension('image/jpeg') will always return 'jpg'. * */ @@ -89,7 +90,7 @@ class MimeClass { 'ksp' => 'application/x-kspread', 'kwt' => 'application/x-kword', 'kwd' => 'application/x-kword', - // ms office 97: + // MS office 97: 'doc' => 'application/msword', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', @@ -113,9 +114,9 @@ class MimeClass { 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', 'sldm' => 'application/vnd.ms-powerpoint.slide.macroEnabled.12', - // wordperfect (who cares?): + // Wordperfect (who cares?): 'wpd' => 'application/wordperfect', - // common and generic containers: + // Common and generic containers: 'pdf' => 'application/pdf', 'eps' => 'application/postscript', 'ps' => 'application/postscript', @@ -133,6 +134,7 @@ class MimeClass { 'xht' => 'application/xhtml+xml', 'xhtml' => 'application/xhtml+xml', 'xsl' => 'text/xml', + 'xslt' => 'text/xml', 'xml' => 'text/xml', 'csv' => 'text/csv', 'tsv' => 'text/tab-separated-values', @@ -174,6 +176,8 @@ class MimeClass { "movie" => "video/x-sgi-movie", "flv" => "video/x-flv", "swf" => "application/x-shockwave-flash", + 'mkv' => "video/x-matroska", + 'wmv' => 'video/x-ms-wmv', // audio: "mp3" => "audio/mpeg", "mp4a" => "audio/mp4", @@ -182,15 +186,18 @@ class MimeClass { "ogg" => "audio/ogg", "flac" => "audio/x-flac", "wav" => "audio/vnd.wave", - // compressed formats: (note: http://svn.cleancode.org/svn/email/trunk/mime.types) + /* Compressed formats: + (note: http://svn.cleancode.org/svn/email/trunk/mime.types).*/ "tgz" => "application/x-gzip", "gz" => "application/x-gzip", "tar" => "application/x-tar", "gtar" => "application/x-gtar", "zip" => "application/x-zip", - // others: + // others: 'bin' => 'application/octet-stream', + 'json' => 'application/json', ); + private $private_file_extensions; private $system_types; private $system_exts; @@ -201,10 +208,10 @@ class MimeClass { */ public function __construct() { - // populate the reverse shortlist: + // Populate the reverse shortlist: $this->private_file_extensions = array_flip($this->private_mime_types); - // pick up a local mime.types file if it is available + // Pick up a local mime.types file if it is available. if (is_readable('mime.types')) { $this->etc_mime_types = 'mime.types'; } @@ -216,7 +223,7 @@ class MimeClass { * for backwards-compatibility with our old mimetype class. * * @param type $filename - * @return type + * @return type */ public function getType($filename) { return $this->get_mimetype($filename); @@ -224,40 +231,47 @@ class MimeClass { /** * function: get_mimetype - * description: returns a mimetype associated with the file extension of $filename + * description: returns a mimetype associated with the + * file extension of $filename * * @param type $filename * @param type $debug - * @return type + * @return string + * mimetype associated with the file extension of $filename */ public function get_mimetype($filename, $debug = FALSE) { $ext = strtolower(substr($filename, strrpos($filename, '.') + 1)); if (!empty($this->private_mime_types[$ext])) { - if (TRUE === $debug) + if (TRUE === $debug) { return array('mime_type' => $this->private_mime_types[$ext], 'method' => 'from_array'); + } return $this->private_mime_types[$ext]; } if (function_exists('file_get_mimetype')) { $drupal_mimetype = file_get_mimetype($filename); if ('application/octet-stream' != $drupal_mimetype) { - if (TRUE == $debug) + if (TRUE == $debug) { return array('mime_type' => $drupal_mimetype, 'method' => 'file_get_mimetype'); + } return $drupal_mimetype; } } - if (!isset($this->system_types)) + if (!isset($this->system_types)) { $this->system_types = $this->system_extension_mime_types(); + } if (isset($this->system_types[$ext])) { - if (TRUE == $debug) + if (TRUE == $debug) { return array('mime_type' => $this->system_types[$ext], 'method' => 'mime.types'); + } return $this->system_types[$ext]; } - if (TRUE === $debug) + if (TRUE === $debug) { return array('mime_type' => 'application/octet-stream', 'method' => 'last_resort'); + } return 'application/octet-stream'; } @@ -267,34 +281,38 @@ class MimeClass { * * @param type $mime_type * @param type $debug - * @return type + * @return type */ public function get_extension($mime_type, $debug = FALSE) { if (!empty($this->private_file_extensions[$mime_type])) { - if (TRUE == $debug) + if (TRUE == $debug) { return array('extension' => $this->private_file_extensions[$mime_type], 'method' => 'from_array'); + } return $this->private_file_extensions[$mime_type]; } - if (!isset($this->system_exts)) + if (!isset($this->system_exts)) { $this->system_exts = $this->system_mime_type_extensions(); + } if (isset($this->system_exts[$mime_type])) { - if (TRUE == $debug) + if (TRUE == $debug) { return array('extension' => $this->system_exts[$mime_type], 'method' => 'mime.types'); + } return $this->system_exts[$mime_type]; } - if (TRUE == $debug) + if (TRUE == $debug) { return array('extension' => 'bin', 'method' => 'last_resort'); + } return 'bin'; } /** * function: system_mime_type_extensions * description: populates an internal array of mimetype/extension associations - * from the system mime.types file, or a local mime.types if one is found (see - * __constuctor). + * from the system mime.types file, or a local mime.types if one is found (see + * __constuctor). * return: array of mimetype => extension */ private function system_mime_type_extensions() { @@ -303,15 +321,18 @@ class MimeClass { $file = fopen($this->etc_mime_types, 'r'); while (($line = fgets($file)) !== FALSE) { $line = trim(preg_replace('/#.*/', '', $line)); - if (!$line) + if (!$line) { continue; + } $parts = preg_split('/\s+/', $line); - if (count($parts) == 1) + if (count($parts) == 1) { continue; + } // A single part means a mimetype without extensions, which we ignore. $type = array_shift($parts); - if (!isset($out[$type])) + if (!isset($out[$type])) { $out[$type] = array_shift($parts); + } // We take the first ext from the line if many are present. } fclose($file); @@ -322,8 +343,8 @@ class MimeClass { /** * function: system_mime_type_extensions * description: populates an internal array of mimetype/extension associations - * from the system mime.types file, or a local mime.types if one is found (see - * __constuctor). + * from the system mime.types file, or a local mime.types if one is found (see + * __constuctor). * return: array of extension => mimetype */ private function system_extension_mime_types() { @@ -332,15 +353,18 @@ class MimeClass { $file = fopen($this->etc_mime_types, 'r'); while (($line = fgets($file)) !== FALSE) { $line = trim(preg_replace('/#.*/', '', $line)); - if (!$line) + if (!$line) { continue; + } $parts = preg_split('/\s+/', $line); - if (count($parts) == 1) + if (count($parts) == 1) { continue; + } // A single part means a mimetype without extensions, which we ignore. $type = array_shift($parts); - foreach ($parts as $part) + foreach ($parts as $part) { $out[$part] = $type; + } } fclose($file); } @@ -348,4 +372,3 @@ class MimeClass { } } - diff --git a/ObjectDetails.inc b/ObjectDetails.inc index 38409615..30121080 100644 --- a/ObjectDetails.inc +++ b/ObjectDetails.inc @@ -72,6 +72,11 @@ function fedora_repository_object_details_XSLT($item) { } $xmlstr = $item->get_datastream_dissemination($dsid); + $default_to_dc = FALSE; + if (empty($xmlstr) && variable_get('islandora_object_details_xslt_default_dc', FALSE) && $dsid != 'DC' && $dsid != 'QDC') { + $xmlstr = $item->get_datastream_dissemination('DC'); + $default_to_dc = TRUE; + } if (empty($xmlstr)) { return t('Error - could not find datastream @dsid on object @pid
Please contact the site administrator.', array('@dsid' => $dsid, '@pid' => $item->pid)); @@ -88,7 +93,13 @@ function fedora_repository_object_details_XSLT($item) { $proc->setParameter('', 'path', $path); $input = NULL; - $xsl_file = variable_get('islandora_object_details_xslt_sheet', 'sites/all/modules/islandora/object_details_xslts/convertQDC.xsl'); + if (!$default_to_dc) { + $xsl_file = variable_get('islandora_object_details_xslt_sheet', 'sites/all/modules/islandora/object_details_xslts/convertQDC.xsl'); + } + else { + $xsl_file = 'sites/all/modules/islandora/object_details_xslts/convertQDC.xsl'; + } + // set an error message in case xslt parsing fails $output = t("Failed to parse xslt file at @xsltFile", array('@xsltFile' => $xsl_file)); if (is_readable($xsl_file)) { @@ -126,7 +137,11 @@ function fedora_repository_object_details_table($item) { $dsid = array_key_exists('QDC', $item->get_datastreams_list_as_array()) ? 'QDC' : 'DC'; } $xmlstr = $item->get_datastream_dissemination($dsid); - + + if (empty($xmlstr) && variable_get('islandora_object_details_table_default_dc', FALSE) && $dsid != 'DC' && $dsid != 'QDC') { + $dsid = 'DC'; + $xmlstr = $item->get_datastream_dissemination($dsid); + } if (empty($xmlstr)) { return t('Error - could not find datastream @dsid on object @pid
Please contact the site administrator.', array('@dsid' => $dsid, '@pid' => $item->pid)); @@ -136,7 +151,7 @@ function fedora_repository_object_details_table($item) { $headers = array( array( - 'data' => t('Metadata'), + 'data' => t('Metadata (@dsid)', array('@dsid' => $dsid)), 'colspan' => 2, ), ); @@ -191,6 +206,11 @@ function fedora_repository_object_details_XSLT_config() { '#default_value' => variable_get('islandora_object_details_xslt_datastream', 'DC'), '#required' => TRUE, ); + $form['config']['default_dc'] = array( + '#type' => 'checkbox', + '#title' => t("If the datastream to transform is unavailable, attempt to transform using the DC datastream"), + '#default_value' => variable_get('islandora_object_details_xslt_default_dc', FALSE), + ); $form['submit'] = array( '#type' => 'submit', '#value' => t("Submit"), @@ -210,6 +230,7 @@ function fedora_repository_object_details_XSLT_config_submit($form, &$form_state variable_set('islandora_object_details_display_table', 'xslt'); variable_set('islandora_object_details_xslt_sheet', $form_state['values']['xslt']); variable_set('islandora_object_details_xslt_datastream', $form_state['values']['dsid']); + variable_set('islandora_object_details_xslt_default_dc', $form_state['values']['default_dc']); drupal_set_message('Object Details view has been set to XSLT and your configuration has been saved'); } @@ -253,6 +274,11 @@ function fedora_repository_object_details_table_config() { '#default_value' => variable_get('islandora_object_details_table_datastream', 'DC'), '#required' => TRUE, ); + $form['config']['default_dc'] = array( + '#type' => 'checkbox', + '#title' => t("If the datastream to transform is unavailable, attempt to transform using the DC datastream"), + '#default_value' => variable_get('islandora_object_details_table_default_dc', FALSE), + ); $form['submit'] = array( '#type' => 'submit', '#value' => t("Submit"), @@ -272,5 +298,6 @@ function fedora_repository_object_details_table_config() { function fedora_repository_object_details_table_config_submit($form, &$form_state) { variable_set('islandora_object_details_display_table', 'table'); variable_set('islandora_object_details_table_datastream', $form_state['values']['dsid']); + variable_set('islandora_object_details_table_default_dc', $form_state['values']['default_dc']); drupal_set_message('Object Details view has been set to Table and your configuration has been saved'); } diff --git a/ObjectHelper.inc b/ObjectHelper.inc index d34e64c3..ad196f81 100644 --- a/ObjectHelper.inc +++ b/ObjectHelper.inc @@ -93,7 +93,7 @@ class ObjectHelper { return ' '; } - if (!fedora_repository_access(OBJECTHELPER :: $OBJECT_HELPER_VIEW_FEDORA, $pid, $user)) { + if (!fedora_repository_check_perm(OBJECTHELPER :: $OBJECT_HELPER_VIEW_FEDORA, $pid, $user)) { drupal_set_message(t("You do not have access Fedora objects within the attempted namespace."), 'error'); drupal_access_denied(); return ' '; @@ -137,9 +137,6 @@ class ObjectHelper { $fedoraPass = $user->pass; } - $dataStreamInfo = $item->get_datastream_info($dsID); - $contentSize = $dataStreamInfo->datastream->size; - if (function_exists("curl_init")) { $url = variable_get('fedora_base_url', 'http://localhost:8080/fedora') . '/objects/' . $pid . '/datastreams/' . $dsID . '/content'; $query_options = array(); @@ -181,7 +178,10 @@ class ObjectHelper { if ($curl_stat !== FALSE) { $info = curl_getinfo($ch); - + // Fixes an IE issue (ISLANDORA-311) + // http://support.microsoft.com/kb/316431 + drupal_set_header("Cache-Control: private", TRUE); + //Set what headers we can... if ($mimeType = $info['content_type']) { drupal_set_header("Content-Type: $mimeType"); @@ -298,7 +298,7 @@ class ObjectHelper { drupal_set_message(t('You must specify an object pid and datastream ID.'), 'error'); return ''; } - if (!fedora_repository_access(ObjectHelper :: $OBJECT_HELPER_VIEW_FEDORA, $pid, $user)) { + if (!fedora_repository_check_perm(ObjectHelper :: $OBJECT_HELPER_VIEW_FEDORA, $pid, $user)) { drupal_set_message(t('You do not have the appropriate permissions'), 'error'); return; } @@ -333,7 +333,7 @@ class ObjectHelper { drupal_set_message(t('You must specify an object pid and datastream ID.'), 'error'); return ''; } - if (!fedora_repository_access(ObjectHelper :: $OBJECT_HELPER_VIEW_FEDORA, $pid, $user)) { + if (!fedora_repository_check_perm(ObjectHelper :: $OBJECT_HELPER_VIEW_FEDORA, $pid, $user)) { drupal_set_message(t('You do not have the appropriate permissions'), 'error'); return; } @@ -368,7 +368,7 @@ class ObjectHelper { $item = new Fedora_Item($pid); $purge_image = ' '; - if (user_access(ObjectHelper :: $PURGE_FEDORA_OBJECTSANDSTREAMS)) { + if (fedora_repository_check_perm(ObjectHelper :: $PURGE_FEDORA_OBJECTSANDSTREAMS, $pid)) { $allow = TRUE; if (module_exists('fedora_fesl')) { $allow = fedora_fesl_check_roles($pid, 'write'); @@ -388,7 +388,7 @@ class ObjectHelper { // Add an icon to replace a datastream // @TODO Note: using l(theme_image(..), ...); for these image links (and other links) may remove the need to have clean urls enabled. $replace_image = ' '; - if (user_access(ObjectHelper :: $ADD_FEDORA_STREAMS)) { + if (fedora_repository_check_perm(ObjectHelper :: $ADD_FEDORA_STREAMS, $pid)) { $allow = TRUE; if (module_exists('fedora_fesl')) { $allow = fedora_fesl_check_roles($pid, 'write'); @@ -533,7 +533,7 @@ class ObjectHelper { $dsid = array_key_exists('QDC', $ds_list) ? 'QDC' : 'DC'; $path = drupal_get_path('module', 'fedora_repository'); - if (user_access(ObjectHelper :: $EDIT_FEDORA_METADATA)) { + if (fedora_repository_check_perm(ObjectHelper :: $EDIT_FEDORA_METADATA, $pid)) { $allow = TRUE; if (module_exists('fedora_fesl')) { $allow = fedora_fesl_check_roles($pid, 'write'); @@ -573,7 +573,7 @@ class ObjectHelper { $dataStreamBody = ''; $fedoraItem = new Fedora_Item($object_pid); - if (user_access(ObjectHelper :: $VIEW_DETAILED_CONTENT_LIST)) { + if (fedora_repository_check_perm(ObjectHelper :: $VIEW_DETAILED_CONTENT_LIST, $object_pid)) { $availableDataStreamsText = 'Detailed List of Content'; $mainStreamLabel = NULL; @@ -606,7 +606,7 @@ class ObjectHelper { $dataStreamBody = theme('table', $headers, $DSs); //if they have access let them add a datastream - if (user_access(ObjectHelper::$ADD_FEDORA_STREAMS) && //If allowed throw Drupal + if (fedora_repository_check_perm(ObjectHelper::$ADD_FEDORA_STREAMS, $object_pid) && //If allowed throw Drupal ((module_exists('fedora_fesl') && fedora_fesl_check_roles($object_pid, 'write')) || //And allowed throw FESL !module_exists('fedora_fesl'))) { //Or not using FESL, draw the add datastream form. $dataStreamBody .= drupal_get_form('add_stream_form', $object_pid); @@ -673,36 +673,6 @@ class ObjectHelper { return $cmodels; } - /** - * determines whether we can see the object or not - * checks PID namespace permissions, and user permissions - * @global type $user - * @param type $op - * @param type $pid - * @return type - */ - function fedora_repository_access($op, $pid = NULL, $as_user = NULL) { - $returnValue = FALSE; - - if ($pid == NULL) { - $pid = variable_get('fedora_repository_pid', 'islandora:root'); - } - - $isRestricted = variable_get('fedora_namespace_restriction_enforced', TRUE); - $namespace_access = NULL; - if (!$isRestricted) { - $namespace_access = TRUE; - } - else { - $pid_namespace = substr($pid, 0, strpos($pid, ':') + 1); //Get the namespace (with colon) - $allowed_namespaces = explode(" ", variable_get('fedora_pids_allowed', 'default: demo: changeme: islandora: ilives: islandora-book: books: newspapers: ')); - - $namespace_access = in_array($pid_namespace, $allowed_namespaces); - } - - return ($namespace_access && user_access($op, $as_user)); - } - /** * Get the query to find parent objects. * @@ -795,7 +765,7 @@ class ObjectHelper { * @return boolean */ function get_and_do_datastream_rules($pid, $dsid, $file = '') { - if (!user_access('ingest new fedora objects')) { + if (!fedora_repository_check_perm('ingest new fedora objects', $pid)) { drupal_set_message(t('You do not have permission to add datastreams.')); return FALSE; } @@ -810,6 +780,7 @@ class ObjectHelper { * Get a tree of related pids - for the basket functionality * * FIXME: This doesn't actually get a tree... + * XXX: Is this still required, without basket being in? * * @param type $pid * @return type diff --git a/PagerSetup.inc b/PagerSetup.inc new file mode 100644 index 00000000..c4fb7c32 --- /dev/null +++ b/PagerSetup.inc @@ -0,0 +1,62 @@ + $e->getMessage()), NULL, WATCHDOG_ERROR); - return 'Error getting solr search results class. Check watchdog for more info.'; - } - return $implementation->$solrFunction($query, $startPage, $fq, $dismax); - } - - /** - * build solr search form ?? - * @param type $repeat - * @param type $pathToSearchTerms - * @param type $query - * @return type - */ - function build_solr_search_form($repeat = NULL, $pathToSearchTerms = NULL, $query = NULL) { - $types = $this->get_search_terms_array(NULL, 'solrSearchTerms.xml'); - $queryArray = NULL; - if (isset($query)) { - $queryArray = explode('AND', $query); - } - - $andOrArray = array( - 'AND' => 'and', - //'OR' => 'or' //removed or for now as it would be a pain to parse - ); - $form = array(); - - if (!isset($repeat)) { - $repeat = variable_get('islandora_solr_search_block_repeat', t('3')); - } - $var0 = explode(':', $queryArray[0]); - $var1 = explode(':', $queryArray[1]); - $form['search_type']['type1'] = array( - '#title' => t(''), - '#type' => 'select', - '#options' => $types, - '#default_value' => trim($var0[0]) - ); - $form['fedora_terms1'] = array( - '#size' => '24', - '#type' => 'textfield', - '#title' => t(''), - '#required' => TRUE, - '#default_value' => (count($var0) >= 2 ? trim($var0[1]) : ''), - ); - $form['andor1'] = array( - '#title' => t(''), - '#type' => 'select', - '#default_value' => 'AND', - '#options' => $andOrArray - ); - $form['search_type']['type2'] = array( - '#title' => t(''), - '#type' => 'select', - '#options' => $types, - '#default_value' => (count($var1) >= 2 ? trim($var1[0]) : ''), - ); - $form['fedora_terms2'] = array( - '#size' => '24', - '#type' => 'textfield', - '#title' => t(''), - '#default_value' => (count($var1) >= 2 ? $var1[1] : ''), - ); - if ($repeat > 2 && $repeat < 9) { //don't want less then 2 or more then 9 - for ($i = 3; $i < $repeat + 1; $i++) { - $t = $i - 1; - $field_and_term = explode(':', $queryArray[$t]); - $form["andor$t"] = array( - '#title' => t(''), - '#type' => 'select', - '#default_value' => 'AND', - '#options' => $andOrArray - ); - $form['search_type']["type$i"] = array( - '#title' => t(''), - '#type' => 'select', - '#options' => $types, - '#default_value' => trim($field_and_term[0]) - ); - $form["fedora_terms$i"] = array( - '#size' => '24', - '#type' => 'textfield', - '#title' => t(''), - '#default_value' => (count($field_and_term) >= 2 ? trim($field_and_term[1]) : ''), - ); - } - } - - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('search') - ); - return $form; - } - - /** - * build simple solr form ?? - * @return string - */ - function build_simple_solr_form() { - //$form = array(); - $form["search_query"] = array( - '#size' => '30', - '#type' => 'textfield', - '#title' => t(''), - // '#default_value' => (count($field_and_term) >= 2 ? trim($field_and_term[1]) : ''), - ); - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('search') - ); - return $form; - } - - /** - * theme solr search form ?? - * @param type $form - * @return type - */ - function theme_solr_search_form($form) { - if (!isset($repeat)) { - $repeat = variable_get('islandora_solr_search_block_repeat', t('3')); - } - - $output = drupal_render($form['search_type']['type1']); - $output .= drupal_render($form['fedora_terms1']); - $output .= drupal_render($form['andor1']) . drupal_render($form['search_type']['type2']); - $output .= drupal_render($form['fedora_terms2']); - if ($repeat > 2 && $repeat < 9) { - for ($i = 3; $i < $repeat + 1; $i++) { - $t = $i - 1; - $output .= drupal_render($form["andor$t"]) . drupal_render($form['search_type']["type$i"]); - $output .= drupal_render($form["fedora_terms$i"]); - } - } - $output .= drupal_render($form['submit']); - $output .= drupal_render($form); - return $output; - } - - /** - * quick search ?? - * @param type $type - * @param type $query - * @param type $showForm - * @param type $orderBy - * @param type $userArray - * @return type - */ - function quickSearch($type, $query, $showForm = 1, $orderBy = 0, & $userArray) { - module_load_include('inc', 'fedora_repository', 'ObjectHelper'); - module_load_include('inc', 'fedora_repository', 'api/fedora_utils'); - if (user_access('view fedora collection')) { - $numberOfHistPerPage = '5000'; //hack for IR they do not want next button - $luceneQuery = NULL; - // Demo search string ?operation=gfindObjects&indexName=DemoOnLucene&query=fgs.DS.first.text%3Achristmas&hitPageStart=11&hitPageSize=10 - $keywords = explode(' ', $query); - - foreach ($keywords as $keyword) { - $luceneQuery .= $type . ':' . $keyword . '+AND+'; - } - $luceneQuery = substr($luceneQuery, 0, strlen($luceneQuery) - 5); - - $indexName = variable_get('fedora_index_name', 'DemoOnLucene'); - $keys = htmlentities(urlencode($query)); - $searchUrl = variable_get('fedora_fgsearch_url', 'http://localhost:8080/fedoragsearch/rest'); - $searchString = '?operation=gfindObjects&indexName=' . $indexName . '&restXslt=copyXml&query=' . $luceneQuery; - $searchString .= '&hitPageSize=' . $numberOfHistPerPage . '&hitPageStart=1'; - //$searchString = htmlentities($searchString); - $searchUrl .= $searchString; - - // $objectHelper = new ObjectHelper(); - - $resultData = do_curl($searchUrl, 1); - if (isset($userArray)) { - $doc = new DOMDocument(); - $doc->loadXML($resultData); - $xPath = new DOMXPath($doc); - // Add users to department list. This is a hack as not all users will be in dupal - $nodeList = $xPath->query('//field[@name="refworks.u1"]'); - foreach ($nodeList as $node) { - if (!in_array($node->nodeValue, $userArray)) { - $userArray[] = $node->nodeValue; - } - } - } - if ($showForm) { - $output = 'Quick Search
' . drupal_get_form('fedora_repository_quick_search_form') . '
'; - } - $output .= $this->applyXSLT($resultData, $orderBy); - return $output; - } - } - - /** - * gets term from a lucene index and displays them in a list - * @param type $fieldName - * @param type $startTerm - * @param type $displayName - * @return type - */ - function getTerms($fieldName, $startTerm, $displayName = NULL) { - module_load_include('inc', 'fedora_repository', 'ObjectHelper'); - module_load_include('inc', 'fedora_repository', 'api/fedora_utils'); - $indexName = variable_get('fedora_index_name', 'DemoOnLucene'); - $searchUrl = variable_get('fedora_fgsearch_url', 'http://localhost:8080/fedoragsearch/rest'); - if ($startTerm == NULL) { - $startTerm = ""; - } - $startTerm = drupal_urlencode($startTerm); - $query = 'operation=browseIndex&startTerm=' . $startTerm . '&fieldName=' . $fieldName . '&termPageSize=20&indexName=' . $indexName . '&restXslt=copyXml&resultPageXslt=copyXml'; - // $query=drupal_urlencode($query); - $query = '?' . $query; - $searchString = $searchUrl . $query; - - $objectHelper = new ObjectHelper(); - - $resultData = do_curl($searchString, 1); - $path = drupal_get_path('module', 'fedora_repository'); - - $output .= $this->applySpecifiedXSLT($resultData, $path . '/xsl/browseIndexToResultPage.xslt', $displayName); - //$output .= '
'.$alpha_out; - return $output; - } - - /** - * custom search ?? - * @param type $query - * @param type $startPage - * @param type $xslt - * @param type $numberOfHistPerPage - * @return type - */ - function custom_search($query, $startPage=1, $xslt= '/xsl/advanced_search_results.xsl', $numberOfHistPerPage = 50) { - module_load_include('inc', 'fedora_repository', 'ObjectHelper'); - module_load_include('inc', 'fedora_repository', 'api/fedora_utils'); - - if (user_access('view fedora collection')) { - //$numberOfHistPerPage = '50';//hack for IR they do not want next button - $luceneQuery = NULL; - $indexName = variable_get('fedora_index_name', 'DemoOnLucene'); - $copyXMLFile = 'copyXml'; - // if($indexName=='ilives' || $indexName=='BasicIndex'){ - // $copyXMLFile = 'copyXmliLives'; - // } - $query = trim($query); - $query = htmlentities(urlencode($query)); - $searchUrl = variable_get('fedora_fgsearch_url', 'http://localhost:8080/fedoragsearch/rest'); - $searchString = '?operation=gfindObjects&indexName=' . $indexName . '&restXslt=' . $copyXMLFile . '&query=' . $query; - $searchString .= '&hitPageSize=' . $numberOfHistPerPage . '&hitPageStart=' . $startPage; - //$searchString = htmlentities($searchString); - $searchUrl .= $searchString; - - //$objectHelper = new ObjectHelper(); - - $resultData = do_curl($searchUrl, 1); - //var_dump($resultData);exit(0); - // $doc = new DOMDocument(); - // $doc->loadXML($resultData); - - $output .= $this->applyLuceneXSLT($resultData, $startPage, $xslt, $query); - return $output; - } - } - - /** - * apply specified xslt ?? - * @global type $user - * @param type $resultData - * @param type $pathToXSLT - * @param type $displayName - * @return type - */ - function applySpecifiedXSLT($resultData, $pathToXSLT, $displayName = NULL) { - $proc = NULL; - global $user; - if (!$resultData) { - drupal_set_message(t('No data found!')); - return ' '; //no results - } - try { - $proc = new XsltProcessor(); - } catch (Exception $e) { - drupal_set_message(t('Error loading ' . $pathToXSLT . ' xslt!') . $e->getMessage()); - return ' '; - } - - //$proc->setParameter('', 'searchUrl', url('search') . '/fedora_repository'); //needed in our xsl - $proc->setParameter('', 'objectsPage', base_path()); - $proc->setParameter('', 'userID', $user->uid); - if (isset($displayName)) { - $proc->setParameter('', 'displayName', $displayName); - } - else { - $proc->setParameter('', 'displayName', "test"); - } - - $xsl = new DomDocument(); - - $test = $xsl->load($pathToXSLT); - - if (!isset($test)) { - drupal_set_message(t('Error loading ' . $pathToXSLT . ' xslt!')); - return t('Error loading !pathToXSLT xslt.', array('!pathToXSLT' => $pathToXSLT)); - } - - $input = new DomDocument(); - - $didLoadOk = $input->loadXML($resultData); - - if (!isset($didLoadOk)) { - drupal_set_message(t('Error loading XML data!')); - return t('Error loading XML data.'); - } - else { - $proc->importStylesheet($xsl); - $newdom = $proc->transformToDoc($input); - return $newdom->saveXML(); - } - } - - //default function for lucene results - - /** - * apply an xslt to lucene gsearch search results - * - * @param $resultData - * @param $startPage - * @param $xslt_file - * @param $query the query that was executed. May want to pass this on. - */ - function applyLuceneXSLT($resultData, $startPage = 1, $xslt_file = '/xsl/results.xsl', $query=NULL) { - $path = drupal_get_path('module', 'fedora_repository'); - $test = $xslt_file; - $isRestricted = variable_get('fedora_namespace_restriction_enforced', TRUE); - if (!isRestricted && $xslt_file == NULL) { - $xslt_file = '/xsl/unfilteredresults.xsl'; - } - $proc = NULL; - if (!$resultData) { - //drupal_set_message(t('No Results!')); - return ' '; //no results - } - try { - $proc = new XsltProcessor(); - } catch (Exception $e) { - drupal_set_message(t('Error loading results xslt!') . $e->getMessage()); - return ' '; - } - if (isset($query)) { - $proc->setParameter('', 'fullQuery', $query); - } - //inject into xsl stylesheet - global $user; - $proc->setParameter('', 'userID', $user->uid); - $proc->setParameter('', 'searchToken', drupal_get_token('fedora_repository_advanced_search')); //token generated by Drupal, keeps tack of what tab etc we are on - $proc->setParameter('', 'searchUrl', url('search') . '/fedora_repository'); //needed in our xsl - $proc->setParameter('', 'objectsPage', base_path()); - $proc->setParameter('', 'allowedPidNameSpaces', variable_get('fedora_pids_allowed', 'default: demo: changeme: islandora: ilives: islandora-book: books: newspapers: ')); - $proc->setParameter('', 'hitPageStart', $startPage); - $proc->registerPHPFunctions(); - $xsl = new DomDocument(); - - $test = $xsl->load($path . $xslt_file); - if (!isset($test)) { - drupal_set_message(t('Error loading search results xslt!')); - return t('Error loading search results XSLT.'); - } - - $input = new DomDocument(); - $didLoadOk = $input->loadXML($resultData); - - if (!isset($didLoadOk)) { - drupal_set_message(t('Error loading search results!')); - return t('Error loading search results.'); - } - else { - $proc->importStylesheet($xsl); - $newdom = $proc->transformToDoc($input); - return $newdom->saveXML(); - } - } - - /** - * xslt for islandscholar these xslt functions can probably be pulled into one - * @param type $resultData - * @param type $orderBy - * @return type - */ - function applyXSLT($resultData, $orderBy = 0) { - $path = drupal_get_path('module', 'fedora_repository'); - $proc = NULL; - if (!$resultData) { - //drupal_set_message(t('No Results!')); - return ' '; //no results - } - try { - $proc = new XsltProcessor(); - } catch (Exception $e) { - drupal_set_message(t('Error loading results xslt!') . " " . $e->getMessage()); - return ' '; - } - - //inject into xsl stylesheet - //$proc->setParameter('', 'searchToken', drupal_get_token('search_form')); //token generated by Drupal, keeps tack of what tab etc we are on - $proc->setParameter('', 'userID', $user->uid); - $proc->setParameter('', 'searchUrl', url('search') . '/fedora_repository'); //needed in our xsl - $proc->setParameter('', 'objectsPage', base_path()); - $proc->setParameter('', 'allowedPidNameSpaces', variable_get('fedora_pids_allowed', 'default: demo: changeme: islandora: ilives: islandora-book: books: newspapers: ')); - $proc->setParameter('', 'orderBy', $orderBy); - $xsl = new DomDocument(); - - $test = $xsl->load($path . '/ir/xsl/results.xsl'); - if (!isset($test)) { - drupal_set_message(t('Error loading search results xslt!')); - return t('Error loading search results XSLT.'); - } - - $input = new DomDocument(); - $didLoadOk = $input->loadXML($resultData); - - if (!isset($didLoadOk)) { - drupal_set_message(t('Error loading search results!')); - return t('Error loading search results.'); - } - else { - $xsl = $proc->importStylesheet($xsl); - $newdom = $proc->transformToDoc($input); - return $newdom->saveXML(); - } - } - - /** - * theme advanced search form ?? - * @param type $form - * @param type $repeat - * @return type - */ - function theme_advanced_search_form($form, $repeat=NULL) { - if (!isset($repeat)) { - $repeat = variable_get('fedora_repository_advanced_block_repeat', t('3')); - } - - $output = drupal_render($form['search_type']['type1']); - $output .= drupal_render($form['fedora_terms1']); - $output .= drupal_render($form['andor1']) . drupal_render($form['search_type']['type2']); - $output .= drupal_render($form['fedora_terms2']); - if ($repeat > 2 && $repeat < 9) { - for ($i = 3; $i < $repeat + 1; $i++) { - $t = $i - 1; - $output .= drupal_render($form["andor$t"]) . drupal_render($form['search_type']["type$i"]); - $output .= drupal_render($form["fedora_terms$i"]); - } - } - $output .= drupal_render($form['submit']); - $output .= drupal_render($form); - return $output; - } - - /** - * build search form, custom blocks should set the number of repeats or it will use the default - * @param type $repeat - * @param type $pathToSearchTerms - * @param type $query - * @return string - */ - function build_advanced_search_form($repeat = NULL, $pathToSearchTerms = NULL, $query = NULL) { - $types = $this->get_search_terms_array($pathToSearchTerms); - $queryArray = NULL; - if (isset($query)) { - $queryArray = explode('AND', $query); - } - - $andOrArray = array( - 'AND' => 'and', - //'OR' => 'or' //removed or for now as it would be a pain to parse - ); - $form = array(); - - if (!isset($repeat)) { - $repeat = variable_get('fedora_repository_advanced_block_repeat', t('3')); - } - $var0 = explode(':', $queryArray[0]); - $var1 = explode(':', $queryArray[1]); - $form['search_type']['type1'] = array( - '#title' => t(''), - '#type' => 'select', - '#options' => $types, - '#default_value' => trim($var0[0]) - ); - $form['fedora_terms1'] = array( - '#size' => '24', - '#type' => 'textfield', - '#title' => t(''), - '#required' => TRUE, - '#default_value' => (count($var0) >= 2 ? trim($var0[1]) : ''), - ); - $form['andor1'] = array( - '#title' => t(''), - '#type' => 'select', - '#default_value' => 'AND', - '#options' => $andOrArray - ); - $form['search_type']['type2'] = array( - '#title' => t(''), - '#type' => 'select', - '#options' => $types, - '#default_value' => (count($var1) >= 2 ? trim($var1[0]) : ''), - ); - $form['fedora_terms2'] = array( - '#size' => '24', - '#type' => 'textfield', - '#title' => t(''), - '#default_value' => (count($var1) >= 2 ? $var1[1] : ''), - ); - if ($repeat > 2 && $repeat < 9) { //don't want less then 2 or more then 9 - for ($i = 3; $i < $repeat + 1; $i++) { - $t = $i - 1; - $field_and_term = explode(':', $queryArray[$t]); - $form["andor$t"] = array( - '#title' => t(''), - '#type' => 'select', - '#default_value' => 'AND', - '#options' => $andOrArray - ); - $form['search_type']["type$i"] = array( - '#title' => t(''), - '#type' => 'select', - '#options' => $types, - '#default_value' => trim($field_and_term[0]) - ); - $form["fedora_terms$i"] = array( - '#size' => '24', - '#type' => 'textfield', - '#title' => t(''), - '#default_value' => (count($field_and_term) >= 2 ? trim($field_and_term[1]) : ''), - ); - } - } - - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('search') - ); - return $form; - } - - /** - * get search terms array - * @param type $path - * @param string $file - * @return type - */ - function get_search_terms_array($path = NULL, $file = NULL) { - if (!isset($path)) { - $path = drupal_get_path('module', 'fedora_repository'); - } - $xmlDoc = new DomDocument(); - if (!isset($file)) { - $file = 'searchTerms.xml'; - } - $xmlDoc->load($path . '/' . $file); - $nodeList = $xmlDoc->getElementsByTagName('term'); - $types = array(); - for ($i = 0; $i < $nodeList->length; $i++) { - $field = $nodeList->item($i)->getElementsByTagName('field'); - $value = $nodeList->item($i)->getElementsByTagName('value'); - $fieldValue = $field->item(0)->nodeValue; - $valueValue = $value->item(0)->nodeValue; - $types["$fieldValue"] = "$valueValue"; - } - return $types; - } - -} diff --git a/api/fedora_collection.inc b/api/fedora_collection.inc index 200fb324..52b830df 100644 --- a/api/fedora_collection.inc +++ b/api/fedora_collection.inc @@ -70,8 +70,7 @@ function export_collection($collection_pid, $relationship = 'isMemberOfCollectio function get_related_items_as_xml($collection_pid, $relationship = array('isMemberOfCollection'), $limit = 10000, $offset = 0, $active_objects_only = TRUE, $cmodel = NULL, $orderby = '$title') { module_load_include('inc', 'fedora_repository', 'ObjectHelper'); - global $user; - if (!fedora_repository_access(OBJECTHELPER :: $OBJECT_HELPER_VIEW_FEDORA, $pid, $user)) { + if (!fedora_repository_check_perm(OBJECTHELPER :: $OBJECT_HELPER_VIEW_FEDORA, $pid)) { drupal_set_message(t("You do not have access to Fedora objects within the attempted namespace or access to Fedora denied."), 'error'); return array(); } diff --git a/api/fedora_item.inc b/api/fedora_item.inc index d4c8aff0..ae524fd9 100644 --- a/api/fedora_item.inc +++ b/api/fedora_item.inc @@ -1,9 +1,9 @@ objectProfile = & Fedora_Item::$instantiated_pids[$pid]->objectProfile; $this->datastreams = & Fedora_Item::$instantiated_pids[$pid]->datastreams; $this->datastreams_list = & Fedora_Item::$instantiated_pids[$pid]->datastreams_list; + $this->ownerId = & Fedora_Item::$instantiated_pids[$pid]->ownerId; } else { if (empty(self::$connection_helper)) { @@ -72,10 +79,12 @@ class Fedora_Item { if (!empty($raw_objprofile)) { $this->objectProfile = $raw_objprofile->objectProfile; $this->datastreams = $this->get_datastreams_list_as_array(); + $this->ownerId = Fedora_Item::getOwnerId($pid); } else { $this->objectProfile = ''; $this->datastreams = array(); + $this->ownerId = NULL; } Fedora_Item::$instantiated_pids[$pid] = &$this; } @@ -92,6 +101,7 @@ class Fedora_Item { /** * Exists + * * @return type */ function exists() { @@ -100,12 +110,14 @@ class Fedora_Item { /** * Add datastream from file + * * @param type $datastream_file * @param type $datastream_id * @param type $datastream_label * @param type $datastream_mimetype * @param type $controlGroup * @param type $logMessage + * * @return type */ function add_datastream_from_file($datastream_file, $datastream_id, $datastream_label = NULL, $datastream_mimetype = '', $controlGroup = 'M', $logMessage = NULL) { @@ -118,7 +130,7 @@ class Fedora_Item { drupal_set_message(t('The datastream file %datastream_file could not be read! (likely due to permissions...)', array('%datastream_file' => $datastream_file)), 'warning'); return; } - + if (empty($datastream_mimetype)) { // Get mime type from the file extension. $mimetype_helper = new MimeClass(); @@ -130,7 +142,7 @@ class Fedora_Item { $datastream_url = drupal_urlencode($datastream_file); $url = file_create_url($datastream_url); - // add_datastream_from_url forces a re-sync of the datastream list + // Add_datastream_from_url forces a re-sync of the datastream list. $return_value = $this->add_datastream_from_url($url, $datastream_id, $datastream_label, $datastream_mimetype, $controlGroup, $logMessage); if ($original_path != $datastream_file) { @@ -141,12 +153,14 @@ class Fedora_Item { /** * Add datastream from url + * * @param type $datastream_url * @param type $datastream_id * @param type $datastream_label * @param type $datastream_mimetype * @param type $controlGroup * @param type $logMessage + * * @return type */ function add_datastream_from_url($datastream_url, $datastream_id, $datastream_label = NULL, $datastream_mimetype = '', $controlGroup = 'M', $logMessage = NULL) { @@ -158,15 +172,16 @@ class Fedora_Item { // Fedora has some problems getting files from HTTPS connections sometimes, so if we are getting a file // from the local drupal, we try to pass a HTTP url instead of a HTTPS one. - if(stripos($datastream_url, 'https://') !== FALSE && stripos($datastream_url, $base_url) !== FALSE) { + if (stripos($datastream_url, 'https://') !== FALSE && stripos($datastream_url, $base_url) !== FALSE) { $datastream_url = str_ireplace('https://', 'http://', $datastream_url); } + $datastream_label = truncate_utf8($datastream_label, 255, TRUE, TRUE); $params = array( 'pid' => $this->pid, 'dsID' => $datastream_id, 'altIDs' => NULL, - 'dsLabel' => truncate_utf8($datastream_label, 255, TRUE, TRUE), + 'dsLabel' => $datastream_label, 'versionable' => TRUE, 'MIMEType' => $datastream_mimetype, 'formatURI' => NULL, @@ -175,23 +190,31 @@ class Fedora_Item { 'dsState' => 'A', 'checksumType' => 'DISABLED', 'checksum' => 'none', - 'logMessage' => ($logMessage != NULL) ? $logMessage : 'Ingested object ' . $datastream_id + 'logMessage' => ($logMessage != NULL) ? $logMessage : 'Ingested object ' . $datastream_id, ); $soap_result = $this->soap_call('addDataStream', $params); - // make sure to refresh the datastream list after adding so this item stays in sync with the repository - $this->datastreams = $this->get_datastreams_list_as_array(); + + // Add new DS to the DS list so the item is in sync with the repository. + $this->datastreams[$datastream_id] = array( + 'label' => $datastream_label, + 'MIMEType' => $datastream_mimetype, + 'URL' => ($this->url() . '/' . $datastream_id . '/' . + drupal_urlencode($datastream_label)),); + return $soap_result; } /** * Add datastream from string + * * @param type $str * @param type $datastream_id * @param type $datastream_label * @param type $datastream_mimetype * @param type $controlGroup * @param type $logMessage + * * @return type */ function add_datastream_from_string($str, $datastream_id, $datastream_label = NULL, $datastream_mimetype = 'text/xml', $controlGroup = 'M', $logMessage = NULL) { @@ -200,7 +223,7 @@ class Fedora_Item { $tmpfile = fopen($tmpfilename, 'w'); fwrite($tmpfile, $str, strlen($str)); fclose($tmpfile); - // add_datastream_from_file forces a re-sync of the datastream list + // Add_datastream_from_file forces a re-sync of the datastream list. $returnvalue = $this->add_datastream_from_file($tmpfilename, $datastream_id, $datastream_label, $datastream_mimetype, $controlGroup, $logMessage); unlink($tmpfilename); return $returnvalue; @@ -208,7 +231,9 @@ class Fedora_Item { /** * Wrapper to add new or modify existing datastream + * * @global url $base_url + * * @param url $external_url * @param string $dsid * @param string $label @@ -229,6 +254,33 @@ class Fedora_Item { } } + /** + * + * @param unknown_type $el + * @param unknown_type $object + * @param unknown_type $type + */ + protected function buildRelsStatement(&$el, $object, $type) { + if ($type > 0) { + $el->appendChild($el->ownerDocument->createTextNode($object)); + if ($type == RELS_TYPE_STRING) { + $el->setAttribute('rdf:datatype', 'http://www.w3.org/2001/XMLSchema#string'); + } + elseif ($type == RELS_TYPE_INT) { + $el->setAttribute('rdf:datatype', 'http://www.w3.org/2001/XMLSchema#int'); + } + elseif ($type == RELS_TYPE_DATETIME) { + $el->setAttribute('rdf:datatype', 'http://www.w3.org/2001/XMLSchema#dateTime'); + } + else { + // Plain literal. + } + } + else { + $el->setAttribute('rdf:resource', $object); + } + } + /** * Add a relationship string to this object's RELS-EXT. * @@ -236,8 +288,8 @@ class Fedora_Item { * * @param string $relationship * The predicate/relationship tag to add - * @param string $object - * The object to be related to. + * @param string|array $object + * The object(s) to be related to. * @param string $namespaceURI * The predicate namespace. * @param int $literal_value @@ -247,16 +299,19 @@ class Fedora_Item { * - 2: string (explicitly typed) * - 3: integer * - 4: dateTime + * * @return ??? - * Value returned from SOAP call for modify_datastream. + * Value returned from SOAP call for modify_datastream. */ function add_relationship($relationship, $object, $namespaceURI = RELS_EXT_URI, $literal_value = RELS_TYPE_URI) { static $relsextxml = NULL; if ($relsextxml === NULL) { - $relsextxml = new DOMDocument(); //Avoid new instantiations in long-running processes + // Avoid new instantiations in long-running processes. + $relsextxml = new DOMDocument(); } - - $ds_list = $this->get_datastreams_list_as_array(); + + $ds_list = $this->datastreams; + $f_prefix = 'info:fedora/'; if (!array_key_exists('RELS-EXT', $ds_list)) { $rdf_string = <<get_datastream_dissemination('RELS-EXT'); - - if ($literal_value == REL_TYPE_URI && strpos($object, $f_prefix) !== 0) { - $object = $f_prefix . $object; - } $relsextxml->loadXML($relsext); $description = $relsextxml->getElementsByTagNameNS('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'Description'); if ($description->length == 0) { - //XXX: This really shouldn't be done; lower case d doesn't fit the schema. Warn users to fix the data and generators, pending deprecation. + // XXX: This really shouldn't be done; lower case d doesn't fit the schema. Warn users to fix the data and generators, pending deprecation. $description = $relsextxml->getElementsByTagNameNS('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'description'); if ($description->length > 0) { drupal_set_message(t('RDF with lower case "d" in "description" encountered. Should be uppercase! PID: %pid', array('%pid' => $this->pid)), 'warning'); @@ -285,42 +336,83 @@ RDF; } $description = $description->item(0); - // Create the new relationship node. - $newrel = $relsextxml->createElementNS($namespaceURI, $relationship); - - if ($literal_value > 0) { - $newrel->appendChild($relsextxml->createTextNode($object)); - if ($literal_value == RELS_TYPE_STRING) { - $newrel->setAttribute('rdf:datatype', 'http://www.w3.org/2001/XMLSchema#string'); - } - elseif ($literal_value == RELS_TYPE_INT) { - $newrel->setAttribute('rdf:datatype', 'http://www.w3.org/2001/XMLSchema#int'); + // Casting a string to an array gives an array containing the string, and + // casting an array to an array does nothing. + foreach ((array)$object as $obj) { + if ($literal_value == RELS_TYPE_URI && strpos($obj, $f_prefix) !== 0) { + $obj = $f_prefix . $obj; } - elseif ($literal_value == RELS_TYPE_DATETIME) { - $newrel->setAttribute('rdf:datatype', 'http://www.w3.org/2001/XMLSchema#dateTime'); - } - else { - //plain literal. + + // Create the new relationship node. + $newrel = $relsextxml->createElementNS($namespaceURI, $relationship); + + $this->buildRelsStatement($newrel, $obj, $literal_value); + + $description->appendChild($newrel); + } + + return $this->modify_datastream($relsextxml->saveXML(), 'RELS-EXT', "Fedora Object-to-Object Relationship Metadata", 'application/rdf+xml'); + } + + /** + * Extension of add_relationship(), which acts on RELS-INT. + * + * @param $dsid + * A string containing either the base dsid (EXAMPLE) + * or URI to the datastream (info:fedora/pid/EXAMPLE) + */ + function add_dsid_relationship($dsid, $relationship, $object, $namespaceURI = RELS_EXT_URI, $literal_value = RELS_TYPE_URI) { + static $relsxml = NULL; + if ($relsxml === NULL) { + // Avoid new instantiations in long-running processes. + $relsxml = new DOMDocument(); + } + + $f_prefix = 'info:fedora/'; + if (!array_key_exists('RELS-INT', $this->datastreams)) { + $rdf_string = << +RDF; + $this->add_datastream_from_string($rdf_string, 'RELS-INT', 'Fedora datastream relationship metadata', 'application/rdf+xml', 'X'); + } + + $rels_text = $this->get_datastream_dissemination('RELS-INT'); + + if (strpos($dsid, $f_prefix) !== 0) { + $dsid = $f_prefix . $this->pid . '/' . $dsid; + } + + $relsxml->loadXML($rels_text); + $descs = $relsxml->getElementsByTagNameNS('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'Description'); + $description = NULL; + foreach ($descs as $desc) { + if ($desc->getAttributeNS('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'about') == $dsid) { + $description = $desc; + break; } } - else { - $newrel->setAttribute('rdf:resource', $object); + + // Create the description element if we didn't find it... + if ($description === NULL) { + $description = $relsxml->createElementNS('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'rdf:Description'); + $description->setAttributeNS('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'rdf:about', $dsid); + $relsxml->documentElement->appendChild($description); } - $description->appendChild($newrel); - - return $this->modify_datastream($relsextxml->saveXML(), 'RELS-EXT', "Fedora Object-to-Object Relationship Metadata", 'application/rdf+xml'); - //print ($description->dump_node()); - /* - $params = array( 'pid' => $this->pid, - 'relationship' => $relationship, - 'object' => $object, - 'isLiteral' => FALSE, - 'datatype' => '', - ); + foreach ((array)$object as $obj) { + if ($literal_value == RELS_TYPE_URI && strpos($obj, $f_prefix) !== 0) { + $obj = $f_prefix . $object; + } + + // Create the new relationship node. + $newrel = $relsxml->createElementNS($namespaceURI, $relationship); - return $this->soap_call( 'addRelationship', $params ); - */ + $this->buildRelsStatement($newrel, $obj, $literal_value); + + $description->appendChild($newrel); + } + + return $this->modify_datastream($relsxml->saveXML(), 'RELS-INT', "Fedora Datastream Relationship Metadata", 'application/rdf+xml'); } /** @@ -331,7 +423,9 @@ RDF; * @param string $relationship * The predicate/relationship tag to delete * @param string $object - * The object to be related to. (NULL/value for which empty() evaluates to true will remove all relations of the given type, ignoring $literal_value) + * The object to be related to. (NULL/value for which empty() + * evaluates to true will remove all relations of the given type, + * ignoring $literal_value) * @param string $namespaceURI * The predicate namespace. * @param int $literal_value @@ -340,35 +434,98 @@ RDF; * Whether or not this operation has produced any changes in the RELS-EXT */ function purge_relationships($relationship, $object, $namespaceURI = RELS_EXT_URI, $literal_value = FALSE) { - $relsext = $this->get_datastream_dissemination('RELS-EXT'); - - $relsextxml = new DomDocument(); - $relsextxml->loadXML($relsext); + $relsext = trim($this->get_datastream_dissemination('RELS-EXT')); + + $relsextxml = new DOMDocument(); $modified = FALSE; - $rels = $relsextxml->getElementsByTagNameNS($namespaceURI, $relationship); - if (!empty($rels)) { - foreach ($rels as $rel) { - if ( //If either no object is specified, or the object matches (in either the literal or URI case), remove this node from it's parent, and mark as changed. - empty($object) || - (($literal_value == RELS_TYPE_URI) && $rel->getAttributeNS('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'resource') == $object) || - (($literal_value == RELS_TYPE_PLAIN_LITERAL) && $rel->textContent == $object) || - (($literal_value == RELS_TYPE_STRING) && $rel->getAttribute('rdf:datatype') == 'http://www.w3.org/2001/XMLSchema#string' && $rel->textContent == $object) || - (($literal_value == RELS_TYPE_INT) && $rel->getAttribute('rdf:datatype') == 'http://www.w3.org/2001/XMLSchema#int' && intval($rel->textContent) == $object)) { - $rel->parentNode->removeChild($rel); - $modified = TRUE; + + if ($relsext && $relsextxml->loadXML($relsext)) { + $rels = $relsextxml->getElementsByTagNameNS($namespaceURI, $relationship); + if (!empty($rels)) { + // Iterate backwards so if we delete something our pointer doesn't get out of sync. + for ($i = $rels->length; $i > 0; $i--) { + $rel = $rels->item($i - 1); + // Foreach ($rels as $rel) { // moving forward like this caused iteration errors when something was deleted. + if ( + // If either no object is specified, or the object matches (in either the literal or URI case), remove this node from it's parent, and mark as changed. + empty($object) || + (($literal_value == RELS_TYPE_URI) && $rel->getAttributeNS('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'resource') == $object) || + (($literal_value == RELS_TYPE_PLAIN_LITERAL) && $rel->textContent == $object) || + (($literal_value == RELS_TYPE_STRING) && $rel->getAttribute('rdf:datatype') == 'http://www.w3.org/2001/XMLSchema#string' && $rel->textContent == $object) || + (($literal_value == RELS_TYPE_INT) && $rel->getAttribute('rdf:datatype') == 'http://www.w3.org/2001/XMLSchema#int' && intval($rel->textContent) == $object)) { + $rel->parentNode->removeChild($rel); + $modified = TRUE; + } } } + + // Save changes. + if ($modified) { + $this->modify_datastream($relsextxml->saveXML(), 'RELS-EXT', "Fedora Object-to-Object Relationship Metadata", 'text/xml'); + } } - - //Save changes. - if ($modified) { - $this->modify_datastream($relsextxml->saveXML(), 'RELS-EXT', "Fedora Object-to-Object Relationship Metadata", 'text/xml'); + // Return whether or not we've introduced any changes. + return $modified; + } + + /** + * Extension of purge_relationships, which acts on RELS-INT. + * + * @param string $dsid + * A string containing either the base dsid (EXAMPLE) + * or URI to the datastream (info:fedora/pid/EXAMPLE) + */ + function purge_dsid_relationships($dsid, $relationship, $object, $namespaceURI = RELS_EXT_URI, $literal_value = FALSE) { + $f_prefix = 'info:fedora/'; + if (strpos($dsid, $f_prefix) !== 0) { + $dsid = $f_prefix . $this->pid . '/' . $dsid; } - - //Return whether or not we've introduced any changes. + + $relsxml = new DOMDocument(); + $relsint = trim($this->get_datastream_dissemination('RELS-INT')); + $modified = FALSE; + if ($relsint && $relsxml->loadXML($relsint)) { + + + $descs = $relsxml->getElementsByTagNameNS('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'Description'); + $description = NULL; + foreach ($descs as $desc) { + if ($dsid === NULL || $desc->getAttributeNS('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'about') == $dsid) { + $rels = $desc->getElementsByTagNameNS($namespaceURI, $relationship); + if (!empty($rels)) { + // Iterate backwards so if we delete something our pointer doesn't get out of sync. + for ($i = $rels->length; $i>0; $i--) { + $rel = $rels->item($i-1); + // foreach ($rels as $rel) { // moving forward like this caused iteration errors when something was deleted + // If either no object is specified, or the object matches (in either the literal or URI case), remove this node from it's parent, and mark as changed. + if ( + empty($object) || + (($literal_value == RELS_TYPE_URI) && $rel->getAttributeNS('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'resource') == $object) || + (($literal_value == RELS_TYPE_PLAIN_LITERAL) && $rel->textContent == $object) || + (($literal_value == RELS_TYPE_STRING) && $rel->getAttribute('rdf:datatype') == 'http://www.w3.org/2001/XMLSchema#string' && $rel->textContent == $object) || + (($literal_value == RELS_TYPE_INT) && $rel->getAttribute('rdf:datatype') == 'http://www.w3.org/2001/XMLSchema#int' && intval($rel->textContent) == $object)) { + $rel->parentNode->removeChild($rel); + $modified = TRUE; + } + } + } + + if ($desc->getAttributeNS('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'about') == $dsid) { + break; + } + } + } + + // Save changes. + if ($modified) { + $this->modify_datastream($relsxml->saveXML(), 'RELS-INT', "Fedora Datastream Relationship Metadata", 'text/xml'); + } + } + + // Return whether or not we've introduced any changes. return $modified; } - + /** * Removes the given relationship from the item's RELS-EXT and re-saves it. * @@ -432,6 +589,7 @@ RDF; /** * Export as foxml + * * @return type */ function export_as_foxml() { @@ -450,6 +608,7 @@ RDF; * @param string $pattern to search for, including wildcards. * @param string $field The field to search on, e.g. pid, title, cDate. See http://www.fedora-commons.org/confluence/display/FCR30/REST+API#RESTAPI-findObjects for details * @param int $max_results not used at this time + * * @return Array of pid => title pairs that match the results */ static function find_objects_by_pattern($pattern = '*', $field = 'pid', $max_results = 100, $resultFields = array()) { @@ -511,10 +670,12 @@ RDF; /** * Get datastream dissemination + * * @param type $dsid * @param type $as_of_date_time * @param type $quiet - * @return null + * + * @return null */ function get_datastream_dissemination($dsid, $as_of_date_time = "", $quiet=TRUE) { if (!array_key_exists($dsid, $this->datastreams)) { @@ -526,7 +687,7 @@ RDF; 'dsID' => $dsid, 'asOfDateTime' => $as_of_date_time, ); - + // Make soap call with quite $object = self::soap_call('getDataStreamDissemination', $params, $quiet); if (!empty($object)) { @@ -541,8 +702,10 @@ RDF; /** * Get datastream + * * @param type $dsid * @param type $as_of_date_time + * * @return type */ function get_datastream($dsid, $as_of_date_time = '', $quiet = TRUE) { @@ -561,13 +724,15 @@ RDF; /** * Get datastream history + * * @param type $dsid + * * @return type */ function get_datastream_history($dsid) { $params = array( 'pid' => $this->pid, - 'dsID' => $dsid + 'dsID' => $dsid, ); $object = self::soap_call('getDatastreamHistory', $params); $ret = FALSE; @@ -580,10 +745,12 @@ RDF; /** * Get dissemination + * * @param type $service_definition_pid * @param type $method_name * @param type $parameters * @param type $as_of_date_time + * * @return string */ function get_dissemination($service_definition_pid, $method_name, $parameters = array(), $as_of_date_time = NULL) { @@ -606,8 +773,8 @@ RDF; } /** - * Retrieves and returns a SimpleXML list of this item's datastreams, and stores them - * as an instance variable for caching purposes. + * Retrieves and returns a SimpleXML list of this item's datastreams, + * and stores them as an instance variable for caching purposes. * * @return SimpleXMLElement */ @@ -615,7 +782,7 @@ RDF; //if ( empty( $this->datastreams_list ) ) { $params = array( 'pid' => $this->pid, - 'asOfDateTime' => "" + 'asOfDateTime' => "", ); $this->datastreams_list = $this->soap_call('listDataStreams', $params); @@ -624,7 +791,7 @@ RDF; } /** - * * DatastreamControlGroup controlGroup - String restricted to the values of "X", "M", "R", or "E" (InlineXML,Managed Content,Redirect, or External Referenced). + * DatastreamControlGroup controlGroup - String restricted to the values of "X", "M", "R", or "E" (InlineXML,Managed Content,Redirect, or External Referenced). * String ID - The datastream ID (64 characters max). * String versionID - The ID of the most recent datastream version * String[] altIDs - Alternative IDs for the datastream, if any. @@ -641,21 +808,23 @@ RDF; * * @param string $dsid + * * @return datastream object - * get the mimetype size etc. in one shot. instead of iterating throught the datastream list for what we need + * get the mimetype size etc. in one shot. instead of iterating throught the datastream list for what we need */ function get_datastream_info($dsid, $as_of_date_time = '') { $params = array( 'pid' => $this->pid, 'dsID' => $dsid, - 'asOfDateTime' => $as_of_date_time + 'asOfDateTime' => $as_of_date_time, ); return $this->soap_call('getDatastream', $params); } /** - * Returns an associative array of this object's datastreams. Results look like this: + * Returns an associative array of this object's datastreams. + * Results look like this: * * 'DC' => * array @@ -681,7 +850,7 @@ RDF; if (!is_array($this->datastreams_list->datastreamDef)) { $xml_list = array($xml_list); } - + foreach ($xml_list as $ds) { if (!is_object($ds)) { print_r($ds); @@ -705,7 +874,7 @@ RDF; $this->get_datastreams_list_as_SimpleXML(); $mimetype = ''; - foreach ($datastream_list as $datastream) { + foreach ($this->datastreams_list as $datastream) { foreach ($datastream as $datastreamValue) { if ($datastreamValue->ID == $dsid) { return $datastreamValue->MIMEType; @@ -720,6 +889,7 @@ RDF; * Currently the Fedora API call getRelationships is reporting an uncaught * exception so we will parse the RELS-EXT ourselves and simulate the * documented behaviour. + * * @param String $relationship - filter the results to match this string. */ function get_relationships($relationship = NULL) { @@ -749,8 +919,26 @@ RDF; return $relationships; } - function get_rdf_relationships() { - + /** + * Retrieves RELS-EXT values from item + * + * @param array $namespaces + * + * @return array + */ + function get_rdf_relationships($namespaces = null) { + if ($namespaces == NULL) { + $namespaces = array( + RELS_EXT_URI, + FEDORA_MODEL_URI, + ISLANDORA_PAGE_URI, + ISLANDORA_RELS_EXT_URI, + ISLANDORA_RELS_INT_URI, + ); + } + if (!is_array($namespaces)) { + $namespaces = array($namespaces); + } $relationships = array(); try { $relsext = $this->get_datastream_dissemination('RELS-EXT'); @@ -764,13 +952,16 @@ RDF; $relsextxml->loadXML($relsext); $relsextxml->normalizeDocument(); $allTags = array(); - $allTags[] = $relsextxml->getElementsByTagNameNS(RELS_EXT_URI, '*'); - $allTags[] = $relsextxml->getElementsByTagNameNS(FEDORA_MODEL_URI, '*'); - $allTags[] = $relsextxml->getElementsByTagNameNS(ISLANDORA_PAGE_URI, '*'); + foreach ($namespaces as $namespace) { + $allTags[] = $relsextxml->getElementsByTagNameNS($namespace, '*'); + } + foreach ($allTags as $tags) { foreach ($tags as $child) { - $value = preg_replace('/info:fedora\//','',$child->getAttributeNS('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'resource')); - + $value = preg_replace('/info:fedora\//', '', $child->getAttributeNS('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'resource')); + if (!$value) { + $value = $child->textContent; + } $relationships[$child->tagName][] = $value; } } @@ -786,6 +977,7 @@ RDF; /** * Creates a RELS-EXT XML stream from the supplied array and saves it to * the item on the server. + * * @param $relationships */ function save_relationships($relationships) { @@ -804,7 +996,6 @@ RDF; } // Do the messy work constructing the RELS-EXT XML. Because addRelationship is broken. - return FALSE; } @@ -812,12 +1003,12 @@ RDF; * Set the object to a deleted state */ function move_to_trash($log_message = 'Flagged deleted using Islandora API.', $quiet = TRUE) { - // Loop through the datastreams and mark them deleted + // Loop through the datastreams and mark them deleted. foreach ($this->get_datastreams_list_as_array() as $dsid => $info) { $this->set_datastream_state($dsid, 'D'); } - // Create a message to mark the object deleted + // Create a message to mark the object deleted. $params = array( 'pid' => $this->pid, 'state' => 'D', @@ -826,7 +1017,7 @@ RDF; 'ownerId' => null, ); - // Send message to mark the object deleted + // Send message to mark the object deleted. return self::soap_call('modifyObject', $params, $quiet); } @@ -838,27 +1029,31 @@ RDF; */ function purge($log_message = 'Purged using Islandora API.', $force = FALSE) { - // Flag the object to be deleted first + // Flag the object to be deleted first. $this->move_to_trash($log_message); - // Create the delete message + // Create the delete message. $params = array( 'pid' => $this->pid, 'logMessage' => $log_message, - 'force' => $force + 'force' => $force, ); - // Delete the object + $this->forget(); + + // Delete the object. return $this->soap_call('purgeObject', $params); } /** * Purge datastream + * * @param type $dsID * @param type $start_date * @param type $end_date * @param type $log_message * @param type $force + * * @return type */ function purge_datastream($dsID, $start_date = NULL, $end_date = NULL, $log_message = 'Purged datastream using Islandora API', $force = FALSE) { @@ -871,7 +1066,7 @@ RDF; 'force' => $force, ); $soap_result = $this->soap_call('purgeDatastream', $params); - // make sure to refresh the datastream list after adding so this item stays in sync with the repository + // Make sure to refresh the datastream list after adding so this item stays in sync with the repository. $this->datastreams = $this->get_datastreams_list_as_array(); return $soap_result; } @@ -879,17 +1074,20 @@ RDF; /** * URL * @global type $base_url + * * @return type */ function url() { return url('fedora/repository/' . $this->pid . (!empty($this->objectProfile) ? '/-/' . drupal_urlencode($this->objectProfile->objLabel) : ''), array( - 'absolute' => TRUE + 'absolute' => TRUE, )); } /** * Get Next PID in Namespace + * * @param $pid_namespace string + * * @return string */ static function get_next_PID_in_namespace($pid_namespace = '', $number_of_pids = 1) { @@ -917,14 +1115,16 @@ RDF; /** * ingest from FOXML + * * @param type $foxml + * * @return Fedora_Item */ static function ingest_from_FOXML(DOMDocument $foxml) { $params = array( 'objectXML' => $foxml->saveXML(), 'format' => 'info:fedora/fedora-system:FOXML-1.1', - 'logMessage' => 'Fedora Object Ingested' + 'logMessage' => 'Fedora Object Ingested', ); $object = self::soap_call('ingest', $params); return new Fedora_Item($object->objectPID); @@ -932,7 +1132,9 @@ RDF; /** * ingest from FOXML file + * * @param type $foxml_file + * * @return type */ static function ingest_from_FOXML_file($foxml_file) { @@ -943,12 +1145,13 @@ RDF; /** * ingest from FOXML files in directory + * * @param type $path */ static function ingest_from_FOXML_files_in_directory($path) { - // Open the directory + // Open the directory. $dir_handle = @opendir($path); - // Loop through the files + // Loop through the files. while ($file = readdir($dir_handle)) { if ($file == "." || $file == ".." || strtolower(substr($file, strlen($file) - 4)) != '.xml') { continue; @@ -957,39 +1160,102 @@ RDF; try { self::ingest_from_FOXML_file($path . '/' . $file); } catch (exception $e) { - + } } - // Close + // Close. closedir($dir_handle); } /** * Modify Object + * * @param $label string * @param $state string * @param $ownerId string * @param $logMessage string * @param $quiet boolean + * * @return type */ function modify_object($label = '', $state = NULL, $ownerId = NULL, $logMessage = 'Modified by Islandora API', $quiet=TRUE) { - $params = array( 'pid' => $this->pid, - 'ownerId' => $ownerId, + // Default to the current owner if none is provided.. + 'ownerId' => (($ownerId !== NULL) ? + $ownerId : + $this->ownerId), 'state' => $state, 'label' => $label, - 'logMessage' => $logMessage + 'logMessage' => $logMessage, ); return self::soap_call('modifyObject', $params, $quiet); } + /** + * Work around function, due to file_create_url not URL encoding stuff. + * + * Parses and reassembles the URL, exploding, rawurlencoding and imploding + * the path components along the way. + * + * @param $url + * A string containing an HTTP(S) URL to attempt. + * + * @return string + * The results of the HTTP request if successful; boolean FALSE otherwise. + */ + protected static function try_http_get_content($url) { + // Can throw a warning prior to 5.3.3. + $parsed_url = @parse_url($url); + $supported_schemes = array( + 'http', + 'https', + ); + + $content = FALSE; + + if ($parsed_url && array_key_exists('scheme', $parsed_url) && in_array($parsed_url['scheme'], $supported_schemes)) { + $components = explode('/', $parsed_url['path']); + $components = array_map('rawurlencode', $components); + $fixed_url = url( + t( + '!scheme://!user:!pass@!host:!port/!path', + array( + '!scheme' => $parsed_url['scheme'], + '!user' => rawurlencode($parsed_url['user']), + '!pass' => rawurlencode($parsed_url['pass']), + '!host' => $parsed_url['host'], + '!port' => $parsed_url['port'], + '!path' => implode('/', $components), + ) + ), + array( + 'query' => $parsed_url['query'], + 'fragment' => $parsed_url['fragment'], + ) + ); + $result = drupal_http_request($fixed_url); + + if ((int) ($result->code / 100) === 2) { + $content = $result->data; + } + else { + watchdog('fedora_repository', 'Failed making HTTP request to @URL. Info: @info', array( + '@URL' => $fixed_url, + '@info' => print_r($result, TRUE), + ), 'warning'); + } + } + + return $content; + } + /** * Wrap modify by value and reference * - * Wrap modify by value and reference, so that the proper one gets called in the correct instance. (value if inline XML, reference otherwise) + * Wrap modify by value and reference, so that the proper one gets called + * in the correct instance. (value if inline XML, reference otherwise) * * First tries to treat the passed in value as a filename, tries using as contents second. * Coerces the data into what is required, and passes it on to the relevant function. @@ -1002,59 +1268,78 @@ RDF; * A label to withwhich to update the datastream * @param string $mime_type * Mimetype for the data being pushed into the datastream - * @param boolean $force + * @param boolean $force * Dunno, refer to underlying functions/SOAP interface. We just pass it like a chump. * @param string $logMessage * A message for the audit log. * @param boolean $quiet - * Error suppression? Refer to soap_call for usage (just passed along here). + * Error suppression? Refer to soap_call for usage + * (just passed along here). */ function modify_datastream($filename_or_content, $dsid, $label, $mime_type, $force = FALSE, $logMessage='Modified by Islandora API', $quiet=FALSE) { $toReturn = NULL; - - //Determine if it's inline xml; if it is, modify by value + + // Determine if it's inline xml; if it is, modify by value. if ($this->get_datastream($dsid)->controlGroup === 'X') { $content = ''; if (is_file($filename_or_content) && is_readable($filename_or_content)) { $content = file_get_contents($filename_or_content); } else { - $content = $filename_or_content; + // XXX: Get the contents to deal with fopen not being allowed for remote access + //in some OSs + $temp_content = self::try_http_get_content($filename_or_content); + if ($temp_content !== FALSE) { + $content = $temp_content; + } + else { + $content = $filename_or_content; + } } - + $toReturn = $this->modify_datastream_by_value($content, $dsid, $label, $mime_type, $force, $logMessage); } - //Otherwise, write to web-accessible temp file and modify by reference. + // Otherwise, write to web-accessible temp file and modify by reference. else { $file = ''; $created_temp = FALSE; if (is_file($filename_or_content) && is_readable($filename_or_content)) { - $file = $filename_or_content; + $file = $filename_or_content; $original_path = $file; // Temporarily move file to a web-accessible location. file_copy($file, file_directory_path()); $created_temp = ($original_path != $file); } else { - //Push contents to a web-accessible file - $file = file_save_data($filename_or_content, file_directory_path()); + // XXX: Get the contents to deal with fopen not being allowed for remote access + // in some OSs + $temp_content = self::try_http_get_content($filename_or_content); + if ($temp_content !== FALSE) { + $filename_or_content = $temp_content; + } + + // Push contents to a web-accessible file. + $file = file_save_data($filename_or_content, file_create_filename($label, file_directory_path())); $created_temp = TRUE; } - - $file_url = file_create_url($file); - + + $parts = explode(DIRECTORY_SEPARATOR, $file); + $parts = array_map('rawurlencode', $parts); + $file_url = file_create_url(implode(DIRECTORY_SEPARATOR, $parts)); + $toReturn = $this->modify_datastream_by_reference($file_url, $dsid, $label, $mime_type, $force, $logMessage); - + if ($created_temp && is_file($file) && is_writable($file)) { file_delete($file); } } - + return $toReturn; } - + /** * Modify datastream by reference + * * @param type $external_url * @param type $dsid * @param type $label @@ -1062,9 +1347,18 @@ RDF; * @param type $force * @param type $logMessage * @param type $quiet + * * @return type */ function modify_datastream_by_reference($external_url, $dsid, $label, $mime_type, $force = FALSE, $logMessage = 'Modified by Islandora API', $quiet=FALSE) { + global $base_url; + + // Fedora has some problems getting files from HTTPS connections sometimes, so if we are getting a file + // from the local drupal, we try to pass a HTTP url instead of a HTTPS one. + if (stripos($external_url, 'https://') !== FALSE && stripos($external_url, $base_url) !== FALSE) { + $external_url = str_ireplace('https://', 'http://', $external_url); + } + $params = array( 'pid' => $this->pid, 'dsID' => $dsid, @@ -1076,13 +1370,14 @@ RDF; 'checksumType' => 'DISABLED', 'checksum' => 'none', 'logMessage' => $logMessage, - 'force' => $force + 'force' => $force, ); return self::soap_call('modifyDatastreamByReference', $params, $quiet); } /** * Modify datastream by value + * * @param type $content * @param type $dsid * @param type $label @@ -1090,6 +1385,7 @@ RDF; * @param type $force * @param type $logMessage * @param type $quiet + * * @return type */ function modify_datastream_by_value($content, $dsid, $label, $mime_type, $force = FALSE, $logMessage = 'Modified by Islandora API', $quiet=FALSE) { @@ -1104,11 +1400,18 @@ RDF; 'checksumType' => 'DISABLED', 'checksum' => 'none', 'logMessage' => $logMessage, - 'force' => $force + 'force' => $force, ); return self::soap_call('modifyDatastreamByValue', $params, $quiet); } + /** + * + * @param unknown_type $dsid + * @param unknown_type $state + * @param unknown_type $log_message + * @param unknown_type $quiet + */ function set_datastream_state($dsid, $state, $log_message = 'Modified by Islandora API', $quiet = FALSE) { $valid_states = array('A', 'D', 'I'); if (array_search($state, $valid_states) !== FALSE) { @@ -1141,10 +1444,10 @@ RDF; self::$connection_helper = new ConnectionHelper(); } $url = ( - in_array($function, self::$SoapManagedFunctions)? - variable_get('fedora_soap_manage_url', 'http://localhost:8080/fedora/wsdl?api=API-M') : - variable_get('fedora_soap_url', 'http://localhost:8080/fedora/services/access?wsdl') - ); + in_array($function, self::$SoapManagedFunctions) ? + variable_get('fedora_soap_manage_url', 'http://localhost:8080/fedora/wsdl?api=API-M') : + variable_get('fedora_soap_url', 'http://localhost:8080/fedora/services/access?wsdl') + ); try { $soap_client = self::$connection_helper->getSoapClient($url); if (isset($soap_client)) { @@ -1176,23 +1479,28 @@ RDF; * @param string $pid if none given, getnextpid will be called. * @param string $state The initial state, A - Active, I - Inactive, D - Deleted * @param type $label - * @param type $owner + * @param string $owner + * Used to set an object's ownerId attribute. Defaults to current user's + * name. If we are not a Drupal user(ie. Drush) defaults to ''. + * * @return DOMDocument */ static function create_object_FOXML($pid = '', $state = 'A', $label = 'Untitled', $owner = '') { $foxml = new DOMDocument("1.0", "UTF-8"); $foxml->formatOutput = TRUE; if (empty($pid)) { - // Call getNextPid + // Call getNextPid. $pid = self::get_next_PID_in_namespace(); } if (empty($owner)) { global $user; - if (!empty($user->uid)) { // Default to current Drupal user. - $owner = $user->uid; + // Default to current Drupal user. + if (!empty($user->name)) { + $owner = $user->name; } - else { // We are not inside Drupal - $owner = 'fedoraAdmin'; + // We are annonamous user. + elseif ($user->uid == 0) { + $owner = 'anonymous'; } } @@ -1202,7 +1510,7 @@ RDF; $root_element->setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:schemaLocation", "info:fedora/fedora-system:def/foxml# http://www.fedora.info/definitions/1/0/foxml1-1.xsd"); $foxml->appendChild($root_element); - // FOXML object properties section + // FOXML object properties section. $object_properties = $foxml->createElementNS("info:fedora/fedora-system:def/foxml#", "foxml:objectProperties"); $state_property = $foxml->createElementNS("info:fedora/fedora-system:def/foxml#", "foxml:property"); $state_property->setAttribute("NAME", "info:fedora/fedora-system:def/model#state"); @@ -1226,10 +1534,12 @@ RDF; /** * ingest new item + * * @param type $pid * @param type $state * @param type $label * @param type $owner + * * @return type */ static function ingest_new_item($pid = '', $state = 'A', $label = '', $owner = '') { @@ -1238,7 +1548,9 @@ RDF; /** * fedora item exists + * * @param type $pid + * * @return type */ static function fedora_item_exists($pid) { @@ -1246,13 +1558,35 @@ RDF; return $item->exists(); } - /* * ****************************************************** - * Relationship Functions - * ****************************************************** */ - /** - * Returns an associative array of relationships that this item has - * in its RELS-EXT. + * This function will retrieve the ownerId + * object property from Fedora using the SOAP API. + * + * @param string $PID + * The Fedora PID to retrieve the */ -} + static function getOwnerId($PID) { + $params = array( + 'query' => array( + 'conditions' => array( + array( + 'property' => 'pid', + 'operator' => 'eq', + 'value' => $PID, + ), + ), + 'terms' => '', + ), + 'resultFields' => array('pid', 'ownerId'), + 'maxResults' => 1, + ); + $response = Fedora_Item::soap_call('findObjects', $params); + + if (!$response) { + return FALSE; + } + $ownerId = $response->result->resultList->objectFields->ownerId; + return $ownerId; + } +} diff --git a/api/fedora_utils.inc b/api/fedora_utils.inc index a730d7a4..dbf28b81 100644 --- a/api/fedora_utils.inc +++ b/api/fedora_utils.inc @@ -1,23 +1,23 @@ 63) + if (strlen($new_dsid) > 63) { $new_dsid = substr($new_dsid, -63); + } - if (preg_match('/^[^a-zA-Z]/', $dsid)) + if (preg_match('/^[^a-zA-Z]/', $dsid)) { $new_dsid = 'x' . $new_dsid; + } - if (strlen($new_dsid) == 0) + if (strlen($new_dsid) == 0) { $new_dsid = 'item' . rand(1, 100); + } return $new_dsid; } @@ -229,9 +245,8 @@ function fix_dsid($dsid) { /** * Function: get_collections_as_option_array * - * Description: Returns an associative array of all collection objects in Fedora instance - * * @return array + * Returns an associative array of all collection objects in Fedora instance */ function get_collections_as_option_array() { module_load_include('inc', 'fedora_repository', 'api/fedora_utils'); @@ -244,7 +259,7 @@ function get_collections_as_option_array() { and $object ) order by $title'; $url = variable_get('fedora_repository_url', 'http://localhost:8080/fedora/risearch'); - + $options = array( 'type' => 'tuples', 'flush' => 'TRUE', @@ -254,9 +269,9 @@ function get_collections_as_option_array() { 'stream' => 'on', 'query' => $query, ); - //The url function will take care of URL encoding... + // The url function will take care of URL encoding. $content = do_curl(url($url, array('query' => $options))); - + $list = explode("\n", $content); array_shift($list); $list = preg_replace('/info:fedora\//', '', $list); @@ -264,7 +279,8 @@ function get_collections_as_option_array() { $trimmed_names[] = trim($namespace); } $options = array(); - foreach ($list as $item) { //removes blanks + // Removes blanks. + foreach ($list as $item) { if ($item) { $parts = explode(',', $item); $namespace = explode(':', $parts[0]); @@ -283,46 +299,75 @@ function get_collections_as_option_array() { /** * Function: get_content_models_as_option_array * - * Description: Returns an associative array of all available content models in Fedora instance - * * @return array + * associative array of all available content models in Fedora instance */ function get_content_models_as_option_array() { - module_load_include('inc', 'fedora_repository', 'api/fedora_item'); - module_load_include('inc', 'fedora_repository', 'api/fedora_utils'); - $restricted = variable_get('fedora_namespace_restriction_enforced', TRUE); - $allowed_string = variable_get('fedora_pids_allowed', 'default: demo: changeme: islandora:'); - $namespaces = explode(':', $allowed_string); - foreach ($namespaces as $namespace) { - if ($namespace) { - $allowed[] = trim($namespace); - } + module_load_include('inc', 'fedora_repository', 'api/fedora_item'); + module_load_include('inc', 'fedora_repository', 'api/fedora_utils'); + $restricted = variable_get('fedora_namespace_restriction_enforced', TRUE); + $allowed_string = variable_get('fedora_pids_allowed', 'default: demo: changeme: islandora:'); + $namespaces = explode(':', $allowed_string); + foreach ($namespaces as $namespace) { + if ($namespace) { + $allowed[] = trim($namespace); } - $query = 'select $object $title from <#ri> - where ($object $title - and ($object - or $object ) - and $object ) - order by $title'; - - $url = variable_get('fedora_repository_url', 'http://localhost:8080/fedora/risearch'); - $url .= "?type=tuples&flush=TRUE&format=csv&limit=1000&lang=itql&stream=on&query="; - $content = do_curl($url . htmlentities(urlencode($query))); - $list = explode("\n", $content); - array_shift($list); - $list = preg_replace('/info:fedora\//', '', $list); - foreach ($list as $item) { //removes blanks - if ($item) { - $parts = explode(',', $item); - $nameparts = explode(':', $parts[0]); - if (!$restricted || in_array($nameparts[0], $allowed)) { - - if (!preg_match('/fedora-system/', $nameparts[0])) { - $options[$parts[0]] = $parts[1] . ' ~ ' . $parts[0]; - } - } + } + $query = 'select $object $title from <#ri> + where ($object $title + and ($object + or $object ) + and $object ) + order by $title'; + + $url = variable_get('fedora_repository_url', 'http://localhost:8080/fedora/risearch'); + $url .= "?type=tuples&flush=TRUE&format=csv&limit=1000&lang=itql&stream=on&query="; + $content = do_curl($url . htmlentities(urlencode($query))); + $list = explode("\n", $content); + array_shift($list); + $list = preg_replace('/info:fedora\//', '', $list); + // Removes blanks. + foreach ($list as $item) { + if ($item) { + $parts = explode(',', $item); + $nameparts = explode(':', $parts[0]); + if (!$restricted || in_array($nameparts[0], $allowed)) { + if (!preg_match('/fedora-system/', $nameparts[0])) { + $options[$parts[0]] = $parts[1] . ' ~ ' . $parts[0]; } + } } + } + + return $options; +} - return $options; -} \ No newline at end of file +/** + * This function will retrieve the collections that the given PID belongs to. + * + * @param string $PID + * The PID to find the parents of. + * + * @return array + * $object_PIDs the list of PIDs of the collections that the + * indicated object is a member of. + */ +function get_parent_collections_from_pid($PID) { + $query_string = 'select $parent from <#ri> + where ($object $parent + or $object $parent) + and $object \'' . $PID . '\' + order by $object'; + + $query_string = htmlentities(urlencode($query_string)); + $url = variable_get('fedora_repository_url', 'http://localhost:8080/fedora/risearch'); + $url .= '?type=tuples&flush=true&format=csv&limit=13000&lang=itql&stream=on&query=' . $query_string; + + $content = do_curl($url, TRUE); + + $results = explode("\n", $content); + $object_PIDs = preg_replace('/^info:fedora\/|"parent"| /', '', $results); + $object_PIDs = array_values(array_filter($object_PIDs)); + + return $object_PIDs; +} diff --git a/api/tuque.inc b/api/tuque.inc index 553c4fe6..e53f6d5d 100644 --- a/api/tuque.inc +++ b/api/tuque.inc @@ -2,7 +2,7 @@ $islandora_module_path = drupal_get_path('module', 'fedora_repository'); -//do this until we expost these in a module or library +//do this until we export these in a module or library @include_once 'sites/all/libraries/tuque/Datastream.php'; @include_once 'sites/all/libraries/tuque/FedoraApi.php'; @include_once 'sites/all/libraries/tuque/FedoraApiSerializer.php'; @@ -67,7 +67,7 @@ class IslandoraTuque { } if (!isset($url)) { - $url = variable_get('islandora_base_url', 'http://localhost:8080/fedora'); + $url = variable_get('fedora_base_url', 'http://localhost:8080/fedora'); } if(self::exists()) { diff --git a/collection_policy.xsd b/collection_policy.xsd index d5ea6637..35a52bdb 100644 --- a/collection_policy.xsd +++ b/collection_policy.xsd @@ -45,4 +45,4 @@ - \ No newline at end of file + diff --git a/fedora_repository.api.php b/fedora_repository.api.php new file mode 100644 index 00000000..190c9ec1 --- /dev/null +++ b/fedora_repository.api.php @@ -0,0 +1,137 @@ + 'tabpage', + '#title' => t('A TITLE'), + '#content' => 'content') + ); + + return $tabset; +} + +/** + * Implements hook_postprocess_solution_pack(). + * This hook fires after the batch job to ingest a solution pack finishes. + * + * @param string $module + * Name of the module that spcified the solution pack. + */ +function hook_fedora_repository_postprocess_solution_pack($module) { + + // Do something that requires the objects to be ingested ie. add XACML. + return; + +} + +/** + * Implements hook_required_fedora_objects(). + * This hook lets one add objects to the repository through the + * solution pack interface. + * + * @return array + * array( 'path-to-foxml-file', 'pid', 'dsid', 'path-to-datastream-file', + * int dsversion, boolean required) + */ +function hook_required_fedora_objects() { + return array( + 'fedora_repository' => array( + 'module' => 'fedora_repository', + 'title' => 'Islandora Core', + 'objects' => array( + array( + 'pid' => 'islandora:collectionCModel', + 'label' => 'Islandora Collection Content Model', + 'dsid' => 'ISLANDORACM', + 'datastream_file' => "./$module_path/content_models/COLLECTIONCM.xml", + 'dsversion' => 2, + 'cmodel' => 'fedora-system:ContentModel-3.0', + ), + array( + 'pid' => 'islandora:root', + 'label' => 'Islandora Top-level Collection', + 'cmodel' => 'islandora:collectionCModel', + 'datastreams' => array( + array( + 'dsid' => 'COLLECTION_POLICY', + 'datastream_file' => "./$module_path/collection_policies/COLLECTION-COLLECTION POLICY.xml", + ), + array( + 'dsid' => 'TN', + 'datastream_file' => "./$module_path/images/Gnome-emblem-photos.png", + 'mimetype' => 'image/png', + ), + ), + ), + ), + ), + ); +} + +/** + * Implements hook_fedora_repository_can_ingest(). + * Override ingest permissions. + * (from islandora_workflow) + * + * @deprecated + * Deprecated in favour of hook_fedora_repository_check_perm(). + * @param string $collection_pid + * The PID of the collection + * + * @return boolean + * TRUE if the user can ingest into the specified collection, FALSE otherwise. + */ +function hook_fedora_repository_can_ingest($collection_pid) { + + module_load_include('inc', 'islandora_workflow', 'islandora_workflow.permissions'); + return (islandora_workflow_user_collection_permission_check($collection_pid) !== FALSE); + +} + +/** + * Implements hook_fedora_repository_check_perm(). + * + * Hook to allow other modules to allow or deny operations on conditions other + * than the explicit Drupal permissions. + * + * @param string $op + * A string representing the operation to be performed. + * @param string|null $pid + * A string containing the Fedora PID on which the operation is to be + * performed. The (default) value of NULL will use the PID indicated by the + * fedora_repository_pid Drupal variable. + * @param object|null $as_user + * An object representing the user for whom to check the permissions (as + * given by user_load or the $user global). The (default) value of NULL will + * cause permissions to be evaluated for the current user (from the $user + * global). + * + * @return boolean|null + * Either a boolean permitting (TRUE) or forbidding (FALSE) an operation, or + * NULL to make no assertion. + */ +function hook_fedora_repository_check_perm($op, $pid = NULL, $as_user = NULL) { + return NULL; +} diff --git a/fedora_repository.info b/fedora_repository.info index c18dc34a..9b66513a 100644 --- a/fedora_repository.info +++ b/fedora_repository.info @@ -4,5 +4,5 @@ dependencies[] = tabs dependencies[] = islandora_content_model_forms description = Shows a list of items in a fedora collection. package = Islandora -version = 6.x-12.2.0 +version = 6.x-12.3.0-RC1 core = 6.x diff --git a/fedora_repository.install b/fedora_repository.install index 0840e2e4..c4b3ad85 100644 --- a/fedora_repository.install +++ b/fedora_repository.install @@ -1,106 +1,134 @@ -collection settings are correct.', array('@collection-settings' => url('admin/settings/fedora_repository'))); - } - else { - $requirements['fedora-repository']['value'] = $t("Available"); - $requirements['fedora-repository']['severity'] = REQUIREMENT_OK; - } - } - - return $requirements; -} + if (!method_exists('DOMDocument', 'loadHTML')) { + $requirements['dom']['value'] = $t("Not installed"); + $requirements['dom']['severity'] = REQUIREMENT_ERROR; + $requirements['dom']['description'] = $t("Ensure that the PHP DOM XML extension is installed."); + } + else { + $requirements['dom']['value'] = $t("Installed"); + $requirements['dom']['severity'] = REQUIREMENT_OK; + } + + // Test for XSLT + $requirements['xsl']['title'] = $t("PHP XSL extension library"); + if (!class_exists('XSLTProcessor')) { + $requirements['xslt']['value'] = $t("Not installed"); + $requirements['xslt']['severity'] = REQUIREMENT_ERROR; + $requirements['xslt']['description'] = $t("Ensure that the PHP XSL extension is installed."); + } + else { + $requirements['xslt']['value'] = $t("Installed"); + $requirements['xslt']['severity'] = REQUIREMENT_OK; + } + } + elseif ($phase == 'runtime') { + module_load_include('inc', 'fedora_repository', 'api/fedora_utils'); + + $requirements['fedora-repository']['title'] = $t("Fedora server"); + if (!fedora_available()) { + $requirements['fedora-repository']['value'] = $t("Not available"); + $requirements['fedora-repository']['severity'] = REQUIREMENT_ERROR; + $requirements['fedora-repository']['description'] = $t('Ensure that Fedora is running and that the collection settings are correct.', array('@collection-settings' => url('admin/settings/fedora_repository'))); + } + else { + $requirements['fedora-repository']['value'] = $t("Available"); + $requirements['fedora-repository']['severity'] = REQUIREMENT_OK; + } + } + + return $requirements; +} + +/** + * Implements hook_update_N(). + * + * This function will try and update the SOAP WSDLs + * as they were set wrong in previous releases. + */ +function fedora_repository_update_6001() { + // Get variables to check for update. + $API_A_WSDL = variable_get('fedora_soap_url', $default = NULL); + $API_M_WSDL = variable_get('fedora_soap_manage_url', $default = NULL); + + // Update API A if necessary. + $A_WSDL = parse_url($API_A_WSDL, PHP_URL_PATH) . '?' . parse_url($API_A_WSDL, PHP_URL_QUERY); + if ($A_WSDL == '/fedora/services/access?wsdl') { + variable_set('fedora_soap_url', str_replace('/fedora/services/access?wsdl', '/fedora/wsdl?api=API-A', $API_A_WSDL)); + } + + // Update API M if necessary. + $M_WSDL = parse_url($API_M_WSDL, PHP_URL_PATH) . '?' . parse_url($API_M_WSDL, PHP_URL_QUERY); + if ($M_WSDL == '/fedora/services/management?wsdl') { + variable_set('fedora_soap_manage_url', str_replace('/fedora/services/management?wsdl', '/fedora/wsdl?api=API-M', $API_M_WSDL)); + } + + return array( + array('success' => TRUE, 'query' => 'Please check your WSDL paths in Islandora\'s config, this update requires them to be set correctly: access; /fedora/wsdl?api=API-A, management; /fedora/wsdl?api=API-M'), + ); +} diff --git a/fedora_repository.module b/fedora_repository.module index 6b59ed9a..13038770 100644 --- a/fedora_repository.module +++ b/fedora_repository.module @@ -1,4 +1,8 @@ createAdminForm(); + $admin_form = new formClass(); + return $admin_form->createAdminForm(); } /** @@ -18,16 +22,20 @@ function fedora_repository_admin() { */ function fedora_repository_menu() { module_load_include('inc', 'fedora_repository', 'formClass'); - $adminMenu = new formClass(); - return $adminMenu->createMenu(); + $admin_menu = new formClass(); + return $admin_menu->createMenu(); } /** + * Implements hook_help(). * drupal hook to show help * - * @param type $path + * @param string $path + * The path to supply the help for. * @param type $arg - * @return type + * + * @return string + * The help string apropriate to the given path. */ function fedora_repository_help($path, $arg) { switch ($path) { @@ -40,19 +48,17 @@ function fedora_repository_help($path, $arg) { /** * fedora repository purge object + * * @param type $pid * @param type $name - * @return type + * + * @return type */ -function fedora_repository_purge_object($pid = NULL, $name = NULL) { - if (!user_access('purge objects and datastreams')) { +function fedora_repository_purge_object($pid, $name = NULL) { + if (!fedora_repository_check_perm('purge objects and datastreams', $pid)) { drupal_set_message(t('You do not have access to add a datastream to this object.'), 'error'); return ''; } - if ($pid == NULL) { - drupal_set_message(t('You must specify an object pid to purge an object.'), 'error'); - return ''; - } $output = t('Are you sure you wish to purge object %name %pid!
This cannot be undone
', array( '%name' => $name, '%pid' => $pid) @@ -64,15 +70,19 @@ function fedora_repository_purge_object($pid = NULL, $name = NULL) { /** * fedora repository ingest object + * + * XXX: Is this even used? + * * @param type $collection_pid * @param type $collection_label * @param type $content_model - * @return type + * + * @return type */ -function fedora_repository_ingest_object($collection_pid=NULL, $collection_label = NULL, $content_model = NULL) { +function fedora_repository_ingest_object($collection_pid, $collection_label = NULL, $content_model = NULL) { module_load_include('inc', 'fedora_repository', 'api/fedora_utils'); module_load_include('inc', 'fedora_repository', 'ObjectHelper'); - if (!user_access('ingest new fedora objects')) { + if (!fedora_repository_check_perm('ingest new fedora objects', $collection_pid)) { drupal_set_message(t('You do not have permission to ingest.'), 'error'); return ''; } @@ -94,8 +104,8 @@ function fedora_repository_ingest_object($collection_pid=NULL, $collection_label $output = drupal_get_form('fedora_repository_ingest_form', $collection_pid, $collection_label, $content_model); $breadcrumbs = array(); - $objectHelper = new ObjectHelper(); - $objectHelper->getBreadcrumbs($collection_pid, $breadcrumbs); + $object_helper = new ObjectHelper(); + $object_helper->getBreadcrumbs($collection_pid, $breadcrumbs); drupal_set_breadcrumb(array_reverse($breadcrumbs)); return $output; @@ -105,16 +115,18 @@ function fedora_repository_ingest_object($collection_pid=NULL, $collection_label * fedora repository ingest form submit * @global type $base_url * @global type $user + * * @param array $form - * @param array $form_state + * @param array $form_state */ function fedora_repository_ingest_form_submit(array $form, array &$form_state) { -//only validate the form if the submit button was pressed (other buttons may be used for AHAH - if ($form_state['ahah_submission']) { + // Only validate if the submit button was pressed, AHAH may use other buttons. + if (array_key_exists('ahah_submission', $form_state) && $form_state['ahah_submission']) { $form_state['submitted'] = FALSE; return; } - //ddebug_backtrace(); + + if ($form_state['storage']['xml'] && module_exists('islandora_content_model_forms')) { module_load_include('inc', 'islandora_content_model_forms', 'IngestObjectMetadataForm'); $xml_form = new IngestObjectMetadataForm(); @@ -125,7 +137,6 @@ function fedora_repository_ingest_form_submit(array $form, array &$form_state) { module_load_include('inc', 'fedora_repository', 'CollectionClass'); module_load_include('inc', 'fedora_repository', 'CollectionPolicy'); module_load_include('inc', 'fedora_repository', 'ContentModel'); - $contentModelPid = ContentModel::getPidFromIdentifier($form_state['values']['models']); $contentModelDsid = ContentModel::getDSIDFromIdentifier($form_state['values']['models']); $err = TRUE; @@ -143,7 +154,8 @@ function fedora_repository_ingest_form_submit(array $form, array &$form_state) { $err = (!$cm->execFormHandler($form_state['values'], $form_state)); - $_SESSION['fedora_ingest_files'] = ''; //empty this variable + // Empty this variable. + $_SESSION['fedora_ingest_files'] = ''; $attr = $cm->getIngestFormAttributes(); $redirect = $attr['redirect']; @@ -162,17 +174,20 @@ function fedora_repository_ingest_form_submit(array $form, array &$form_state) { /** * fedora repository ingest form validate + * * @param type $form * @param type $form_state - * @return type + * + * @return type */ function fedora_repository_ingest_form_validate($form, &$form_state) { -//only validate the form if the submit button was pressed (other buttons may be used for AHAH - if ($form_state['ahah_submission']) { + // Only validate if the submit button was pressed, AHAH may use other buttons. + $is_ahah_submission = (array_key_exists('ahah_submission', $form_state) && $form_state['ahah_submission']); + if ($is_ahah_submission) { $form_state['submitted'] = FALSE; return; } - if (strpos($form_state['clicked_button']['#id'], 'edit-submit') === 0 && $form_state['ahah_submission'] != 1) { + if (strpos($form_state['clicked_button']['#id'], 'edit-submit') === 0 && !$is_ahah_submission) { switch ($form_state['storage']['step']) { case 1: $form_state['storage']['step']++; @@ -180,28 +195,28 @@ function fedora_repository_ingest_form_validate($form, &$form_state) { break; case 2: -// XML based form. + // XML based form. if ($form_state['storage']['xml']) { module_load_include('inc', 'xml_form_api', 'XMLForm'); $xml_form = new XMLForm($form_state); $xml_form->validate($form, $form_state); } -// Get the uploaded file. + // Get the uploaded file. $validators = array(); $ifl = 'ingest-file-location'; - $fileObject = NULL; - //Check if it's already there; this is what upload_element provides. + $file_object = NULL; + // Check if it's already there; this is what upload_element provides. if (is_a($form_state['values'][$ifl], 'stdClass') && property_exists($form_state['values'][$ifl], '')) { - $fileObject = $form_state['values'][$ifl]; + $file_object = $form_state['values'][$ifl]; } elseif (!empty($_FILES['files']['name'][$ifl])) { - $fileObject = file_save_upload($ifl, $validators); + $file_object = file_save_upload($ifl, $validators); } - if ($fileObject !== NULL && property_exists($fileObject, 'filepath')) { - file_move($fileObject->filepath, 0, 'FILE_EXISTS_RENAME'); - $form_state['values'][$ifl] = $fileObject->filepath; + if ($file_object !== NULL && property_exists($file_object, 'filepath')) { + file_move($file_object->filepath, 0, 'FILE_EXISTS_RENAME'); + $form_state['values'][$ifl] = $file_object->filepath; } if (isset($form_state['values'][$ifl]) && file_exists($form_state['values'][$ifl])) { @@ -221,8 +236,8 @@ function fedora_repository_ingest_form_validate($form, &$form_state) { if (!empty($file)) { if (!in_array($dformat, $allowedMimeTypes)) { - form_set_error($ifl, - t('The uploaded file\'s mimetype (@mime) is not associated with this Content Model. The allowed types are: @allowed', array( + form_set_error($ifl, + t("The uploaded file's mimetype (@mime) is not associated with this Content Model. The allowed types are: @allowed", array( '@mime' => $dformat, '@allowed' => implode(', ', $allowedMimeTypes), ))); @@ -246,44 +261,48 @@ function fedora_repository_ingest_form_validate($form, &$form_state) { /** * fedora repository ingest form + * * @param type $form_state * @param type $collection_pid * @param type $collection_label * @param type $content_model - * @return type + * + * @return type */ function fedora_repository_ingest_form(&$form_state, $collection_pid, $collection_label = NULL, $content_model = NULL) { module_load_include('inc', 'fedora_repository', 'formClass'); -// For the sake of easily maintaining the module in different core versions create our own form_values variable. + // For the sake of easily maintaining the module in different core versions + // create our own form_values variable. if (empty($form_state['storage']['step'])) { $form_state['storage']['step'] = 1; } - $ingestForm = new formClass(); + $ingest_form = new formClass(); $form_state['storage']['content_model'] = $content_model; $form_state['storage']['collection_pid'] = $collection_pid; - $form = $ingestForm->createIngestForm($collection_pid, $collection_label, $form_state); + $form = $ingest_form->createIngestForm($collection_pid, $collection_label, $form_state); return $form; } /** * fedora repository purge object form + * * @global type $base_url + * * @param type $form_state * @param type $pid * @param type $referrer - * @return type + * + * @return mixed + * NULL or the form array. */ function fedora_repository_purge_object_form(&$form_state, $pid, $referrer = NULL) { global $base_url; - if (!user_access('purge objects and datastreams')) { - return NULL; - } - if ($pid == NULL) { + if (!fedora_repository_check_perm('purge objects and datastreams', $pid)) { return NULL; } $form['pid'] = array( '#type' => 'hidden', - '#value' => "$pid" + '#value' => "$pid", ); if (!strstr(drupal_get_destination(), urlencode('fedora/repository'))) { $form['referrer'] = array( @@ -292,50 +311,47 @@ function fedora_repository_purge_object_form(&$form_state, $pid, $referrer = NUL ); } if (!isset($form_state['storage']['confirm'])) { -// do your normal $form definition here - - + // Do your normal $form definition here. $form['submit'] = array( '#type' => 'image_button', '#src' => drupal_get_path('module', 'fedora_repository') . '/images/purge_big.png', '#value' => t('Purge'), '#suffix' => 'Purge this object', ); - if (!empty($collectionPid)) { - $collectionPid = $_SESSION['fedora_collection']; - } -//$form['#rebuild'] = $false; return $form; } else { -// ALSO do $form definition here. Your final submit handler (after user clicks Yes, I Confirm) will only see $form_state info defined here. Form you create here passed as param1 to confirm_form + /* ALSO do $form definition here. Your final submit handler + * (after user clicks Yes, I Confirm) + * will only see $form_state info defined here. + * Form you create here passed as param1 to confirm_form*/ - return confirm_form($form, 'Confirm Purge Object', $referrer, 'Are you sure you want to delete this object? This action cannot be undone.', 'Delete', 'Cancel'); //Had better luck leaving off last param 'name' + // Had better luck leaving off last param 'name'. + return confirm_form($form, 'Confirm Purge Object', $referrer, 'Are you sure you want to delete this object? This action cannot be undone.', 'Delete', 'Cancel'); } + return $form; } /** * add stream - * @param type $collection_pid + * + * @param type $pid * @param type $collectionName - * @return type + * + * @return type */ -function add_stream($collection_pid=NULL, $collectionName=NULL) { +function add_stream($pid, $collectionName=NULL) { module_load_include('inc', 'fedora_repository', 'api/fedora_utils'); if (!valid_pid($collection_pid)) { drupal_set_message(t("This PID is not valid!"), 'error'); return ' '; } - if (!user_access('ingest new fedora objects')) { + if (!fedora_repository_check_perm('add fedora datastreams', $pid)) { drupal_set_message(t('You do not have permission to ingest.'), 'error'); return ''; } - if ($collection_pid == NULL) { - drupal_set_message(t('You must specify an collection object pid to ingest an object.'), 'error'); - return ''; - } $output .= drupal_get_form('fedora_repository_add_stream_form', $pid); return $output; @@ -344,9 +360,11 @@ function add_stream($collection_pid=NULL, $collectionName=NULL) { /** * add stream form submit * @global type $base_url + * * @param type $form * @param type $form_state - * @return type + * + * @return type */ function add_stream_form_submit($form, &$form_state) { global $base_url; @@ -354,14 +372,15 @@ function add_stream_form_submit($form, &$form_state) { $form_state['rebuild'] = TRUE; return; } - + module_load_include('inc', 'fedora_repository', 'ObjectHelper'); module_load_include('inc', 'fedora_repository', 'api/fedora_item'); $pathToModule = drupal_get_path('module', 'fedora_repository'); $pid = $form_state['values']['pid']; $dsid = $form_state['values']['stream_id']; - $dsLabel = $form_state['values']['stream_label'] . substr($form_state['storage']['stream_url'], strrpos($form_state['storage']['stream_url'], '.')); // Add the file extention to the end of the label.; + // Add the file extention to the end of the label. + $dsLabel = $form_state['values']['stream_label'] . substr($form_state['storage']['stream_url'], strrpos($form_state['storage']['stream_url'], '.')); try { $item = new Fedora_Item($pid); @@ -377,15 +396,18 @@ function add_stream_form_submit($form, &$form_state) { drupal_set_message(t('@message', array('@message' => check_plain($e->getMessage()))), 'error'); return; } - unset($form_state['storage']); //Using storage; need to unset it for forms to work properly... + // Using storage; need to unset it for forms to work properly... + unset($form_state['storage']); $form_state['rebuild'] = TRUE; } /** * add stream form + * * @param type $form_state * @param type $pid - * @return type + * + * @return type */ function add_stream_form(&$form_state, $pid) { module_load_include('inc', 'fedora_repository', 'formClass'); @@ -395,9 +417,11 @@ function add_stream_form(&$form_state, $pid) { /** * add stream form validate + * * @param type $form * @param type $form_state - * @return type + * + * @return type */ function add_stream_form_validate($form, &$form_state) { module_load_include('inc', 'fedora_repository', 'MimeClass'); @@ -428,14 +452,14 @@ function add_stream_form_validate($form, &$form_state) { // 'file_validate_image_resolution' => array('85x85'), // 'file_validate_size' => array(30 * 1024), ); - + $controlGroup = $form_state['storage']['control_group'] = $form_state['values']['control_group']; if ((($controlGroup && in_array($controlGroup, array('X', 'M'))) || !$controlGroup) && (($fileObject = file_save_upload('add-stream-file-location', $validators)))) { // Move the uploaded file to Drupal's files directory. $file_path = $fileObject->filepath; file_move($file_path, 0, FILE_EXISTS_RENAME); $form_state['values']['add-stream-file-location'] = $file_path; - + $form_state['storage']['stream_url'] = file_create_url($file_path); } elseif ($controlGroup && in_array($controlGroup, array('M', 'R', 'E')) && ($ref = $form_state['values']['ds_reference'])) { @@ -444,10 +468,10 @@ function add_stream_form_validate($form, &$form_state) { else { form_set_error('', t('No file given when "X" or "M", or no reference given when "M", "R" or "E".')); } - + $mimeClass = new MimeClass(); $mimetype = $form_state['storage']['ds_mimetype'] = $mimeClass->getType($form_state['storage']['stream_url']); - + if (!$controlGroup) { if ($mimetype == 'text/xml') { $form_state['storage']['control_group'] = 'X'; @@ -456,7 +480,7 @@ function add_stream_form_validate($form, &$form_state) { $form_state['storage']['control_group'] = 'M'; } } - + // TODO: Add error checking here. $form_state['rebuild'] = FALSE; } @@ -464,10 +488,12 @@ function add_stream_form_validate($form, &$form_state) { /** * fedora repository purge stream * @global type $user + * * @param type $pid * @param type $dsId * @param type $name - * @return type + * + * @return type */ function fedora_repository_purge_stream($pid = NULL, $dsId = NULL, $name = NULL) { module_load_include('inc', 'fedora_repository', 'ObjectHelper'); @@ -476,7 +502,7 @@ function fedora_repository_purge_stream($pid = NULL, $dsId = NULL, $name = NULL) drupal_set_message(t('You must specify an object pid and DataStream ID to purge a datastream'), 'error'); return ' '; } - if (!fedora_repository_access(OBJECTHELPER :: $PURGE_FEDORA_OBJECTSANDSTREAMS, $pid, $user)) { + if (!fedora_repository_check_perm(OBJECTHELPER :: $PURGE_FEDORA_OBJECTSANDSTREAMS, $pid, $user)) { drupal_set_message(t("You do not have access to Fedora objects within the attempted namespace or you do not have permission to purge objects."), 'error'); return ' '; } @@ -488,18 +514,26 @@ function fedora_repository_purge_stream($pid = NULL, $dsId = NULL, $name = NULL) return $output; } +/** + * Validates the purge object form. + * + * @param array $form + * The form to validate. + * @param array $form_state + * The state of the form to validate + */ function fedora_repository_purge_object_form_validate($form, &$form_state) { module_load_include('inc', 'fedora_repository', 'api/fedora_collection'); $pid = $form_state['values']['pid']; - $objectHelper = new ObjectHelper(); - $contentModels = $objectHelper->get_content_models_list($pid); - foreach ($contentModels as $contentModel) { - if ($contentModel->pid == 'islandora:collectionCModel') { - $member_pids = get_related_items_as_array($pid, 'isMemberOfCollection'); + $object_helper = new ObjectHelper(); + $content_models = $object_helper->get_content_models_list($pid); + foreach ($content_models as $content_model) { + if ($content_model->pid == 'islandora:collectionCModel') { + $member_pids = get_related_items_as_array($pid, 'isMemberOfCollection', 10000, 0, FALSE); if (is_array($member_pids) && ! empty($member_pids)) { - form_set_error('new_collection_pid', t("Please purge all members of this collection before deleting the collection itself.")); - return; + form_set_error('new_collection_pid', t("Please purge all members of this collection before deleting the collection itself.")); + return; } } } @@ -507,27 +541,37 @@ function fedora_repository_purge_object_form_validate($form, &$form_state) { /** * fedora repository purge object form submit + * * @param type $form + * The submited form. * @param type $form_state - * @return type + * The state of the submitted form. */ function fedora_repository_purge_object_form_submit($form, &$form_state) { module_load_include('inc', 'fedora_repository', 'ConnectionHelper'); + module_load_include('inc', 'fedora_repository', 'api/fedora_utils'); + $pid = $form_state['values']['pid']; + $parents = get_parent_collections_from_pid($pid); + if (!isset($form_state['storage']['confirm'])) { - $form_state['storage']['confirm'] = TRUE; // this will cause the form to be rebuilt, entering the confirm part of the form - $form_state['rebuild'] = TRUE; // along with this + /* This will cause the form to be rebuilt, + * entering the confirm part of the form.*/ + $form_state['storage']['confirm'] = TRUE; + // Along with this. + $form_state['rebuild'] = TRUE; } else { -// this is where you do your processing after they have pressed the confirm button + /* This is where you do your processing after + * they have pressed the confirm button.*/ $params = array( "pid" => $pid, "logMessage" => "Purged", - "force" => "" + "force" => "", ); try { - $soapHelper = new ConnectionHelper(); - $client = $soapHelper->getSoapClient(variable_get('fedora_soap_manage_url', 'http://localhost:8080/fedora/wsdl?api=API-M')); + $soap_helper = new ConnectionHelper(); + $client = $soap_helper->getSoapClient(variable_get('fedora_soap_manage_url', 'http://localhost:8080/fedora/wsdl?api=API-M')); $object = $client->__soapCall('purgeObject', array($params)); unset($form_state['storage']['confirm']); } catch (exception $e) { @@ -539,39 +583,33 @@ function fedora_repository_purge_object_form_submit($form, &$form_state) { } return; } - if (!empty($form_state['values']['referrer'])) { - $form_state['redirect'] = $form_state['values']['referrer']; - } - elseif (empty($collectionPid) && !empty($_SESSION['fedora_collection']) && $_SESSION['fedora_collection'] != $pid) { - $collectionPid = $_SESSION['fedora_collection']; - $form_state['redirect'] = "fedora/repository/$collectionPid/"; - } - else { - $form_state['redirect'] = 'fedora/repository/'; - } + // Set the form's redirect to its first identifiable parent collection. + $form_state['redirect'] = "fedora/repository/$parents[0]/"; } } /** * fedora repository purge stream form + * * @param type $form_state * @param type $pid * @param type $dsId - * @return type + * + * @return type */ function fedora_repository_purge_stream_form(&$form_state, $pid, $dsId) { $form['pid'] = array( '#type' => 'hidden', - '#value' => "$pid" + '#value' => "$pid", ); $form['dsid'] = array( '#type' => 'hidden', - '#value' => "$dsId" + '#value' => "$dsId", ); $form['submit'] = array( '#type' => 'submit', - '#value' => t('Purge') + '#value' => t('Purge'), ); return $form; @@ -579,9 +617,11 @@ function fedora_repository_purge_stream_form(&$form_state, $pid, $dsId) { /** * fedora repository purge stream form submit + * * @global type $base_url + * * @param type $form - * @param array $form_state + * @param array $form_state */ function fedora_repository_purge_stream_form_submit($form, &$form_state) { global $base_url; @@ -597,6 +637,13 @@ function fedora_repository_purge_stream_form_submit($form, &$form_state) { $form_state['redirect'] = "fedora/repository/$pid"; } +/** + * + * @param unknown_type $form_state + * @param unknown_type $pid + * @param unknown_type $dsid + * @param unknown_type $label + */ function fedora_repository_download_datastream_form(&$form_state, $pid, $dsid, $label) { module_load_include('inc', 'fedora_repository', 'ObjectHelper'); $form = array( @@ -606,8 +653,8 @@ function fedora_repository_download_datastream_form(&$form_state, $pid, $dsid, $ '#value' => t('Download'), ), ); - - if (user_access(ObjectHelper::$EDIT_FEDORA_METADATA)) { + + if (fedora_repository_check_perm(ObjectHelper::$EDIT_FEDORA_METADATA, $pid)) { $item = new Fedora_Item($pid); $versions = $item->get_datastream_history($dsid); $version_array = array(); @@ -619,10 +666,10 @@ function fedora_repository_download_datastream_form(&$form_state, $pid, $dsid, $ else { $version_array[] = $versions->createDate; } - + if (count($version_array) > 1) { $form['#attributes'] = array( - 'onsubmit' => 'this.action="' . $form['#action'] . '/" + this.version.value;' + 'onsubmit' => 'this.action="' . $form['#action'] . '/" + this.version.value;', ); $form['version'] = array( '#type' => 'select', @@ -630,17 +677,19 @@ function fedora_repository_download_datastream_form(&$form_state, $pid, $dsid, $ ); } } - + return $form; } /** * fedora repository replace stream + * * @param type $pid * @param type $dsId * @param type $dsLabel * @param type $collectionName - * @return type + * + * @return string */ function fedora_repository_replace_stream($pid, $dsId, $dsLabel = '', $collectionName = NULL) { if ($pid == NULL || $dsId == NULL) { @@ -654,11 +703,13 @@ function fedora_repository_replace_stream($pid, $dsId, $dsLabel = '', $collectio /** * fedora repository replace stream form + * * @param type $form_state * @param type $pid * @param type $dsId * @param type $dsLabel - * @return type + * + * @return type */ function fedora_repository_replace_stream_form(&$form_state, $pid, $dsId, $dsLabel) { module_load_include('inc', 'fedora_repository', 'formClass'); @@ -670,13 +721,13 @@ function fedora_repository_replace_stream_form(&$form_state, $pid, $dsId, $dsLab * fedora repository replace stream form validate * @param type $form * @param type $form_state - * @return type + * @return type */ function fedora_repository_replace_stream_form_validate($form, &$form_state) { // If a file was uploaded, process it. if (isset($_FILES['files']) && is_uploaded_file($_FILES['files']['tmp_name']['file'])) { - // attempt to save the uploaded file + // Attempt to save the uploaded file. $file = file_save_upload('file', array(), file_directory_path()); // set error is file was not uploaded @@ -684,7 +735,7 @@ function fedora_repository_replace_stream_form_validate($form, &$form_state) { form_set_error('file', 'Error uploading file.'); return; } - + /* ----------------------------------------------------------------- * TODO: need a better way to get mimetypes */ @@ -692,7 +743,7 @@ function fedora_repository_replace_stream_form_validate($form, &$form_state) { module_load_include('inc', 'fedora_repository', 'MimeClass'); $mime = new MimeClass(); $mimetype = $form_state['storage']['mime_type'] = $mime->getType($file->filepath); - + if ($mimetype == 'text/xml' && !DOMDocument::load($file->filepath)) { form_set_error('file', 'Invalid XML format. (XML could not be parsed)'); return; @@ -710,7 +761,7 @@ function fedora_repository_replace_stream_form_validate($form, &$form_state) { * fedora repository replace stream form submit * @global type $base_url * @param type $form - * @param array $form_state + * @param array $form_state */ function fedora_repository_replace_stream_form_submit($form, &$form_state) { $file = $form_state['values']['file']; @@ -718,11 +769,11 @@ function fedora_repository_replace_stream_form_submit($form, &$form_state) { $pid = $form_state['values']['pid']; $dsid = $form_state['values']['dsId']; $dsLabel = $form_state['values']['dsLabel']; - - $streamUrl = ($file !== NULL) ? + + $streamUrl = ($file !== NULL) ? file_create_url($file->filepath): url($form_state['values']['reference'], array('absolute' => TRUE)); - + // Remove the original file extension from the label and add the new one // use strrpos to get the last dot if (($indexOfDot = strrpos($dsLabel, '.')) !== FALSE) { @@ -745,7 +796,7 @@ function fedora_repository_replace_stream_form_submit($form, &$form_state) { * @global type $user * @param type $pid * @param type $dsId - * @return type + * @return type */ function fedora_repository_edit_qdc_page($pid = NULL, $dsId = NULL) { module_load_include('inc', 'fedora_repository', 'ObjectHelper'); @@ -754,7 +805,7 @@ function fedora_repository_edit_qdc_page($pid = NULL, $dsId = NULL) { drupal_set_message(t('You must specify an object pid and a Dublin Core DataStream ID to edit metadata'), 'error'); return ' '; } - if (!fedora_repository_access(OBJECTHELPER :: $EDIT_FEDORA_METADATA, $pid, $user)) { + if (!fedora_repository_check_perm(OBJECTHELPER :: $EDIT_FEDORA_METADATA, $pid, $user)) { drupal_set_message(t("You do not have access to Fedora objects within the attempted namespace or you do not have permission to edit meta data for this object."), 'error'); return ' '; } @@ -764,12 +815,14 @@ function fedora_repository_edit_qdc_page($pid = NULL, $dsId = NULL) { } /** - * fedora repository edit qdc form + * fedora repository edit qdc form * @global type $user + * * @param type $form_state * @param type $pid * @param type $dsId - * @return type + * + * @return type */ function fedora_repository_edit_qdc_form(&$form_state, $pid, $dsId = NULL) { module_load_include('inc', 'fedora_repository', 'ContentModel'); @@ -778,7 +831,7 @@ function fedora_repository_edit_qdc_form(&$form_state, $pid, $dsId = NULL) { drupal_set_message(t('You must specify an object pid!'), 'error'); } global $user; - if (!fedora_repository_access(OBJECTHELPER :: $EDIT_FEDORA_METADATA, $pid, $user)) { + if (!fedora_repository_check_perm(OBJECTHELPER :: $EDIT_FEDORA_METADATA, $pid, $user)) { drupal_set_message(t("You do not have access to Fedora objects within the attempted namespace or you do not have permission to edit meta data for this object."), 'error'); return ' '; } @@ -787,26 +840,28 @@ function fedora_repository_edit_qdc_form(&$form_state, $pid, $dsId = NULL) { module_load_include('inc', 'fedora_repository', 'ConnectionHelper'); $soapHelper = new ConnectionHelper(); $client = $soapHelper->getSoapClient(variable_get('fedora_soap_url', 'http://localhost:8080/fedora/services/access?wsdl')); - -// Check if there is a custom edit metadata function defined in the content model. + + // Check if there's a custom edit metadata function in the content model. $output = ''; if (($cm = ContentModel::loadFromObject($pid)) !== FALSE) { $output = $cm->buildEditMetadataForm($pid, $dsId); } if (empty($output)) { -// There is no custom function, so just load the standard QDC form. + // There is no custom function, so just load the standard QDC form. $metaDataForm = new formClass(); -//currently we only edit the dc metadata. If you defined a custom form with a custom handler you are sol for now. - return $metaDataForm->createMetaDataForm($pid, $dsId, $client, $form_state); + // Currently we only edit the dc metadata. + // If you defined a custom form with a custom handler you are sol for now. + $output = $metaDataForm->createMetaDataForm($pid, $dsId, $client, $form_state); } return $output; } /** * fedora repository edit qdc form validate + * * @param type $form - * @param boolean $form_state + * @param boolean $form_state */ function fedora_repository_edit_qdc_form_validate($form, &$form_state) { if ($form_state['storage']['xml']) { @@ -821,12 +876,14 @@ function fedora_repository_edit_qdc_form_validate($form, &$form_state) { } /** - * Check if there is a custom edit metadata function defined in the content model. If so, - * call it, if not do the submit action for the standard QDC metadata. Custom forms will - * need to implement their own equivalent to the FormClass->updateMetaData function + * Check if there is a custom edit metadata function defined in the + * content model. If so, call it, if not do the submit action for the + * standard QDC metadata. Custom forms willneed to implement their own + * equivalent to the FormClass->updateMetaData function * * @param array $form * @param array $form_state + * * @return */ function fedora_repository_edit_qdc_form_submit($form, &$form_state) { @@ -843,7 +900,8 @@ function fedora_repository_edit_qdc_form_submit($form, &$form_state) { $soap_helper = new ConnectionHelper(); $client = $soap_helper->getSoapClient(variable_get('fedora_soap_manage_url', 'http://localhost:8080/fedora/wsdl?api=API-M')); - // Check the content model for a custom edit metadata form submit function. + /* Check the content model for a custom + * edit metadata form submit function.*/ if (isset($form_state['values']['pid'])) { module_load_include('inc', 'fedora_repository', 'ContentModel'); if (($cm = ContentModel::loadFromObject($form_state['values']['pid'])) !== FALSE) { @@ -879,21 +937,6 @@ function fedora_repository_perm() { ); } -/** - * drupal hook - * determines if a user has access to what they are asking for - * - * @param type $op - * @param type $node - * @param type $account - * @return type - */ -function fedora_repository_access($op, $node = NULL, $account = NULL) { - module_load_include('inc', 'fedora_repository', 'ObjectHelper'); - $objectHelper = new ObjectHelper(); - return $objectHelper->fedora_repository_access($op, $node, $account); -} - /** * Grabs a stream from fedora sets the mimetype and returns it. $dsID is the * datastream id. @@ -918,7 +961,7 @@ function makeObject($pid, $dsID) { return ' '; } global $user, $conf; - if (!fedora_repository_access(OBJECTHELPER :: $OBJECT_HELPER_VIEW_FEDORA, $pid, $user)) { + if (!fedora_repository_check_perm(OBJECTHELPER :: $OBJECT_HELPER_VIEW_FEDORA, $pid, $user)) { drupal_access_denied(); return; drupal_set_message(t("You do not have access to Fedora objects within the attempted namespace."), 'error'); @@ -934,8 +977,8 @@ function makeObject($pid, $dsID) { } /** - * Implementation of hook_islandora_tabs(). - * + * Implements hook_islandora_tabs(). + * * @param $content_models array * An array of ContentModel objects to which the current Fedora Object * subscribes. @@ -949,12 +992,12 @@ function makeObject($pid, $dsID) { */ function fedora_repository_islandora_tabs($content_models, $pid, $page_number) { $cmodels_tabs = array(); - + foreach ($content_models as $content_model) { $content_model_fieldset = $content_model->displayExtraFieldset($pid, $page_number); - - // Each content model may return either a tabpage array or plain HTML. If - // it is HTML, stick it in a tabpage. + + // Each content model may return either a tabpage array or plain HTML. + // If it is HTML, stick it in a tabpage. if (is_array($content_model_fieldset)) { $cmodels_tabs = array_merge($cmodels_tabs, $content_model_fieldset); } @@ -966,24 +1009,24 @@ function fedora_repository_islandora_tabs($content_models, $pid, $page_number) { ); } } - - //can disable showing the object details tab in admin UI + + // Can disable showing the object details tab in admin UI. if (variable_get('fedora_repository_show_object_details_tab', TRUE)) { // Add a 'manage object' tab for all objects, where detailed list of content is shown. // XXX: Perhaps this should be extracted into its own object? module_load_include('inc', 'fedora_repository', 'plugins/FedoraObjectDetailedContent'); $obj = new FedoraObjectDetailedContent($pid); - + $object_details = $obj->showFieldSets(); $cmodels_tabs = array_merge($cmodels_tabs, $object_details); } - + return $cmodels_tabs; } /** - * Implementation of hook_islandora_tabs_alter(). - * + * Implements hook_islandora_tabs_alter(). + * * @param &$tabs array * The array of tabs/tabset to alter. * @param $params array @@ -992,8 +1035,8 @@ function fedora_repository_islandora_tabs($content_models, $pid, $page_number) { * @see fedora_repository_get_items() */ function fedora_repository_islandora_tabs_alter(&$tabs, $params) { - //Deselect all other tabs if the fedora_object_details tab is supposed - // to be selected. + // Deselect all other tabs if the fedora_object_details tab is supposed + // to be selected. $object_details_key = 'fedora_object_details'; if ($tabs[$object_details_key]['#selected']) { foreach (element_children($tabs) as $key) { @@ -1006,23 +1049,26 @@ function fedora_repository_islandora_tabs_alter(&$tabs, $params) { /** * Menu callback for "fedora/repository". - * + * * If user is allow, and we are given a PID and a sensical DSID, return the * datastream via the makeObject() function; otherwise, call out to the PIDs' * ContentModels and all Drupal modules for Islandora tabs. * - * @global $user stdObject - * @param $pid string - * An optional string containing the PID of an object. (defaults to islandora:root) - * @param $dsId string + * @global stdObject $user + * + * @param string $pid + * An optional string containing the PID of an object. + * (defaults to islandora:root) + * @param string $dsId * An optional string containing the dsid of an object. ("-" will be ignored * to allow later parameters without including one). - * @param $collection string + * @param string $collection * The collection name... Deprecated. - * @param $page_number string/integer(?) + * @param string/integer(?) $page_number * A page number to start on... Seems to be going towards deprecation? - * @param $limit string/integer(?) + * @param string/integer(?) $limit * Used to limit the number of results returned? Deprecated? + * * @return string * A string containing markup for the rendered tabs. */ @@ -1061,7 +1107,7 @@ function fedora_repository_get_items($pid = NULL, $dsId = NULL, $collection = NU drupal_set_message(t("Invalid dsID!"), 'error'); return ' '; } - if (!fedora_repository_access(OBJECTHELPER::$OBJECT_HELPER_VIEW_FEDORA, $pid, $user)) { + if (!fedora_repository_check_perm(OBJECTHELPER::$OBJECT_HELPER_VIEW_FEDORA, $pid, $user)) { if (user_access('access administration pages')) { drupal_set_message(t("PIDs may be added to allowed namespaces, or all namespace restrictions removed !here", array('!here' => l('here', 'admin/settings/fedora_repository'))), 'warning'); } @@ -1080,37 +1126,39 @@ function fedora_repository_get_items($pid = NULL, $dsId = NULL, $collection = NU exit; return ' '; } - if ($dsId != NULL && $dsId != '-') { //if we have a dsID return the stream otherwise query for a collection of objects -//probably should check pid as well here. + // If we have a dsID return the stream + // otherwise query for a collection of objects. + if ($dsId != NULL && $dsId != '-') { + // Probably should check pid as well here. return makeObject($pid, $dsId); } $breadcrumbs = array(); $objectHelper->getBreadcrumbs($pid, $breadcrumbs); drupal_set_breadcrumb(array_reverse($breadcrumbs)); - + drupal_set_title(truncate_utf8($item->objectProfile->objLabel, 56, TRUE, TRUE)); $content_models = $objectHelper->get_content_models_list($pid); - - //Get the tabs from all modules... + + // Get the tabs from all modules... $hook_tabs = module_invoke_all('islandora_tabs', $content_models, $pid, $page_number); - + $cmodels_tabs = array( '#type' => 'tabset', ); $cmodels_tabs += $hook_tabs; - - //Assemble parameters, to pass during alter - $params = array( + + // Assemble parameters, to pass during alter. + $params = array( 'content_models' => $content_models, 'pid' => $pid, 'page' => $page_number, ); - - //Allow returned tabs to be altered, before return. + + // Allow returned tabs to be altered, before return. drupal_alter('islandora_tabs', $cmodels_tabs, $params); - + return tabs_render($cmodels_tabs); } @@ -1118,7 +1166,7 @@ function fedora_repository_get_items($pid = NULL, $dsId = NULL, $collection = NU * fedora repository urlencode string * FIXME: URL-encoding is not the same as HTML/XML encoding... * @param type $str - * @return type + * @return type */ function fedora_repository_urlencode_string($str) { return htmlentities($str); @@ -1128,12 +1176,12 @@ function fedora_repository_urlencode_string($str) { * Uses makeobject to get a stream. Sets the Content Disposition in the header so it suggests a filename * and sends it as an attachment. This should prompt for a download of the object. * - * @global type $user + * @global type $conf * @param type $pid * @param type $dsId * @param type $label * @param type $version - * @return type + * @return type */ function fedora_object_as_attachment($pid, $dsId, $label=NULL, $version=NULL) { module_load_include('inc', 'fedora_repository', 'ObjectHelper'); @@ -1152,33 +1200,36 @@ function fedora_object_as_attachment($pid, $dsId, $label=NULL, $version=NULL) { /** * repository page + * * @param type $pid * @param type $dsId * @param type $collection * @param type $pageNumber - * @return type + * @return type */ function repository_page($pid = NULL, $dsId = NULL, $collection = NULL, $pageNumber = NULL) { -//do security check at fedora_repository_get_items function as it has to be called there in case -//someone trys to come in a back door. + // Do security check at fedora_repository_get_items function as + // it has to be called there in case someone trys to come in a back door. return fedora_repository_get_items($pid, $dsId, $collection, $pageNumber); } /** * repository service + * + * XXX: Is this even used? + * * @global type $user * @param type $pid * @param type $servicePid * @param type $serviceMethod - * @return type + * @return type */ function repository_service($pid = NULL, $servicePid = NULL, $serviceMethod = NULL) { module_load_include('inc', 'fedora_repository', 'api/fedora_item'); module_load_include('inc', 'fedora_repository', 'ObjectHelper'); global $user; - if (!fedora_repository_access(OBJECTHELPER::$OBJECT_HELPER_VIEW_FEDORA, $pid, $user)) { -//drupal_set_message(t("You do not have access to Fedora objects within the attempted namespace or access to Fedora denied"), 'error'); + if (!fedora_repository_check_perm(OBJECTHELPER::$OBJECT_HELPER_VIEW_FEDORA, $pid, $user)) { drupal_access_denied(); if (user_access('access administration pages')) { drupal_set_message(t("PIDs may be added to allowed namespaces, or all namespace restrictions removed @here", array('@here' => l('here', 'admin/settings/fedora_repository'))), 'error'); @@ -1204,267 +1255,17 @@ function repository_service($pid = NULL, $servicePid = NULL, $serviceMethod = NU exit(); } -//Search Stuff ******************************************************************** - -/** - * Implementation of hook_search(). - * sends a search query to fedora fgsearch which is backed by Lucene - * In our implementation of Fedora we have api-a and api-m locked down - * to authorized users but at the object level. We can query Lucene and the - * RI index to get a list of results without authorization but to view any - * datastreams users must be authorized. - * - * @param type $op - * @param type $keys - * @return array - */ -function fedora_repository_search($op = 'search', $keys = NULL) { - module_load_include('inc', 'fedora_repository', 'ObjectHelper'); - module_load_include('inc', 'fedora_repository', 'api/fedora_utils'); - - switch ($op) { - case 'name': - if (user_access('view fedora collection')) { - return t('Digital Repository', array('-9')); - } - case 'search': - if (user_access('view fedora collection')) { -//demo search string ?operation=gfindObjects&indexName=DemoOnLucene&query=fgs.DS.first.text%3Achristmas&hitPageStart=11&hitPageSize=10 - $resultData = NULL; - $numberOfHitsPerPage = NULL; - $index = strpos($keys, '.'); - $test = substr($keys, 0, $index + 1); - $type = NULL; - if ($index > 0) { - $index = strpos($keys, ':'); - $type = substr($keys, 0, $index); - $keys = substr($keys, $index + 1); - } - - $index = strpos($keys, ':'); - $startPage = substr($keys, 0, $index); - if ($index > 1) { - $keys = substr($keys, $index + 1); - } - - if (!$startPage) { - $startPage = 1; - } - - $xmlDoc = NULL; - - $path = drupal_get_path('module', 'fedora_repository'); - $xmlDoc = new DomDocument(); - $xmlDoc->load($path . '/searchTerms.xml'); - $nodeList = $xmlDoc->getElementsByTagName('default'); - if (!$type) { -//$type = 'dc.description'; - $type = $nodeList->item(0)->nodeValue; - } - $nodeList = $xmlDoc->getElementsByTagName('number_of_results'); - $numberOfHitsPerPage = $nodeList->item(0)->nodeValue; - - $indexName = variable_get('fedora_index_name', 'DemoOnLucene'); - $keys = htmlentities(urlencode($keys)); - $searchQuery = NULL; - if (isset($type) && strcmp($type, ':')) { - $searchQuery = $type . ':' . $keys; - } - else { - $searchQuery = $keys; - } -//$searchQuery.=" AND (PID:vre OR PID:vre:ref OR PID:demo OR PID:changeme)"; - - $searchUrl = variable_get('fedora_fgsearch_url', 'http://localhost:8080/fedoragsearch/rest'); - $searchString = '?operation=gfindObjects&indexName=' . $indexName . '&restXslt=copyXml&query=' . $searchQuery; - $searchString .= '&hitPageSize=' . $numberOfHitsPerPage . '&hitPageStart=' . $startPage; -//$searchString = htmlentities(urlencode($searchString)); - $searchUrl .= $searchString; - $objectHelper = new ObjectHelper(); - $resultData = do_curl($searchUrl); - - $results[] = array( - array( - 'data' => $resultData, - 'colspan' => 2 - ) - ); - return $results; - } - } // switch ($op) -} - -/** - * Implementation of hook_search_page(). - * Display the search results - * - * @param type $resultData - * @return array - */ -function fedora_repository_search_page($resultData) { - $path = drupal_get_path('module', 'fedora_repository'); - $isRestricted = variable_get('fedora_namespace_restriction_enforced', TRUE); - $proc = NULL; - if (!$resultData[0][0]['data']) { - return ''; //no results - } - $text = utf8_encode($resultData[0][0]['data']); - - try { - $proc = new XsltProcessor(); - } catch (Exception $e) { - $out[] = array( - array( - 'data' => $e->getMessage(), - 'colspan' => 2 - ) - ); - return $out; - } - -//inject into xsl stylesheet - $proc->setParameter('', 'searchToken', drupal_get_token('search_form')); //token generated by Drupal, keeps tack of what tab etc we are on - $proc->setParameter('', 'searchUrl', url('search') . '/fedora_repository'); //needed in our xsl - $proc->setParameter('', 'objectsPage', base_path()); - $proc->setParameter('', 'allowedPidNameSpaces', variable_get('fedora_pids_allowed', 'default: demo: changeme: islandora: ilives: islandora-book: books: newspapers: ')); - $proc->registerPHPFunctions(); - $xsl = new DomDocument(); - if ($isRestricted) { - $xsl->load($path . '/xsl/results.xsl'); - } - else { - $xsl->load($path . '/xsl/unfilteredresults.xsl'); - } - - $input = new DomDocument(); - $didLoadOk = $input->loadXML(utf8_encode($resultData[0][0]['data'])); - - if (!$didLoadOk) { - $results[] = array( - array( - 'data' => 'Error parsing results', - 'colspan' => 2 - ) - ); - } - else { - $xsl = $proc->importStylesheet($xsl); - $newdom = $proc->transformToDoc($input); - - $results[] = array( - array( - 'data' => $newdom->saveHTML(), - 'colspan' => 2 - ) - ); - } - - $header = array( - array( - 'data' => t('Collection results'), - NULL, - ), - (NULL) - ); - - $output .= theme('table', $header, $results); - return $output; -} - -/** - * Implementation of hook_form_alter(). - * allows the advanced search form in drupal - * - * @param type $form - * @param type $form_state - * @param type $form_id - */ -function fedora_repository_form_alter(&$form, &$form_state, $form_id) { -// Advanced node search form - module_load_include('inc', 'fedora_repository', 'SearchClass'); - $path = drupal_get_path('module', 'fedora_repository'); - if ($form_id == 'search_form' && arg(1) == 'fedora_repository' && user_access('use advanced search')) { - $default_value = $form['basic']['inline']['keys']['#default_value']; - $index = strpos($default_value, '.'); - $test = substr($default_value, 0, $index + 1); - $type = NULL; - if ($index > 0) { - $index = strpos($default_value, ':'); - $type = substr($default_value, 0, $index); - $default_value = substr($default_value, $index + 1); - } - $form['basic']['inline']['keys']['#default_value'] = $default_value; -// Keyword boxes: - $form['advanced'] = array( - '#type' => 'fieldset', - '#title' => t('Advanced search'), - '#collapsible' => TRUE, - '#collapsed' => TRUE, - '#attributes' => array( - 'class' => 'search-advanced' - ), - ); - $form['advanced']['keywords'] = array( - '#prefix' => '
', - '#suffix' => '
', - ); - $xmlDoc = new DomDocument(); - $xmlDoc->load($path . '/searchTerms.xml'); - $nodeList = $xmlDoc->getElementsByTagName('term'); - $searchClass = new SearchClass(); - $types = $searchClass->get_search_terms_array(); - - $form['advanced']['type'] = array( - '#type' => 'select', - '#title' => t('Choose a field to search'), - '#prefix' => '
', '#suffix' => '
', '#options' => $types, - '#default_value' => $type, - ); - $form['advanced']['submit'] = array( - '#type' => 'submit', - '#value' => t('Advanced search'), - '#prefix' => '
', '#suffix' => '
', - ); - $form['#validate'][] = 'fedora_repository_search_validate'; - } -} - /** - * Implementation of hook_search_validate() + * Implements hook_theme(). * - * @param type $form - * @param type $form_state - */ -function fedora_repository_search_validate($form, &$form_state) { -// Initialise using any existing basic search keywords. - $keys = $form_state['values']['processed_keys']; - - if (isset($form_state['values']['type'])) { - $type = $form_state['values']['type']; - if ($type) { - $keys = $type . ':' . $keys; - } - } - - if (!empty($keys)) { - form_set_value($form['basic']['inline']['processed_keys'], trim($keys), $form_state); //set the form string - } -} - -/** - * fedora repository theme - * @return type + * @return array + * The themes for the fedora_repository module. */ function fedora_repository_theme() { return array( - 'fedora_repository_mnpl_advanced_search_form' => array( - 'arguments' => array( - 'form' => NULL, - ), - ), 'fedora_repository_time' => array( 'arguments' => array( - 'element' => NULL + 'element' => NULL, ), 'fedora_repository_solution_packs_list' => array( 'arguments' => array( @@ -1476,369 +1277,75 @@ function fedora_repository_theme() { } /** - * Get a list of terms from a lucene index + * fedora repository required fedora objects * - * @param type $field - * @param type $startTerm - * @param type $displayName - * @return type + * @return array + * array( 'path-to-foxml-file', + * 'pid', + * 'dsid', + * 'path-to-datastream-file', + * int dsversion, + * boolean required) */ -function fedora_repository_list_terms($field, $startTerm = NULL, $displayName = NULL) { - module_load_include('inc', 'fedora_repository', 'SearchClass'); - $searchClass = new SearchClass(); - return $searchClass->getTerms($field, $startTerm, $displayName); -} +function fedora_repository_fedora_repository_required_fedora_objects() { -/** - * fedora repository mnpl advanced search form - * @return type - */ -function fedora_repository_mnpl_advanced_search_form() { - module_load_include('inc', 'fedora_repository', 'SearchClass'); - $searchClass = new SearchClass(); - return $searchClass->build_advanced_search_form(); + $module_path = drupal_get_path('module', 'fedora_repository'); + return array( + 'fedora_repository' => array( + 'module' => 'fedora_repository', + 'title' => 'Islandora Core', + 'objects' => array( + array( + 'pid' => 'islandora:collectionCModel', + 'label' => 'Islandora Collection Content Model', + 'dsid' => 'ISLANDORACM', + 'datastream_file' => "./$module_path/content_models/COLLECTIONCM.xml", + 'dsversion' => 2, + 'cmodel' => 'fedora-system:ContentModel-3.0', + ), + array( + 'pid' => 'islandora:root', + 'label' => 'Islandora Top-level Collection', + 'cmodel' => 'islandora:collectionCModel', + 'datastreams' => array( + array( + 'dsid' => 'COLLECTION_POLICY', + 'datastream_file' => "./$module_path/collection_policies/COLLECTION-COLLECTION POLICY.xml", + ), + array( + 'dsid' => 'TN', + 'datastream_file' => "./$module_path/images/Gnome-emblem-photos.png", + 'mimetype' => 'image/png', + ), + ), + ), + ), + ), + ); } /** - * theme fedora repository mnpl advanced search form - * @param type $form - * @return type + * Functions to create a time selector form element type. */ -function theme_fedora_repository_mnpl_advanced_search_form($form) { - module_load_include('inc', 'fedora_repository', 'SearchClass'); - $advanced_search_form = new SearchClass(); - return $advanced_search_form->theme_advanced_search_form($form); -} +function fedora_repository_elements() { + $type['fedora_repository_time'] = array( + "#input" => TRUE, + "#process" => array("fedora_repository_expand_time"), + ); -/** - * fedora repository mnpl advanced search - * @param type $query - * @param type $startPage - * @return type - */ -function fedora_repository_mnpl_advanced_search($query, $startPage = 1) { - module_load_include('inc', 'fedora_repository', 'SearchClass'); - $searchClass = new SearchClass(); - $retVal = $searchClass->custom_search($query, $startPage); - return $searchClass->custom_search($query, $startPage); -} - -/** - * fedora repository mnpl_advanced search form submit - * @param type $form - * @param type $form_state - */ -function fedora_repository_mnpl_advanced_search_form_submit($form, &$form_state) { - $type_id = $form_state['values']['type']; - $repeat = variable_get('fedora_repository_advanced_block_repeat', t('3')); - $searchString = $form_state['values']['type1'] . ':' . $form_state['values']['fedora_terms1']; - if ($form_state['values']['fedora_terms2'] != '') { - $searchString .=' +' . $form_state['values']['andor1'] . '+' . $form_state['values']['type2'] . ':' . $form_state['values']['fedora_terms2']; - } - if ($repeat > 2 && $repeat < 9) { - for ($i = 3; $i < $repeat + 1; $i++) { - $t = $i - 1; - if ($form_state['values']["fedora_terms$i"] != '') { - $searchString .= '+' . $form_state['values']["andor$t"] . '+' . $form_state['values']["type$i"] . ':' . $form_state['values']["fedora_terms$i"]; - } - } - } - drupal_goto("fedora/repository/mnpl_advanced_search/$searchString"); -} - -/** - * fedora repository install demo page - * @return type - */ -function fedora_repository_install_demos_page() { - $output = drupal_get_form('fedora_repository_demo_objects_form'); - return $output; -} - -/** - * fedora repository demo objects form - * @return string - */ -function fedora_repository_demo_objects_form() { - module_load_include('inc', 'fedora_repository', 'ObjectHelper'); - module_load_include('inc', 'fedora_repository', 'api/fedora_item'); - $form = array(); - $existing_demos = array(); - - $form['install_demos'] = array( - '#title' => t('Islandora Demo Collections'), - '#type' => 'fieldset', - '#description' => t('Install demo image and document collections and content models.'), - ); - $demo_objects = array(); -// Check if the top-level islandora collection exists. If not, display a button to ingest. - - $form['install_demos']['demo_collections'] = array( - '#type' => 'checkboxes', - '#title' => t('Collections to ingest'), - '#options' => array(), - '#description' => t('Choose which demo collections you would like ingested into the repository.'), - ); - - foreach (array( -'islandora:collectionCModel' => 'Islandora default content models', - 'islandora:root' => 'Islandora top-level collection', - 'islandora:demos' => 'Islandora demos collection', - 'islandora:largeimages' => 'Sample large image content model (requires Djatoka and Kakadu.)', - ) - as $available_demo => $available_demo_desc) { - try { - $demo_objects[$available_demo] = new Fedora_Item($available_demo); - } catch (exception $e) { - - } - - if (empty($demo_objects[$available_demo]->objectProfile)) { -//The demo objects collection does not exist in the repository, display a button to ingest them. - $form['install_demos']['demo_collections']['#options'][$available_demo] = $available_demo_desc; - } - else { - array_push($existing_demos, $demo_objects[$available_demo]); - } - } - -// Check if the SmileyStuff collectoin exists, and if it has a COLLECTION_VIEW datastream. If it doesn't then we can add it. - - $smiley_stuff = new Fedora_Item('demo:SmileyStuff'); - if (!empty($smiley_stuff->objectProfile)) { - $datastreams_list = $smiley_stuff->get_datastreams_list_as_array(); - if (empty($datastreams_list['COLLECTION_VIEW'])) { - $form['install_demos']['demo_collections']['#options']['demo:SmileyStuff'] = 'Add Islandora Collection View to Fedora Smiley Stuff Collection'; - } - else { - $demo_objects['demo:SmileyStuff'] = $smiley_stuff; - } - } - else { - $form['install_demos']['smileynote'] = array( - '#value' => '

If you install the ' . l('fedora demo objects', 'https://wiki.duraspace.org/display/FCR30/Demonstration+Objects') . ' Islandora can display them as a collection.

' - ); - } - - $form['install_demos']['ingest'] = array( - '#type' => 'submit', - '#name' => 'install_demos', - '#value' => 'Install Selected Demos', - '#disabled' => (empty($form['install_demos']['demo_collections']['#options'])) ? TRUE : FALSE, - ); - - $form['existing_demos'] = array( - '#prefix' => '

Demo collections already installed in this repository:

    ', - '#suffix' => '
', - ); - - if (!empty($existing_demos)) { - foreach ($existing_demos as $pid => $demo_object) { - - $form['existing_demos'][$demo_object->pid] = array( - '#prefix' => '
  • ', - '#value' => l($demo_object->pid, $demo_object->url()), - '#suffix' => '
  • ', - ); - } - } - - return $form; -} - -/** - * fedora repository demo objects form submit - * @global type $base_url - * @param type $form - * @param type $form_state - */ -function fedora_repository_demo_objects_form_submit($form, &$form_state) { - module_load_include('inc', 'fedora_repository', 'api/fedora_item'); - module_load_include('inc', 'fedora_repository', 'api/dublin_core'); - module_load_include('inc', 'fedora_repository', 'api/fedora_utils'); - global $base_url; - if ($form_state['clicked_button']['#name'] == 'install_demos') { - if (!empty($form_state['values']['demo_collections']['islandora:collectionCModel'])) { - try { - $collectioncm = Fedora_Item::ingest_new_item('islandora:collectionCModel', 'A', 'Islandora Collection Content Model'); - $collectioncm->add_relationship('hasModel', 'fedora-system:ContentModel-3.0', FEDORA_MODEL_URI); - $collectioncm->add_datastream_from_file(drupal_get_path('module', 'fedora_repository') . '/content_models/COLLECTIONCM.xml', 'ISLANDORACM', 'Islandora Content Model.xml', 'application/xml', 'X'); - } catch (exception $e) { - - } - try { - $strictpdfcm = Fedora_Item::ingest_new_item('islandora:strict_pdf', 'A', 'Strict PDF Content Model'); - $strictpdfcm->add_relationship('hasModel', 'fedora-system:ContentModel-3.0', FEDORA_MODEL_URI); - $strictpdfcm->add_datastream_from_file(drupal_get_path('module', 'fedora_repository') . '/content_models/STRICT_PDFCM.xml', 'ISLANDORACM', 'Islandora Content Model.xml', 'application/xml', 'X'); - } catch (exception $e) { - - } - -// Install a collection object that points to all content model objects - try { - $cmodel_collection_xml = Fedora_Item::create_object_FOXML('islandora:ContentModelCollection'); - $cmodel_collection = Fedora_Item::ingest_from_FOXML($cmodel_collection_xml); - -//$dc = new Dublin_Core(new Fedora_Item('islandora:ContentModelCollection')); - $dc = new Dublin_Core($cmodel_collection); - $dc->set_element('dc:title', array('Installed Content Model')); - $dc->save(); - $cmodel_collection->add_datastream_from_string('select $object $title from <#ri> - where ($object $title - and ($object - or $object ) - and $object ) - order by $title', 'QUERY', 'Content Model Collection Query', 'text/plain'); - $cmodel_collection->add_relationship('isMemberOfCollection', 'islandora:root'); - $cmodel_collection->add_relationship('hasModel', 'islandora:collectionCModel', FEDORA_MODEL_URI); - $cmodel_collection->add_datastream_from_file(drupal_get_path('module', 'fedora_repository') . '/collection_views/simple_list_view.xml', 'COLLECTION_VIEW', 'Collection View', 'text/xml', 'X'); - $cmodel_collection->add_datastream_from_file(drupal_get_path('module', 'fedora_repository') . '/images/contentModel.jpg', 'TN', 'Thumbnail', 'image/jpg', 'M'); - drupal_set_message(t("Successfully installed islandora:ContentModelCollection.", array('@base_url' => check_plain($base_url))), 'message'); - } catch (exception $e) { - - } - } - - if (!empty($form_state['values']['demo_collections']['islandora:root'])) { - $new_item = Fedora_Item::ingest_new_item('islandora:root', 'A', 'Islandora Top-level Collection'); - $new_item->add_relationship('hasModel', 'islandora:collectionCModel', FEDORA_MODEL_URI); - $cp = $new_item->add_datastream_from_file(drupal_get_path('module', 'fedora_repository') . '/collection_policies/COLLECTION-COLLECTION POLICY.xml', 'COLLECTION_POLICY', 'Collection Policy', 'text/xml', 'X'); - try { - $tn = $new_item->add_datastream_from_file(drupal_get_path('module', 'fedora_repository') . '/images/Gnome-emblem-photos.png', 'TN', 'Thumbnail.png', 'image/png', 'M'); - drupal_set_message(t("Successfully installed islandora:root.", array('@base_url' => check_plain($base_url))), 'message'); - } catch (exception $e) { - - } - } - - if (!empty($form_state['values']['demo_collections']['islandora:demos'])) { - $new_item = fedora_item::ingest_new_item('islandora:demos', 'A', 'Islandora Demo Collection'); - $new_item->add_relationship('isMemberOfCollection', 'islandora:root'); - $new_item->add_relationship('hasModel', 'islandora:collectionCModel', FEDORA_MODEL_URI); - $cp = $new_item->add_datastream_from_file(drupal_get_path('module', 'fedora_repository') . '/collection_policies/COLLECTION-COLLECTION POLICY.xml', 'COLLECTION_POLICY', 'Collection Policy', 'text/xml', 'X'); - -// $cv = $new_item->add_datastream_from_file( drupal_get_path('module', 'fedora_repository') . '/collection_views/COLLECTION_VIEW.xml', 'COLLECTION_VIEW', 'Collection View.xml', 'text/xml', 'X'); - $tn = $new_item->add_datastream_from_file(drupal_get_path('module', 'fedora_repository') . '/images/Gnome-emblem-photos.png', 'TN', 'Thumbnail.png', 'image/png', 'M'); - try { - $new_item = Fedora_Item::ingest_new_item('islandora:pdf_collection', 'A', 'PDF Collection'); - $new_item->add_relationship('isMemberOfCollection', 'islandora:demos'); - $new_item->add_relationship('hasModel', 'islandora:collectionCModel', FEDORA_MODEL_URI); - $cp = $new_item->add_datastream_from_file(drupal_get_path('module', 'fedora_repository') . '/collection_policies/PDF-COLLECTION POLICY.xml', 'COLLECTION_POLICY', 'Collection Policy', 'text/xml', 'X'); - $tn = $new_item->add_datastream_from_file(drupal_get_path('module', 'fedora_repository') . '/images/Crystal_Clear_mimetype_pdf.png', 'TN', 'Thumbnail.png', 'image/png', 'M'); - drupal_set_message(t("Successfully installed islandora:demos.", array('@base_url' => check_plain($base_url))), 'message'); - } catch (exception $e) { - - } - } - - if (!empty($form_state['values']['demo_collections']['demo:SmileyStuff'])) { - $smiley_stuff = new Fedora_Item('demo:SmileyStuff'); - $new_item = $smiley_stuff->add_datastream_from_file(drupal_get_path('module', 'fedora_repository') . '/collection_views/SmileyStuff-COLLECTION_VIEW.xml', 'COLLECTION_VIEW', 'Collection View', 'text/xml', 'X'); - $smiley_stuff->add_relationship('isMemberOfCollection', 'info:fedora/islandora:demos'); - $tn = $smiley_stuff->add_datastream_from_file(drupal_get_path('module', 'fedora_repository') . '/images/smileytn.png', 'TN', 'Thumbnail.png', 'image/png', 'M'); - $cp = $smiley_stuff->add_datastream_from_file(drupal_get_path('module', 'fedora_repository') . '/collection_policies/JPG-COLLECTION POLICY.xml', 'COLLECTION_POLICY', 'Collection Policy.xml', 'application/xml', 'X'); - - $cm = new Fedora_Item('demo:DualResImage'); - try { - $cmstream = $cm->add_datastream_from_file(drupal_get_path('module', 'fedora_repository') . '/content_models/STANDARD JPG.xml', 'ISLANDORACM', 'Content Model.xml', 'application/xml', 'X'); - } catch (exception $e) { - - } - $dual_res_image_collection_cmodel = new Fedora_Item('demo:DualResImageCollection'); - try { - $cmstream = $dual_res_image_collection_cmodel->add_datastream_from_file(drupal_get_path('module', 'fedora_repository') . '/content_models/COLLECTIONCM.xml', 'ISLANDORACM', 'Islandora Content Model.xml', 'application/xml', 'X'); - drupal_set_message(t("Successfully installed demo:SmileyStuff collection view.", array('@base_url' => check_plain($base_url))), 'message'); - } catch (exception $e) { - - } - } - - if (!empty($form_state['values']['demo_collections']['islandora:largeimages'])) { - $error = ''; - foreach (array('islandora_jp2Sdep-slideCModel.xml', 'islandora_mods2htmlSdef.xml', 'islandora_mods2htmlSdep.xml', - 'islandora_slideCModel.xml', 'islandora_viewerSdep-slideCModel.xml', 'ilives_jp2Sdef.xml', 'ilives_viewerSdef.xml') as $foxml_file) { - try { - $item = Fedora_Item::ingest_from_FOXML_file(drupal_get_path('module', 'fedora_repository') . '/content_models/' . $foxml_file); - } catch (exception $e) { - $error .= " - Problem ingesting $foxml_file"; - } - } - try { - $item = Fedora_Item::ingest_from_FOXML_file(drupal_get_path('module', 'fedora_repository') . '/content_models/islandora_largeimages.xml'); - $tn = $item->add_datastream_from_file(drupal_get_path('module', 'fedora_repository') . '/images/Gnome-emblem-photos.png', 'TN', 'Thumbnail.png', 'image/png', 'M'); - drupal_set_message(t("Successfully installed islandora:largeimages.", array('@base_url' => check_plain($base_url))), 'message'); - } catch (exception $e) { - $error .= " - Problem ingesting islandora:largeimages collection"; - } - } - - if (!empty($error)) { - drupal_set_message(t('Some problems occurred: @error', array('@error' => $error))); - } - } -} - -/** - * fedora repository required fedora objects - * @return type - */ -function fedora_repository_required_fedora_objects() { -// array( 'path-to-foxml-file', 'pid', 'dsid', 'path-to-datastream-file', int dsversion, boolean required) - $module_path = drupal_get_path('module', 'fedora_repository'); - return array( - 'fedora_repository' => array( - 'module' => 'fedora_repository', - 'title' => 'Islandora Core', - 'objects' => array( - array( - 'pid' => 'islandora:collectionCModel', - 'label' => 'Islandora Collection Content Model', - 'dsid' => 'ISLANDORACM', - 'datastream_file' => "./$module_path/content_models/COLLECTIONCM.xml", - 'dsversion' => 2, - 'cmodel' => 'fedora-system:ContentModel-3.0', - ), - array( - 'pid' => 'islandora:root', - 'label' => 'Islandora Top-level Collection', - 'cmodel' => 'islandora:collectionCModel', - 'datastreams' => array( - array( - 'dsid' => 'COLLECTION_POLICY', - 'datastream_file' => "./$module_path/collection_policies/COLLECTION-COLLECTION POLICY.xml", - ), - array( - 'dsid' => 'TN', - 'datastream_file' => "./$module_path/images/Gnome-emblem-photos.png", - 'mimetype' => 'image/png', - ), - ), - ), - ), - ), - ); -} - -/** - * Functions to create a time selector form element type. - */ -function fedora_repository_elements() { - $type['fedora_repository_time'] = array( - "#input" => TRUE, - "#process" => array("fedora_repository_expand_time"), - ); - - return $type; + return $type; } /** * fedora repository expand time + * * @param type $element - * @return string + * + * @return string */ function fedora_repository_expand_time($element) { -// Default to current time, check default_value but set value so that if -// default value is present it will override value + // Default to current time, check default_value but set value so that if + // default value is present it will override value. if (empty($element['#default_value'])) { $element['#value'] = array( 'hour' => intval(format_date(time(), 'custom', 'h')), @@ -1876,8 +1383,10 @@ function fedora_repository_expand_time($element) { /** * fedora repository time + * * @param type $element - * @return type + * + * @return type */ function fedora_repository_time($element) { $output = '
    ' . $element['#children'] . '
    '; @@ -1886,339 +1395,22 @@ function fedora_repository_time($element) { /** * theme fedora repository time + * * @param type $element - * @return type + * + * @return type */ function theme_fedora_repository_time($element) { $output = '
    ' . $element['#children'] . '
    '; return theme('form_element', $element, $output); } -/* Export (basket) functionality */ - -/** - * fedora repository remove item from basket - * @param type $pid - */ -function fedora_repository_remove_item_from_basket($pid) { - - module_load_include('inc', 'fedora_repository', 'ObjectHelper'); - $pids = empty($_SESSION['basket']['processed']) ? array() : $_SESSION['basket']['processed']; - - $objectHelper = new ObjectHelper(); -// getting child PIDs if any - $cpids = $objectHelper->get_child_pids(array($pid)); - - if (array_key_exists($pid, $pids)) { -// remove item from basket - unset($_SESSION['basket']['processed'][$pid]); - } - if (!empty($cpids)) { // there are children - foreach ($cpids as $child_pid => $value) { -// remove child item from basket recursively - fedora_repository_remove_item_from_basket($child_pid); - } - } -} - -/** - * fedora repository basket - * @return type - */ -function fedora_repository_basket() { - $pids = _fedora_repository_get_basket_pids(); - $output = drupal_get_form('fedora_repository_basket_form', $pids); - - return $output; -} - -function fedora_repository_basket_form($form_state, $pids) { - $form = array(); - - if (!empty($pids)) { - $form['pid'] = array(); - $form['title'] = array(); - $form['desc'] = array(); - } - else { - return; - } - - ksort($pids); - foreach ($pids as $pid => $arr) { - $cbs[$pid] = ''; - - $form['pid'][$pid] = array('#value' => l($pid, "fedora/repository/$pid")); - $form['title'][$pid] = array('#value' => $arr['title']); - $form['desc'][$pid] = array('#value' => $arr['desc']); - } - - $form['remove'] = array( - '#type' => 'checkboxes', - '#options' => $cbs, - ); - - $form['remove_submit'] = array( - '#type' => 'submit', - '#value' => t('Remove selected'), - ); - - $form['remove_all'] = array( - '#type' => 'submit', - '#value' => t('Empty basket'), - ); - - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Export selected'), - ); - - $form['submit_all'] = array( - '#type' => 'submit', - '#value' => t('Export all'), - ); - - return $form; -} - -/** - * theme fedora repository basket form - * @param type $form - * @return string - */ -function theme_fedora_repository_basket_form($form) { - $header = array( - theme('table_select_header_cell'), - t('PID'), - t('Title'), - t('Description'), - ); - - if (isset($form['pid']) && is_array($form['pid'])) { - foreach (element_children($form['pid']) as $key) { - $rows[] = array( - drupal_render($form['remove'][$key]), - drupal_render($form['pid'][$key]), - drupal_render($form['title'][$key]), - drupal_render($form['desc'][$key]), - ); - } - } - else { - $rows[] = array(array('data' => t('Your basket is empty.'), 'colspan' => '4')); - } - - $output = theme('table', $header, $rows); - - $frm = drupal_render($form); - $output = $frm . $output . $frm; - - return $output; -} - -/** - * fedora repository basket form validate - * @param type $form - * @param type $form_state - */ -function fedora_repository_basket_form_validate($form, &$form_state) { - -} - -/** - * fedora repository basket form submit - * @global type $user - * @param type $form - * @param type $form_state - * @return type - */ -function fedora_repository_basket_form_submit($form, &$form_state) { - if ($form_state['values']['op'] == $form_state['values']['remove_submit']) { - $pids = $form_state['clicked_button']['#post']['remove']; - - if (isset($pids)) { - foreach ($pids as $pid) { - fedora_repository_remove_from_basket($pid); - } - drupal_set_message(t("Selected objects removed")); - return; - } - } - - if ($form_state['values']['op'] == $form_state['values']['remove_all']) { - _fedora_repository_empty_basket(); - drupal_set_message(t("Basket emptied")); - return; - } - - if ($form_state['values']['op'] == $form_state['values']['submit_all']) { - $msg = t("All objects exported to staging area"); - $pids = _fedora_repository_get_basket_pids(); - } - elseif ($form_state['values']['op'] == $form_state['values']['submit']) { - $msg = t("Selected objects exported to staging area"); - $pids = array_filter($form_state['values']['remove']); - } - - if (!empty($pids)) { - global $user; - $log = array(); - $success = TRUE; - $export_dir = variable_get('export_area', file_directory_path() . '/fedora_export_area') . '/' . $user->name . '/' . date("Ymd-His"); - $foxml_dir = $export_dir . '/foxml'; - - if (!file_exists($foxml_dir) && !@mkdir($foxml_dir, 0775, TRUE)) { - drupal_set_message(t("Failed to create foxml dir @dir. Check that export dir exsits and has correct permissions", array('@dir' => $foxml_dir)), 'error'); - return FALSE; - } - - module_load_include('inc', 'fedora_repository', 'api/fedora_export'); - foreach ($pids as $pid => $arr) { - - $objects_dir = $export_dir . '/objects/' . $pid; - if (!file_exists($objects_dir) && !@mkdir($objects_dir, 0775, TRUE)) { - drupal_set_message(t("Failed to create objects dir @dir. Check that export dir exsits and has correct permissions", array('@dir' => $objects_dir)), 'error'); - return FALSE; - } - - if (!export_to_export_area($pid, $foxml_dir, $objects_dir, $log)) { - $success = FALSE; - } - } - $msg = $success ? $msg : t("Failed to export objects to staging area"); - $msg .= ":
    " . implode("
    ", $log); - - drupal_set_message($msg, $success ? 'info' : 'error'); -//_fedora_repository_empty_basket(); - } - else { - drupal_set_message(t("No objects selected or basket empty"), 'error'); - } - - return; -} - -/** - * Get all pids saved to the basket. - * - * @return type - */ -function _fedora_repository_get_basket_pids() { - -// Set empty defaults if basket elements are missing - $_SESSION['basket'] = isset($_SESSION['basket']) ? $_SESSION['basket'] : array('processed' => array(), 'unprocessed' => array()); - $_SESSION['basket']['processed'] = isset($_SESSION['basket']['processed']) ? $_SESSION['basket']['processed'] : array(); - $_SESSION['basket']['unprocessed'] = isset($_SESSION['basket']['unprocessed']) ? $_SESSION['basket']['unprocessed'] : array(); - - $pids = empty($_SESSION['basket']['processed']) ? array() : $_SESSION['basket']['processed']; - - module_load_include('inc', 'fedora_repository', 'ObjectHelper'); - $ob = new ObjectHelper(); - foreach ($_SESSION['basket']['unprocessed'] as $pid) { -// Check if the pid already exists in the tree - if (array_key_exists($pid, $pids)) { - continue; - } - - $pids += $ob->get_all_related_pids($pid); -// $pids += array($pid); - } - - $_SESSION['basket']['processed'] = $pids; - $_SESSION['basket']['unprocessed'] = array(); - - return $pids; -} - -/** - * fedora repository empty basket - */ -function _fedora_repository_empty_basket() { - unset($_SESSION['basket']); -} - -/** - * fedora repository add to basket - * @param type $pid - * @param type $warn - * @param type $searchResultsFlag - */ -function fedora_repository_add_to_basket($pid, $warn = TRUE, $searchResultsFlag = FALSE) { - if ($warn && _is_added_to_basket($pid)) { - drupal_set_message(t("Object already in basket")); - } - - if (!isset($_SESSION['basket'])) { - $_SESSION['basket'] = array(); - $_SESSION['basket']['unprocessed'] = array($pid => $pid); - } - else { - $_SESSION['basket']['unprocessed'][$pid] = $pid; - } - - if (!$searchResultsFlag) { - drupal_goto('fedora/basket'); - } -} - -/** - * fedora repository remove from basket - * @param type $pid - * @return type - */ -function fedora_repository_remove_from_basket($pid) { - if (isset($_SESSION['basket']['unprocessed'][$pid])) { - unset($_SESSION['basket']['unprocessed'][$pid]); - } - - if (isset($_SESSION['basket']['processed'][$pid])) { - unset($_SESSION['basket']['processed'][$pid]); - } - return; -} - -/** - * theme add to basket link - * @param type $pid - * @param type $type - * @return type - */ -function theme_add_to_basket_link($pid, $type = 'object') { - $object = t($type); - $path = drupal_urlencode($pid); - - $save = "export_big.png"; - $saved = "exported_big.png"; -// $path = drupal_get_path('module', 'fedora_repository').'/images/'.$save ; - /* - var_dump($path); - var_dump(theme('image',drupal_get_path('module', 'fedora_repository').'/images/'.$save)); - die(); - */ - if (!_is_added_to_basket($pid)) { - return l( - theme('image', drupal_get_path('module', 'fedora_repository') . '/images/' . $save, t("Add to basket"), t("Add this @object to my basket", array('@object' => $object))), "fedora/repository/addToBasket/" . $path, array('html' => TRUE) - ); - } - - return theme('image', drupal_get_path('module', 'fedora_repository') . '/images/' . $saved, t("In basket"), t("This @object is already in your basket", array('@object' => $object))); -} - -/** - * is added to basket - * @param type $pid - * @param type $account - * @return type - */ -function _is_added_to_basket($pid, $account = NULL) { - return isset($_SESSION['basket']['unprocessed'][$pid]) || isset($_SESSION['basket']['processed'][$pid]); -// return db_result(db_query("SELECT uid FROM {repository_basket} WHERE uid = %d AND pid = '%s'", $account->uid, $pid)); -} - /** * fedora repository display schema + * * @param type $file - * @return type + * + * @return type */ function fedora_repository_display_schema($file) { $path = drupal_get_path('module', 'fedora_repository'); @@ -2233,43 +1425,49 @@ function fedora_repository_display_schema($file) { /** * fedora repository batch reingest object - * @param type $object - * @param type $context - * @return type - */ -function fedora_repository_batch_reingest_object($object, &$context) { - + * + * @param array $object + * An array defining an object to ingest. + * @param string $module_name + * The string needed in the finished callback to be + * sent out in the postprocess hook. + * @param array $context + * Variables shared between batch iterations + * and finished callback + */ +function fedora_repository_batch_reingest_object($object, $module_name, &$context) { module_load_include('inc', 'fedora_repository', 'api/fedora_item'); module_load_include('inc', 'fedora_repository', 'api/fedora_utils'); + $context['results']['module_name'] = $module_name; + if (!empty($object) && is_array($object)) { $pid = $object['pid']; if (!valid_pid($pid)) { return NULL; } - + // Does the object exist? If so, purge it. - //dd("About to test existence of PID: $pid"); $item = new Fedora_Item($pid); if ($item->exists()) { - //dd(' Found'); $item->purge(t('Remove during re-install batch job')); - //dd(' Purged'); } + // Need to have this a couple places... + // (After trying from FOXML and later for individual DSs) + $new_item = NULL; + // Seems like this might be getting messed up due to scope?. + $datastreams = array(); - $new_item = NULL; //Need to have this a couple places... (After trying from FOXML and later for individual DSs) - $datastreams = array(); //Seems like this might be getting messed up due to scope? - -// Ingest the object from the source file. + // Ingest the object from the source file. if (!empty($object['foxml_file'])) { $foxml_file = $object['foxml_file']; $new_item = Fedora_Item::ingest_from_FOXML_file($foxml_file); if ($new_item->exists()) { -// Batch operation was successful; can still add additional DSs, though + // Batch operation was successful; can still add additional DSs, though. $context['message'][] = t('%pid installed.', array('%pid' => $new_item->pid)); } } - + if (!empty($object['dsid']) && !empty($object['datastream_file'])) { $datastreams[] = array( 'dsid' => $object['dsid'], @@ -2282,9 +1480,7 @@ function fedora_repository_batch_reingest_object($object, &$context) { $label = !empty($object['label']) ? $object['label'] : ''; if (!isset($new_item)) { - //dd(' Not found, creating'); $new_item = Fedora_Item::ingest_new_item($pid, 'A', $label); - //dd(' Created'); } elseif (!empty($label)) { $new_item->modify_object($label); @@ -2292,17 +1488,12 @@ function fedora_repository_batch_reingest_object($object, &$context) { if (isset($new_item)) { if (!empty($object['cmodel'])) { - //dd(' relating to cmodel'); $new_item->add_relationship('hasModel', $object['cmodel'], FEDORA_MODEL_URI); - //dd(' related to cmodel'); } if (!empty($object['parent'])) { - //dd(' adding parent'); $new_item->add_relationship('isMemberOfCollection', $object['parent']); - //dd(' parent added'); } - foreach ((array)$datastreams as $ds) { - //dd("trying to add ds: {$ds['dsid']}"); + foreach ((array) $datastreams as $ds) { if ($ds['dsid'] == 'DC') { $new_item->modify_datastream_by_value(file_get_contents($ds['datastream_file']), $ds['dsid'], $ds['label'], 'text/xml'); } @@ -2315,14 +1506,30 @@ function fedora_repository_batch_reingest_object($object, &$context) { } /** - * Content model, collection view and collection policy datastreams may now optionally define a version + * This function will send the postprocess solution pack hook. + * It is referenced by the solution pack form's batch finished entry. + * + */ +function fedora_repository_solutionpack_send_postprocess($success, $results, $operations) { + // Hook to let solution pack objects be modified. + // Not using module_invoke so solution packs can be expanded by other modules. + if ($success) { + module_invoke_all('fedora_repository_postprocess_solution_pack', $results['module_name']); + } +} + +/** + * Content model, collection view and collection policy datastreams may + * now optionally define a version * number in their top-level XML element as an attribute, as in: * attributes()->version) { + + if (!empty($doc) && $version = (int) $doc->attributes()->version) { $return = $version; } - + return $return; } /** * theme fedora repository solution pack list + * * @param type $solution_packs - * @return string + * + * @return string */ function theme_fedora_repository_solution_packs_list($solution_packs) { module_load_include('inc', 'fedora_repository', 'api/fedora_item'); @@ -2357,9 +1566,11 @@ function theme_fedora_repository_solution_packs_list($solution_packs) { } /** - * Implementation of hook_forms() + * Implements hook_forms(). + * * @param string $form_id - * @return array + * + * @return array */ function fedora_repository_forms($form_id) { $forms = array(); @@ -2372,7 +1583,7 @@ function fedora_repository_forms($form_id) { } /** - * Implementation of hook_imagecache_default_presets(). + * Implements hook_imagecache_default_presets(). */ function fedora_repository_imagecache_default_presets() { return array( @@ -2396,18 +1607,18 @@ function fedora_repository_imagecache_default_presets() { /** * Actually render an image, given an arbitrary path and preset. - * + * * Note: If imagecache_external is not available, the full-sized image will be * produced... Might want to look into restricting the display size by adding * the width and height attributes to the theme('image') call, based on the * selected preset? (get the presets and figure out the size from its actions?) - * + * * @param $tn_path string * @param $imagecache_preset string * @return * Markup for the image, making use of imagecache_external if it is available. */ -function _fedora_repository_render_image($tn_path, $imagecache_preset = 'fedora_repository_collection_thumbnail') { +function _fedora_repository_render_image($tn_path, $imagecache_preset = 'fedora_repository_collection_thumbnail', $truncated_title = '', $title = '') { $thumbnail = NULL; if ($thumbnail === NULL && module_exists('imagecache_external') && @@ -2425,11 +1636,14 @@ function _fedora_repository_render_image($tn_path, $imagecache_preset = 'fedora_ /** * Render an image, given a PID, DSID and preset. - * + * * Produces a Drupal path for the image, passes to * _fedora_repository_render_image(), and returns the result. - * + * * @see _fedora_repository_render_image() + * @todo + * Set the title/alt text(truncated title) for passing into _fedora_repository_render_image() + * * @param $pid string * A string containing a Fedora PID. * @param $dsid @@ -2447,10 +1661,97 @@ function fedora_repository_render_image($pid, $dsid, $imagecache_preset = 'fedor /** * Convenience function used in XSLT callback... - * - * @param $string string + * + * @param string $string * A string containing some markup to convert to a domnode. */ function fedora_repository_string_to_domnode($string) { return DOMDocument::loadXML($string); } + +/** + * Permission check function at old name. + * + * Defers the call to fedora_repository_check_perm() and displays a message + * to encourage any people using the old function to change their code. + * + * @deprecated + */ +function fedora_repository_access() { + drupal_set_message(t('Contact your code maintainer to change all occurences of fedora_repository_access() to fedora_repository_check_perm().')); + return call_user_func_array('fedora_repository_check_perm', func_get_args()); +} + +/** + * Hookable access check for module-specific permissions. + * + * @global $user + * @see hook_fedora_repository_check_perm() + * + * @param string $op + * The operation to be performed. + * @param string|null $pid + * A PID to check, or NULL to use the root collection PID. + * @param object|null $as_user + * An account to check the permission on, or NULL to use the current user. + * @param boolean $reset_cache + * A boolean to reset the static cache, if required in long-running processes. + * + * @return boolean + * A boolean indicating if the operation should be permitted (TRUE) or denied + * (FALSE). + */ +function fedora_repository_check_perm($op, $pid = NULL, $as_user = NULL, $reset_cache = FALSE) { + static $cache = array(); + + if ($reset_cache) { + $cache = array(); + } + // The PID can be empty for the root object. + if (empty($pid)) { + $pid = variable_get('fedora_repository_pid', 'islandora:root'); + } + if ($as_user === NULL) { + global $user; + $as_user = $user; + } + + // Populate the cache on a miss. + if (!isset($cache[$op][$pid][$as_user->uid])) { + $results = module_invoke_all('fedora_repository_check_perm', $op, $pid, $as_user); + // Nothing returned FALSE, and something returned TRUE. + $cache[$op][$pid][$as_user->uid] = (!in_array(FALSE, $results, TRUE) && in_array(TRUE, $results, TRUE)); + } + + return $cache[$op][$pid][$as_user->uid]; +} + +/** + * Implements hook_fedora_repository_check_perm(). + * + * Checks the PID namespace if restrictions are enabled, in addition to + * permitting according to Drupal permissions. + */ +function fedora_repository_fedora_repository_check_perm($op, $pid, $user) { + $to_return = TRUE; + if (variable_get('fedora_namespace_restriction_enforced', TRUE)) { + // Get the namespace (with colon) + $pid_namespace = substr($pid, 0, strpos($pid, ':') + 1); + $allowed_namespaces = explode(" ", variable_get('fedora_pids_allowed', 'default: demo: changeme: islandora: ilives: islandora-book: books: newspapers: ')); + + $to_return = in_array($pid_namespace, $allowed_namespaces); + } + + if ($to_return && user_access($op, $user)) { + // Straight Drupal permissions, let's allow it. + return TRUE; + } + elseif ($to_return === FALSE) { + // PID namespace is outside of those allowed. Forbid! + return FALSE; + } + else { + // Neither allowing of forbidding, to allow other modules to override. + return NULL; + } +} diff --git a/fedora_repository.solutionpacks.inc b/fedora_repository.solutionpacks.inc index b6c40412..09ad20d4 100644 --- a/fedora_repository.solutionpacks.inc +++ b/fedora_repository.solutionpacks.inc @@ -2,26 +2,38 @@ /** * @file - * Invokes a hook to any dependent modules asking them if their installations require - * any fedora objects to be present. Modules implementing this hook should return an array + * Invokes a hook to any dependent modules asking them if their + * installations require any fedora objects to be present. + * Modules implementing this hook should return an array * of arrays of the form: * - * array( 'pid', 'path-to-foxml-file', 'dsid', 'path-to-datastream-file', int dsversion) + * array( 'pid', 'path-to-foxml-file', + * 'dsid', + * 'path-to-datastream-file', + * int dsversion) * - * where the last three options are optional. A module can either point to a simple - * foxml file to install, or can specify a datastreamstream to check for, with a - * path to load the datastream from if it isn't there. Optionally a version number - * can be included, to enable updating of content model or collection policy streams - * that may have been updated. THis is a simple whole number that should be incremented - * when changed. This value appears in as an attribute of the topmost element of the stream, + * where the last three options are optional. + * A module can either point to a simple foxml file to install, + * or can specify a datastreamstream to check for, with a + * path to load the datastream from if it isn't there. + * Optionally a version number can be included, + * to enable updating of content model or collection policy streams + * that may have been updated. + * This is a simple whole number that should be incremented when changed. + * This value appears in as an attribute of the topmost element of the stream, * e.g.,: * - * + * $solution_pack_info) { $objects = array(); @@ -42,18 +54,27 @@ function fedora_repository_solution_packs_page() { } /** - * Check for installed objects and add a 'Update' or 'Install' button if some objects are missing. - * @param array $solution_pack + * Check for installed objects and add a 'Update' or 'Install' button if + * some objects are missing. + * + * @param array &$form_state + * The current state of the form. + * @param unknown $solution_pack_module + * Module name of that solution pack. + * @param string $solution_pack_name + * Human readable name for the solution pack. + * @param array $objects + * Defaults to an empty array. */ function fedora_repository_solution_pack_form(&$form_state, $solution_pack_module, $solution_pack_name, $objects = array()) { - + // Check each object to see if it is in the repository. module_load_include('inc', 'fedora_repository', 'api/fedora_item'); global $base_path; $needs_update = FALSE; $needs_install = FALSE; $form = array(); - + $form['solution_pack_module'] = array( '#type' => 'hidden', '#value' => $solution_pack_module, @@ -161,14 +182,20 @@ function fedora_repository_solution_pack_form(&$form_state, $solution_pack_modul return $form; } +/** + * Submit handler for solution pack form. + * + * @param array $form + * The form submitted. + * @param array_reference $form_state + * The state of the form submited. + */ function fedora_repository_solution_pack_form_submit($form, &$form_state) { - $what = $form_state; + $module_name = $form_state['values']['solution_pack_module']; - // This should be replaced with module_invoke - //$solution_pack_info = call_user_func($module_name . '_required_fedora_objects'); - $solution_pack_info = module_invoke($module_name, 'required_fedora_objects'); - + $solution_pack_info = module_invoke($module_name, 'fedora_repository_required_fedora_objects'); + $batch = array( 'title' => t('Installing / updating solution pack objects'), 'file' => drupal_get_path('module', 'fedora_repository') . '/fedora_repository.module', @@ -178,11 +205,25 @@ function fedora_repository_solution_pack_form_submit($form, &$form_state) { foreach ($solution_pack_info[$module_name]['objects'] as $object) { // Add this object to the batch job queue. - $batch['operations'][] = array('fedora_repository_batch_reingest_object', array($object)); + // Module name is needed in the finished callback. + $batch['operations'][] = array('fedora_repository_batch_reingest_object', array($object, $module_name)); } + + // Tell the batch to call the function to send out a postprocess hook. + $batch['finished'] = 'fedora_repository_solutionpack_send_postprocess'; + batch_set($batch); + } +/** + * Writes a form entry into the database. + * + * @param string $form_name + * The name of the form. + * @param unknown_type $form_xml + * The form definition. + */ function solution_pack_add_form($form_name, $form_xml) { $result = db_result(db_query('Select name from {xml_forms} where name = "%s"', $form_name)); if (!$result) { @@ -194,6 +235,14 @@ function solution_pack_add_form($form_name, $form_xml) { } } +/** + * Writes a form association to the database + * + * @param string $content_model + * content model PID + * @param string $form_name + * Name of the form + */ function solution_pack_add_form_association($content_model, $form_name) { $result = db_result(db_query('Select content_model from {islandora_content_model_forms} where content_model = "%s" and form_name = "%s"', $content_model, $form_name)); @@ -205,6 +254,6 @@ function solution_pack_add_form_association($content_model, $form_name) { $object->title_field = "['titleInfo']['title']"; $object->transform = 'mods_to_dc.xsl'; $result = drupal_write_record('islandora_content_model_forms', $object); - drupal_set_message(t("Added association between @cm and @name", array("@cm" => $content_model, "@name"=>$form_name))); + drupal_set_message(t("Added association between @cm and @name", array("@cm" => $content_model, "@name" => $form_name))); } } diff --git a/fedora_repository.test.inc b/fedora_repository.test.inc new file mode 100644 index 00000000..3e710fb8 --- /dev/null +++ b/fedora_repository.test.inc @@ -0,0 +1,161 @@ + + * + * administrator + * + * + */ +abstract class IslandoraTestCase extends DrupalWebTestCase { + + /** + * User with the rights required to perform the test + */ + protected $privileged_user; + + /** + * Override this method to provide the name of the module, + * e.g. the name of the .module file + * + * @return string - The name of the module + */ + abstract protected function getModuleName(); + + /** + * Returns basic permissions needed for running Islandora tests. + * Override this method to provide additional permissions, but + * be sure to append your new permissions to the return value + * of parent::getUserPermissions and return that. + * + * @return array - An array of strings describing permissions + */ + protected function getUserPermissions() { + return array( + 'access content', + 'add fedora datastreams', + 'edit fedora meta data', + 'edit tags datastream', + 'ingest new fedora objects', + 'purge objects and datastreams', + 'view fedora collection', + 'view detailed list of content', + ); + } + + /** + * Creates a user with permissions required for the test, and logs in. + */ + protected function createPrivilegedUser() { + // Create a role with the permissions from getUserPermissions() + $role = $this->drupalCreateRole($this->getUserPermissions()); + + // Create a user model + $user = array( + 'name' => 'simpletestuser', + 'mail' => 'simpletestuser@example.com', + 'roles' => array( $role => $role ), + 'pass' => 'simpletestpass', + 'status' => 1, + ); + + // Create a user from the model + $this->privileged_user = user_save('', $user); + + // Add the raw password so we can log in + $this->privileged_user->pass_raw = $user['pass']; + + // Log in + !$this->drupalLogin($this->privileged_user); + } + + /** + * Automatically generates all module dependencies and enables them in order. + * Also logs in a privileged user with the appropriate permissions for the + * test. + * + * If you need to override this method to provide extra functionality, + * please be sure to call parent::setUp so dependency resolution and + * authentication still happen. + */ + public function setUp() { + // Grab all the available modules + $modules = module_rebuild_cache(); + + // Grab the module to test's dependencies + $dependencies = $modules[$this->getModuleName()]->info['dependencies']; + + // Sort them so they're in the correct order to enable + $dependencies = array_reverse($dependencies); + + // Add our module to the end + $dependencies[] = $this->getModuleName(); + + // Enable the module's dependencies in order + call_user_func_array('parent::setUp', $dependencies); + + // Authenticate the privileged user + $this->createPrivilegedUser(); + } + + public function invoke($hook_name) { + $args = func_get_args(); + array_unshift($args, $this->getModuleName()); + return call_user_func_array('module_invoke', $args); + } +} + +/** + * Class containing tests that are common to all solution packs. + */ +abstract class SolutionPackTestCase extends IslandoraTestCase { + + /** + * Tests the fedora_repository_required_fedora_objects hook. + * + * Validates the schema of the array returned by the hook. The array should + * be roughly of the form: + * [ + * module_name => + * [ + * 'module' => module_name, + * 'title' => module_title, + * 'objects' => + * [ + * ... + * ] + * ] + * ] + * + * Where each entry of the 'objects' sub-array should be arrays themselves, + * each containing the information needed for drupal_get_form(). + * + * Note that the root key of the array is the actual module name (e.g. + * islandora_audio_sp, islandora_image_sp, etc...), not 'module_name' + */ + public function testFedoraRepositoryRequiredFedoraObjects() { + + // Invoke the hook + $results = $this->invoke('fedora_repository_required_fedora_objects'); + + // Validate the schema of the returned data structure + $this->assertNotNull($results, 'A non-null result was returned from the fedora_repository_required_fedora_objects hook.'); + $this->assertTrue(is_array($results), 'An array was returned from the fedora_repository_required_fedora_objects hook.'); + $this->assertTrue(array_key_exists($this->getModuleName(), $results), "Returned array has top level key that is equal to the module's short form name"); + $this->assertTrue(is_array($results[$this->getModuleName()]), "Value associated with top level key that is equal to the module's short form name is an array"); + $this->assertTrue(array_key_exists('module', $results[$this->getModuleName()]), "Top level array has 'module' key"); + $this->assertEqual($results[$this->getModuleName()]['module'], $this->getModuleName(), "Value associated with 'module' key is equal to the module's short form name"); + $this->assertTrue(array_key_exists('title', $results[$this->getModuleName()]), "Top level array has 'title' key"); + $this->assertTrue($results[$this->getModuleName()]['title'], "Title string is not empty"); + $this->assertTrue(array_key_exists('objects', $results[$this->getModuleName()]), "Returned array has second level key equal to 'object'"); + $this->assertTrue(is_array($results[$this->getModuleName()]['objects']), "Value associated with second level 'object' key is an array"); + } +} diff --git a/formClass.inc b/formClass.inc index 5184cf78..35878b11 100644 --- a/formClass.inc +++ b/formClass.inc @@ -1,7 +1,5 @@ t('Solution Packs'), 'description' => t('Install content models and collections required by installed solution packs.'), 'page callback' => 'fedora_repository_solution_packs_page', + 'access callback' => 'fedora_repository_check_perm', 'access arguments' => array('add fedora datastreams'), 'file' => 'fedora_repository.solutionpacks.inc', 'type' => MENU_LOCAL_TASK, @@ -52,6 +51,7 @@ class formClass { 'page callback' => 'fedora_repository_display_schema', 'page arguments' => array('islandoracm.xsd'), 'type' => MENU_CALLBACK, + 'access callback' => 'fedora_repository_check_perm', 'access arguments' => array('view fedora collection'), ); @@ -60,24 +60,28 @@ class formClass { 'page callback' => 'fedora_repository_display_schema', 'page arguments' => array('collection_policy.xsd'), 'type' => MENU_CALLBACK, + 'access callback' => 'fedora_repository_check_perm', 'access arguments' => array('view fedora collection'), ); $items['fedora'] = array( 'page callback' => 'repository_page', 'type' => MENU_CALLBACK, - 'access arguments' => array('view fedora collection'), + 'access callback' => 'fedora_repository_check_perm', + 'access arguments' => array('view fedora collection', 1), ); $items['fedora/repository'] = array( 'title' => 'Digital Repository', 'page callback' => 'repository_page', 'type' => MENU_NORMAL_ITEM, - 'access arguments' => array('view fedora collection'), + 'access callback' => 'fedora_repository_check_perm', + 'access arguments' => array('view fedora collection', 2), ); $items['fedora/repository/service'] = array( 'page callback' => 'repository_service', 'type' => MENU_CALLBACK, + 'access callback' => 'fedora_repository_check_perm', 'access arguments' => array('view fedora collection'), ); @@ -85,91 +89,56 @@ class formClass { 'title' => t('Download object'), 'page callback' => 'fedora_object_as_attachment', 'type' => MENU_CALLBACK, + 'access callback' => 'fedora_repository_check_perm', 'access arguments' => array('view fedora collection') ); - + $items['fedora/repository/editmetadata'] = array( 'title' => t('Edit metadata'), 'page callback' => 'fedora_repository_edit_qdc_page', 'type' => MENU_CALLBACK, - 'access arguments' => array('edit fedora meta data') + 'access callback' => 'fedora_repository_check_perm', + 'access arguments' => array('edit fedora meta data', 3) ); - + $items['fedora/repository/purgeStream'] = array( 'title' => t('Purge data stream'), 'page callback' => 'fedora_repository_purge_stream', 'type' => MENU_CALLBACK, - 'access arguments' => array('purge objects and datastreams') + 'access callback' => 'fedora_repository_check_perm', + 'access arguments' => array('purge objects and datastreams', 3) ); - + $items['fedora/repository/replaceStream'] = array( 'title' => t('Replace Stream'), 'page callback' => 'fedora_repository_replace_stream', 'type' => MENU_CALLBACK, - 'access arguments' => array('add fedora datastreams'), + 'access callback' => 'fedora_repository_check_perm', + 'access arguments' => array('add fedora datastreams', 3), ); - + $items['fedora/repository/purgeObject'] = array( 'title' => t('Purge object'), 'page callback' => 'fedora_repository_purge_object', 'type' => MENU_CALLBACK, - 'access arguments' => array('purge objects and datastreams') + 'access callback' => 'fedora_repository_check_perm', + 'access arguments' => array('purge objects and datastreams', 3) ); - + $items['fedora/repository/addStream'] = array( 'title' => t('Add stream'), 'page callback' => 'add_stream', 'type' => MENU_CALLBACK, - 'access arguments' => array('add fedora datastreams') + 'access callback' => 'fedora_repository_check_perm', + 'access arguments' => array('add fedora datastreams', 3) ); - - //new for mnpl****************************************** - $items['fedora/repository/mnpl_advanced_search'] = array( - 'title' => t('Repository advanced search'), - 'page callback' => 'fedora_repository_mnpl_advanced_search', - 'type' => MENU_CALLBACK, - 'access arguments' => array('view fedora collection') - ); - + $items['fedora/ingestObject'] = array( 'title' => t('Ingest object'), 'page callback' => 'fedora_repository_ingest_object', 'type' => MENU_CALLBACK, - 'access arguments' => array('add fedora datastreams') - ); - - $items['fedora/repository/list_terms'] = array( - 'title' => t('List terms'), - 'page callback' => 'fedora_repository_list_terms', - 'type' => MENU_CALLBACK, - 'access arguments' => array('view fedora collection') - ); - - /* Export functionality */ - $items['fedora/basket'] = array( - 'title' => t('Fedora Basket'), - 'description' => t('View and download objects added to your basket'), - 'page callback' => 'fedora_repository_basket', - 'access arguments' => array('view fedora collection'), - 'type' => MENU_CALLBACK, - ); - - $items['fedora/repository/addToBasket'] = array( - 'page callback' => 'fedora_repository_add_to_basket', - 'type' => MENU_CALLBACK, - 'access arguments' => array('view fedora collection'), - ); - - $items['fedora/repository/removeFromBasket'] = array( - 'page callback' => 'fedora_repository_remove_from_basket', - 'type' => MENU_CALLBACK, - 'access arguments' => array('view fedora collection'), - ); - - $items['fedora/repository/add_search_results_to_basket'] = array( - 'page callback' => 'fedora_repository_add_search_results_to_basket', - 'type' => MENU_CALLBACK, - 'access arguments' => array('view fedora collection'), + 'access callback' => 'fedora_repository_check_perm', + 'access arguments' => array('add fedora datastreams', 2) ); $items['admin/settings/fedora_repository/object_details_xslt'] = array( @@ -194,7 +163,7 @@ class formClass { /** * Create admin form - * @return array + * @return array */ function createAdminForm() { if (!user_access('administer site configuration')) { @@ -221,7 +190,7 @@ class formClass { '#required' => TRUE, '#weight' => -16, ); - + $form['fedora_repository_url'] = array( '#type' => 'textfield', @@ -230,16 +199,16 @@ class formClass { '#description' => t('The url of the Fedora server'), '#required' => TRUE, '#weight' => -14 ); - + $form['fedora_soap_url'] = array( '#type' => 'textfield', '#title' => t('Fedora SOAP Url'), - '#default_value' => variable_get('fedora_soap_url', 'http://localhost:8080/fedora/services/access?wsdl'), + '#default_value' => variable_get('fedora_soap_url', 'http://localhost:8080/fedora/wsdl?api=API-A'), '#description' => t('The URL to use for SOAP connections'), '#required' => TRUE, '#weight' => -12, '#suffix' => '

    ' . ( - fedora_available() ? + fedora_available() ? theme('image', 'misc/watchdog-ok.png') . t('Successfully connected to Fedora server at @fedora_soap_url', array('@fedora_soap_url' => variable_get('fedora_soap_url', ''))) : theme('image', 'misc/watchdog-error.png') . t('Unable to connect to Fedora server at @fedora_soap_url', array('@fedora_soap_url' => variable_get('fedora_soap_url', '')))) . '

    ', ); @@ -347,7 +316,7 @@ class formClass { '#default_value' => variable_get('fedora_object_restrict_datastreams', FALSE), '#description' => t('When enabled, restricts access to fedora object datastreams that are not listed in the Islandora Content Model for the object (unless the user is an administrator).'), ); - + $form['advanced']['fedora_repository_use_imagecache_external_in_collection_view'] = array( '#type' => 'checkbox', '#title' => t('Allow imagecache_external use for thumbnails in collection view'), @@ -355,14 +324,14 @@ class formClass { '#description' => t('If enabled, the default collection list view (or ' . 'anywhere the function "@function" is used) will try to use ' . 'imagecache_external, defaulting to the "@preset" preset. XSLTs may ' . - 'be updated to use this function.', + 'be updated to use this function.', array( '@function' => '_fedora_repository_render_image()', '@preset' => 'fedora_repository_collection_thumbnail', '@xsl' => 'sparql_to_html.xsl', )), ); - + $form['advanced']['fedora_control_group_control_during_ingest'] = array( '#type' => 'checkbox', '#title' => t('Allow control groups select in datastream ingest'), @@ -370,12 +339,28 @@ class formClass { '#default_value' => variable_get('fedora_control_group_control_during_ingest', FALSE), ); + //FITS functionality + $form['advanced']['enable_fits'] = array( + '#type' => 'checkbox', + '#title' => t('Enable FITS support?'), + '#description' => t('Whether or not we should create a FITS datastream upon object ingest.'), + '#default_value' => variable_get('enable_fits', FALSE), + ); + + //FITS Path + $form['advanced']['fits_path'] = array( + '#type' => 'textfield', + '#title' => t('Path to FITS executable'), + '#description' => t("Path to FITS program on your server. It must be accessible by Drupal (i.e. apache user)."), + '#default_value' => variable_get('fits_path','/usr/local/bin/fits.sh'), + ); + //Export functionality $form['advanced']['module']['export_area'] = array( '#type' => 'textfield', '#title' => t('Export area'), '#default_value' => variable_get('export_area', file_directory_path() . '/fedora_export_area'), - '#description' => t("Path to the export area. It must be accessible by druapl (i.e. apache user)."), + '#description' => t("Path to the export area. It must be accessible by drupal (i.e. apache user)."), '#required' => TRUE, ); @@ -390,7 +375,7 @@ class formClass { * @param type $form_id * @param type $form_values * @param type $client - * @return type + * @return type */ function updateMetaData($form_id, $form_values, $client) { // ====================================== @@ -409,13 +394,13 @@ class formClass { // DC elements $previousElement = NULL; // Used in case we have to nest elements for qualified dublin core. - + $label = null; foreach ($form_values as $key => $value) { //echo ($key); if ($key == 'dc:title-0') { $label = $value; - } + } $index = strrpos($key, '-'); $key = substr($key, 0, $index); $test = substr($key, 0, 2); @@ -441,8 +426,8 @@ class formClass { { $object = new Fedora_Item($form_values['pid']); $object->modify_object($label); - } - + } + $dom->appendChild($oai); if (!$client) { @@ -472,7 +457,7 @@ class formClass { * to determine if this user is allowed to ingest in this collection * we assume if they are able to modify objects in the collection they can ingest as well. * @param type $collection_pid - * @return type + * @return type */ function can_ingest_here($collection_pid) { module_load_include('inc', 'fedora_repository', 'SecurityClass'); @@ -483,12 +468,16 @@ class formClass { /** * Drupal's permissions at this point no xacml yet. xacml decisions are made by fedora * @param type $collection_pid - * @return type + * @return type */ function canShowIngestForm($collection_pid) { - if (!user_access('ingest new fedora objects')) { - drupal_set_message(t('You do not have permission to ingest.'), 'error'); - return FALSE; + if (!fedora_repository_check_perm('ingest new fedora objects', $collection_pid)) { + $ingest_override_array = module_invoke_all('fedora_repository_can_ingest', $collection_pid); + $overrides = array_filter($ingest_override_array); + if (empty($overrides)) { + drupal_set_message(t('You do not have permission to ingest.'), 'error'); + return FALSE; + } } module_load_include('inc', 'fedora_repository', 'SecurityClass'); $security_class = new SecurityClass(); @@ -508,11 +497,11 @@ class formClass { /** * Creates the first page of the ingest form for editing QDC. - * + * * @param string $collection_pid * @param string $collection_label * @param array $form_state - * + * * @return array */ function createQDCIngestFormPageOne($collection_pid, $collection_label, array &$form_state) { @@ -558,11 +547,11 @@ class formClass { /** * Create the second page of the ingest form for editing QDC - * + * * @param string $collection_pid * @param string $collection_label * @param array $form_state - * + * * @return array */ function createQDCIngestFormPageTwo($collection_pid, $collection_label, array &$form_state) { @@ -593,11 +582,11 @@ class formClass { /** * Create the QDC Ingest Form. - * + * * @param type $collection_pid * @param type $collection_label - * @param array $form_state - * + * @param array $form_state + * * @return array */ function createQDCIngestForm($collection_pid, $collection_label, array &$form_state) { @@ -613,18 +602,18 @@ class formClass { /** * Create a multi step form (wizard) for ingesting objects into Fedora - * + * * @param string $collection_pid * @param string $collection_label * @param array $form_state - * - * @return array + * + * @return array */ function createIngestForm($collection_pid, $collection_label, array &$form_state) { if (!$this->canShowIngestForm($collection_pid)) { return FALSE; } - + drupal_set_title($collection_label); if (module_exists('islandora_content_model_forms')) { module_load_include('inc', 'islandora_content_model_forms', 'IngestObjectMetadataForm'); @@ -643,7 +632,7 @@ class formClass { * this function may not be being used * @param type $pid * @param type $form_state - * @return string + * @return string */ function createAddDataStreamForm($pid, &$form_state) { //dump_vars($form_state); @@ -723,7 +712,7 @@ class formClass { // '#required'=>'TRUE', '#description' => t('The file to upload. (Only for Managed and Inline)') ); - + if (variable_get('fedora_control_group_control_during_ingest', FALSE)) { $form['fieldset']['ds_reference'] = array( '#type' => 'textfield', @@ -732,7 +721,7 @@ class formClass { '#description' => t('A URL reference to resolve for the contents of the datastream. (Required for External and Redirect, but will still work for Managed and Inline.)'), ); } - + $form['#redirect'] = "fedora/repository/$pid/"; $form['fieldset']['submit'] = array( '#type' => 'submit', @@ -758,7 +747,7 @@ class formClass { '#weight' => -1, ); } - + if (variable_get('fedora_control_group_control_during_ingest', FALSE)) { $form['fieldset']['control_group'] = array( '#type' => 'select', @@ -778,13 +767,13 @@ class formClass { /** * Create QDC Edit form. - * + * * @param string $pid * @param string $dsid * @param object $client * @param array $form_state - * - * @return string + * + * @return string */ function createQDCEditForm($pid, $dsid, $client, &$form_state) { module_load_include('inc', 'fedora_repository', 'api/fedora_item'); @@ -869,7 +858,7 @@ class formClass { * @param type $dsid * @param type $client * @param boolean $form_state - * @return type + * @return type */ function createMetaDataForm($pid, $dsid, $client, &$form_state) { if (module_exists('islandora_content_model_forms')) { @@ -890,13 +879,13 @@ class formClass { * @param type $dsId * @param type $dsLabel * @param type $form_state - * @return type + * @return type */ function createReplaceDataStreamForm($pid, $dsId, $dsLabel, &$form_state) { $form = array(); $form['#attributes']['enctype'] = 'multipart/form-data'; - + module_load_include('inc', 'fedora_repository', 'api/fedora_item'); $item = new Fedora_Item($pid); $info = $item->get_datastream_info($dsId); @@ -922,7 +911,7 @@ class formClass { '#value' => t('If both a file and a reference are given, the file will be given preference.'), ); } - + $form['pid'] = array( '#type' => 'value', '#value' => $pid, diff --git a/object_details_xslts/convertQDC.xsl b/object_details_xslts/convertQDC.xsl index 5d881e35..036eb20a 100644 --- a/object_details_xslts/convertQDC.xsl +++ b/object_details_xslts/convertQDC.xsl @@ -9,7 +9,7 @@
    - + @@ -30,4 +30,4 @@ - \ No newline at end of file + diff --git a/object_details_xslts/mods2html.xsl b/object_details_xslts/mods2html.xsl index 3f794523..59e13a50 100644 --- a/object_details_xslts/mods2html.xsl +++ b/object_details_xslts/mods2html.xsl @@ -51,6 +51,7 @@

    MetaData

    +
    diff --git a/plugins/FedoraObjectDetailedContent.inc b/plugins/FedoraObjectDetailedContent.inc index f1d7949b..709b9203 100644 --- a/plugins/FedoraObjectDetailedContent.inc +++ b/plugins/FedoraObjectDetailedContent.inc @@ -55,14 +55,14 @@ class FedoraObjectDetailedContent { if (!isset($profile)) { // default behaviour watchdog('fedora_repository', "Error while reading the default object details display profile: @e", array("@e" => $e->getMessage()), WATCHDOG_WARNING); - $dc_html = $objectHelper->getFormattedDC($this->item); + $dc_returned = $objectHelper->getFormattedDC($this->item); } else { // invoke the requested display profile require_once(drupal_get_path('module', $profile['module']) ."/". $profile['file']); $details_function = $profile['function']; if (function_exists($details_function)) { - $dc_html = $details_function($this->item); + $dc_returned = $details_function($this->item); } else { // problem - display profile not found @@ -70,16 +70,31 @@ class FedoraObjectDetailedContent { } } + $dc_array = array(); $i = 0; - if (fedora_repository_access(OBJECTHELPER :: $VIEW_DETAILED_CONTENT_LIST, $this->pid, $user)) { - $tabset['fedora_object_details']['tabset']['view'] = array( - '#type' => 'tabpage', - '#title' => t('View'), - 'dc' => array( - '#type' => 'markup', - '#value' => $dc_html, //XXX: This could easily be done in Drupal, instead of using an XSL - '#weight' => $i++ - ), + if (is_array($dc_returned)) { + $dc_array = $dc_returned; + $dc_array['#weight'] = $i++; + } + elseif (!empty($dc_returned)) { + $dc_array = array( + '#type' => 'markup', + '#value' => $dc_returned, //XXX: This could easily be done in Drupal, instead of using an XSL + '#weight' => $i++ + ); + } + + $tabset['fedora_object_details']['tabset']['view'] = array( + '#type' => 'tabpage', + '#title' => t('View'), + ); + + if (!empty($dc_array)) { + $tabset['fedora_object_details']['tabset']['view']['dc'] = $dc_array; + } + + if (fedora_repository_check_perm(ObjectHelper :: $VIEW_DETAILED_CONTENT_LIST, $this->pid, $user)) { + $tabset['fedora_object_details']['tabset']['view'] += array( 'list' => array( '#type' => 'fieldset', '#title' => t('Detailed List of Content'), @@ -100,6 +115,11 @@ class FedoraObjectDetailedContent { '#weight' => $i++, ), ), + ); + } + + if (fedora_repository_check_perm(ObjectHelper :: $PURGE_FEDORA_OBJECTSANDSTREAMS, $this->pid, $user)) { + $tabset['fedora_object_details']['tabset']['view'] += array( 'purge' => array( '#type' => 'markup', '#value' => $purge_form, @@ -108,7 +128,7 @@ class FedoraObjectDetailedContent { ); } - if (fedora_repository_access(OBJECTHELPER :: $EDIT_FEDORA_METADATA, $this->pid, $user)) { + if (fedora_repository_check_perm(OBJECTHELPER :: $EDIT_FEDORA_METADATA, $this->pid, $user)) { $editform = drupal_get_form('fedora_repository_edit_qdc_form', $this->pid, 'DC'); $tabset['fedora_object_details']['tabset']['edit'] = array( '#type' => 'tabpage', @@ -119,7 +139,8 @@ class FedoraObjectDetailedContent { } $ts = $tabset['fedora_object_details']['tabset']; - if (array_key_exists('view', $ts) || array_key_exists('edit', $ts)) { + if ((array_key_exists('view', $ts) && (count(element_children($ts['view'])) > 0)) || + (array_key_exists('edit', $ts) && (count(element_children($ts['edit'])) > 0 || array_key_exists('#content', $ts['edit'])))) { return $tabset; } else { diff --git a/plugins/ShowStreamsInFieldSets.inc b/plugins/ShowStreamsInFieldSets.inc index e75ddec1..ed9ba511 100644 --- a/plugins/ShowStreamsInFieldSets.inc +++ b/plugins/ShowStreamsInFieldSets.inc @@ -121,7 +121,7 @@ EOJS '#content' => $dl_link . $dc_html, ); - if (fedora_repository_access(OBJECTHELPER :: $EDIT_FEDORA_METADATA, $this->pid, $user)) { + if (fedora_repository_check_perm(OBJECTHELPER :: $EDIT_FEDORA_METADATA, $this->pid, $user)) { $editform = drupal_get_form('fedora_repository_edit_qdc_form', $this->pid, 'DC'); $tabset['first_tab']['tabs']['edit'] = array( '#type' => 'tabpage', diff --git a/plugins/fedora_imageapi.info b/plugins/fedora_imageapi.info index 83454b47..2396c740 100644 --- a/plugins/fedora_imageapi.info +++ b/plugins/fedora_imageapi.info @@ -3,5 +3,5 @@ description = Adds image manipulation support through a REST interface package = Islandora Dependencies dependencies[] = fedora_repository dependencies[] = imageapi -version = 6.x-12.2.0 +version = 6.x-12.3.0-RC1 core = 6.x diff --git a/plugins/fits.inc b/plugins/fits.inc new file mode 100644 index 00000000..15e8a12e --- /dev/null +++ b/plugins/fits.inc @@ -0,0 +1,96 @@ +pid = $pid; + $this->item = new Fedora_Item($this->pid); + } + } + + /** + * extract metadata + * @param type $parameterArray + * @param type $dsid + * @param type $file + * @param type $file_ext + * @return type + */ + function extractFits($parameterArray, $dsid, $file, $file_ext) { + if (variable_get('enable_fits', FALSE) == 1) { + $file_name = '_' . $dsid . '.xml'; + $output = array(); + exec(variable_get('fits_path', '/usr/local/bin/fits.sh') .' -i ' . escapeshellarg($file) . '', $output); + if ( !file_put_contents($file . $file_name, implode("\n", $output)) ) { + //drupal_set_message(t("error writing fits file %s", array('%s' => "$file.$file_name"))); + return FALSE; + } + $_SESSION['fedora_ingest_files']["$dsid"] = $file . $file_name; + return TRUE; + } + return TRUE; //this prevents getting the error following content model rules message when fits generation is turned off + } + + /** + * display metadata + * @return type + */ + function displayFits() { + $output = ''; + $fits = $this->item->get_datastream_dissemination('TECHMD_FITS'); + if (trim($fits) != '') { + $fitsDom = DOMDocument::loadXML($this->item->get_datastream_dissemination('FITS')); + if ($fitsDom != NULL) { + $description = $fitsDom->getElementsByTagName('fits'); + if ($description->length > 0) { + $description = $description->item(0); + $output .= ''; + + $fieldset = array( + '#title' => t("!text", array('!text' => 'FITS Technical Metadata')), + '#collapsible' => TRUE, + '#collapsed' => TRUE, + '#value' => $output + ); + $output = theme('fieldset', $fieldset); + } + } + } + return $output; + } + +} diff --git a/plugins/herbarium.inc b/plugins/herbarium.inc index 0ad13fd6..e8ef429f 100644 --- a/plugins/herbarium.inc +++ b/plugins/herbarium.inc @@ -186,7 +186,7 @@ class Herbarium { ); module_load_include('inc', 'fedora_repository', 'ObjectHelper'); $obj = new ObjectHelper(); - if (fedora_repository_access(OBJECTHELPER :: $EDIT_FEDORA_METADATA, $this->pid, $user)) { + if (fedora_repository_check_perm(OBJECTHELPER :: $EDIT_FEDORA_METADATA, $this->pid, $user)) { $editform = drupal_get_form('fedora_repository_edit_qdc_form', $this->pid, 'DARWIN_CORE'); $tabset['third_tab']['tabset']['edit'] = array( '#type' => 'tabpage', diff --git a/plugins/qt_viewer.inc b/plugins/qt_viewer.inc index 74f34a3e..d02b7a6d 100644 --- a/plugins/qt_viewer.inc +++ b/plugins/qt_viewer.inc @@ -151,7 +151,7 @@ class ShowQtStreamsInFieldSets { 'poster' => array( '#type' => 'markup', '#value' => theme('image', "fedora/repository/{$this->pid}/{$pframe->ID}/poster.jpg", '', '', NULL, FALSE) - ) + ), 'play' => array( '#type' => 'markup', '#prefix' => '
    ', @@ -167,7 +167,7 @@ class ShowQtStreamsInFieldSets { '#value' => l(t('Download Media File'), "fedora/repository/{$this->pid}/OBJ/MOV.mov", array('attributes' => array('class' => 'download'))), ); } - $src = url("fedora/repository/{$this->pid}/{$media->ID}/MOV.mov"; + $src = url("fedora/repository/{$this->pid}/{$media->ID}/MOV.mov"); $qtparams = "'autostart', '" . ($pframe !== FALSE ? 'TRUE' : 'FALSE') . "', "; $init = << $tag_title_text ))), ); - if (user_access('modify fedora datastreams') || user_access('add fedora tags')) { + if (fedora_repository_check_perm('modify fedora datastreams', $pid) || + fedora_repository_check_perm('edit tags datastream', $pid)) { // Delete button for each existing tag. $form_tag['delete'] = array( '#type' => 'imagebutton', @@ -86,7 +87,8 @@ function fedora_repository_image_tagging_form($form_state, $pid) { ); } } - if (user_access('modify fedora datastreams') || user_access('add fedora tags')) { + if (fedora_repository_check_perm('modify fedora datastreams', $pid) || + fedora_repository_check_perm('edit tags datastream', $pid)) { $form['tags-wrapper']['addtag'] = array( '#type' => 'textfield', '#title' => t('New Tag'), diff --git a/xsl/sparql_to_html.xsl b/xsl/sparql_to_html.xsl index 79cc438e..1b5872b8 100644 --- a/xsl/sparql_to_html.xsl +++ b/xsl/sparql_to_html.xsl @@ -90,8 +90,6 @@ - - @@ -103,17 +101,9 @@ - - + - - - - - - - +