Skip to content
Snippets Groups Projects
Forked from UNL Information Services / UNL-CMS
795 commits behind the upstream repository.
unl.module 16.75 KiB
<?php

function unl_node_prepare($node) {
  $node->menu['expanded'] = 1;
}

/**
 * Implementation of hook_wywiwyg_plugin() found in wysiwyg.api.php
 */
function unl_wysiwyg_plugin($editor) {
  switch ($editor) {
    case 'tinymce':
      return array(
        'unl' => array(
          // A URL to the plugin's homepage.
          'url' => 'http://gforge.unl.edu/gf/project/wdn_tinymce/',
           // The full path to the native editor plugin.
          'path' => $editor['library path'] . '/plugins/unl',
          // A list of editor extensions provided by this native plugin.
          // Extensions are not displayed as buttons and touch the editor's
          // internals, so you should know what you are doing.
          'extensions' => array(
            'unl' => 'UNL Extension'
          ),
          // Boolean whether this plugin is a native plugin, i.e. shipped with
          // the editor. Definition must be ommitted for plugins provided by
          // other modules.
          'internal' => TRUE,
          // Boolean whether the editor needs to load this plugin. When TRUE,
          // the editor will automatically load the plugin based on the 'path'
          // variable provided. If FALSE, the plugin either does not need to
          // be loaded or is already loaded by something else on the page.
          // Most plugins should define TRUE here.
          'load' => TRUE,
          // A list of buttons provided by this native plugin. The key has to
          // match the corresponding JavaScript implementation. The value is
          // is displayed on the editor configuration form only.
          'buttons' => array(
            'unlZenBox'   => 'UNL Zen Box',
            'unlZenTable' => 'UNL Zen Table',
            'unlLayout'   => 'UNL Layout',
            'unlTooltip'  => 'UNL Tooltip',
          ),
          // A list of global, native editor configuration settings to
          // override. To be used rarely and only when required.
          'options' => array(
            'skin' => 'unl',
            'table_styles' => 'ZenTable Bright (yellow)=zentable bright;ZenTable Cool (blue)=zentable cool;ZenTable Energetic (orange)=zentable energetic;ZenTable Soothing (green)=zentable soothing;ZenTable Primary (red)=zentable primary;ZenTable Neutral (gray)=zentable neutral;', 'doctype' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
            'valid_elements' => '*[*]',
          ),
        )
        // Wysiwyg wrapper plugin AJAX callback.
        // 'callback' => url('myplugin/browse'),
        // 'icon' => drupal_get_path('module', 'mymodule') . '/myplugin/myplugin.png',
        // Might need to be set later on; after retrieving customized editor
        // layout.
        //'theme_advanced_buttons1' => array(t('Button title (optional)') => 'myplugin'),
      );
  }
}

function unl_permission() {
  return array(
    'unl migration' => array(
      'title'       => t('Migration'),
      'description' => t('Migrate UNL Template based sites to drupal'),
    ),

    'unl site creation' => array(
      'title'       => t('Site Creation'),
      'description' => t('Create new drupal sites using the UNL profile'),
      'restrict access' => TRUE,
    ),

    'unl grant all permissions' => array(
      'title'       => t('Grant All Permissions'),
      'description' => t('If this is not checked, a user can only grant permissions that they themselves have. Requires the "Administer permissions" permission.'),
      'restrict access' => TRUE,
    ),

    'unl administer administrator permissions' => array(
      'title'       => t('Administer Administrator\'s Permissions'),
      'description' => t('If this is not checked, a user can not change the permissions of the administrator role. Requires the "Administer permissions" permission.'),
      'restrict access' => TRUE,
    ),

    'unl theme settings' => array(
      'title' => t('Change Theme Settings'),
      'description' => t('Allow this role to change the current theme settings.'),
    )
  );
}

/**
 * Adds UNL Migration Tool to the Content menu for admin
 */
