You are here

tft.pages.inc in Taxonomy File Tree 7.2

Defines all page callbacks for TFT.

File

includes/tft.pages.inc
View source
<?php

/**
 * @file
 * Defines all page callbacks for TFT.
 */

/**
 * Page callback: check file access and start transfer.
 */
function tft_download_file($nid = NULL) {
  $node = node_load($nid);
  if (empty($node->field_file[LANGUAGE_NONE][0]['fid'])) {
    drupal_not_found();
  }
  elseif (node_access('view', $node)) {
    $file = file_load($node->field_file[LANGUAGE_NONE][0]['fid']);

    // If using private file system check hook_file_download
    $schema = file_uri_scheme($file->uri);
    if ($schema == 'private') {
      $headers = module_invoke_all('file_download', $file->uri);

      // If there is no module granting access or one denying access do not grant access
      if (empty($headers) || in_array(-1, $headers)) {
        drupal_access_denied();
        drupal_exit();
      }
    }
    $http_headers = array(
      'Content-Type' => $file->filemime,
      'Content-Disposition' => 'attachment; filename="' . $file->filename . '"',
    );
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
      $http_headers['Cache-Control'] = 'must-revalidate, post-check=0, pre-check=0';
      $http_headers['Pragma'] = 'public';
    }
    else {
      $http_headers['Pragma'] = 'no-cache';
    }
    file_transfer($file->uri, $http_headers);
  }
  else {
    drupal_access_denied();
  }
  return '';
}

/**
 * Page callback: file content list.
 *
 * @param  int $tid = 0
 *
 * @return string
 */
function tft($tid = 0) {

  // Check if the user has access to this tree
  if (!tft_term_access($tid)) {
    drupal_access_denied();
    return;
  }
  watchdog('tft tid', '<pre>' . print_r($tid, TRUE) . '</pre>');
  drupal_set_title(variable_get('tft_page_title', t("Taxonomy File Tree")));
  if ($tid) {
    $name = db_query("SELECT name FROM {taxonomy_term_data} WHERE tid = :tid", array(
      ':tid' => $tid,
    ))
      ->fetchField();
  }
  else {
    $name = t("Root");
  }

  // Store the URL query. Need the current path for some AJAX callbacks.
  $_SESSION['tft']['q'] = $_GET['q'];

  // Store the current term tid.
  $_SESSION['tft']['root_tid'] = $tid;

  // Add CSS and Javascript files.
  $path = drupal_get_path('module', 'tft');
  drupal_add_js(array(
    'tftDirectory' => drupal_get_path('module', 'tft'),
    'cleanUrl' => variable_get('clean_url', 0),
  ), 'setting');
  drupal_add_js($path . '/js/jquery.tablesorter.min.js');
  drupal_add_js($path . '/js/tft.js');
  drupal_add_css($path . '/css/tft.css');
  $data = array(
    'folder_name' => $name,
    'folder_menu' => tft_theme_folder_menu_links(tft_get_folder_menu_links($tid)),
    'folder_content' => tft_content_table($tid),
    'folder_add_content_links' => tft_theme_add_content_links(tft_get_add_content_links($tid)),
  );
  return theme('tft', $data);
}

/**
 * Form: add a term.
 */
function tft_add_term_form($form, $form_state) {
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t("Name"),
    '#required' => TRUE,
    '#weight' => -10,
  );
  $parent = !empty($_GET['parent']) ? (int) $_GET['parent'] : 0;
  if (!tft_term_access($parent)) {
    drupal_set_message(t("You do not have access to this folder. You cannot modify or delete it."), 'error');
    if ($destination = str_replace('%23', '#', $_GET['destination'])) {
      drupal_goto($destination);
    }
    else {
      drupal_goto();
    }
  }
  $form['parent'] = array(
    '#type' => 'hidden',
    '#value' => $parent,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t("Add"),
  );
  $parts = explode('#', str_replace('%23', '#', $_GET['destination']));
  $form['cancel'] = array(
    '#markup' => l(t("cancel"), $parts[0], array(
      'attributes' => array(
        'class' => array(
          'tft-cancel-button',
        ),
      ),
      'fragment' => isset($parts[1]) ? $parts[1] : '',
    )),
  );
  return $form;
}

