unl.module 42.9 KB
Newer Older
1
2
<?php

3
4
require_once dirname(__FILE__) . '/includes/common.php';

Eric Rasmussen's avatar
   
Eric Rasmussen committed
5
/**
6
 * Implements hook_help().
Eric Rasmussen's avatar
   
Eric Rasmussen committed
7
8
9
 */
function unl_help($path, $arg) {
  switch ($path) {
10
11
12
13
    case 'admin/modules/uninstall':
      if ((module_exists('unl_multisite') && conf_path() == 'sites/default') || unl_table_is_shared('role_permission')) {
        return '<h1>Be careful! Uninstalling a module clears its permissions which are shared globally between sites!</h1>';
      }
Eric Rasmussen's avatar
   
Eric Rasmussen committed
14
    case 'admin/people/permissions':
15
16
17
      if ((module_exists('unl_multisite') && conf_path() == 'sites/default') || unl_table_is_shared('role_permission')) {
        return '<h1>Be careful! Permissions are shared globally between sites!</h1>';
      }
Eric Rasmussen's avatar
   
Eric Rasmussen committed
18
19
20
21
22
    case 'user/unl/technical_feedback':
      return '<p>Consider visiting the Web Developer Network <a href="http://wdn.unl.edu/help/irc.shtml" target="_blank">chat room</a> as well.</p>';
  }
}

23
/**
24
 * Implements hook_entity_info_alter().
25
26
27
28
29
30
31
32
33
 */
function unl_entity_info_alter(&$entity_info) {
  // Add additional view_mode to admin/structure/types/manage/CONTENTTYPE/display for an abbriviated teaser (for use in sidebars, etc)
  $entity_info['node']['view modes']['abbr_teaser'] = array(
    'label' => t('Abbriviated teaser'),
    'custom settings' => TRUE,
  );
}

34
/**
35
 * Implements hook_context_plugins(). (Context module)
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
 */
function unl_context_plugins() {
  $plugins = array();
  $plugins['unl_context_reaction_linkrelhome'] = array(
    'handler' => array(
      'path' => drupal_get_path('module', 'unl') .'/plugins',
      'file' => 'unl_context_reaction_linkrelhome.inc',
      'class' => 'unl_context_reaction_linkrelhome',
      'parent' => 'context_reaction',
    ),
  );
  $plugins['unl_context_reaction_blockremove'] = array(
    'handler' => array(
      'path' => drupal_get_path('module', 'unl') .'/plugins',
      'file' => 'unl_context_reaction_blockremove.inc',
      'class' => 'unl_context_reaction_blockremove',
      'parent' => 'context_reaction',
    ),
  );
  return $plugins;
}

/**
59
 * Implements hook_context_registry(). (Context module)
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
 */
function unl_context_registry() {
  return array(
    'reactions' => array(
      'linkrelhome' => array(
        'title' => t('link rel="home" tag'),
        'plugin' => 'unl_context_reaction_linkrelhome',
      ),
      'blockremove' => array(
        'title' => t('Block Remove'),
        'plugin' => 'unl_context_reaction_blockremove',
      ),
    ),
  );
}

/**
77
 * Implements hook_context_page_reaction(). (Context module)
78
79
80
81
82
83
84
 */
function unl_context_page_reaction() {
  if ($plugin = context_get_plugin('reaction', 'linkrelhome')) {
    $plugin->execute();
  }
}

85
/**
86
 * Implements hook_page_alter().
87
88
89
90
 */
function unl_page_alter(&$page) {
  // Add UNLcms technical feedback link to toolbar
  if (isset($page['page_top']['toolbar'])) {
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
    $page['page_top']['toolbar']['#pre_render'][] = 'unl_toolbar_add_links';
  }
}

/**
 * Implements hook_block_list_alter().
 */
function unl_block_list_alter(&$blocks) {
  // Hide all content area blocks on 404 page if using the 'unl-404' menu callback.
  $status = drupal_get_http_header('status');
  if ($status == '404 Not Found' && variable_get('site_404') == 'unl-404') {
    foreach ($blocks as $key => $block) {
      if (in_array($block->region, array('content', 'sidebar_first', 'sidebar_second'))) {
        unset($blocks[$key]);
      }
106
    }
107
  }
108
109
110
111
112
113
114
}

/**
 * Custom function called from unl_page_alter() to add links to the toolbar.
 */
