xc_dewey.module 10.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
<?php
/**
 * @file
 * This class is about to parse and translate Dewey Decimal Classification numbers
 * to human readable texts
 *
 * TODO:
 * - to understand and handle / (e.g. 821/.040901)
 * - to understand and handle . (e.g. 821/.040901)
 * - to handle actual Drupal language
 * - use Ajax the same way as we handle images
 * - find siblings
 *
 * @copyright (c) 2010-2011 eXtensible Catalog Organization
 */


/**
 * The Maximal depth of Dewey classification which OCLC provides translation for
 * @var unknown_type
 */
define('XC_DEWEY_MAX_DEPTH', 3);

/**
 * Implements hook_menu().
 */
function xc_dewey_menu() {
  // public URLs
  $items['xc_dewey/ajax/resolve'] = array(
    'title' => 'Resolve Dewey number Ajax gateway',
    'description' => 'Resolve Dewey number Ajax gateway',
    'page callback' => 'xc_dewey_resolve',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  // Admin URLs
  // Dewey root
  $items['admin/xc/dewey'] = array(
    'title' => 'Dewey numbers',
    'description' => 'The Dewey Decimal Classification is a classification schema invented by John Louis Kossuth Dewey. The XC Dewey module use the dewey.info web service to resolve Dewey numbers into human readable numbers. Here you can find the administrative commands related to this module.',
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('administer xc'),
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module', 'system'),
    'type' => MENU_NORMAL_ITEM,
    'weight' => 20,
  );

  $items['admin/xc/dewey/list'] = array(
    'title' => 'List of cached Dewey numbers',
    'page callback' => 'xc_dewey_list',
    'access arguments' => array('administer xc'),
    'type' => MENU_NORMAL_ITEM,
  );

  $items['admin/xc/dewey/fulfill'] = array(
    'title' => 'Fulfill Dewey number cache',
    'description' => 'Fulfill Dewey number cache in order to speed up display. The dewey.info\'s response time might be slow. With this command the Drupal administrator can start a process, which resolves all Dewey numbers from 0 to 999, and stores the results into cache. The result of this function will speed up Dewey number resolving in query time, but be prepared, that this function runs for a while.',
    'page callback' => 'xc_dewey_fulfill',
    'access arguments' => array('administer xc'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * @todo Please document this function.
 * @see http://drupal.org/node/1354
 */
function xc_dewey_resolve() {
tombui's avatar
tombui committed
73
  //TODO from Tom, could use explode to replace split if needed.
74
  $dewey_numbers = explode(',', $_GET['numbers']);
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386

  $items = array();
  foreach ($dewey_numbers as $dewey_number) {
    $translated = array();
    for ($i = 1; strlen($dewey_number) >= $i && $i <= XC_DEWEY_MAX_DEPTH; $i++) {
      $translated[] = xc_dewey_linker(substr($dewey_number, 0, $i));
    }
    if (strlen($dewey_number) > XC_DEWEY_MAX_DEPTH) {
      $translated[] = xc_dewey_linker($dewey_number);
    }
    $items[] = join(' > ', $translated);
  }

  $result = array();
  if (!empty($items)) {
    $hierarchy = count($items) > 1 ? theme('item_list', array('items' => $items)) : $items[0];
    $result = array(
      'xc_dewey' => array(
        'meta' => array(
          'id' => 'xc-dewey',
          'title' => t('Dewey Classification System'),
        ),
        'content' => array('Dewey hierarchy' => $hierarchy),
      ),
    );
  }

  drupal_json_output($result);
}

/**
 * Implements hook_xc_display_full().
 */
function xc_dewey_xc_display_full($op, $xc_record) {
  if ($op == 'enhance') {

    // handling display modes. Possible modes are 'normal', 'ajax' and 'none'
    $display_mode = variable_get('xc_dewey_ajax', 'normal');
    if ($display_mode == 'none') {
      return;
    }
    elseif ($display_mode == 'ajax') {
      // TODO: handle ajax
      $dewey_numbers = xc_dewey_extract_numbers($xc_record);
      if ($dewey_numbers === FALSE) {
        return;
      }
      drupal_add_js(drupal_get_path('module', 'xc_util') . '/xc_util.js');
      drupal_add_js(drupal_get_path('module', 'xc_dewey') . '/xc_dewey.js');
      drupal_add_js(array('xc_dewey' => array(
          'numbers' => $dewey_numbers,
          'url' => url('xc_dewey/ajax/resolve', array('absolute' => TRUE)),
        )), array('type' => 'setting', 'scope' => JS_DEFAULT));
      return array(
        'xc_dewey' => array(
          'meta' => array(
            'type' => 'ajax',
            'id' => 'xc-dewey',
          ),
        ),
      );
    }
    // rest is handling of normal mode

    $dewey_numbers = xc_dewey_extract_numbers($xc_record);
    if ($dewey_numbers === FALSE) {
      return;
    }

    $items = array();
    foreach ($dewey_numbers as $dewey_number) {
      $translated = array();
      for ($i = 1; strlen($dewey_number) >= $i && $i <= XC_DEWEY_MAX_DEPTH; $i++) {
        $translated[] = xc_dewey_linker(substr($dewey_number, 0, $i));
      }
      if (strlen($dewey_number) > XC_DEWEY_MAX_DEPTH) {
        $translated[] = xc_dewey_linker($dewey_number);
      }
      $items[] = join(' > ', $translated);
    }
    if (!empty($items)) {
      $hierarchy = count($items) > 1 ? theme('item_list', array('items' => $items)) : $items[0];
      return array(
        'xc_dewey' => array(
          'meta' => array(
            'type' => 'normal',
            'id' => 'xc-dewey',
            'title' => t('Dewey Classification System'),
          ),
          'content' => array('Dewey hierarchy' => $hierarchy),
        ),
      );
    }
  }
}

/**
 * Translate Dewey number
 * @param $dewey_number (String)
 *   A Dewey number
 * @return (array)
 *   An array of string, each items reflect to a hierarchial level
 */
function xc_dewey_get($dewey_number) {
  $translated = array();
  if (!preg_mmatch('/^\d+$/', substr($dewey_number, 0, XC_DEWEY_MAX_DEPTH))) {
    $translated[$dewey_number] = $dewey_number;
  }
  else {
    for ($i = 1; strlen($dewey_number) >= $i && $i <= XC_DEWEY_MAX_DEPTH; $i++) {
      $key = drupal_substr($dewey_number, 0, $i);
      $translated[$key] = xc_dewey_translate($key);
    }
    if (strlen($dewey_number) > XC_DEWEY_MAX_DEPTH) {
      $translated[$dewey_number] = $dewey_number;
    }
  }
  return $translated;
}

/**
 * Make link based on the parts
 * @param $part
 * @return unknown_type
 */
function xc_dewey_linker($part) {
  if (strlen($part) <= XC_DEWEY_MAX_DEPTH) {
    $translated = xc_dewey_translate($part);
  }
  else {
    $translated = $part;
  }

  // TODO: fix it
  $xc_dewey_do_link = variable_get('xc_dewey_do_link', FALSE);
  if ($xc_dewey_do_link) {
    return l($translated, 'xc/search/*', array('query' => 'filter[]=dcterms__subject_dcterms__DDC_s:' . $part . '*'));
  }
  else {
    return $translated;
  }
}

/**
 * The Dewey translator. This function use OCLC's dewey.info service to get information
 * about Dewey numbers, and use the skos:prefLabel element which contains the human
 * readable label of it.
 *
 * @param $part (int)
 *   The Dewey number to translate
 * @return (String)
 *   The English meaning of a Dewey number
 */
function xc_dewey_translate($part) {
  static $xc_deweys, $xc_dewey_languages = array(
    'af' => 1,
    'ar' => 1,
    'de' => 1,
    'en' => 1,
    'es' => 1,
    'fr' => 1,
    'no' => 1,
    'pt' => 1,
    'ru' => 1,
    'sv' => 1,
    'zh' => 1,
  );

  if (!preg_match('/^\d+$/', $part)) {
    return '';
  }

  // TODO: get language from Drupal
  $language = 'en';

  // checking level variable, and set default if user would like to get an undefined one
  if (!isset($xc_dewey_languages[$language])) {
    $language = 'en';
  }

  if (!isset($xc_deweys)) {
    $deweys = variable_get('xc_dewey', array());
  }
  if (!isset($deweys[$part])) {
    $url = 'http://dewey.info/class/' . $part . '/e22/about.' . $language . '.rdf';
    $result = drupal_http_request($url);
    if (preg_match('/<skos:prefLabel[^<>]*>(.*?)<\/skos:prefLabel>/', $result->data, $matches)) {
      $deweys[$part] = htmlspecialchars_decode($matches[1]);
    }
    else {
      $deweys[$part] = 'unknown';
    }
    variable_set('xc_dewey', $deweys);
  }
  return $deweys[$part];
}

/**
 * Fulfills the Dewey number cache
 */
function xc_dewey_fulfill() {
  drupal_set_time_limit(0);
  $numbers = range(0, 999);
  foreach ($numbers as $number) {
    xc_dewey_translate($number);
    if (strlen($number) == 1) {
      // create 0x
      $number = sprintf('%02d', $number);
      xc_dewey_translate($number);

      // create 00x
      xc_dewey_translate(sprintf('%03d', $number));
    }
    elseif (strlen($number) == 2) {
      // create 0xx
      xc_dewey_translate(sprintf('%03d', $number));
    }
  }

  return t('Dewey numbers are set. You can review list of existing Dewey numbers !here',
    array('!here' => l(t('here'), 'admin/xc/dewey/list')));
}

/**
 * Returns the formatted list of Dewey numbers
 */
function xc_dewey_list() {
  $dewey = variable_get('xc_dewey', array());
  ksort($dewey);

  $rows = array();
  foreach ($dewey as $key => $value) {
    $rows[] = array($key, $value);
  }

  return theme('table', array('header' => array('DDC', t('Meaning')), 'rows' => $rows));
}

/**
 * Implements hook_form_alter().
 *
 * Modify the full record display option form
 *
 * @param $form (Array)
 *   FAPI form definition
 * @param $form_state (Array)
 *   FAPI form state
 * @param $form_id (String)
 *   Form identifier
 */
function xc_dewey_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {

    // full record display form
    case 'xc_search_full_record_display_options_form':
      $form['enhancements']['xc_dewey_ajax'] = array(
        '#title' => t('<em>Dewey numbers</em>'),
        '#type' => 'radios',
        '#options' => array(
          'normal' => t('Load it normally with the other parts of the page.'),
          'ajax' => t('Load it after the page were served (Ajax method).'),
          'none' => t('Do not display Dewey numbers at all.'),
        ),
        '#default_value' => variable_get('xc_dewey_ajax', 'normal'),
      );

      $form['#submit'][] = 'xc_dewey_full_record_display_options_form_submit';

      break;
  }
}

/**
 * Submit handler for full record display form
 *
 * Saves the value of xc_dewey_ajax Drupal variable
 *
 * @param $form (Array)
 *   FAPI form definition
 * @param $form_state (Array)
 *   FAPI form state
 */
function xc_dewey_full_record_display_options_form_submit($form, &$form_state) {
  $xc_dewey_ajax = $form_state['values']['xc_dewey_ajax'];
  variable_set('xc_dewey_ajax', $xc_dewey_ajax);
}

/**
 * Extracts the Dewey numbers from the XC schema records
 *
 * @param $xc_record (Array)
 */
function xc_dewey_extract_numbers($xc_record) {

  // dcterms__subject_DDC_s
  if (empty($xc_record['dcterms:subject'])) {
    return FALSE;
  }

  $dewey_numbers = array();
  foreach ($xc_record['dcterms:subject'] as $key => $instance) {
    if ($instance['@type'] == 'dcterms:DDC') {
      $dewey_numbers[] = $instance['#value'];
    }
  }
  if (empty($dewey_numbers)) {
    return FALSE;
  }
  $dewey_numbers = array_values(array_unique($dewey_numbers));

  return $dewey_numbers;
}