dmBridge PHP API
DMGenericTemplateHelper.php
00001 <?php
00002 #
00003 # dmBridge: a data access framework for CONTENTdm(R)
00004 #
00005 # Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
00006 # Education, on behalf of the University of Nevada, Las Vegas
00007 #
00008 
00019 class DMGenericTemplateHelper extends DMAbstractTemplateHelper
00020 implements DMTemplateHelper {
00021 
00025    private $body_scripts = array();
00026 
00030    private $head_scripts = array();
00031 
00035    private $meta_tags = array();
00036 
00040    private $stylesheets = array();
00041 
00046    public function __construct(DMAbstractView $view,
00047          DMSession $session = null) {
00048       parent::__construct($view, $session);
00049       $this->addMetaTag("text/html; charset=utf-8", null, "Content-Type");
00050       $this->addMetaTag("public", null, "Cache-Control");
00051       $this->addMetaTag("public", null, "Pragma");
00052       $this->addMetaTag(DMConfigXML::getInstance()->getFeedCopyright(),
00053             "copyright");
00054    }
00055 
00063    public function  __call($method, $args) {
00064       // check for non-module template helpers
00065       $all_helpers = $this->getView()->getAllHelpers();
00066       foreach ($all_helpers as $helper) {
00067          if (method_exists($helper, $method)) {
00068             return call_user_func_array(array($helper, $method), $args);
00069          }
00070       }
00071       throw new DMNoSuchMethodException($method);
00072    }
00073 
00081    public function getHtmlAtomFeedURL() {
00082       return $this->getFeedURL("atom");
00083    }
00084 
00100    public function addBodyScriptTag($src, $type = "text/javascript") {
00101       $tagvals = array(
00102          'src' => $src,
00103          'type' => $type
00104       );
00105 
00106       // if the script already exists, overwrite it
00107       $count = count($this->body_scripts);
00108       for ($i = 0; $i < $count; $i++) {
00109          if ($src == $this->body_scripts[$i]['src']) {
00110             $this->body_scripts[$i] = $tagvals;
00111             return;
00112          }
00113       }
00114 
00115       // it doesn't exist, so add it
00116       $this->body_scripts[] = $tagvals;
00117    }
00118 
00123    public function getHtmlBodyScriptTags(array $exclude_filenames = array()) {
00124       $tags = "";
00125       foreach ($this->body_scripts as $script) {
00126          if (!in_array(basename($script['src']), $exclude_filenames)) {
00127             $tags .= sprintf('<script type="%s" src="%s"></script>',
00128                   $script['type'], $script['src']);
00129          }
00130       }
00131       return $tags;
00132    }
00133 
00143    public function removeBodyScriptTag($src) {
00144       $count = count($this->body_scripts);
00145       for ($i = 0; $i < $count; $i++) {
00146          if ($src == $this->body_scripts[$i]['src']) {
00147             unset($this->body_scripts[$i]);
00148             return true;
00149          }
00150       }
00151       return false;
00152    }
00153 
00161    public function getHtmlCollectionsAsPulldown() {
00162       $cols = array();
00163       $cols = DMCollection::getAuthorized();
00164       $dxml = new DMDOMDocument("1.0", "utf-8");
00165       $dxml->loadXML("<form/>");
00166       $select = $dxml->createElement("select");
00167       $select->setAttribute("id", "dmSelectCollection");
00168       $select->setAttribute("class", "dmCollections");
00169       $select->setAttribute("onchange", "window.location = this.value");
00170 
00171       $option = $dxml->createElement("option", "Select a collection...");
00172       $select->appendChild($option);
00173 
00174       foreach ($cols as $c) {
00175          $query = new DMObjectQuery();
00176          $query->addCollection($c);
00177          $option = $dxml->createElement(
00178             "option", DMString::websafe($c->getName()));
00179          $option->setAttribute("value", $query->getURI());
00180          $collection = $this->getView()->getCollection();
00181          if ($collection) {
00182             if ($c->getAlias() == $collection->getAlias()) {
00183                $option->setAttribute("selected", "selected");
00184             }
00185          }
00186          $select->appendChild($option);
00187       }
00188       $dxml->documentElement->appendChild($select);
00189 
00190       $noscript = $dxml->createElement("noscript");
00191       $input = $dxml->createElement("input");
00192       $input->setAttribute("type", "submit");
00193       $input->setAttribute("value", "Go");
00194       $noscript->appendChild($input);
00195       $dxml->documentElement->appendChild($noscript);
00196 
00197       $dxml->formatOutput = true;
00198       return $dxml->saveHTML($dxml->documentElement);
00199    }
00200 
00212    public function getHtmlFormattedFlash() {
00213       $tmp = DMHTTPRequest::getCurrent()->getSession()->getFlash();
00214       if (!$tmp instanceof DMFlash) {
00215          return false;
00216       }
00217       $flash = clone $tmp;
00218       DMHTTPRequest::getCurrent()->getSession()->unsetFlash();
00219       $status = "dmNeutral";
00220       if ($flash->getStatus() === true) {
00221          $status = "dmSuccess";
00222       } else if ($flash->getStatus() === false) {
00223          $status = "dmFailure";
00224       }
00225       $msg = sprintf('<p class="%s">%s</p>',
00226          trim("dmFlash " . $status),
00227          DMString::websafe($flash->getValue()));
00228       return $msg;
00229    }
00230 
00246    public function addHeadScriptTag($src, $type = "text/javascript") {
00247       $tagvals = array(
00248          'src' => $src,
00249          'type' => $type
00250       );
00251 
00252       // if the script already exists, overwrite it
00253       $count = count($this->head_scripts);
00254       for ($i = 0; $i < $count; $i++) {
00255          if ($src == $this->head_scripts[$i]['src']) {
00256             $this->head_scripts[$i] = $tagvals;
00257             return;
00258          }
00259       }
00260 
00261       // it doesn't exist, so add it
00262       $this->head_scripts[] = $tagvals;
00263    }
00264 
00268    public function getHtmlHeadScriptTags() {
00269       $tags = "";
00270       foreach ($this->head_scripts as $script) {
00271          $tags .= sprintf('<script type="%s" src="%s"></script>',
00272                $script['type'], $script['src']);
00273       }
00274       return $tags;
00275    }
00276 
00286    public function removeHeadScriptTag($src) {
00287       $count = count($this->head_scripts);
00288       for ($i = 0; $i < $count; $i++) {
00289          if ($src == $this->head_scripts[$i]['src']) {
00290             unset($this->head_scripts[$i]);
00291             return true;
00292          }
00293       }
00294       return false;
00295    }
00296 
00308    public function getHtmlLoginPageLink(
00309          $login_text = "Login", $logout_text = "Logout") {
00310       if (DMHTTPRequest::getCurrent()->getSession()->getUser()) {
00311          $dest = $this->getView()->getLogoutURI();
00312          $text = $logout_text;
00313       } else {
00314          $dest = $this->getView()->getLoginView()->getURI();
00315          $text = $login_text;
00316       }
00317       return sprintf('<a href="%s">%s</a>',
00318          DMString::websafe($dest), DMString::websafe($text));
00319    }
00320 
00327    public function getHtmlLoginForm() {
00328       $html = sprintf('<form action="%s" method="post">
00329             <fieldset id="dmLoginForm">
00330                <legend>Login</legend>
00331 
00332                <label for="username">Username:</label>
00333                <input id="dmLoginUsername" type="text" name="username"
00334                   size="20" maxlength="30">
00335                <br>
00336 
00337                <label for="password">Password:</label>
00338                <input id="dmLoginPassword" type="password" name="password"
00339                   size="20" maxlength="30">
00340                <br>
00341 
00342                <input type="submit" value="Login">
00343             </fieldset>
00344          </form>',
00345          DMInternalURI::getURIWithParams("objects/login"));
00346       return $html;
00347    }
00348 
00361    public function addMetaTag($content, $name, $http_equiv = null) {
00362       $tagvals = array(
00363          'content' => $content,
00364          'name' => $name,
00365          'http-equiv' => $http_equiv
00366       );
00367 
00368       // if the tag already exists, overwrite it
00369       $count = count($this->meta_tags);
00370       for ($i = 0; $i < $count; $i++) {
00371          if ($name == $this->meta_tags[$i]['name']
00372                || $http_equiv == $this->meta_tags[$i]['http-equiv']) {
00373             $this->meta_tags[$i] = $tagvals;
00374             return;
00375          }
00376       }
00377 
00378       // it doesn't already exist, so add it
00379       $this->meta_tags[] = $tagvals;
00380    }
00381 
00385    public function getHtmlMetaTags() {
00386       $tags = "";
00387       foreach ($this->meta_tags as $mt) {
00388          $tag = sprintf('<meta content="%s"', $mt['content']);
00389          if ($mt['name']) {
00390             $tag .= sprintf(' name="%s"', $mt['name']);
00391          }
00392          if ($mt['http-equiv']) {
00393             $tag .= sprintf(' http-equiv="%s"', $mt['http-equiv']);
00394          }
00395          $tags .= $tag .= '>';
00396       }
00397       return $tags;
00398    }
00399 
00409    public function removeMetaTag($name = null, $http_equiv = null) {
00410       $count = count($this->meta_tags);
00411       for ($i = 0; $i < $count; $i++) {
00412          if ((!is_null($name) && $name == $this->meta_tags[$i]['name'])
00413                || (!is_null($http_equiv) && $http_equiv == $this->meta_tags[$i]['http-equiv'])) {
00414             unset($this->meta_tags[$i]);
00415             return true;
00416          }
00417       }
00418       return false;
00419    }
00420 
00432    public function getHtmlRecentlyViewedObjectsAsList($limit = 5, $thumbs = false) {
00433       $dxml = new DMDOMDocument("1.0", "utf-8");
00434       $dxml->loadXML("<ol/>");
00435       $dxml->documentElement->setAttribute("class", "dmRecentObjectLinks");
00436 
00437       $objects = $this->getView()->getRecentlyViewedObjects($limit);
00438 
00439       foreach (array_reverse($objects) as $obj) {
00440          $li = $dxml->createElement("li");
00441          $dxml->documentElement->appendChild($li);
00442 
00443          $a = $dxml->createElement("a");
00444          $a->setAttribute("href", $obj->getURI());
00445 
00446          $frag = $dxml->createDocumentFragment();
00447          if ($thumbs) {
00448             $img = $dxml->createElement("img");
00449             $img->setAttribute("class", "dmThumbnail");
00450             $img->setAttribute("src", $obj->getThumbnailURL());
00451             $img->setAttribute("alt", "Page thumbnail");
00452             $frag->appendChild($img);
00453          }
00454          $frag->appendChild($dxml->createTextNode(
00455                $obj->getMetadata("title")));
00456          $a->appendChild($frag);
00457          $li->appendChild($a);
00458       }
00459 
00460       return $dxml->saveHTML($dxml->documentElement);
00461    }
00462 
00474    public function addStylesheetTag($href, $type = "text/css",
00475          $media = "screen") {
00476       $tagvals = array(
00477          'type' => $type,
00478          'media' => $media,
00479          'href' => $href
00480       );
00481 
00482       // if the stylesheet already exists, overwrite it
00483       $count = count($this->stylesheets);
00484       for ($i = 0; $i < $count; $i++) {
00485          if ($href == $this->stylesheets[$i]['href']) {
00486             $this->stylesheets[$i] = $tagvals;
00487             return;
00488          }
00489       }
00490 
00491       // it doesn't exist, so add it
00492       $this->stylesheets[] = $tagvals;
00493    }
00494 
00498    public function getHtmlStylesheetTags() {
00499       $tags = "";
00500       foreach ($this->stylesheets as $sheet) {
00501          $tags .= sprintf(
00502                '<link rel="stylesheet" type="%s" media="%s" href="%s">',
00503                $sheet['type'], $sheet['media'], $sheet['href']);
00504       }
00505       return $tags;
00506    }
00507 
00517    public function removeStylesheetTag($href) {
00518       $count = count($this->stylesheets);
00519       for ($i = 0; $i < $count; $i++) {
00520          if ($href == $this->stylesheets[$i]['href']) {
00521             unset($this->stylesheets[$i]);
00522             return true;
00523          }
00524       }
00525       return false;
00526    }
00527 
00539    public function getHtmlTagsAsCloud($tag_limit = 20, $num_classes = 10,
00540          $randomize = true) {
00541       $tq = new DMTagQuery(DMDataStoreFactory::getDataStore());
00542       $tq->setNumResultsPerPage($tag_limit);
00543       $tq->addCollection($this->getView()->getCollection());
00544       $tq->setApproved(1);
00545       $tq->setSortByFrequency(true);
00546 
00547       $tags = $tq->getSearchResultsAsCounts();
00548       $counts = array_slice($tags, 0, $tag_limit, true);
00549       if (!count($counts)) {
00550          return "<!-- no results for cloud -->";
00551       }
00552 
00553       // calculate class numbering interval
00554       $min = min($counts);
00555       $max = max($counts);
00556       $diff = ($max - $min > 0) ? $max - $min : 1;
00557       $interval = ($num_classes - 1) / $diff;
00558 
00559       // generate the tags
00560       $tags = array();
00561       foreach ($counts as $value => $count) {
00562          // generate the query string
00563          $qs = array(
00564             'CISOBOX1' => $value,
00565             'CISOFIELD1' => "any",
00566             'CISOROOT' => $this->getView()->getCollection()->getAlias(),
00567             'CISOOP1' => "all"
00568          );
00569          $class_no = round(1 + ($count - $min) * $interval);
00570          $uri = DMInternalURI::getURIWithParams("objects", $qs);
00571          $tags[] = sprintf('<a class="dmTag dmTag%d" href="%s">%s</a>',
00572             $class_no,
00573             $uri,
00574             DMString::websafe($value));
00575          unset($qs);
00576       }
00577       return implode("\n", $tags);
00578    }
00579 
00586    public function getHtmlTermLinkedToSearch($text_to_link,
00587          DMObjectQuery $query) {
00588       // The basic idea is to build a DMObjectQuery based on the supplied
00589       // method parameters, and then use the return value of its getURI()
00590       // method.
00591       return sprintf('<a class="dmSearchTermLink" href="%s">%s</a>',
00592          $query->getURI(), $text_to_link);
00593    }
00594 
00613    public function getHtmlVocabularyAsCloud(array $field_nicks,
00614          $tag_limit = 20, $num_classes = 10, $sample_size = 512,
00615          $randomize = true) {
00616       /* Unfortunately cdm doesn't have a direct way of retrieving frequency
00617       data using the API. We will compile it ourselves here */
00618       $query = new DMObjectQuery();
00619       $query->addCollection($this->getView()->getCollection());
00620       $maxresults = ($sample_size > 1024) ? 1024 : $sample_size;
00621       $maxresults = ($sample_size < 10) ? 10 : $sample_size;
00622       $query->setNumResultsPerPage($maxresults);
00623       foreach ($field_nicks as $nick) {
00624          $predicate = new DMQueryPredicate();
00625          $predicate->setField(new DMDCElement($nick));
00626          $query->addPredicate($predicate);
00627       }
00628       $results = $query->getSearchResults();
00629 
00630       if (!count($results)) {
00631          return "<!-- no results for cloud -->";
00632       }
00633 
00634       // compile all unique terms in the $vocab array
00635       $vocab = array();
00636       foreach ($results as $obj) {
00637          foreach ($field_nicks as $nick) {
00638             $value = $obj->getField($nick);
00639             if ($value) {
00640                // split up semicolon-separated terms
00641                $tmp = explode("; ", $value);
00642                foreach ($tmp as &$t) {
00643                   $t = rtrim(trim($t), ".,;");
00644                   if (strlen($t) < 1) {
00645                      unset($t);
00646                   }
00647                }
00648                $vocab = array_merge($vocab, $tmp);
00649             }
00650          }
00651       }
00652 
00653       $counts = array_count_values($vocab);
00654       // enforce $tag_limit
00655       arsort($counts, SORT_NUMERIC);
00656       $counts = array_slice($counts, 0, $tag_limit, true);
00657 
00658       if (!count($counts)) {
00659          return "<!-- no results for cloud -->";
00660       }
00661 
00662       if ($randomize) {
00663          $tmp = array();
00664          $keys = array_keys($counts);
00665          shuffle($keys);
00666          foreach($keys as $key) {
00667             $tmp[$key] = $counts[$key];
00668             //unset($array[$key]);
00669          }
00670          $counts = $tmp;
00671       }
00672 
00673       // calculate class numbering interval
00674       $min = min($counts);
00675       $max = max($counts);
00676       $diff = ($max - $min > 0) ? $max - $min : 1;
00677       $interval = ($num_classes - 1) / $diff;
00678 
00679       // generate the tags
00680       $tags = array();
00681       foreach ($counts as $term => $c) {
00682          // generate the query string
00683          $qs = array(
00684             'CISOBOX1' => $term,
00685             'CISOFIELD1' => 'any',
00686             'CISOROOT' => $this->getView()->getCollection()->getAlias(),
00687             'CISOOP1' => 'all'
00688          );
00689          $class_no = round(1 + ($c - $min) * $interval);
00690          $uri = DMInternalURI::getURIWithParams("objects", $qs);
00691          $tags[] = sprintf('<a class="dmTag dmTag%d" href="%s">%s</a>',
00692             $class_no,
00693             $uri,
00694             DMString::websafe($term));
00695          unset($qs);
00696       }
00697       return implode("\n", $tags);
00698    }
00699 
00711    public function getHtmlVocabularyAsList(DMDCElement $field,
00712          $linked = true) {
00713       $vocab = $field->getVocabulary(false);
00714       natcasesort($vocab);
00715 
00716       $dxml = new DMDOMDocument("1.0", "utf-8");
00717       $dxml->loadXML("<ul/>");
00718       $dxml->documentElement->setAttribute("class", "dmVocabList");
00719 
00720       for ($i = 0; $i < count($vocab); $i++) {
00721          $li = $dxml->createElement('li');
00722          $li->setAttribute('class', 'dmVocabTerm');
00723          if ($linked) {
00724             $qs = array(
00725                'CISOBOX1' => $vocab[$i],
00726                'CISOFIELD1' => $field->getNick(),
00727                'CISOOP1' => "exact",
00728                'CISOROOT' => $field->getCollection()->getAlias()
00729             );
00730             $a = $dxml->createElement("a", DMString::websafe($vocab[$i]));
00731             $a->setAttribute("href",
00732                sprintf("/%s/?%s",
00733                   DMString::websafe(trim(dirname($_SERVER['PHP_SELF']), "/")),
00734                   DMString::websafe(urldecode(http_build_query($qs)))));
00735             $li->appendChild($a);
00736          } else {
00737             $li->nodeValue = DMString::websafe($vocab[$i]);
00738          }
00739          $dxml->documentElement->appendChild($li);
00740       }
00741       return $dxml->saveHTML($dxml->documentElement);
00742    }
00743 
00752    public function getHtmlVocabularyForSelect(DMDCElement $field) {
00753       $vocab = $field->getVocabulary(false);
00754       natcasesort($vocab);
00755       $terms = array();
00756       foreach ($vocab as $term) {
00757          $terms[] = sprintf("<option>%s</option>", DMString::websafe($term));
00758       }
00759       return implode("\n", $terms);
00760    }
00761 
00766    protected function getFeedURL($format) {
00767       $uri = DMHTTPRequest::getCurrent()->getURI();
00768       $uri->setExtension($format);
00769       return $uri->__toString();
00770    }
00771 
00772 }
 All Data Structures Functions Variables