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

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

Eric Rasmussen's avatar
   
Eric Rasmussen committed
5
6
7
8
9
10
11
12
13
14
15
16
/**
 * Implementation of hook_help().
 */
function unl_help($path, $arg) {
  switch ($path) {
    case 'admin/people/permissions':
      return '<h1>Be careful! Permissions are shared globally between sites on UNLcms!</h1>';
    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>';
  }
}

17
18
19
20
21
22
23
24
25
26
27
/**
 * Implementation of hook_entity_info_alter().
 */
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,
  );
}

28
/**
29
30
31
32
33
34
35
36
37
 * Implementation of hook_html_head_alter().
 */
function unl_html_head_alter(&$head_elements) {
  // If <link rel="home"> has already been set elsewhere (in a Context for example) then return...
  foreach ($head_elements as $key => $element) {
    if ($element["#tag"] == 'link' && isset($element['#attributes']['rel']) && $element['#attributes']['rel'] == 'home') {
      return;
    }
  }
38

39
40
41
42
43
44
45
46
  // If we are in a drilled down menu, change the home link to the drilled down item.
  $current_menu_link = _unl_get_current_menu_link();
  if ($current_menu_link && $current_menu_link->depth > 1) {
    $home_path = drupal_get_path_alias($current_menu_link->link_path);
  }
  else {
    $home_path = '<front>';
  }
47

48
49
50
51
52
  // ...otherwise add a <link rel="home"> tag with the front page as the href attribute
  $element = array(
    '#tag' => 'link',
    '#attributes' => array(
      'rel' => 'home',
53
      'href' => url($home_path, array('absolute' => TRUE)),
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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
    ),
    '#type' => 'html_tag'
  );
  $head_elements['drupal_add_html_head_link:home'] = $element;
}

/**
 * Implementation of hook_context_plugins(). (Context module)
 */
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;
}

/**
 * Implementation of hook_context_registry(). (Context module)
 */
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',
      ),
    ),
  );
}

/**
 * Implementation of hook_context_page_reaction(). (Context module)
 */
function unl_context_page_reaction() {
  if ($plugin = context_get_plugin('reaction', 'linkrelhome')) {
    $plugin->execute();
  }
}

111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/**
 * Implementation of hook_page_alter().
 */
function unl_page_alter(&$page) {
  // Add UNLcms technical feedback link to toolbar
  if (isset($page['page_top']['toolbar'])) {
      $page['page_top']['toolbar']['#pre_render'][] = 'unl_toolbar_add_links';
    }
}

/**
 * Custom function called from unl_page_alter() to add links to the toolbar.
 */
function unl_toolbar_add_links($toolbar) {
  $link['html'] = TRUE;
126
  $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;">Feedback</span>';
127
128
129
130
131
132
133
134
  $link['title'] = t("!icon", array('!icon' => $icon));
  $link['attributes']['title'] = t('Submit technical feedback/issues/problems about the UNLcms system');
  $link['href'] = 'user/unl/technical_feedback';

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

135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
/**
 * Implementation of hook_page_build().
 */
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');
  }
}

/**
 * Implementation of hook_field_attach_view_alter().
151
152
153
154
 */
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) {
155
156
    $element = isset($output[$field_name]['#field_name']) ? $output[$field_name]['#field_name'] : '';
    switch ($element) {
157
      case 'field_hrorgunit':
158
        $result = unl_url_get_contents('http://directory.unl.edu/departments/?view=deptlistings&org_unit='.$element['#items'][0]['value'].'&format=partial');
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
        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:
    }
  }
}

/**
 * Implementation of hook_node_access().
 */
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;
  }
}

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

211
212
213
214
215
216
217
218
219
220
/**
 * Implementation of hook_node_presave().
 */
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;
221
222
223
224
225
      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;
      }
226
227
228
229
    }
  }
}

230
231
232
/**
 * Implementation of hook_permission().
 */
233
234
function unl_permission() {
  return array(
235
236
237
    '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.'),
238
239
      'restrict access' => TRUE,
    ),