function unl_toolbar_add_links($toolbar) {
  $link['html'] = TRUE;
115
  $icon = '<span style="background-image:url('. base_path() . 'sites/all/modules/unl/images/feedback_toolbar.png); background-repeat: no-repeat; width:17px; height:14px; text-indent:-9999px; display:block; margin: 3px 0;">Support</span>';
116
  $link['title'] = t("!icon", array('!icon' => $icon));
117
118
  $link['attributes']['title'] = t('Submit feedback/issues/problems concerning the UNLcms system');
  $link['href'] = 'user/unl/support';
119
120
121
122
123

  $toolbar['toolbar_user']['#links'] = array_merge(array('unl' => $link), $toolbar['toolbar_user']['#links']);
  return $toolbar;
}

124
/**
125
 * Implements hook_page_build().
126
127
128
129
130
131
132
133
134
135
136
137
138
 */
function unl_page_build(&$page) {
  if (module_exists('context')) {
    if ($plugin = context_get_plugin('reaction', 'blockremove')) {
      $plugin->execute($page);
    }
    // See block_page_build. Clear static cache b/c in overlay form submissions
    // hook_page_build can get called more than once per page load.
    drupal_static_reset('context_reaction_block_list');
  }
}

/**
139
 * Implements hook_field_attach_view_alter().
140
141
142
143
 */
function unl_field_attach_view_alter(&$output, $context) {
  // Replace the field named field_hrorgunit containing an org unit number with that unit's listing from the UNL directory
  foreach (element_children($output) as $field_name) {
144
145
    $element = isset($output[$field_name]['#field_name']) ? $output[$field_name]['#field_name'] : '';
    switch ($element) {
146
      case 'field_hrorgunit':
147
        $result = unl_url_get_contents('http://directory.unl.edu/departments/?view=deptlistings&org_unit='.$element['#items'][0]['value'].'&format=partial');
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
        if (!empty($result) && $result != '<div id="all_employees"></div>') {
          drupal_add_css('http://directory.unl.edu/css/peoplefinder_default.css', 'external');
          drupal_add_js('http://directory.unl.edu/scripts/peoplefinder.js', 'external');
          drupal_add_js('var PF_URL = "http://directory.unl.edu/", ANNOTATE_URL = "http://annotate.unl.edu/";', 'inline');
          // Need to check to see if directory.unl.edu only returned a partial result. If so, result will have a message in between the closing ul and div tags like so: </ul><p>Try refining your search.</p></div></div>
          if (!preg_match('/<\/ul>\s*\n*\s*<\/div><\/div>/', $result)) {
            // Extra message at the bottom indicating not all results returned - hide it
            drupal_add_css('#all_employees > * > p {display:none;}', 'inline');
            // Alert the user to visit the directory site
            drupal_add_js('jQuery(document).ready(function(){jQuery("#all_employees .result_head").css("font-size","13px").html("We\'re a big department! Partial listing shown below, please visit <a href=\"http://directory.unl.edu/departments/'.$element['#items'][0]['value'].'#all_employees\">our department lisiting on the UNL Directory</a> to see everyone.");});', 'inline');
          }
        }
        else {
          $result = '<p>Please visit the <a href="http://directory.unl.edu/">UNL Directory</a> for listings.</p>';
        }
        foreach ($element['#items'] as $delta => $item) {
          $element[$delta]['#markup'] = $result;
        }
        break;
      default:
    }
  }
}

/**
173
 * Implements hook_node_access().
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
 */
function unl_node_access($node, $op, $account) {
  // When content types are created they have blank permissions so base access on the 'Basic page' type. This is done because with shared permissions subsites can't edit permissions.
  //@TODO Make this configureable i.e. make it possible to opt-out certain types from this.
  switch($op) {
    case 'view':
      break;
    case 'create':
      return user_access('create page content', $account) ? NODE_ACCESS_ALLOW : NODE_ACCESS_IGNORE;
    case 'update':
      if (isset($node->uid) && $node->uid == $account->uid) {
        return user_access('edit own page content', $account) ? NODE_ACCESS_ALLOW : NODE_ACCESS_IGNORE;
      }
      return user_access('edit any page content', $account) ? NODE_ACCESS_ALLOW : NODE_ACCESS_IGNORE;
    case 'delete':
      if (isset($node->uid) && $node->uid == $account->uid) {
        return user_access('delete own page content', $account) ? NODE_ACCESS_ALLOW : NODE_ACCESS_IGNORE;
      }
      return user_access('delete any page content', $account) ? NODE_ACCESS_ALLOW : NODE_ACCESS_IGNORE;
  }
}

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