function unl_menu() {
  $access = array();
  $items['admin/content/unl/migration'] = array(
    'title'            => 'UNL Migration Tool',
    'description'      => 'Migrate a static UNL template page into drupal',
    'access arguments' => array('unl migration'),
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('unl_migration'),
    'type'             => MENU_LOCAL_TASK,
    'file'             => 'unl_migration.php',
  );

  $items['admin/themes'] = array(
    'title' => 'Appearance',
    'description' => 'Configure your theme.',
    'access callback' => 'unl_user_access',
    'access arguments' => array(array('!administer themes', 'unl theme settings')),
    'page callback' => 'drupal_get_form',
    'position' => 'left',
    'weight' => -6,
  );

  if (conf_path() == 'sites/default') {
    $items['admin/sites/unl'] = array(
      'title'            => 'UNL Site Creation Tool',
      'description'      => 'Create and manage UNL Drupal sites and aliases.',
      'access arguments' => array('unl site creation'),
      'page callback'    => 'unl_sites_page',
      'type'             => MENU_LOCAL_TASK,
      'file'             => 'unl_site_creation.php',
    );

    $items['admin/sites/unl/sites'] = array(
      'title'       => 'Sites',
      'description' => 'Create and manage UNL Drupal sites.',
      'type'        => MENU_DEFAULT_LOCAL_TASK,
      'weight'      => -8,
    );

    $items['admin/sites/unl/aliases'] = array(
      'title'            => 'Aliases',
      'description'      => 'Manage aliases of UNL Drupal sites.',
      'access arguments' => array('unl site creation'),
      'page callback'    => 'unl_aliases_page',
      'type'             => MENU_LOCAL_TASK,
      'file'             => 'unl_site_creation.php',
    );

    $items['admin/sites/unl/wdn_registry'] = array(
      'title'            => 'WDN Registry',
      'description'      => 'Settings for the connection to the WDN Registry.',
      'access arguments' => array('unl site creation'),
      'page callback'    => 'drupal_get_form',
      'page arguments'   => array('unl_wdn_registry'),
      'type'             => MENU_LOCAL_TASK,
      'file'             => 'unl_site_creation.php',
    );
  }

  return $items;
}

function unl_menu_alter(&$items) {
  foreach (array('module', 'file', 'page arguments') as $key) {
    $items['admin/themes'][$key] = $items['admin/appearance/settings/' . variable_get('theme_default')][$key];
  }

  return $items;
}