240

241
242
243
244
    '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,
245
    ),
246

247
    'unl theme settings' => array(
248
      'title'       => t('Change Theme Settings'),
249
      'description' => t('Allow this role to change the current theme settings.'),
250
251
252
253
254
    ),

    'unl imce javascript upload' => array(
      'title'       => t('Upload Javascript Files Through IMCE'),
    ),
255
  );
256
257
}

258
259
260
261
262
263
264
265
266
267
268
/**
 * 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;
  }
}

269
270
271
272
273
/**
 * Implements hook_preprocess_page().
 */
function unl_preprocess_page(&$vars) {
  switch (current_path()) {
274
275
276
277
278
279
280
    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 />';
281
      break;
282
283
284
    case 'admin/modules':
      if (!unl_user_is_administrator()) {
        // Changed here rather than using hook_help because the later merely appends to the existing text.
285
        $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>';
286
      }
287
      break;
288
289
290
  }
}

291
/**
292
 * Implements hook_menu().
293
 */
294
function unl_menu() {
295
296
  $items = array();

297
298
299
300
301
302
303
304
  // 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,
  );

305
306
307
308
309
310
311
312
  // Output html snippets for regions.
   $items['sharedcode/%'] = array(
    'title' => 'sharedcode files',
    'access arguments' => array('access content'),
    'page callback' => 'unl_sharedcode',
    'page arguments' => array(1),
  );

313
314
  // Returns confirmation 'user_loggedin' if user is logged into the system
   $items['user/unl/whoami'] = array(
315
316
317
318
    'title' => 'UNL Whoami Tool',
    'access callback' => TRUE,
    'page callback' => 'unl_whoami',
    'file' => 'unl_whoami.php',
319
  );
320

321
  // Returns UNLcms technical feedback form
322
  $items['user/unl/technical_feedback'] = array(
323
324
325
326
327
328
329
    'title' => 'UNLcms Technical Feeedback Form',
    'description' => 'Submit technical feedback/issues/problems about the UNLcms system.',
    'access callback' => 'user_is_logged_in',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('unl_technical_feedback'),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'technical_feedback.php',
330
  );
331

332
  $items['admin/content/unl/reset'] = array(
333
334
    'title' => 'Reset Site',
    'description' => 'Remove all nodes, menu items, etc from this site.',
335
    'access arguments' => array('administer nodes'),
336
337
338
    'page callback' => 'drupal_get_form',
    'page arguments' => array('unl_reset_site'),
    'file' => 'includes/reset_site.php',
339
  );
340

341
  // Redirect the Appearance link away from admin/appearance for users who can't Administer themes but can Change Theme Settings
342
343
344
345
346
347
348
349
350
  $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,
  );
351

352
  // Hello world type page for performance/uptime monitoring
353
  $items['_status'] = array(
354
355
    'title' => 'Still Alive',
    'page callback' => 'unl_still_alive',
356
357
    'access callback' => TRUE,
  );
358

359
  // UNL Settings
360
  $items['admin/config/system/unl'] = array(
361
362
    'title' => 'UNL',
    'description' => 'Configure UNL System Settings',
363
    'access arguments' => array('administer site configuration'),
364
365
366
367
    'page callback' => 'drupal_get_form',
    'page arguments' => array('unl_config'),
    'file' => 'includes/unl.admin.inc',
    'weight' => 1,
368
  );
369

370
371
372
373
374
  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',
375
      'page arguments' => array($GLOBALS['user']->uid),
376
377
378
379
380
381
382
383
384
385
386
      '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',
387
      'page arguments' => array($GLOBALS['user']->uid),
388
389
390
391
392
393
394
      'access callback' => '_unl_imce_file_browser_access',
      'file' => 'inc/imce.page.inc',
      'file path' => drupal_get_path('module', 'imce'),
      'type' => MENU_NORMAL_ITEM,
    );
  }

395
  return $items;
396
}
397