200
/**
201
 * Implements hook_node_presave().
202
203
204
205
206
207
208
209
 */
function unl_node_presave($node) {
  // Tidy html in fields that are text areas
  foreach(field_info_instances('node', $node->type) as $field) {
    if (substr($field['widget']['type'], 0, 13) == 'text_textarea') {
      $field_name = $field['field_name'];
      $lang = $node->language;
      $node_field = $node->$field_name;
210
211
212
213
214
      if (isset($node_field[$lang][0]['value'])) {
        $tidied_value = unl_tidy($node_field[$lang][0]['value']);
        $node_field[$lang][0]['value'] = $tidied_value;
        $node->$field_name = $node_field;
      }
215
216
217
218
    }
  }
}

219
/**
220
 * Implements hook_permission().
221
 */
222
223
function unl_permission() {
  return array(
224
225
226
    '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.'),
227
228
      'restrict access' => TRUE,
    ),
229

230
231
232
233
    '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,
234
    ),
235

236
    'unl theme settings' => array(
237
      'title'       => t('Change Theme Settings'),
238
      'description' => t('Allow this role to change the current theme settings.'),
239
240
241
242
243
    ),

    'unl imce javascript upload' => array(
      'title'       => t('Upload Javascript Files Through IMCE'),
    ),
244
  );
245
246
}

247
248
249
250
251
252
253
254
255
256
257
/**
 * Implements hook_preprocess_node().
 */
function unl_preprocess_node(&$vars) {
  // Full page representation wanted for 404 page
  $status = drupal_get_http_header('status');
  if ($status == '404 Not Found') {
    $vars['page'] = TRUE;
  }
}

258
259
260
261
262
/**
 * Implements hook_preprocess_page().
 */
function unl_preprocess_page(&$vars) {
  switch (current_path()) {
263
264
265
266
267
268
269
    case 'admin/help':
      // Override default help_help text about what to do after install
      $vars['page']['help']['system_help']['#markup'] = '<h2>UNLcms Help</h2><p>Help is available from:</p>
                      <ul><li><a href="http://unlcms.unl.edu/guide">Online Guide</a></li>
                          <li><a href="http://unlcms.unl.edu/community">Users Group</a>, the second Tuesday of each month at 3:00pm in Nebraska Union</li>
                          <li><a href="http://wdn.unl.edu/help/irc.shtml">WDN Chat Room</a></li></ul>
                      <p>Below are help topics automatically generated by Drupal.</p><hr />';
270
      break;
271
272
273
    case 'admin/modules':
      if (!unl_user_is_administrator()) {
        // Changed here rather than using hook_help because the later merely appends to the existing text.
274
        $vars['page']['help']['system_help']['#markup'] = '<p>Not all modules can be turned on/off. If you have questions about modules on this page or modules not yet part of the UNL project <a href="user/unl/technical_feedback">contact an administrator</a>.</p>';
275
      }
276
      break;
277
278
279
  }
}

280
/**
281
 * Implements hook_menu().
282
 */
283
function unl_menu() {
284
285
  $items = array();

286
287
288
289
290
291
292
293
  // 404 page pulled from default site.
  $items['unl-404'] = array(
    'title' => 'Page not found',
    'access callback' => TRUE,
    'page callback' => 'unl_404_page',
    'type' => MENU_CALLBACK,
  );

294
295
296
297
298
299
300
301
  // Output html snippets for regions.
   $items['sharedcode/%'] = array(
    'title' => 'sharedcode files',
    'access arguments' => array('access content'),
    'page callback' => 'unl_sharedcode',
    'page arguments' => array(1),
  );

302
303
  // Returns confirmation 'user_loggedin' if user is logged into the system
   $items['user/unl/whoami'] = array(
304
305
306
307
    'title' => 'UNL Whoami Tool',
    'access callback' => TRUE,
    'page callback' => 'unl_whoami',
    'file' => 'unl_whoami.php',
308
  );
309

310
311
312
313
  // Returns UNLcms support form
  $items['user/unl/support'] = array(
    'title' => 'UNLcms Support Form',
    'description' => 'Submit feedback/issues/problems concerning the UNLcms system.',
314
315
    'access callback' => 'user_is_logged_in',
    'page callback' => 'drupal_get_form',
316
    'page arguments' => array('unl_support'),
317
    'type' => MENU_NORMAL_ITEM,
318
    'file' => 'unl_support.php',
319
  );
320

321
  $items['admin/content/unl/reset'] = array(
322
323
    'title' => 'Reset Site',
    'description' => 'Remove all nodes, menu items, etc from this site.',
324
    'access arguments' => array('administer nodes'),
325
326
327
    'page callback' => 'drupal_get_form',
    'page arguments' => array('unl_reset_site'),
    'file' => 'includes/reset_site.php',
328
  );
329

330
  // Redirect the Appearance link away from admin/appearance for users who can't Administer themes but can Change Theme Settings
331
332
333
334
335
336
337
338
339
  $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,
  );