function unl_form_alter(&$form, $form_state, $form_id) {
  // Make new menu items expanded by default.
  if ($form_id == 'menu_edit_item' && $form['mlid']['#value'] == 0) {
    $form['expanded']['#default_value'] = TRUE;
  }
  if ($form_id == 'system_site_information_settings') {
    $form['site_information']['https'] = array(
      '#type' => 'checkbox',
      '#title' => 'SSL Enabled',
      '#default_value' => variable_get('https', FALSE),
    );
    $form['#submit'][] = 'unl_system_settings_form_submit';
  }

  /**
   * Modify the Permissions and Roles forms for non-administrators
   */
  $admin_role_id = variable_get('user_admin_role', -1);
  if (!in_array($admin_role_id, array_keys($GLOBALS['user']->roles))) {
    switch ($form_id) {
      // Add additional validation on admin/people/permissions/roles/edit/%
      case 'user_admin_role' :
        $form['#validate'][] = 'unl_user_admin_role_validate';
        break;
      // Hide administrator role on admin/people/permissions/roles
      case 'user_admin_roles' :
        foreach ($form['roles'] as $key => $role) {
          if (isset($role['#role']->rid) && $role['#role']->rid == $admin_role_id) {
            unset($form['roles'][$key]);
          }
        }
        break;
      // Hide administrator column on admin/people/permissions
      case 'user_admin_permissions' :
        if (!user_access('unl grant all permissions')) {
          // Remove permissions this user doesn't have from the headings list.
          foreach ($form['permission'] as $permission => $sub_form) {
            if (is_int($permission)) {
              continue;
            }
            if (!user_access($permission)) {
              unset($form['permission'][$permission]);
            }
          }

          // Remove any empty permission section headings.
          $permission_sections = array_keys($form['permission']);
          foreach ($permission_sections as $index => $permission_section) {
            if (!is_int($permission_section)) {
              continue;
            }
            if (!isset($permission_sections[$index + 1]) || is_int($permission_sections[$index + 1])) {
              unset($form['permission'][$permission_section]);
            }
          }

          // Remove the permissions this user doesn't have from the checkboxes list.
          foreach ($form['checkboxes'] as $role_id => $sub_form) {
            foreach ($sub_form['#options'] as $permission => $value) {
              if (!user_access($permission)) {
                unset($form['checkboxes'][$role_id]['#options'][$permission]);
              }
            }
          }
        }

        // Unset the administrator checkbox column if user can't administer administrator permissions
        if (!user_access('unl administer administrator permissions')) {
          unset($form['role_names'][$admin_role_id]);
          unset($form['role_names']['#value'][$admin_role_id]);
          unset($form['checkboxes'][$admin_role_id]);
        }

        // Make these settings unavailable even if they are enabled for the user
        $administrator_permissions = array(
          'unl administer administrator permissions',
          'unl site creation',
          'administer modules',
          'administer themes',
          'administer software updates',
          'administer imce',
          'administer filters',
        );
        foreach ($form['permission'] as $permission => $sub_form) {
          if (in_array($permission, $administrator_permissions)) {
            unset($form['permission'][$permission]);
          }
        }
        foreach ($form['checkboxes'] as $admin_role_id => $sub_form) {
          foreach ($sub_form['#options'] as $permission => $value) {
            if (in_array($permission, $administrator_permissions)) {
              unset($form['checkboxes'][$admin_role_id]['#options'][$permission]);
            }
          }
        }
        break;
      default :
        break;
    }
  }

  /**
   * On the node edit form, hide the "Provide a menu link" checkbox since we'll
   * be using the menu to build a site hierarchy.  Instead, add a button that will
   * determine whether or not the menu link is visible or not.
   */
  if (substr($form_id, -10) == '_node_form') {
    $form['menu']['#title'] = 'Site hierachy';

    $form['menu']['enabled']['#default_value'] = TRUE;
    $form['menu']['enabled']['#prefix'] = '<div style="display: none;">';
    $form['menu']['enabled']['#suffix'] = '</div>';

    $form['menu']['link']['link_title']['#required'] = TRUE;


    $mlid = $form['menu']['link']['mlid']['#value'];
    if ($mlid) {
      $menu_link = menu_link_load($mlid);
      $default_visible = ($menu_link['hidden'] ? 0 : 1);
    }
    else {
      $default_visible = 0;
    }
    $form['menu']['visible'] = array(
      '#type' => 'checkbox',
      '#title' => 'Display in menu',
      '#default_value' => $default_visible,
      '#weight' => 0,
    );

    $form['actions']['submit']['#submit'][] = 'unl_node_form_submit';

    // Also turn on revisioning by default
    $form['revision_information']['revision']['#default_value'] = TRUE;
    unset($form['revision_information']['revision']['#states']);

    // Also hide the "Promoted to front page" option
    $form['options']['promote']['#prefix'] = '<div style="display:none;">';
    $form['options']['promote']['#suffix'] = '</div>';

    // Also hide the "Sticky at top of lists" option
    $form['options']['sticky']['#prefix'] = '<div style="display:none;">';
    $form['options']['sticky']['#suffix'] = '</div>';
  }
}

/**
 * When a node is modified, update its menu link to be hidden or not based on the user input.
 */
function unl_node_form_submit($form, &$form_state) {
  $menu_data = $form_state['values']['menu'];

  if ($menu_data['mlid']) {
    $menu_link = menu_link_load($menu_data['mlid']);
  }
  else {
    list($parent_menu_name, $parent_mlid) = explode(':', $menu_data['parent']);
    $menu_links = menu_load_links($parent_menu_name);
    foreach ($menu_links as $menu_link) {
      if ($menu_link['plid'] != $parent_mlid) {
        continue;
      }
      if ($menu_link['link_path'] != 'node/' . $form_state['values']['nid']) {
        continue;
      }
      break;
    }
  }

  $menu_link['hidden'] = $menu_data['visible'] ? 0 : 1;
  menu_link_save($menu_link);
}