/**
 * Validation callback: for tft_add_term_form().
 *
 * Check for forbidden characters in the 'folder' name.
 */
function tft_add_term_form_validate($form, &$form_state) {

  // If the user can only add terms to an OG term
  // @todo OG logic !!
  if (!user_access(TFT_PERM__ADD_TERMS)) {
    if (!tft_term_access($form_state['values']['parent'])) {
      form_set_error('name');
      drupal_set_message(t("You must select a parent folder that is part of a group you're a member of."), 'error');
      if ($_GET['destination']) {
        drupal_goto(urldecode($_GET['destination']));
      }
      else {
        drupal_goto();
      }
      exit;
    }
  }

  // Check for forbidden characters
  if (strpos($form_state['values']['name'], ',') !== FALSE || strpos($form_state['values']['name'], '+') !== FALSE) {
    form_set_error('name', t("The following characters are not allowed: ',' (comma) and +"));
  }
}

/**
 * Submission callback: for tft_add_term_form().
 */
function tft_add_term_form_submit($form, &$form_state) {
  tft_add_term($form_state['values']['name'], $form_state['values']['parent']);
}

/**
 * Form: edit a term.
 */
function tft_edit_term_form($form, $form_state, $tid) {
  global $user;
  if (!tft_term_access($tid, $user, 'edit')) {
    drupal_set_message(t("You do not have access to this folder. You cannot modify or delete it."), 'error');
    if ($destination = str_replace('%23', '#', $_GET['destination'])) {
      drupal_goto($destination);
    }
    else {
      drupal_goto();
    }
  }

  // @todo OG logic !!
  if (tft_is_archive_folder($tid)) {
    drupal_set_message(t("Archive folders cannot be edited."), 'error');
    if ($destination = str_replace('%23', '#', $_GET['destination'])) {
      drupal_goto($destination);
    }
    else {
      drupal_goto();
    }
  }
  $name = db_query("SELECT name FROM {taxonomy_term_data} WHERE tid = :tid", array(
    ':tid' => $tid,
  ))
    ->fetchField();

  // If no name was found
  if (!$name) {
    drupal_set_message(t("An error occured. The '@tid' folder could not be found. Please contact the site administrator.", array(
      '@tid' => $tid,
    )), 'error');
    if ($destination = str_replace('%23', '#', $_GET['destination'])) {
      drupal_goto($destination);
    }
    else {
      drupal_goto();
    }
  }
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t("Name"),
    '#required' => TRUE,
    '#default_value' => $name,
    '#weight' => -10,
  );
  $form['tid'] = array(
    '#type' => 'hidden',
    '#value' => $tid,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t("Save"),
  );
  $parts = explode('#', str_replace('%23', '#', $_GET['destination']));
  $form['cancel'] = array(
    '#markup' => l(t("cancel"), $parts[0], array(
      'attributes' => array(
        'class' => array(
          'tft-cancel-button',
        ),
      ),
      'fragment' => isset($parts[1]) ? $parts[1] : '',
    )),
  );
  return $form;
}

/**
 * Validation callback: for tft_edit_term_form().
 */

// @todo DRY
function tft_edit_term_form_validate($form, &$form_state) {

  // Check for forbidden characters
  if (strpos($form_state['values']['name'], ',') !== FALSE || strpos($form_state['values']['name'], '+') !== FALSE) {
    form_set_error('name', t("The following characters are not allowed: ',' (comma) and +"));
  }
}

/**
 * Submission callback: for tft_edit_term_form()
 */
function tft_edit_term_form_submit($form, &$form_state) {
  tft_update_term($form_state['values']['tid'], $form_state['values']['name']);
  drupal_set_message(t("The folder '@name' was updated.", array(
    '@name' => $form_state['values']['name'],
  )));
}

/**
 * Form: delete a term.
 */