340

341
  // Hello world type page for performance/uptime monitoring
342
  $items['_status'] = array(
343
344
    'title' => 'Still Alive',
    'page callback' => 'unl_still_alive',
345
346
    'access callback' => TRUE,
  );
347

348
  // UNL Settings
349
  $items['admin/config/system/unl'] = array(
350
351
    'title' => 'UNL',
    'description' => 'Configure UNL System Settings',
352
    'access arguments' => array('administer site configuration'),
353
354
355
356
    'page callback' => 'drupal_get_form',
    'page arguments' => array('unl_config'),
    'file' => 'includes/unl.admin.inc',
    'weight' => 1,
357
  );
358

359
360
361
362
363
  if (module_exists('imce')) {
    // Add IMCE file browser to Content section
    $items['admin/content/imce-file-browser'] = array(
      'title' => 'File browser',
      'page callback' => 'imce_user_page',
364
      'page arguments' => array($GLOBALS['user']->uid),
365
366
367
368
369
370
371
372
373
374
375
      'access callback' => '_unl_imce_file_browser_access',
      'file' => 'inc/imce.page.inc',
      'file path' => drupal_get_path('module', 'imce'),
      'type' => MENU_LOCAL_TASK,
      'weight' => -10,
    );
    // Add IMCE file browser to Add content list
    $items['node/add/imce-file-upload'] = array(
      'title' => 'File upload',
      'description' => 'Upload files from your computer, such as PDF documents, to the file system.',
      'page callback' => 'imce_user_page',
376
      'page arguments' => array($GLOBALS['user']->uid),
377
378
379
380
381
382
383
      'access callback' => '_unl_imce_file_browser_access',
      'file' => 'inc/imce.page.inc',
      'file path' => drupal_get_path('module', 'imce'),
      'type' => MENU_NORMAL_ITEM,
    );
  }

384
  return $items;
385
}
386

387
/**
388
 * Implements hook_menu_alter().
389
 */
390
function unl_menu_alter(&$items) {
391
392
  // This duplicates the form at admin/appearance/settings/unl_wdn for roles that can't 'administer themes' but have 'unl theme settings' permission.
  // For these users the Appearance link is changed to point to admin/themes
393
394
395
  foreach (array('module', 'file', 'page arguments') as $key) {
    $items['admin/themes'][$key] = $items['admin/appearance/settings/' . variable_get('theme_default')][$key];
  }
396
397
398
399
400
401
402
  // Put all user pages in the admin theme
  $items['user']['theme callback'] = '_unl_get_admin_theme';
  // Make sure all Workbench Moderation admin pages are in the admin theme
  if (module_exists('workbench_moderation')) {
    $items['node/%node/moderation']['theme callback'] = '_unl_get_admin_theme';
    $items['node/%node/moderation/%/unpublish']['theme callback'] = '_unl_get_admin_theme';
  }
403

404
405
406
407
408
409
410
411
  // Add a menu hook for the image module to use clean file URLs.
  if (variable_get('unl_clean_file_url') && module_exists('image')) {
    $directory_path = file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath();
    $items['styles/%image_style'] = $items[$directory_path . '/styles/%image_style'];
    // This parameter is how "deep" to look into request_path() for the image's path.
    // Since clean URLs have no "prefix", we can just set it to 1.
    $items['styles/%image_style']['page arguments'] = array(1);
  }
412

413
  $items['admin/modules/uninstall']['access callback'] = 'unl_user_is_administrator';
414
415
}

416
417
418
419
420
421
422
423
424
425
426
427
428
/**
 * Custom page callback.
 */