function unl_system_settings_form_submit($form, &$form_state) {
  variable_set('https', (bool) $form_state['values']['https']);
}

function unl_theme() {
  return array(
    'unl_table' => array(
      'render element' => 'form',
    ),
  );
}

function unl_url_outbound_alter(&$path, &$options, $original_path) {
  $path_parts = parse_url($path);
  if (isset($path_parts['scheme']) || $path == 'user/cas') {
    return;
  }

  $user = $GLOBALS['user'];
  $user_roles = array_keys($user->roles);
  $generic_user = TRUE;
  foreach ($user_roles as $user_role) {
    if (in_array($user_role, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
      continue;
    }
    $generic_user = FALSE;
  }

  $options['https'] = (bool) (variable_get('https', 0) && !$generic_user);
}

function unl_user_access($permissions, $account = NULL) {
  foreach ($permissions as $permission) {
    if (substr($permission, 0, 1) == '!') {
      $permission = substr($permission, 1);
      $result = !user_access($permission, $account);
    }
    else {
      $result = user_access($permission, $account);
    }

    if (!$result) {
      return FALSE;
    }
  }

  return TRUE;
}

/**
 * Additional validation on the user_admin_role form (admin/people/permissions/roles/edit/%)
 * to prevent a user from deleting the administrator role.
 */
function unl_user_admin_role_validate($form, &$form_state) {
  $admin_role_id = variable_get('user_admin_role', -1);

  if ($form_state['values']['op'] == t('Delete role')) {
    $role = user_role_load_by_name($form_state['values']['name']);
    if ($role && $role->rid == $admin_role_id) {
      form_set_error('name', t('The role name %name can not be deleted. Seriously dude. Seriously.', array('%name' => $form_state['values']['name'])));
    }
  }
}

function unl_cron() {
  if (PHP_SAPI == 'cli') {
    return;
  }

  $queue = DrupalQueue::get('unl_migration');
  if ($queue->numberOfItems() > 0) {
    require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'unl_migration.php';
    $item = $queue->claimItem(120);
    $queue->deleteItem($item);
    unl_migration_queue_step($item->data);
  }

  if (conf_path() == 'sites/default') {

    $wdn_registry_info = array(
      'database' => variable_get('unl_wdn_registry_database'),
      'username' => variable_get('unl_wdn_registry_username'),
      'password' => variable_get('unl_wdn_registry_password'),
      'host'     => variable_get('unl_wdn_registry_host'),
      'driver'   => 'mysql',
    );

    if (!$wdn_registry_info['database']) {
      return;
    }

    Database::addConnectionInfo('wdn_registry', 'default', $wdn_registry_info);
    db_set_active('wdn_registry');

    try {
      $data = db_select('site_request', 'r')
        ->fields('r')
        ->where('`url` IS NULL')
        ->execute()
        ->fetchAll();
    }
    catch (Exception $e) {
      db_set_active();
      return;
    }

    $sites_to_create = array();
    foreach ($data as $site) {
      $path = $site->department . '/' . $site->site_name;
      $path = strtolower($path);
      $path = strtr($path, array(' ' => ''));

      $db_prefix = $site->site_name;
      $db_prefix = strtolower($db_prefix);
      $db_prefix = strtr($db_prefix, array(' ' => ''));

      $path = 'incubator/' . $path;

      $sites_to_create[] = array(
        'site_path'      => $path,
        'uri'            => url($path),
        'clean_url'      => TRUE,
        'db_prefix'      => $db_prefix,
        'site_admin'     => $site->site_admin,
        'migration_url'  => $site->migration_url,
        'migration_path' => $site->migration_path,
      );

      if (variable_get('unl_wdn_registry_production')) {
        db_update('site_request')
          ->fields(array('url' => url($path)))
          ->condition('id', $site->id)
          ->execute();
      }
    }

    db_set_active();

    foreach ($sites_to_create as $site_to_create) {
      try {
        db_insert('unl_sites')->fields($site_to_create)->execute();
      }
      catch (PDOException $e) {
        // Ignore duplicate records.
        if ($e->getCode() != 23000) {
          throw $e;
        }
      }
    }
  }
}