function tft_delete_term_form($form, $form_state, $tid) {
  global $user;
  if (!tft_term_access($tid, $user, 'delete')) {
    drupal_set_message(t("You do not have access to this folder. You cannot modify or delete it."), 'error');
    if ($destination = str_replace('%23', '#', $_GET['destination'])) {
      drupal_goto($destination);
    }
    else {
      drupal_goto();
    }
  }

  // @todo OG logic !!
  if (tft_is_archive_folder($tid)) {
    drupal_set_message(t("Archive folders cannot be deleted."), 'error');
    if ($destination = str_replace('%23', '#', $_GET['destination'])) {
      drupal_goto($destination);
    }
    else {
      drupal_goto();
    }
  }
  $name = db_query("SELECT name FROM {taxonomy_term_data} WHERE tid = :tid", array(
    ':tid' => $tid,
  ))
    ->fetchField();

  // If no name was found
  if (!$name) {
    drupal_set_message(t("An error occured. The '@tid' folder could not be found. Please contac tthe site administrator.", array(
      '@tid' => $tid,
    )), 'error');
    if ($destination = str_replace('%23', '#', $_GET['destination'])) {
      drupal_goto($destination);
    }
    else {
      drupal_goto();
    }
  }

  // Check that this term has no child terms or files
  if (tft_check_term_is_deletable($tid)) {
    drupal_set_title(t("Are you sure you want to delete the folder @term ?", array(
      '@term' => $name,
    )));
    $form['tid'] = array(
      '#type' => 'hidden',
      '#value' => $tid,
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t("Delete"),
      '#attributes' => array(
        'class' => array(
          'delete-button',
        ),
      ),
    );
    $parts = explode('#', str_replace('%23', '#', $_GET['destination']));
    $form['cancel'] = array(
      '#markup' => l(t("cancel"), $parts[0], array(
        'attributes' => array(
          'class' => array(
            'tft-cancel-button',
          ),
        ),
        'fragment' => isset($parts[1]) ? $parts[1] : '',
      )),
    );
    return $form;
  }
  else {
    drupal_set_message(t("<em>@name</em> contains files and/or child folders. Move or delete these before deleting this folder.", array(
      '@name' => $name,
    )), 'error');
    if ($destination = str_replace('%23', '#', $_GET['destination'])) {
      drupal_goto($destination);
    }
    else {
      drupal_goto();
    }
  }
}

/**
 * Submission callback: for tft_delete_term_form().
 */
function tft_delete_term_form_submit($form, $form_state) {
  taxonomy_term_delete($form_state['values']['tid']);
}

/**
 * Form: reorganize folder items.
 */
function tft_manage_folders_form($form, $form_state, $tid = 0) {
  $path = drupal_get_path('module', 'tft');
  drupal_add_css($path . '/css/tft.css');
  drupal_add_js($path . '/js/tft.js');
  if (variable_get('tft_use_weight', 0)) {
    drupal_add_js($path . '/js/tft.tabledrag.js');
  }
  $tree = tft_tree($tid);
  if (!tft_term_access($tid)) {
    drupal_access_denied();
    return;
  }
  if (!$tid) {
    $root_depth = 0;
  }
  else {
    $root_depth = tft_get_depth($tid) + 1;
  }
  $form['#tid'] = $tid;
  $form['table'] = array(
    '#tree' => TRUE,
  );
  _tft_manage_folders_form($tree, $form, $root_depth, $tid, TRUE, FALSE);
  $form['save'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );
  if (isset($_GET['destination'])) {
    $_SESSION['tft']['q'] = $_GET['destination'];
    $url = str_replace('%23', '#', $_GET['destination']);
  }
  elseif (isset($_SESSION['tft']['q'])) {
    $url = str_replace('%23', '#', $_SESSION['tft']['q']);
  }
  if ($url) {
    $parts = explode('#', $url);
    $form['cancel'] = array(
      '#markup' => l(t("cancel"), $parts[0], array(
        'attributes' => array(
          'class' => array(
            'tft-cancel-button',
          ),
        ),
        'fragment' => isset($parts[1]) ? $parts[1] : '',
      )),
    );
  }
  return $form;
}