function unl_404_page() {
  $database = $GLOBALS['databases']['default']['default'];
  $database['prefix'] = unl_get_shared_db_prefix();
  Database::addConnectionInfo('default_site', 'default', $database);
  // Switch database connection to default site.
  db_set_active('default_site');

  $default_404 = unl_shared_variable_get('site_404');
  // @TODO: $default_404 should look like "node/182" but is there a safer way to retrieve nid?
  $node = node_load(substr($default_404, 5));
429
430
431
432
433
434
435
436
437
  if ($node) {
    drupal_set_title($node->title);
    $build = node_view($node, 'full');
    $build['links']['#access'] = FALSE;
    $build['#contextual_links'] = NULL;
  }
  else {
    $build = array();
  }
438
439
440
441
442
443

  // Restore database connection.
  db_set_active();
  return drupal_render($build);
}

444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
/**
 * Custom function that creates html snippet output at sharedcode/% paths to
 *   mimic files that once existed on static UNL templated sites.
 */
function unl_sharedcode($file = null) {
  foreach (system_region_list($GLOBALS['theme']) as $region_key => $region_name) {
    if ($blocks = block_get_blocks_by_region($region_key)) {
      $regions[$region_key] = $blocks;
    }
    else {
      $regions[$region_key] = array();
    }
  }

  switch ($file) {
    case 'footer.html':
    case 'footer_content':
      $region = 'footercontent';
      break;
    case 'footerContactInfo.html':
    case 'contact_us':
      $region = 'contactinfo';
      break;
    case 'navigation.html':
    case 'navigation_links':
      $region = 'navlinks';
      break;
    case 'relatedLinks.html':
    case 'related_links':
      $region = 'leftcollinks';
      break;
    default:
      drupal_not_found();
      return;
  }

  drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
  drupal_add_http_header('Content-Language', 'en');
  print render($regions[$region]);
  exit;
}

486
/**
487
 * Implements hook_file_validate().
488
489
490
491
 * Fires when files are uploaded after Drupal Core sanitization but before saving to file system or db
 */
function unl_file_validate($file) {
  // For IMCE uploads only, check if Drupal core just altered a *.js upload to *.js.txt and correct if permitted
Eric Rasmussen's avatar
Eric Rasmussen committed
492
  if (isset($file->source) && $file->source == 'imce' && substr($file->filename, -7) == '.js.txt' && user_access('unl imce javascript upload')) {
493
494
495
496
497
498
499
    // Chop off the .txt extesnsion that's been added
    $file->destination = substr($file->destination, 0, -4);
    $file->filename = substr($file->filename, 0, -4);
  }
  return;
}

500
/**
501
 * Implements hook_form_FORM_ID_alter() for system_theme_settings.
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
 * This is used in addition to unl_wdn_form_system_theme_settings_alter because that hook
 *   runs before color_form_system_theme_settings_alter which overwrites an attempt
 *   at setting $form['color']['#access'].
 */
function unl_form_system_theme_settings_alter(&$form, &$form_state) {
  global $user;

  $form['advanced_settings']['unl_affiliate']['#access'] = unl_user_is_administrator();

  $is_affiliate = $form['advanced_settings']['unl_affiliate']['#default_value'];

  $form['color']['#access'] = $is_affiliate;
  $form['logo']['#access'] = $is_affiliate;
  $form['favicon']['#access'] = $is_affiliate;

  // These are settings manipulations that we want for UNL but don't necessarily belong in the theme
  if (!$is_affiliate && !unl_user_is_administrator()) {
    $form['theme_settings']['toggle_logo']['#access'] = false;
    $form['theme_settings']['toggle_favicon']['#access'] = false;
    $form['theme_settings']['toggle_name']['#access'] = false;
    $form['theme_settings']['toggle_comment_user_verification']['#access'] = false;
    $form['theme_settings']['toggle_main_menu']['#access'] = false;
    $form['theme_settings']['toggle_secondary_menu']['#access'] = false;
  }
}

528
/**
529
 * Implements hook_form_FORM_ID_alter() for field_ui_display_overview_form.
530
531
532
533
534
535
536
537
 */