398
/**
399
 * Implements hook_menu_alter().
400
 */
401
function unl_menu_alter(&$items) {
402
403
  // 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
404
405
406
  foreach (array('module', 'file', 'page arguments') as $key) {
    $items['admin/themes'][$key] = $items['admin/appearance/settings/' . variable_get('theme_default')][$key];
  }
407
408
409
410
411
412
413
  // 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';
  }
414

415
416
417
418
419
420
421
422
  // 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);
  }
423

424
  $items['admin/modules/uninstall']['access callback'] = 'unl_user_is_administrator';
425
426
}

427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
/**
 * 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));
  drupal_set_title($node->title);
  $build = node_view($node, 'full');
  $build['links']['#access'] = FALSE;
  $build['#contextual_links'] = NULL;

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

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
486
487
488
489
490
491
/**
 * 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;
}

492
/**
493
 * Implementation of hook_file_validate().
494
495
496
497
498
499
500
501
502
503
504
505
 * 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
  if ($file->source == 'imce' && substr($file->filename, -7) == '.js.txt' && user_access('unl imce javascript upload')) {
    // Chop off the .txt extesnsion that's been added
    $file->destination = substr($file->destination, 0, -4);
    $file->filename = substr($file->filename, 0, -4);
  }
  return;
}

506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
/**
 * Implementation of hook_form_FORM_ID_alter() for system_theme_settings.
 * 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;
  }
}

534
535
536
537
538
539
540
541
542
543
/**
 * Implementation of hook_form_FORM_ID_alter() for field_ui_display_overview_form.
 */
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');
  }
}

544
545
546
547
548
/**
 * Implementation of hook_form_FORM_ID_alter() for system_modules.
 */
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
549
  $modules = unl_shared_variable_get('unl_module_whitelist', array());
550
551
552
553
554
555
556
557
558
559
560
561
562
563

  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;
          }
        }
      }
    }
  }
}

564
565
566
567
568
569
570
571
572
573
/**
 * Implementation of hook_form_FORM_ID_alter() for system_logging_settings.
 */
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;
  }
}

574
575
576
/**
 * Implementation of hook_form_alter().
 */
577
function unl_form_alter(&$form, $form_state, $form_id) {
578
579
580
581
  // Make new menu items expanded by default.
  if ($form_id == 'menu_edit_item' && $form['mlid']['#value'] == 0) {
    $form['expanded']['#default_value'] = TRUE;
  }
582

583
584
585
586
587
588
  if ($form_id == 'system_site_information_settings') {
    $form['site_information']['https'] = array(
      '#type' => 'checkbox',
      '#title' => 'SSL Enabled',
      '#default_value' => variable_get('https', FALSE),
    );
589

590
591
592
593
594
    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;
595
      }
596
597
598
599
600
601
602
603
      $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'),
      );
      $form['#submit'][] = 'unl_system_settings_form_submit';
    }
604
  }
605

606
  // Modifications for non-administrators
607
  $admin_role_id = unl_shared_variable_get('user_admin_role', -1);
608
609
610
611
612
613
614
615
616
617
618
619
  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]);
          }
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
649
650
651
652
        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]);
              }
            }
653
          }
654
        }
655
656
657
658
659
660

        // 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]);
661
        }
662
663
664
665
666
667
668
669
670
671
672
673

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

691
692
693
694
695
696
697
698
699
  // 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']);
      }
    }
700

701
702
703
    // 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';
704
705
706
707
    $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;
708

709
710
711
712
713
714
715
716
717
718
719
720
721
722
    $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,
    );
723

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

726
    // Also turn on revisioning
Tim Steiner's avatar
Tim Steiner committed
727
728
    $form['revision_information']['revision']['#default_value'] = TRUE;
    unset($form['revision_information']['revision']['#states']);
729
  }
730

731
  // 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)