/**
 * Form helper. Flattens the terms tree and creates the form elements.
 * @see tft_manage_folders_form()
 *
 * @param  array $tree
 * @param  array &$form
 * @param  int $root_depth = 0
 *             The depth of the root term
 * @param  int $root_tid = NULL
 *             The root tid
 */
function _tft_manage_folders_form($tree, &$form, $root_depth = 0, $root_tid = NULL) {
  if (!isset($form['#use_weight'])) {
    $form['#use_weight'] = variable_get('tft_use_weight', 0);
  }
  foreach ($tree as $data) {

    // @todo OG logic !
    if ($root_tid && isset($data['tid']) && $data['tid'] == tft_get_archive_tid($root_tid)) {
      continue;
    }
    $data['depth'] = isset($data['tid']) ? tft_get_depth($data['tid']) - $root_depth : tft_get_depth($data['parent']) - $root_depth + 1;
    $key = 'tft-admin-' . (isset($data['nid']) ? 'node-' . $data['nid'] : 'term-' . $data['tid']);
    $form['table'][$key] = array();
    $form['table'][$key]['name'] = array(
      '#type' => 'textfield',
      '#default_value' => $data['name'],
      '#maxlength' => 255,
      '#required' => TRUE,
    );
    if (isset($data['type']) && $data['type'] == 'node') {
      $form['table'][$key]['name']['#required'] = FALSE;
      $form['table'][$key]['name']['#attributes'] = array(
        'disabled' => 'disabled',
      );
    }
    $form['table'][$key]['parent'] = array(
      '#type' => 'textfield',
      '#default_value' => $data['parent'],
      '#size' => 6,
      '#attributes' => array(
        'class' => array(
          'taxonomy_term_hierarchy-parent',
        ),
      ),
    );
    $form['table'][$key]['id'] = array(
      '#type' => 'hidden',
      '#default_value' => isset($data['nid']) ? $data['nid'] : $data['tid'],
      '#attributes' => array(
        'class' => array(
          'taxonomy_term_hierarchy-' . (isset($data['nid']) ? 'nid' : 'tid'),
        ),
      ),
    );
    $form['table'][$key]['type'] = array(
      '#type' => 'hidden',
      '#value' => isset($data['type']) ? $data['type'] : 'term',
    );
    $form['table'][$key]['depth'] = array(
      '#type' => 'value',
      '#value' => $data['depth'],
    );
    if ($form['#use_weight']) {
      $form['table'][$key]['weight'] = array(
        '#type' => 'weight',
        '#delta' => 50,
        '#default_value' => $data['weight'],
        '#attributes' => array(
          'class' => array(
            'taxonomy_term_hierarchy-weight',
          ),
        ),
      );
    }
    if (isset($data['children'])) {
      _tft_manage_folders_form($data['children'], $form, $root_depth, $root_tid);
    }
  }
}

/**
 * Theme the term reordering form.
 * @see tft_manage_folders_form().
 */