function unl_form_field_ui_display_overview_form_alter(&$form, &$form_state, $form_id) {
  // Add additional label display options in Manage Display section of content type editing (admin/structure/types/manage/content-type/display)
  foreach ($form['#fields'] as $key => $field) {
    $form['fields'][$field]['label']['#options'] += array('h2'=>'Block: h2','h3'=>'Block: h3','h4'=>'Block: h4','h5'=>'Block: h5','h6'=>'Block: h6');
  }
}

538
/**
539
 * Implements hook_form_FORM_ID_alter() for system_modules.
540
541
542
 */
function unl_form_system_modules_alter(&$form, &$form_state, $form_id) {
  // Whitelist of modules that Site Admin are allowed to turn on and off on admin/modules
543
  $modules = unl_shared_variable_get('unl_module_whitelist', array());
544
545
546
547
548
549
550
551
552
553
554
555
556
557

  if (!unl_user_is_administrator() && isset($form['modules'])) {
    foreach ($form['modules'] as $category_name => $category) {
      if (is_array($category)) {
        foreach ($category as $module_name => $module) {
          if (!in_array($module_name, $modules) && substr($module_name,0,1) !== '#') {
            $form['modules'][$category_name][$module_name]['#disabled'] = true;
          }
        }
      }
    }
  }
}

558
/**
559
 * Implements hook_form_FORM_ID_alter() for system_logging_settings.
560
561
562
563
564
565
566
567
 */
function unl_form_system_logging_settings_alter(&$form, $form_state, $form_id) {
  // Disable ability of non-admins to turn on error reporting on on admin/config/development/logging.
  if (!unl_user_is_administrator()) {
    $form['#disabled'] = true;
  }
}

568
/**
569
 * Implements hook_form_alter().
570
 */
571
function unl_form_alter(&$form, $form_state, $form_id) {
572
573
574
575
  // Make new menu items expanded by default.
  if ($form_id == 'menu_edit_item' && $form['mlid']['#value'] == 0) {
    $form['expanded']['#default_value'] = TRUE;
  }
576

577
578
579
580
581
  if ($form_id == 'system_site_information_settings') {
    $form['site_information']['https'] = array(
      '#type' => 'checkbox',
      '#title' => 'SSL Enabled',
      '#default_value' => variable_get('https', FALSE),
582
      '#disabled' => !unl_user_is_administrator(),
583
    );
584

585
586
587
588
589
    if (conf_path() != 'sites/default') {
      $alternate_uris = unl_get_alternate_base_uris();
      $base_urls = array('_null' => '--Select One--');
      foreach ($alternate_uris as $alternate_uri) {
        $base_urls[$alternate_uri] = $alternate_uri;
590
      }
591
592
593
594
595
      $form['site_information']['unl_primary_base_url'] = array(
        '#title' => 'Primary Base URL',
        '#type' => 'select',
        '#options' => $base_urls,
        '#default_value' => variable_get('unl_primary_base_url'),
596
        '#disabled' => !unl_user_is_administrator(),
597
598
599
      );
      $form['#submit'][] = 'unl_system_settings_form_submit';
    }
600
  }
601

602
  // Modifications for non-administrators
603
  $admin_role_id = unl_shared_variable_get('user_admin_role', -1);
604
605
606
607
608
609
610
611
612
613
614
615
  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]);
          }
616
        }
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
        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]);
              }
            }
649
          }
650
        }
651
652
653
654
655
656

        // 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]);
657
        }
658
659
660
661
662
663
664
665
666
667
668
669

        // 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) {
670
          if (in_array($permission, $administrator_permissions)) {
671
            unset($form['permission'][$permission]);
672
673
          }
        }
674
675
676
677
678
679
680
681
682
683
        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;
684
    }
685
  }
686

687
688
689
690
691
692
693
694
695
  // Node Edit Form
  if (isset($form['#node_edit_form']) && $form['#node_edit_form']) {
    // Tidy existing html in fields that are text areas
    foreach(field_info_instances($form['#entity_type'], $form['#bundle']) as $field) {
      if (substr($field['widget']['type'], 0, 13) == 'text_textarea') {
        $field_name = $field['field_name'];
        $form[$field_name]['und'][0]['#default_value'] = unl_tidy($form[$field_name]['und'][0]['#default_value']);
      }
    }
696

697
698
699
    // 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.
    $form['menu']['#title'] = 'Site hierarchy';
700
701
702
703
    $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;
704

705
706
707
708
709
710
711
712
713
714
715
716
717
718
    $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,
    );
719

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

722
    // Also turn on revisioning