732
  if (in_array($form_id, array('user_register_form', 'user_profile_form')) && user_access('administer users') && !user_access('administer permissions')) {
733
    $roles = array_map('check_plain', user_roles(TRUE));
734
    // 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
735
    unset($roles[$admin_role_id]);
736
737
    $form['account']['roles']['#options'] = $roles;
    $form['account']['roles']['#access'] = !empty($roles);
738
  }
739
740
741
}

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

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

769
770
771
/**
 * Implementation of hook_system_settings_form_submit().
 */
772
773
function unl_system_settings_form_submit($form, &$form_state) {
  variable_set('https', (bool) $form_state['values']['https']);
774
775
776
777
778
779
  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');
  }
780
}
781

782
783
784
/**
 * Implementation of hook_url_outbound_alter().
 */
785
786
787
788
789
function unl_url_outbound_alter(&$path, &$options, $original_path) {
  $path_parts = parse_url($path);
  if (isset($path_parts['scheme']) || $path == 'user/cas') {
    return;
  }
790

791
792
793
794
795
796
797
798
799
  $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;
  }
800

801
802
803
  if (isset($options['https'])) {
    return;
  }
804

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

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

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

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

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

852
853
854
  return $url_part;
}

855
856
857
/**
 * Custom function.
 */
858
859
860
861
862
863
864
865
866
867
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(
868
    "SELECT s.uri, a.base_uri, a.path "
869
870
871
    . "FROM {$shared_prefix}unl_sites AS s "
    . "LEFT JOIN {$shared_prefix}unl_sites_aliases AS a "
    . "  ON s.site_id = a.site_id "
872
    . "WHERE db_prefix=:db_prefix",
873
874
    array(':db_prefix' => $db_prefix)
  )->fetchAll();
875

876
877
878
  if (count($rows) < 1) {
    return array();
  }
879

880
881
  $uris = array($rows[0]->uri);
  foreach ($rows as $row) {
882
883
    if ($row->base_uri . $row->path) {
      $uris[] = $row->base_uri . $row->path;
884
885
    }
  }
886

887
888
889
  return $uris;
}

890
891
892
/**
 * Implementation of hook_init().
 */
893
function unl_init() {
894
  // Redirect to desired URL if needed
895
  $primary_base_url = variable_get('unl_primary_base_url');
896
897
898
899
900
901
902
903
904
  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));

905
    if (conf_path() != 'sites/default' && $primary_base_url != url() && PHP_SAPI != 'cli') {
906
      drupal_goto(url($primary_base_url . request_path(), array('query' => drupal_get_query_parameters())));
907
    }
908
  }
909

910
  // Insert <base> tag
911
  if (variable_get('unl_use_base_tag', TRUE)) {
912
913
914
915
916
917
918
    $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);
    }
919
920
921
922
    $base_tag = array(
      '#type' => 'html_tag',
      '#tag' => 'base',
      '#attributes' => array(
923
        'href' => $base_href
924
925
926
927
      ),
    );
    drupal_add_html_head($base_tag, 'base');
  }
928
  drupal_add_js(array('unl' => array('use_base_tag' => variable_get('unl_use_base_tag', TRUE))), 'setting');
929

930
931
932
933
  // Add JS
  drupal_add_js('sites/all/modules/unl/unl.js');

  // Handle unneeded index.html references
934
935
936
937
938
939
940
941
942
  _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();
943

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

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

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

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

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

/**
 * Custom function to return the current admin theme for use with hook_menu_alter().
 */
974
function _unl_get_admin_theme() {
975
976
977
978
979
980
981
982
983
984
985
986
  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'];
}
987
988
989
990
991
992
993
994
995
996
997
998
999
1000

/**
 * Implements hook_block_view_alter()
 * @param array $data
 * @param stdClass $block
 */
function unl_block_view_alter(&$data, $block) {
  if ($block->module == 'system' && $block->delta == 'main-menu') {
    return unl_block_view_system_main_menu_alter($data, $block);
  }
}

/**
 * Tries to implement hook_block_view_MODULE_DELTA_alter, but since the delta contains a -,
For faster browsing, not all history is shown. View entire blame