function theme_tft_manage_folders_form($vars) {
  $form = $vars['form'];
  drupal_add_tabledrag('tft-outline', 'match', 'parent', 'taxonomy_term_hierarchy-parent', 'taxonomy_term_hierarchy-parent', 'taxonomy_term_hierarchy-tid');
  if ($form['#use_weight']) {
    drupal_add_tabledrag('tft-outline', 'order', 'sibling', 'taxonomy_term_hierarchy-weight');
  }
  $header = array(
    t('Name'),
    t('Parent'),
  );
  if ($form['#use_weight']) {
    $header[] = t('Weight');
  }
  $rows = array();
  foreach ($form['table'] as $key => $item) {
    if (is_array($item) && preg_match('/tft\\-admin\\-(node|term)-[0-9]+/', $key)) {
      $data = array();
      if ($item['type']['#value'] == 'term') {
        $path = drupal_get_path('module', 'tft') . '/img/folder.png';
      }
      else {
        $setting = tft_get_file_setting();
        $db_table = 'field_data_' . $setting['field'];
        $db_table = db_escape_field($db_table);
        $db_field = db_escape_field($setting['field'] . '_fid');
        $mime = db_query("SELECT f.filemime FROM {node_revision} v\n                            LEFT JOIN {node} n ON n.vid = v.vid\n                              LEFT JOIN {" . $db_table . "} c ON c.revision_id = v.vid\n                                LEFT JOIN {file_managed} f ON c.{$db_field} = f.fid\n                        WHERE n.nid = :nid", array(
          ':nid' => $item['id']['#default_value'],
        ))
          ->fetchField();
        $file = (object) array(
          'filemime' => $mime,
        );
        $path = file_icon_path($file);
      }
      $icon = theme('image', array(
        'path' => $path,
        'attributes' => array(
          'class' => array(
            'tft-admin-folder-content-item',
          ),
        ),
      ));
      $data[] = theme('indentation', array(
        'size' => isset($item['depth']['#value']) ? $item['depth']['#value'] : 0,
      )) . $icon . drupal_render($item['name']);
      $data[] = drupal_render($item['parent']) . drupal_render($item['id']) . drupal_render($item['type']);
      if ($form['#use_weight']) {
        $data[] = drupal_render($item['weight']);
      }
      $row = array(
        'data' => $data,
      );
      if (isset($item['#attributes'])) {
        $row = array_merge($row, $item['#attributes']);
      }
      $row['class'][] = 'draggable' . ($item['type']['#value'] == 'node' ? ' tabledrag-leaf' : '');
      $rows[] = $row;
    }
  }
  $form['table'] = array(
    '#markup' => theme('table', array(
      'header' => $header,
      'rows' => $rows,
      'attributes' => array(
        'id' => 'tft-outline',
      ),
    )),
    '#weight' => 1,
  );
  return drupal_render_children($form);
}

/**
 * Submission callback: for tft_manage_folders_form().
 */
function tft_manage_folders_form_submit($form, &$form_state) {
  foreach ($form_state['values']['table'] as $key => $item) {
    if ($item['type'] == 'term') {
      db_update('taxonomy_term_hierarchy')
        ->fields(array(
        'parent' => $item['parent'],
      ))
        ->condition('tid', $item['id'])
        ->execute();
    }
    else {
      $node = node_load($item['id']);

      // Reconstruct list of terms by removing all folder terms.
      $node->tft_folder[LANGUAGE_NONE][0]['tid'] = $item['parent'];
      node_save($node);
    }
    if ($form['#use_weight']) {
      db_delete('tft_folder_content_weight')
        ->condition('type', $item['type'])
        ->condition('id', $item['id'])
        ->execute();
      db_insert('tft_folder_content_weight')
        ->fields(array(
        'id' => $item['id'],
        'type' => $item['type'],
        'parent_tid' => $form['#tid'],
        'weight' => $item['weight'],
      ))
        ->execute();
    }
    if ($item['type'] == 'term') {
      db_update('taxonomy_term_data')
        ->fields(array(
        'name' => $item['name'],
      ))
        ->condition('tid', $item['id'])
        ->execute();
    }
  }
}

Functions

Namesort descending Description
tft Page callback: file content list.
tft_add_term_form Form: add a term.
tft_add_term_form_submit Submission callback: for tft_add_term_form().
tft_add_term_form_validate Validation callback: for tft_add_term_form().
tft_delete_term_form Form: delete a term.
tft_delete_term_form_submit Submission callback: for tft_delete_term_form().
tft_download_file Page callback: check file access and start transfer.
tft_edit_term_form Form: edit a term.
tft_edit_term_form_submit Submission callback: for tft_edit_term_form()
tft_edit_term_form_validate
tft_manage_folders_form Form: reorganize folder items.
tft_manage_folders_form_submit Submission callback: for tft_manage_folders_form().
theme_tft_manage_folders_form Theme the term reordering form.
_tft_manage_folders_form Form helper. Flattens the terms tree and creates the form elements.