Tim Steiner's avatar
Tim Steiner committed
723
724
    $form['revision_information']['revision']['#default_value'] = TRUE;
    unset($form['revision_information']['revision']['#states']);
725
  }
726

727
  // Add the Roles checkboxes to the user edit form for users with ability to 'Administer users' but not 'Administer permissions' (Code below partially taken from user.module)
728
  if (in_array($form_id, array('user_register_form', 'user_profile_form')) && user_access('administer users') && !user_access('administer permissions')) {
729
    $roles = array_map('check_plain', user_roles(TRUE));
730
    // Unset the adminsitrator checkbox, validation code that prevents a user who is not an administrator from granting the administrator role is in the unl_cas module
731
    unset($roles[$admin_role_id]);
732
733
    $form['account']['roles']['#options'] = $roles;
    $form['account']['roles']['#access'] = !empty($roles);
734
  }
735
736
737
}

/**
738
 * Implements hook_node_form_submit().
739
740
 */
function unl_node_form_submit($form, &$form_state) {
741
  // When a node is modified, update its menu link to be hidden or not based on the user input.
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
  $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;
    }
  }
760

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

765
/**
766
 * Implements hook_system_settings_form_submit().
767
 */
768
769
function unl_system_settings_form_submit($form, &$form_state) {
  variable_set('https', (bool) $form_state['values']['https']);
770
771
772
773
774
775
  if ($form_state['values']['unl_primary_base_url'] != '_null') {
    variable_set('unl_primary_base_url', $form_state['values']['unl_primary_base_url']);
  }
  else {
    variable_del('unl_primary_base_url');
  }
776
}
777

778
/**
779
 * Implements hook_url_outbound_alter().
780
 */
781
782
783
784
785
function unl_url_outbound_alter(&$path, &$options, $original_path) {
  $path_parts = parse_url($path);
  if (isset($path_parts['scheme']) || $path == 'user/cas') {
    return;
  }
786

787
788
789
790
791
792
793
794
795
  $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;
  }
796

797
798
799
  if (isset($options['https'])) {
    return;
  }
800

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

804
805
806
807
/**
 * Custom function for implementing user_access for multiple permissions.
 * Feature request: http://drupal.org/node/216897
 */
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
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;
}
823

824
/**
825
 * Custom function for additional validation on the user_admin_role form (admin/people/permissions/roles/edit/%)
826
 * to prevent a user from deleting the administrator role. (This is not needed if permissions are shared and only administrators can edit roles.)
827
828
 */
function unl_user_admin_role_validate($form, &$form_state) {
829
  $admin_role_id = unl_shared_variable_get('user_admin_role', -1);
830
831
832
833
834
835
836
837
838

  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'])));
    }
  }
}

839
840
841
842
/**
 * Custom function to sanitize user created URLs
 */
function unl_sanitize_url_part($url_part) {
843
  $url_part = strtolower($url_part);
844
845
846
  $url_part = preg_replace('/[^a-z0-9]/', '-', $url_part);
  $url_part = preg_replace('/-+/', '-', $url_part);
  $url_part = preg_replace('/(^-)|(-$)/', '', $url_part);
847

848
849
850
  return $url_part;
}

851
852
853
/**
 * Custom function.
 */
854
855
856
857
858
859
860
861
862
863
function unl_get_alternate_base_uris() {
  $shared_prefix = unl_get_shared_db_prefix();
  if (is_array($GLOBALS['databases']['default']['default']['prefix'])) {
    $db_prefix = $GLOBALS['databases']['default']['default']['prefix']['default'];
    $db_prefix = substr($db_prefix, 0, 0 - strlen($shared_prefix) - 1);
  }
  else {
    return array();
  }
  $rows = db_query(
864
    "SELECT s.uri, a.base_uri, a.path "
865
866
867
    . "FROM {$shared_prefix}unl_sites AS s "
    . "LEFT JOIN {$shared_prefix}unl_sites_aliases AS a "
    . "  ON s.site_id = a.site_id "
868
    . "WHERE db_prefix=:db_prefix",
869
870
    array(':db_prefix' => $db_prefix)
  )->fetchAll();
871

872
873
874
  if (count($rows) < 1) {
    return array();
  }
875

876
877
  $uris = array($rows[0]->uri);
  foreach ($rows as $row) {
878
879
    if ($row->base_uri . $row->path) {
      $uris[] = $row->base_uri . $row->path;
880
881
    }
  }
882

883
884
885
  return $uris;
}

886
/**
887
 * Implements hook_init().
888
 */
889
function unl_init() {
890
  // Redirect to desired URL if needed
891
  $primary_base_url = variable_get('unl_primary_base_url');
892
893
894
895
896
897
898
899
900
  if ($primary_base_url) {
    if (substr($primary_base_url, -1) != '/') {
      $primary_base_url .= '/';
    }

    $current_url_schema = parse_url(url(), PHP_URL_SCHEME);
    $primary_base_url_schema = parse_url($primary_base_url, PHP_URL_SCHEME);
    $primary_base_url = $current_url_schema . substr($primary_base_url, strlen($primary_base_url_schema));

901
    if (conf_path() != 'sites/default' && $primary_base_url != url() && PHP_SAPI != 'cli') {
902
903
904
905
      // Ripped off from request_path(), but without removing things like cron.php
      $request_path = strtok($_SERVER['REQUEST_URI'], '?');
      $base_path_len = strlen(rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/'));
      $path = substr(urldecode($request_path), $base_path_len + 1);
906

907
      drupal_goto(url($primary_base_url . $path, array('query' => drupal_get_query_parameters())), array(), 301);
908
    }
909
  }
910

911
  // Insert <base> tag
912
  if (variable_get('unl_use_base_tag', TRUE)) {
913
914
915
916
917
918
919
    $base_href = url('<front>', array('absolute' => TRUE));
    if (substr($base_href, -1) != '/') {
      $base_href .= '/';
    }
    if ($GLOBALS['is_https']) {
      $base_href = str_replace('http://', 'https://', $base_href);
    }
920
921
922
923
    $base_tag = array(
      '#type' => 'html_tag',
      '#tag' => 'base',
      '#attributes' => array(
924
        'href' => $base_href
925
926
927
928
      ),
    );
    drupal_add_html_head($base_tag, 'base');
  }
929
  drupal_add_js(array('unl' => array('use_base_tag' => variable_get('unl_use_base_tag', TRUE))), 'setting');
930

931
  // Add JS
932
  drupal_add_js(drupal_get_path('module', 'unl') . '/unl.js', array('weight' => 50));
933
934

  // Handle unneeded index.html references
935
936
937
938
939
940
941
942
943
  _unl_handle_directory_index();
}

/**
 * Custom function called by unl_init() to redirect users from
 * a non-existant some/path/index.html to an existing some/path.
 */
function _unl_handle_directory_index() {
  $path = current_path();
944

945
946
947
  if (!in_array(basename($path), array('index.html', 'index.htm', 'index.shtml'))) {
    return;
  }
948

949
950
951
  if (drupal_lookup_path('source', $path)) {
    return;
  }
952

953
954
955
956
  if (drupal_lookup_path('source', dirname($path))) {
    drupal_goto(dirname($path));
    return;
  }
957

958
959
960
961
  if (dirname($path) == '.') {
    drupal_goto('<front>');
    return;
  }
962
}
963

964
965
966
967
/**
 * Custom function that outputs a simple "I'm still alive" page to check to see that drupal is working.
 */
function unl_still_alive() {
968
969
970
  header('Content-type: text/plain');
  echo '200 Still Alive';
}
971
972
973
974

/**
 * Custom function to return the current admin theme for use with hook_menu_alter().
 */
975
function _unl_get_admin_theme() {
976
977
978
979
980
981
982
983
984
985
986
987
  return variable_get('admin_theme', '0');
}

/**
 * Custom function for imce access on content administration pages since imce_user_page_access()
 * can't be used because only one file can be included in a hook_menu item ($items['admin/content/filebrowser'])
 */
function _unl_imce_file_browser_access() {
  global $user;
  $profile = imce_user_profile($user);
  return $profile['usertab'];
}
988

989
990
991
992
993
994
995
996
/**
 * Implements hook_stream_wrappers_alter().
 */
function unl_stream_wrappers_alter(&$wrappers) {
  if (variable_get('unl_clean_file_url')) {
    $wrappers['public']['class'] = 'UnlPublicStreamWrapper';
  }
}
997

998
999
1000
class UnlPublicStreamWrapper extends DrupalPublicStreamWrapper {
  function getExternalUrl() {
    $url = $GLOBALS['base_url'];
For faster browsing, not all history is shown. View entire blame