File:  [LON-CAPA] / loncom / interface / lonmenu.pm
Revision 1.369.2.3: download - view: text, annotated - select for diffs
Fri May 18 16:54:56 2012 UTC (12 years ago) by raeburn
Branches: version_2_11_X
- For 2.11.
  - Backport 1.371.

    1: # The LearningOnline Network with CAPA
    2: # Routines to control the menu
    3: #
    4: # $Id: lonmenu.pm,v 1.369.2.3 2012/05/18 16:54:56 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: #
   29: 
   30: =head1 NAME
   31: 
   32: Apache::lonmenu
   33: 
   34: =head1 SYNOPSIS
   35: 
   36: Loads contents of /home/httpd/lonTabs/mydesk.tab, 
   37: used to generate inline menu, and Main Menu page. 
   38: 
   39: This is part of the LearningOnline Network with CAPA project
   40: described at http://www.lon-capa.org.
   41: 
   42: =head1 GLOBAL VARIABLES
   43: 
   44: =over
   45: 
   46: =item @desklines
   47: 
   48: Each element of this array contains a line of mydesk.tab that doesn't start with
   49: cat, prim or scnd. 
   50: It gets filled in the BEGIN block of this module.
   51: 
   52: =item %category_names
   53: 
   54: The keys of this hash are the abbreviations used in mydesk.tab in those lines that 
   55: start with cat, the values are strings representing titles. 
   56: It gets filled in the BEGIN block of this module.
   57: 
   58: =item %category_members
   59: 
   60: TODO 
   61: 
   62: =item %category_positions
   63: 
   64: The keys of this hash are the abbreviations used in mydesk.tab in those lines that
   65: start with cat, its values are position vectors (column, row). 
   66: It gets filled in the BEGIN block of this module.
   67: 
   68: =item $readdesk
   69: 
   70: Indicates that mydesk.tab has been read. 
   71: It is set to 'done' in the BEGIN block of this module.
   72: 
   73: =item @primary_menu
   74: 
   75: The elements of this array reference arrays that are made up of the components
   76: of those lines of mydesk.tab that start with prim:.
   77: It is used by primary_menu() to generate the corresponding menu.
   78: It gets filled in the BEGIN block of this module.
   79: 
   80: =item %primary_sub_menu
   81: 
   82: The keys of this hash reference are the names of items in the primary_menu array 
   83: which have sub-menus.  For each key, the corresponding value is a reference to
   84: an array containing components extracted from lines in mydesk.tab which begin
   85: with primsub:.
   86: This hash, which is used by primary_menu to generate sub-menus, is populated in
   87: the BEGIN block.
   88: 
   89: =item @secondary_menu
   90: 
   91: The elements of this array reference arrays that are made up of the components
   92: of those lines of mydesk.tab that start with scnd.
   93: It is used by secondary_menu() to generate the corresponding menu.
   94: It gets filled in the BEGIN block of this module.
   95: 
   96: =back
   97: 
   98: =head1 SUBROUTINES
   99: 
  100: =over
  101: 
  102: =item prep_menuitems(\@menuitem)
  103: 
  104: This routine wraps a menuitem in proper HTML. It is used by primary_menu() and 
  105: secondary_menu().
  106: 
  107: =item primary_menu()
  108: 
  109: This routine evaluates @primary_menu and returns XHTML for the menu
  110: that contains following links: About, Message, Roles, Help, Logout
  111: @primary_menu is filled within the BEGIN block of this module with 
  112: entries from mydesk.tab 
  113: 
  114: =item secondary_menu()
  115: 
  116: Same as primary_menu() but operates on @secondary_menu.
  117: 
  118: =item innerregister()
  119: 
  120: This gets called in order to register a URL in the body of the document
  121: 
  122: =item clear()
  123: 
  124: =item switch()
  125: 
  126: Switch a button or create a link
  127: Switch acts on the javascript that is executed when a button is clicked.  
  128: The javascript is usually similar to "go('/adm/roles')" or "cstrgo(..)".
  129: 
  130: =item secondlevel()
  131: 
  132: =item openmenu()
  133: 
  134: =item inlinemenu()
  135: 
  136: =item rawconfig()
  137: 
  138: =item utilityfunctions()
  139: 
  140: =item serverform()
  141: 
  142: =item constspaceform()
  143: 
  144: =item get_nav_status()
  145: 
  146: =item hidden_button_check()
  147: 
  148: =item roles_selector()
  149: 
  150: =item jump_to_role()
  151: 
  152: =back
  153: 
  154: =cut
  155: 
  156: package Apache::lonmenu;
  157: 
  158: use strict;
  159: use Apache::lonnet;
  160: use Apache::lonhtmlcommon();
  161: use Apache::loncommon();
  162: use Apache::lonenc();
  163: use Apache::lonlocal;
  164: use Apache::lonmsg();
  165: use LONCAPA qw(:DEFAULT :match);
  166: use HTML::Entities();
  167: 
  168: use vars qw(@desklines %category_names %category_members %category_positions 
  169:             $readdesk @primary_menu %primary_submenu @secondary_menu);
  170: 
  171: my @inlineremote;
  172: 
  173: sub prep_menuitem {
  174:     my ($menuitem) = @_;
  175:     return '' unless(ref($menuitem) eq 'ARRAY');
  176:     my $link;
  177:     if ($$menuitem[1]) { # graphical Link
  178:         $link = "<img class=\"LC_noBorder\""
  179:               . " src=\"" . &Apache::loncommon::lonhttpdurl($$menuitem[1]) . "\"" 
  180:               . " alt=\"" . &mt($$menuitem[2]) . "\" />";
  181:     } else {             # textual Link
  182:         $link = &mt($$menuitem[3]);
  183:     }
  184:     return '<li><a' 
  185:            # highlighting for new messages
  186:            . ( $$menuitem[4] eq 'newmsg' ? ' class="LC_new_message"' : '') 
  187:            . qq| href="$$menuitem[0]" target="_top">$link</a></li>|;
  188: }
  189: 
  190: # primary_menu() evaluates @primary_menu and returns XHTML for the menu
  191: # that contains following links:
  192: # About, Message, Personal, Roles, Help, Logout
  193: # @primary_menu is filled within the BEGIN block of this module with 
  194: # entries from mydesk.tab
  195: sub primary_menu {
  196:     my $menu;
  197:     # each element of @primary contains following array:
  198:     # (link url, icon path, alt text, link text, condition)
  199:     my $public;
  200:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
  201:         || (($env{'user.name'} eq '') && ($env{'user.domain'} eq ''))) {
  202:         $public = 1;
  203:     }
  204:     foreach my $menuitem (@primary_menu) {
  205:         # evaluate conditions 
  206:         next if    ref($menuitem)       ne 'ARRAY';    #
  207:         next if    $$menuitem[4]        eq 'nonewmsg'  # show links depending on
  208:                 && &Apache::lonmsg::mynewmail();       # whether a new msg 
  209:         next if    $$menuitem[4]        eq 'newmsg'    # arrived or not
  210:                 && !&Apache::lonmsg::mynewmail();      # 
  211:         next if    $$menuitem[4]        !~ /public/    ##we've a public user,
  212:                 && $public;                            ##who should not see all
  213:                                                        ##links
  214:         next if    $$menuitem[4]        eq 'onlypublic'# hide links which are 
  215:                 && !$public;                           # only visible to public
  216:                                                        # users
  217:         next if    $$menuitem[4]        eq 'roles'     ##show links depending on
  218:                 && &Apache::loncommon::show_course();  ##term 'Courses' or 
  219:         next if    $$menuitem[4]        eq 'courses'   ##'Roles' wanted
  220:                 && !&Apache::loncommon::show_course(); ##
  221:         
  222:         my $title = $menuitem->[3];
  223:         if (defined($primary_submenu{$title})) {
  224:             my ($link,$target,$numsub);
  225:             if ($menuitem->[0] ne '') {
  226:                 $link = $menuitem->[0];
  227:                 $target = '_top';
  228:             } else {
  229:                 $link = '#';
  230:             }
  231:             if (ref($primary_submenu{$title}) eq 'ARRAY') {
  232:                 $numsub = @{$primary_submenu{$title}};
  233:                 if ($numsub) {
  234:                     $title =
  235:                         '<span class="LC_nobreak">'.$title.
  236:                         '<span class="LC_fontsize_small">'.
  237:                         '&#9660;</span></span>';
  238:                 }
  239:             }
  240:             $menu .= '<li><a href="'.$link.'" target="'.$target.'">'.$title.'</a>';
  241:             if ($numsub) {
  242:                 $menu .= '<ul>';
  243:                 foreach my $item (@{$primary_submenu{$menuitem->[3]}}) {
  244:                     if (ref($item) eq 'ARRAY') {
  245:                         if ($item->[2] eq 'wishlist') {
  246:                             next unless ((&Apache::lonnet::allowed('bre',"/res/$env{'user.domain'}/")) ||
  247:                                          (&Apache::lonnet::allowed('bro',"/res/$env{'user.domain'}/")));
  248:                         } elsif ($item->[2] eq 'reqcrs') {
  249:                             next unless(&check_for_rcrs());
  250:                         } elsif (($item->[2] eq 'portfolio') ||
  251:                                  ($item->[2] eq 'blog')) {
  252:                             if (!&Apache::lonnet::usertools_access(
  253:                                     $env{'user.name'},
  254:                                     $env{'user.domain'},
  255:                                     $item->[2],undef,'tools')) {
  256:                                 next;
  257:                             }
  258:                         }
  259:                         $menu .= '<li style="margin:0;padding:0">'.
  260:                                  '<a href="'.$item->[0].
  261:                                  '" style="padding:0 0 0 10px">'.
  262:                                  $item->[1].'</a></li>';
  263:                     }
  264:                 }
  265:                 $menu .= '</ul>';
  266:             }
  267:             $menu .= '</li>';
  268:         } elsif ($$menuitem[3] eq 'Help') { # special treatment for helplink
  269:             if ($public) {
  270:                 my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
  271:                 my $defdom = &Apache::lonnet::default_login_domain();
  272:                 my $to = &Apache::loncommon::build_recipient_list(undef,
  273:                                                                   'helpdeskmail',
  274:                                                                   $defdom,$origmail);
  275:                 if ($to ne '') {
  276:                     $menu .= &prep_menuitem($menuitem); 
  277:                 }
  278:             } else {
  279:                 $menu .= '<li>'.&Apache::loncommon::top_nav_help('Help').'</li>';
  280:             }
  281:         } else {
  282:             $menu .= prep_menuitem($menuitem);
  283:         }
  284:     }
  285:     $menu =~ s/\[domain\]/$env{'user.domain'}/g;
  286:     $menu =~ s/\[user\]/$env{'user.name'}/g;
  287: 
  288:     return "<ol class=\"LC_primary_menu LC_right\">$menu</ol>";
  289: }
  290: 
  291: #returns hashref {user=>'',dom=>''} containing:
  292: #   own name, domain if user is au
  293: #   name, domain of parent author if user is ca or aa
  294: #empty return if user is not an author or not on homeserver
  295: #
  296: #TODO this should probably be moved somewhere more central
  297: #since it can be used by different parts of the system
  298: sub getauthor{
  299:     return unless $env{'request.role'}=~/^(ca|aa|au)/; #nothing to do if user isn't some kind of author
  300: 
  301:                         #co- or assistent author?
  302:     my ($dom, $user) = ($env{'request.role'} =~ /^(?:ca|aa)\.\/($match_domain)\/($match_username)$/)
  303:                        ? ($1, $2) #domain, username of the parent author
  304:                        : @env{ ('request.role.domain', 'user.name') }; #own domain, username
  305: 
  306:     # current server == home server?
  307:     my $home =  &Apache::lonnet::homeserver($user,$dom);
  308:     foreach (&Apache::lonnet::current_machine_ids()){
  309:         return {user => $user, dom => $dom} if $_ eq $home;
  310:     }
  311: 
  312:     # if wrong server
  313:     return;
  314: }
  315: 
  316: sub secondary_menu {
  317:     my $menu;
  318: 
  319:     my $crstype = &Apache::loncommon::course_type();
  320:     my $crs_sec = $env{'request.course.id'} . ($env{'request.course.sec'} 
  321:                                                ? "/$env{'request.course.sec'}"
  322:                                                : '');
  323:     my $canedit       = &Apache::lonnet::allowed('mdc', $env{'request.course.id'});
  324:     my $canviewgrps   = &Apache::lonnet::allowed('vcg', $crs_sec); 
  325:     my $canmodifyuser = &Apache::lonnet::allowed('cst', $crs_sec); 
  326:     my $canviewwnew   = &Apache::lonnet::allowed('whn', $crs_sec); 
  327:     my $canmodpara    = &Apache::lonnet::allowed('opa', $crs_sec);
  328:     my $canvgr        = &Apache::lonnet::allowed('vgr', $crs_sec);
  329:     my $canmgr        = &Apache::lonnet::allowed('mgr', $crs_sec); 
  330:     my $author        = &getauthor();
  331: 
  332:     my %groups = &Apache::lonnet::get_active_groups(
  333:                      $env{'user.domain'}, $env{'user.name'},
  334:                      $env{'course.' . $env{'request.course.id'} . '.domain'},
  335:                      $env{'course.' . $env{'request.course.id'} . '.num'});
  336: 
  337:     foreach my $menuitem (@secondary_menu) {
  338:         # evaluate conditions 
  339:         next if    ref($menuitem)  ne 'ARRAY';
  340:         next if    $$menuitem[4]   ne 'always'
  341:                 && $$menuitem[4]   ne 'author'
  342:                 && !$env{'request.course.id'};
  343:         next if    $$menuitem[4]   =~ /^mdc/
  344:                 && !$canedit;
  345:         next if    $$menuitem[4]  eq 'nvgr'
  346:                 && $canvgr;
  347:         next if    $$menuitem[4]  eq 'vgr'
  348:                 && !$canvgr;
  349:         next if    $$menuitem[4]   eq 'cst'
  350:                 && !$canmodifyuser;
  351:         next if    $$menuitem[4]   eq 'ncst'
  352:                 && $canmodifyuser;
  353:         next if    $$menuitem[4]   eq 'mgr'
  354:                 && !$canmgr;
  355:         next if    $$menuitem[4]   eq 'nmgr'
  356:                 && $canmgr;
  357:         next if    $$menuitem[4]   eq 'whn'
  358:                 && !$canviewwnew;
  359:         next if    $$menuitem[4]   eq 'opa'
  360:                 && !$canmodpara;
  361:         next if    $$menuitem[4]   =~ /showgroups$/
  362:                 && !$canviewgrps
  363:                 && !%groups;
  364:         next if    $$menuitem[4]    eq 'author'
  365:                 && !$author;
  366: 
  367:         if ($$menuitem[3] eq 'Roles' && $env{'request.course.id'}) {
  368:             # special treatment for role selector
  369:             my $roles_selector = &roles_selector(
  370:                         $env{'course.' . $env{'request.course.id'} . '.domain'},
  371:                         $env{'course.' . $env{'request.course.id'} . '.num'}  );
  372: 
  373:             $menu .= $roles_selector ? "<li>$roles_selector</li>"
  374:                                      : '';
  375:         } else {
  376:             $menu .= &prep_menuitem(\@$menuitem);
  377:         }
  378:     }
  379:     if ($menu =~ /\[url\].*\[symb\]/) {
  380:         my $escurl  = &escape( &Apache::lonenc::check_encrypt(
  381:                              $env{'request.noversionuri'}));
  382: 
  383:         my $escsymb = &escape( &Apache::lonenc::check_encrypt(
  384:                              $env{'request.symb'})); 
  385: 
  386:         if (    $env{'request.state'} eq 'construct'
  387:             and (   $env{'request.noversionuri'} eq '' 
  388:                  || !defined($env{'request.noversionuri'}))) 
  389:         {
  390:             my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
  391:             ($escurl = $env{'request.filename'}) =~ s{^\Q$londocroot\E}{};
  392:             $escurl  = &escape($escurl);
  393:         }    
  394:         $menu =~ s/\[url\]/$escurl/g;
  395:         $menu =~ s/\[symb\]/$escsymb/g;
  396:     }
  397:     $menu =~ s/\[uname\]/$$author{user}/g;
  398:     $menu =~ s/\[udom\]/$$author{dom}/g;
  399: 
  400:     return "<ul id=\"LC_secondary_menu\">$menu</ul>";
  401: }
  402: 
  403: sub innerregister {
  404:     my ($forcereg,$bread_crumbs) = @_;
  405:     my $const_space = ($env{'request.state'} eq 'construct');
  406:     my $is_const_dir = 0;
  407: 
  408:     if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) { return ''; }
  409: 
  410:     $env{'request.registered'} = 1;
  411: 
  412:     undef(@inlineremote);
  413: 
  414:     my $resurl; 
  415:     if ( $env{'request.symb'} && $env{'request.course.id'} ) {
  416: 
  417:         (my $mapurl, my $rid, $resurl) = &Apache::lonnet::decode_symb(&Apache::lonnet::symbread());
  418:         my $coursetitle = $env{'course.'.$env{'request.course.id'}.'.description'};
  419: 
  420:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
  421:         my $restitle = &Apache::lonnet::gettitle(&Apache::lonnet::symbread());
  422: 
  423: #SD
  424: #course_type only Course and Community?
  425: #
  426:         my @crumbs;
  427:         unless (($forcereg) && ($env{'request.noversionuri'} eq '/adm/navmaps')
  428:                 && ($mapurl eq $env{'course.'.$env{'request.course.id'}.'.url'})) {
  429:             @crumbs = ({text  => Apache::loncommon::course_type() 
  430:                                 . ' Contents', 
  431:                         href  => "Javascript:gopost('/adm/navmaps','')"});
  432:         }
  433:         if ($mapurl ne $env{'course.'.$env{'request.course.id'}.'.url'}) { 
  434:             push(@crumbs, {text  => '...',
  435:                            no_mt => 1});
  436:         }
  437: 
  438:         push @crumbs, {text => $maptitle, no_mt => 1} if ($maptitle 
  439:                                                    && $maptitle ne 'default.sequence' 
  440:                                                    && $maptitle ne $coursetitle);
  441: 
  442:         push @crumbs, {text => $restitle, no_mt => 1} if $restitle; 
  443: 
  444:         &Apache::lonhtmlcommon::clear_breadcrumbs();
  445:         &Apache::lonhtmlcommon::add_breadcrumb(@crumbs);
  446:     }elsif (! $const_space){
  447:         #a situation when we're looking at a resource outside of context of a 
  448:         #course or construction space (e.g. with cumulative rights)
  449:         &Apache::lonhtmlcommon::clear_breadcrumbs();
  450:         &Apache::lonhtmlcommon::add_breadcrumb({text => 'View Resource'});
  451:     }
  452: # =============================================================================
  453: # ============================ This is for URLs that actually can be registered
  454:     return '' unless ( ($env{'request.noversionuri'}!~m{^/(res/)*adm/}) 
  455:                        || $forcereg );
  456: 
  457: # -- This applies to homework problems for users with grading privileges
  458: 	my $crs='/'.$env{'request.course.id'};
  459: 	if ($env{'request.course.sec'}) {
  460: 	    $crs.='_'.$env{'request.course.sec'};
  461: 	}
  462: 	$crs=~s/\_/\//g;
  463: 
  464:         my $hwkadd='';
  465:         if ($env{'request.symb'} ne '' &&
  466: 	    $env{'request.filename'}=~/$LONCAPA::assess_re/) {
  467: 	    if (&Apache::lonnet::allowed('mgr',$crs)) {
  468: 		$hwkadd.=&switch('','',7,2,'pgrd.png','Content Grades','grades[_4]',
  469:                        "gocmd('/adm/grades','gradingmenu')",
  470:                        'Content Grades');
  471:             } elsif (&Apache::lonnet::allowed('vgr',$crs)) {
  472: 		$hwkadd.=&switch('','',7,2,'subm.png','Content Submissions','missions[_1]',
  473:                        "gocmd('/adm/grades','submission')",
  474: 		       'Content Submissions');
  475:             }
  476: 	}
  477: 	if ($env{'request.symb'} ne '' &&
  478: 	    &Apache::lonnet::allowed('opa',$crs)) {
  479: 	    $hwkadd.=&switch('','',7,3,'pparm.png','Content Settings','parms[_2]',
  480: 			     "gocmd('/adm/parmset','set')",
  481: 			     'Content Settings');
  482: 	}
  483:         if ($env{'request.symb'}=~/^uploaded/ &&
  484:             &Apache::lonnet::allowed('mdc',$crs)) {
  485:             $hwkadd.=&switch('','',7,4,'docs.png','Folder/Page Content','parms[_2]',
  486:                              "gocmd('/adm/coursedocs','direct')",
  487:                              'Folder/Page Content');
  488:         }
  489: # -- End Homework
  490:         ###
  491:         ### Determine whether or not to display the 'cstr' button for this
  492:         ### resource
  493:         ###
  494:         my $editbutton = '';
  495:         my $noeditbutton = 1;
  496:         my ($cnum,$cdom);
  497:         if ($env{'request.course.id'}) {
  498:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  499:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  500:         }
  501:         if ($env{'user.author'}) {
  502:             if ($env{'request.role'}=~/^(aa|ca|au)/) {
  503: #
  504: # We have the role of an author
  505: #
  506:                 # Set defaults for authors
  507:                 my ($top,$bottom) = ('con-','struct');
  508:                 my $action = "go('/priv/".$env{'user.domain'}.'/'.$env{'user.name'}."');";
  509:                 my $cadom  = $env{'request.role.domain'};
  510:                 my $caname = $env{'user.name'};
  511:                 my $desc = "Enter my construction space";
  512:                 # Set defaults for co-authors
  513:                 if ($env{'request.role'} =~ /^ca/) { 
  514:                     ($cadom,$caname)=($env{'request.role'}=~/($match_domain)\/($match_username)$/);
  515:                     ($top,$bottom) = ('co con-','struct');
  516:                     $action = "go('/priv/".$cadom.'/'.$caname."');";
  517:                     $desc = "Enter construction space as co-author";
  518:                 } elsif ($env{'request.role'} =~ /^aa/) {
  519:                     ($cadom,$caname)=($env{'request.role'}=~/($match_domain)\/($match_username)$/);
  520:                     ($top,$bottom) = ('co con-','struct');
  521:                     $action = "go('/priv/".$cadom.'/'.$caname."');";
  522:                     $desc = "Enter construction space as assistant co-author";
  523:                 }
  524:                 # Check that we are on the correct machine
  525:                 my $home = &Apache::lonnet::homeserver($caname,$cadom);
  526: 		my $allowed=0;
  527: 		my @ids=&Apache::lonnet::current_machine_ids();
  528: 		foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
  529: 		if (!$allowed) {
  530: 		    $editbutton=&switch('','',6,1,$top,,$bottom,$action,$desc);
  531:                     $noeditbutton = 0;
  532:                 }
  533:             }
  534: #
  535: # We are an author for some stuff, but currently do not have the role of author.
  536: # Figure out if we have authoring privileges for the resource we are looking at.
  537: # This should maybe become a privilege check in lonnet
  538: #
  539:             ##
  540:             ## Determine if user can edit url.
  541:             ##
  542:             my $cfile='';
  543:             my $cfuname='';
  544:             my $cfudom='';
  545:             my $uploaded;
  546:             my $switchserver='';
  547:             my $home;
  548:             if ($env{'request.filename'}) {
  549:                 my $file=&Apache::lonnet::declutter($env{'request.filename'});
  550:                 if (defined($cnum) && defined($cdom)) {
  551:                     $uploaded = &is_course_upload($file,$cnum,$cdom);
  552:                 }
  553:                 if (!$uploaded) {
  554: 
  555:                     $file=~s{^(priv/$match_domain/$match_username)}{/$1};
  556:                     $file=~s{^($match_domain/$match_username)}{/priv/$1};
  557: 
  558:                     # Check that the user has permission to edit this resource
  559:                     my $setpriv = 1;
  560:                     ($cfuname,$cfudom)=&Apache::loncacc::constructaccess($file,$setpriv);
  561:                     if (defined($cfudom)) {
  562: 		        $home=&Apache::lonnet::homeserver($cfuname,$cfudom);
  563: 		        my $allowed=0;
  564: 		        my @ids=&Apache::lonnet::current_machine_ids();
  565: 		        foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
  566: 		        if ($allowed) {
  567:                             $cfile=$file;
  568:                         } else {
  569:                             $switchserver=$file;
  570:                         }
  571:                     }
  572:                 }
  573:             }
  574:             # Finally, turn the button on or off
  575:             if (($cfile || $switchserver) && !$const_space) {
  576:                 my $nocrsedit;
  577:                 # Suppress display where CC has switched to student role.
  578:                 if ($env{'request.course.id'}) {
  579:                     unless(&Apache::lonnet::allowed('mdc',
  580:                                                     $env{'request.course.id'})) {
  581:                         $nocrsedit = 1;
  582:                     }
  583:                 }
  584:                 if ($nocrsedit) {
  585:                     $editbutton=&clear(6,1);
  586:                 } else {
  587:                     my $bot = "go('$cfile')";
  588:                     if ($switchserver) {
  589:                         if ( $env{'request.symb'} && $env{'request.course.id'} ) {
  590:                             $cfile = '/adm/switchserver?otherserver='.$home.'&amp;role='.
  591:                                      &HTML::Entities::encode($env{'request.role'},'"<>&').'&amp;symb='.
  592:                                      &HTML::Entities::encode($env{'request.symb'},'"<>&');
  593:                             $bot = "need_switchserver('$cfile');";
  594:                         }
  595:                     }
  596:                     $editbutton=&switch
  597:                        ('','',6,1,'pcstr.png','Edit','resource[_2]',
  598:                         $bot,"Edit this resource");
  599:                     $noeditbutton = 0;
  600:                 }
  601:             } elsif ($editbutton eq '') {
  602:                 $editbutton=&clear(6,1);
  603:             }
  604:         }
  605:         if (($noeditbutton) && ($env{'request.filename'})) { 
  606:             if (&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
  607:                 my $file=&Apache::lonnet::declutter($env{'request.filename'});
  608:                 if (defined($cnum) && defined($cdom)) {
  609:                     if (&is_course_upload($file,$cnum,$cdom)) {
  610:                         my $cfile = &edit_course_upload($file,$cnum,$cdom);
  611:                         if ($cfile) {
  612:                             $editbutton=&switch
  613:                                         ('','',6,1,'pcstr.png','Edit',
  614:                                          'resource[_2]',"go('".$cfile."');",
  615:                                          'Edit this resource');
  616:                         }
  617:                     }
  618:                 }
  619:             }
  620:         }
  621:         if ($env{'request.course.id'}) {
  622:             if ($resurl eq "public/$cdom/$cnum/syllabus") {
  623:                 if ($env{'course.'.$env{'request.course.id'}.'.externalsyllabus'} =~ /\w/) {
  624:                     if (&Apache::lonnet::allowed('mdc',$env{'request.course.id'})) {
  625:                         $editbutton=&switch('','',6,1,'pcstr.png','Edit',
  626:                                             'resource[_2]',
  627:                                             "go('/adm/courseprefs?phase=display&actions=courseinfo')",
  628:                                             'Edit this resource');
  629:                     }
  630:                 }
  631:             }
  632:         }
  633:         ###
  634:         ###
  635: # Prepare the rest of the buttons
  636:         my $menuitems;
  637:         if ($const_space) {
  638: #
  639: # We are in construction space
  640: #
  641: 
  642:             my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
  643: 	    my ($udom,$uname,$thisdisfn) =
  644: 		($env{'request.filename'}=~m{^\Q$londocroot/priv/\E([^/]+)/([^/]+)/(.*)$});
  645:             my $currdir = '/priv/'.$udom.'/'.$uname.'/'.$thisdisfn;
  646:             if ($currdir =~ m-/$-) {
  647:                 $is_const_dir = 1;
  648:             } else {
  649:                 $currdir =~ s|[^/]+$||;
  650: 		my $cleandisfn = &Apache::loncommon::escape_single($thisdisfn);
  651: 		my $esc_currdir = &Apache::loncommon::escape_single($currdir);
  652: #
  653: # Probably should be in mydesk.tab
  654: #
  655:                 $menuitems=(<<ENDMENUITEMS);
  656: s&6&1&list.png&Directory&dir[_1]&golist('$esc_currdir')&List current directory
  657: s&6&2&rtrv.png&Retrieve&version[_1]&gocstr('/adm/retrieve','/priv/$udom/$uname/$cleandisfn')&Retrieve old version
  658: s&6&3&pub.png&Publish&resource[_3]&gocstr('/adm/publish','/priv/$udom/$uname/$cleandisfn')&Publish this resource
  659: s&7&1&del.png&Delete&resource[_2]&gocstr('/adm/cfile?action=delete','/priv/$udom/$uname/$cleandisfn')&Delete this resource
  660: s&7&2&prt.png&Print&printout[_1]&gocstr('/adm/printout','/priv/$udom/$uname/$cleandisfn')&Prepare a printable document
  661: ENDMENUITEMS
  662:             }
  663:                 if (ref($bread_crumbs) eq 'ARRAY') {
  664:                     &Apache::lonhtmlcommon::clear_breadcrumbs();
  665:                     foreach my $crumb (@{$bread_crumbs}){
  666:                         &Apache::lonhtmlcommon::add_breadcrumb($crumb);
  667:                     }
  668:                 }
  669:         } elsif ( defined($env{'request.course.id'}) && 
  670: 		 $env{'request.symb'} ne '' ) {
  671: #
  672: # We are in a course and looking at a registred URL
  673: # Should probably be in mydesk.tab
  674: #
  675: 	    $menuitems=(<<ENDMENUITEMS);
  676: c&3&1
  677: s&2&1&back.png&&&gopost('/adm/flip','back:'+currentURL)&Previous content resource&&1
  678: s&2&3&forw.png&&&gopost('/adm/flip','forward:'+currentURL)&Next content resource&&3
  679: c&6&3
  680: c&8&1
  681: c&8&2
  682: s&8&3&prt.png&Print&printout[_1]&gopost('/adm/printout',currentURL)&Prepare a printable document
  683: s&9&1&sbkm.png&Bookmark&set[_1]bookmark[_2]&set_bookmark()&Set a bookmark for this resource&&1
  684: 
  685: ENDMENUITEMS
  686: 
  687: my $currentURL = &Apache::loncommon::get_symb();
  688: my ($symb_old,$symb_old_enc) = &Apache::loncommon::clean_symb($currentURL);
  689: my $annotation = &Apache::loncommon::get_annotation($symb_old,$symb_old_enc);
  690: $menuitems.="s&9&3&";
  691: if(length($annotation) > 0){
  692: 	$menuitems.="anot2.png";
  693: }else{
  694: 	$menuitems.="anot.png";
  695: }
  696: $menuitems.="&Notes&&annotate()&";
  697: $menuitems.="Make notes and annotations about this resource&&1\n";
  698: 
  699:             unless ($env{'request.noversionuri'}=~/\/(bulletinboard|smppg|navmaps|syllabus|aboutme|viewclasslist|portfolio)(\?|$)/) {
  700: 		if ((!$env{'request.enc'}) && ($env{'request.noversionuri'} !~ m{^/adm/wrapper/ext/})) {
  701: 		    $menuitems.=(<<ENDREALRES);
  702: s&6&3&catalog.png&Info&info[_1]&catalog_info()&Show Metadata
  703: ENDREALRES
  704:                 }
  705: 	        $menuitems.=(<<ENDREALRES);
  706: s&8&1&eval.png&Evaluate&this[_1]&gopost('/adm/evaluate',currentURL,1)&Provide my evaluation of this resource
  707: s&8&2&fdbk.png&Communicate&discuss[_1]&gopost('/adm/feedback',currentURL,1)&Provide feedback messages or contribute to the course discussion about this resource
  708: ENDREALRES
  709: 	    }
  710:         }
  711: 	if ($env{'request.uri'} =~ /^\/res/) {
  712: 	    $menuitems .= (<<ENDMENUITEMS);
  713: s&8&3&prt.png&Print&printout[_1]&gopost('/adm/printout',currentURL)&Prepare a printable document
  714: ENDMENUITEMS
  715: 	}
  716:         my $buttons='';
  717:         foreach (split(/\n/,$menuitems)) {
  718: 	    my ($command,@rest)=split(/\&/,$_);
  719:             my $idx=10*$rest[0]+$rest[1];
  720:             if (&hidden_button_check() eq 'yes') {
  721:                 if ($idx == 21 ||$idx == 23) {
  722:                     $buttons.=&switch('','',@rest);
  723:                 } else {
  724:                     $buttons.=&clear(@rest);
  725:                 }
  726:             } else {  
  727:                 if ($command eq 's') {
  728: 	            $buttons.=&switch('','',@rest);
  729:                 } else {
  730:                     $buttons.=&clear(@rest);
  731:                 }
  732:             }
  733:         }
  734: 
  735: 	    my $addremote=0;
  736: 	    foreach (@inlineremote) { if ($_ ne '') { $addremote=1; last;} }
  737:     if ($addremote) {
  738: 
  739:         &Apache::lonhtmlcommon::clear_breadcrumb_tools();
  740: 
  741:             &Apache::lonhtmlcommon::add_breadcrumb_tool(
  742:                 'navigation', @inlineremote[21,23]);
  743: 
  744:         if(hidden_button_check() ne 'yes') {
  745:             &Apache::lonhtmlcommon::add_breadcrumb_tool(
  746:                 'tools', @inlineremote[93,91,81,82,83]);
  747: 
  748:             #publish button in construction space
  749:             if ($env{'request.state'} eq 'construct'){
  750:                 &Apache::lonhtmlcommon::add_breadcrumb_tool(
  751:                      'advtools', $inlineremote[63]);
  752:             } else {
  753:                 &Apache::lonhtmlcommon::add_breadcrumb_tool(
  754:                      'tools', $inlineremote[63]);
  755:             }
  756:             
  757:             unless ($env{'request.noversionuri'}=~ m{^/adm/(navmaps|viewclasslist)(\?|$)}) {
  758:                 &Apache::lonhtmlcommon::add_breadcrumb_tool(
  759:                     'advtools', @inlineremote[61,71,72,73,74,92]);
  760:             }
  761:         }
  762:     }
  763: 
  764:     return   &Apache::lonhtmlcommon::scripttag('', 'start')
  765:            . &Apache::lonhtmlcommon::breadcrumbs(undef,undef,0)
  766:            . &Apache::lonhtmlcommon::scripttag('', 'end');
  767: }
  768: 
  769: sub is_course_upload {
  770:     my ($file,$cnum,$cdom) = @_;
  771:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
  772:     $uploadpath =~ s{^\/}{};
  773:     if (($file =~ m{^\Q$uploadpath\E/userfiles/docs/}) ||
  774:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/docs/})) {
  775:         return 1;
  776:     }
  777:     return;
  778: }
  779: 
  780: sub edit_course_upload {
  781:     my ($file,$cnum,$cdom) = @_;
  782:     my $cfile;
  783:     if ($file =~/\.(htm|html|css|js|txt)$/) {
  784:         my $ext = $1;
  785:         my $url = &Apache::lonnet::hreflocation('',$file);
  786:         my $home = &Apache::lonnet::homeserver($cnum,$cdom);
  787:         my @ids=&Apache::lonnet::current_machine_ids();
  788:         my $dest;
  789:         if ($home && grep(/^\Q$home\E$/,@ids)) {
  790:             $dest = $url.'?forceedit=1';
  791:         } else {
  792:             unless (&Apache::lonnet::get_locks()) {
  793:                 $dest = '/adm/switchserver?otherserver='.
  794:                         $home.'&role='.$env{'request.role'}.
  795:                         '&url='.$url.'&forceedit=1';
  796:             }
  797:         }
  798:         if ($dest) {
  799:             $cfile = &HTML::Entities::encode($dest,'"<>&');
  800:         }
  801:     }
  802:     return $cfile;
  803: }
  804: 
  805: sub startupremote {
  806:     my ($lowerurl)=@_;
  807:     if ($env{'environment.remote'} eq 'off') {
  808:      return ('<meta HTTP-EQUIV="Refresh" CONTENT="0.5; url='.$lowerurl.'" />');
  809:     }
  810: #
  811: # The Remote actually gets launched!
  812: #
  813:     my $configmenu=&rawconfig();
  814:     my $esclowerurl=&escape($lowerurl);
  815:     my $message=&mt('"Waiting for Remote Control window to load: "+[_1]','waited');
  816:     return(<<ENDREMOTESTARTUP);
  817: <script type="text/javascript">
  818: // <![CDATA[
  819: var timestart;
  820: function wheelswitch() {
  821:     if (typeof(document.wheel) != 'undefined') {
  822:         if (typeof(document.wheel.spin) != 'undefined') {
  823:             var date=new Date();
  824:             var waited=Math.round(30-((date.getTime()-timestart)/1000));
  825:             document.wheel.spin.value=$message;
  826:         }
  827:     }
  828:    if (window.status=='|') {
  829:       window.status='/';
  830:    } else {
  831:       if (window.status=='/') {
  832:          window.status='-';
  833:       } else {
  834:          if (window.status=='-') {
  835:             window.status='\\\\';
  836:          } else {
  837:             if (window.status=='\\\\') { window.status='|'; }
  838:          }
  839:       }
  840:    }
  841: }
  842: 
  843: // ---------------------------------------------------------- The wait function
  844: var canceltim;
  845: function wait() {
  846:    if ((menuloaded==1) || (tim==1)) {
  847:       window.status='Done.';
  848:       if (tim==0) {
  849:          clearTimeout(canceltim);
  850:          $configmenu
  851:          window.location='$lowerurl';
  852:       } else {
  853:           window.location='/adm/remote?action=collapse&url=$esclowerurl';
  854:       }
  855:    } else {
  856:       wheelswitch();
  857:       setTimeout('wait();',200);
  858:    }
  859: }
  860: 
  861: function main() {
  862:    canceltim=setTimeout('tim=1;',30000);
  863:    window.status='-';
  864:    var date=new Date();
  865:    timestart=date.getTime();
  866:    wait();
  867: }
  868: 
  869: // ]]>
  870: </script>
  871: ENDREMOTESTARTUP
  872: }
  873: 
  874: sub setflags() {
  875:     return(<<ENDSETFLAGS);
  876: <script type="text/javascript">
  877: // <![CDATA[
  878:     menuloaded=0;
  879:     tim=0;
  880: // ]]>
  881: </script>
  882: ENDSETFLAGS
  883: }
  884: 
  885: sub maincall() {
  886:     if ($env{'environment.remote'} eq 'off') { return ''; }
  887:     return(<<ENDMAINCALL);
  888: <script type="text/javascript">
  889: // <![CDATA[
  890:     main();
  891: // ]]>
  892: </script>
  893: ENDMAINCALL
  894: }
  895: 
  896: sub load_remote_msg {
  897:     my ($lowerurl)=@_;
  898: 
  899:     if ($env{'environment.remote'} eq 'off') { return ''; }
  900: 
  901:     my $esclowerurl=&escape($lowerurl);
  902:     my $link=&mt('[_1]Continue[_2] on in Inline Menu mode'
  903:                 ,'<a href="/adm/remote?action=collapse&amp;url='.$esclowerurl.'">'
  904:                 ,'</a>');
  905:     return(<<ENDREMOTEFORM);
  906: <p>
  907: <form name="wheel">
  908: <input name="spin" type="text" size="60" />
  909: </form>
  910: </p>
  911: <p>$link</p>
  912: ENDREMOTEFORM
  913: }
  914: 
  915: sub get_menu_name {
  916:     my $hostid = $Apache::lonnet::perlvar{'lonHostID'};
  917:     $hostid =~ s/\W//g;
  918:     return 'LCmenu'.$hostid;
  919: }
  920: 
  921: 
  922: sub reopenmenu {
  923:    if ($env{'environment.remote'} eq 'off') { return ''; }
  924:    my $menuname = &get_menu_name();
  925:    my $nothing = &Apache::lonhtmlcommon::javascript_nothing();
  926:    return('window.open('.$nothing.',"'.$menuname.'","",false);');
  927: }
  928: 
  929: 
  930: sub open {
  931:     my $returnval='';
  932:     if ($env{'environment.remote'} eq 'off') {
  933:         return
  934:         '<script type="text/javascript">'."\n"
  935:        .'// <![CDATA['."\n"
  936:        .'self.name="loncapaclient";'."\n"
  937:        .'// ]]>'."\n"
  938:        .'</script>';
  939:     }
  940:     my $menuname = &get_menu_name();
  941: 
  942: #    unless (shift eq 'unix') {
  943: # resizing does not work on linux because of virtual desktop sizes
  944: #       $returnval.=(<<ENDRESIZE);
  945: #if (window.screen) {
  946: #    self.resizeTo(screen.availWidth-215,screen.availHeight-55);
  947: #    self.moveTo(190,15);
  948: #}
  949: #ENDRESIZE
  950: #    }
  951:     $returnval=(<<ENDOPEN);
  952: // <![CDATA[
  953: window.status='Opening LON-CAPA Remote Control';
  954: var menu=window.open("/res/adm/pages/menu.html?inhibitmenu=yes","$menuname",
  955: "height=375,width=150,scrollbars=no,menubar=no,top=5,left=5,screenX=5,screenY=5");
  956: self.name='loncapaclient';
  957: // ]]>
  958: ENDOPEN
  959:     return '<script type="text/javascript">'.$returnval.'</script>';
  960: }
  961: 
  962: 
  963: # ================================================================== Raw Config
  964: 
  965: sub clear {
  966:     my ($row,$col)=@_;
  967:     $inlineremote[10*$row+$col]='';
  968:     return ''; 
  969: }
  970: 
  971: # ============================================ Switch a button or create a link
  972: # Switch acts on the javascript that is executed when a button is clicked.  
  973: # The javascript is usually similar to "go('/adm/roles')" or "cstrgo(..)".
  974: 
  975: sub switch {
  976:     my ($uname,$udom,$row,$col,$img,$top,$bot,$act,$desc,$cat,$nobreak)=@_;
  977:     $act=~s/\$uname/$uname/g;
  978:     $act=~s/\$udom/$udom/g;
  979:     $top=&mt($top);
  980:     $bot=&mt($bot);
  981:     $desc=&mt($desc);
  982:     my $idx=10*$row+$col;
  983:     $category_members{$cat}.=':'.$idx;
  984: 
  985: # Inline Menu
  986:     if ($nobreak==2) { return ''; }
  987:     my $text=$top.' '.$bot;
  988:     $text=~s/\s*\-\s*//gs;
  989: 
  990:     my $pic=
  991: 	   '<img alt="'.$text.'" src="'.
  992: 	   &Apache::loncommon::lonhttpdurl('/res/adm/pages/'.$img).
  993: 	   '" align="'.($nobreak==3?'right':'left').'" class="LC_icon" />';
  994:     if ($env{'browser.interface'} eq 'faketextual') {
  995: # Main Menu
  996: 	   if ($nobreak==3) {
  997: 	       $inlineremote[$idx]="\n".
  998: 		   '<td class="LC_menubuttons_text" align="right">'.$text.
  999: 		   '</td><td align="left">'.
 1000: 		   '<a href="javascript:'.$act.';">'.$pic.'</a></td></tr>';
 1001: 	   } elsif ($nobreak) {
 1002: 	       $inlineremote[$idx]="\n<tr>".
 1003: 		   '<td align="left">'.
 1004: 		   '<a href="javascript:'.$act.';">'.$pic.'</a></td>
 1005:                     <td class="LC_menubuttons_text" align="left"><a class="LC_menubuttons_link" href="javascript:'.$act.';"><span class="LC_menubuttons_inline_text">'.$text.'</span></a></td>';
 1006: 	   } else {
 1007: 	       $inlineremote[$idx]="\n<tr>".
 1008: 		   '<td align="left">'.
 1009: 		   '<a href="javascript:'.$act.';">'.$pic.
 1010: 		   '</a></td><td class="LC_menubuttons_text" colspan="3">'.
 1011: 		   '<a class="LC_menubuttons_link" href="javascript:'.$act.';"><span class="LC_menubuttons_inline_text">'.$desc.'</span></a></td></tr>';
 1012: 	   }
 1013:     } else {
 1014: # Inline Menu
 1015:       $inlineremote[$idx]=
 1016:        '<a title="'.$desc.'" class="LC_menubuttons_link" href="javascript:'.$act.';">'.$pic.
 1017:        '<span class="LC_menubuttons_inline_text">'.$top.'&nbsp;</span></a>';
 1018:     }
 1019:     return '';
 1020: }
 1021: 
 1022: sub secondlevel {
 1023:     my $output='';
 1024:     my 
 1025:     ($uname,$udom,$rol,$crs,$pub,$con,$row,$col,$prt,$img,$top,$bot,$act,$desc,$cat)=@_;
 1026:     if ($prt eq 'any') {
 1027: 	   $output.=&switch($uname,$udom,$row,$col,$img,$top,$bot,$act,$desc,$cat);
 1028:     } elsif ($prt=~/^r(\w+)/) {
 1029:         if ($rol eq $1) {
 1030:            $output.=&switch($uname,$udom,$row,$col,$img,$top,$bot,$act,$desc,$cat);
 1031:         }
 1032:     }
 1033:     return $output;
 1034: }
 1035: 
 1036: sub inlinemenu {
 1037:     undef(@inlineremote);
 1038:     undef(%category_members);
 1039: # calling rawconfig with "1" will evaluate mydesk.tab, even if there is no active remote control
 1040:     &rawconfig(1);
 1041:     my $output='<table><tr>';
 1042:     for (my $col=1; $col<=2; $col++) {
 1043:         $output.='<td class="LC_mainmenu_col_fieldset">';
 1044:         for (my $row=1; $row<=8; $row++) {
 1045:             foreach my $cat (keys(%category_members)) {
 1046:                if ($category_positions{$cat} ne "$col,$row") { next; }
 1047:                #$output.='<table><tr><td colspan="4" class="LC_menubuttons_category">'.&mt($category_names{$cat}).'</td></tr>';
 1048:                $output.='<div class="LC_Box LC_400Box">';
 1049: 	       $output.='<h3 class="LC_hcell">'.&mt($category_names{$cat}).'</h3>';
 1050:                $output.='<table>';
 1051:                my %active=();
 1052:                foreach my $menu_item (split(/\:/,$category_members{$cat})) {
 1053:                   if ($inlineremote[$menu_item]) {
 1054:                      $active{$menu_item}=1;
 1055:                   }
 1056:                }  
 1057:                foreach my $item (sort(keys(%active))) {
 1058:                   $output.=$inlineremote[$item];
 1059:                }
 1060:                $output.='</table>';
 1061:                $output.='</div>';
 1062:             }
 1063:          }
 1064:          $output.="</td>";
 1065:     }
 1066:     $output.="</tr></table>";
 1067:     return $output;
 1068: }
 1069: 
 1070: sub rawconfig {
 1071: #
 1072: # This evaluates mydesk.tab
 1073: # Need to add more positions and more privileges to deal with all
 1074: # menu items.
 1075: #
 1076:     my $textualoverride=shift;
 1077:     my $output='';
 1078:     return '' unless $textualoverride;
 1079:     my $uname=$env{'user.name'};
 1080:     my $udom=$env{'user.domain'};
 1081:     my $adv=$env{'user.adv'};
 1082:     my $show_course=&Apache::loncommon::show_course();
 1083:     my $author=$env{'user.author'};
 1084:     my $crs='';
 1085:     my $crstype='';
 1086:     if ($env{'request.course.id'}) {
 1087:        $crs='/'.$env{'request.course.id'};
 1088:        if ($env{'request.course.sec'}) {
 1089: 	   $crs.='_'.$env{'request.course.sec'};
 1090:        }
 1091:        $crs=~s/\_/\//g;
 1092:        $crstype = &Apache::loncommon::course_type();
 1093:     }
 1094:     my $pub=($env{'request.state'} eq 'published');
 1095:     my $con=($env{'request.state'} eq 'construct');
 1096:     my $rol=$env{'request.role'};
 1097:     my $requested_domain = $env{'request.role.domain'};
 1098:     foreach my $line (@desklines) {
 1099:         my ($row,$col,$pro,$prt,$img,$top,$bot,$act,$desc,$cat)=split(/\:/,$line);
 1100:         $prt=~s/\$uname/$uname/g;
 1101:         $prt=~s/\$udom/$udom/g;
 1102:         if ($prt =~ /\$crs/) {
 1103:             next unless ($env{'request.course.id'});
 1104:             next if ($crstype eq 'Community');
 1105:             $prt=~s/\$crs/$crs/g;
 1106:         } elsif ($prt =~ /\$cmty/) {
 1107:             next unless ($env{'request.course.id'});
 1108:             next if ($crstype ne 'Community');
 1109:             $prt=~s/\$cmty/$crs/g;
 1110:         }
 1111:         $prt=~s/\$requested_domain/$requested_domain/g;
 1112:         if ($category_names{$cat}!~/\w/) { $cat='oth'; }
 1113:         if ($pro eq 'clear') {
 1114: 	    $output.=&clear($row,$col);
 1115:         } elsif ($pro eq 'any') {
 1116:                $output.=&secondlevel(
 1117: 	  $uname,$udom,$rol,$crs,$pub,$con,$row,$col,$prt,$img,$top,$bot,$act,$desc,$cat);
 1118: 	} elsif ($pro eq 'smp') {
 1119:             unless ($adv) {
 1120:                $output.=&secondlevel(
 1121:           $uname,$udom,$rol,$crs,$pub,$con,$row,$col,$prt,$img,$top,$bot,$act,$desc,$cat);
 1122:             }
 1123:         } elsif ($pro eq 'adv') {
 1124:             if ($adv) {
 1125:                $output.=&secondlevel(
 1126: 	  $uname,$udom,$rol,$crs,$pub,$con,$row,$col,$prt,$img,$top,$bot,$act,$desc,$cat);
 1127:             }
 1128: 	} elsif ($pro eq 'shc') {
 1129:             if ($show_course) {
 1130:                $output.=&secondlevel(
 1131:           $uname,$udom,$rol,$crs,$pub,$con,$row,$col,$prt,$img,$top,$bot,$act,$desc,$cat);
 1132:             }
 1133:         } elsif ($pro eq 'nsc') {
 1134:             if (!$show_course) {
 1135:                $output.=&secondlevel(
 1136: 	  $uname,$udom,$rol,$crs,$pub,$con,$row,$col,$prt,$img,$top,$bot,$act,$desc,$cat);
 1137:             }
 1138:         } elsif (($pro=~/^p(\w+)/) && ($prt)) {
 1139:             my $priv = $1;
 1140:             if ($priv =~ /^mdc(Course|Community)/) {
 1141:                 if ($crstype eq $1) {
 1142:                     $priv = 'mdc';
 1143:                 } else {
 1144:                     next;
 1145:                 }
 1146:             }
 1147: 	    if (&Apache::lonnet::allowed($priv,$prt)) {
 1148:                $output.=&switch($uname,$udom,$row,$col,$img,$top,$bot,$act,$desc,$cat);
 1149:             }
 1150:         } elsif ($pro eq 'course')  {
 1151:             if (($env{'request.course.fn'}) && ($crstype ne 'Community')) {
 1152:                $output.=&switch($uname,$udom,$row,$col,$img,$top,$bot,$act,$desc,$cat);
 1153: 	    }
 1154:         } elsif ($pro eq 'community')  {
 1155:             if (($env{'request.course.fn'}) && ($crstype eq 'Community')) {
 1156:                $output.=&switch($uname,$udom,$row,$col,$img,$top,$bot,$act,$desc,$cat);
 1157:             }
 1158:         } elsif ($pro =~ /^courseenv_(.*)$/) {
 1159:             my $key = $1;
 1160:             if ($crstype ne 'Community') {
 1161:                 my $coursepref = $env{'course.'.$env{'request.course.id'}.'.'.$key};
 1162:                 if ($key eq 'canuse_pdfforms') {
 1163:                     if ($env{'request.course.id'} && $coursepref eq '') {
 1164:                         my %domdefs = &Apache::lonnet::get_domain_defaults($env{'course.'.$env{'request.course.id'}.'.domain'});
 1165:                         $coursepref = $domdefs{'canuse_pdfforms'};
 1166:                     }
 1167:                 }
 1168:                 if ($coursepref) { 
 1169:                     $output.=&switch($uname,$udom,$row,$col,$img,$top,$bot,$act,$desc,$cat);
 1170:                 }
 1171:             }
 1172:         } elsif ($pro =~ /^communityenv_(.*)$/) {
 1173:             my $key = $1;
 1174:             if ($crstype eq 'Community') {
 1175:                 my $coursepref = $env{'course.'.$env{'request.course.id'}.'.'.$key};
 1176:                 if ($key eq 'canuse_pdfforms') {
 1177:                     if ($env{'request.course.id'} && $coursepref eq '') {
 1178:                         my %domdefs = &Apache::lonnet::get_domain_defaults($env{'course.'.$env{'request.course.id'}.'.domain'});
 1179:                         $coursepref = $domdefs{'canuse_pdfforms'};
 1180:                     }
 1181:                 }
 1182:                 if ($coursepref) { 
 1183:                     $output.=&switch($uname,$udom,$row,$col,$img,$top,$bot,$act,$desc,$cat);
 1184:                 }
 1185:             }
 1186:         } elsif ($pro =~ /^course_(.*)$/) {
 1187:             # Check for permissions inside of a course
 1188:             if (($env{'request.course.id'}) && ($crstype ne 'Community') && 
 1189:                 (&Apache::lonnet::allowed($1,$env{'request.course.id'}.
 1190:             ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))
 1191:                  )) {
 1192:                 $output.=&switch($uname,$udom,$row,$col,$img,$top,$bot,$act,$desc,$cat);
 1193: 	    }
 1194:         } elsif ($pro =~ /^community_(.*)$/) {
 1195:             # Check for permissions inside of a community
 1196:             if (($env{'request.course.id'}) && ($crstype eq 'Community') &&   
 1197:                 (&Apache::lonnet::allowed($1,$env{'request.course.id'}.
 1198:             ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))
 1199:                  )) {
 1200:                 $output.=&switch($uname,$udom,$row,$col,$img,$top,$bot,$act,$desc,$cat);
 1201:             }
 1202:         } elsif ($pro eq 'author') {
 1203:             if ($author) {
 1204:                 if ((($prt eq 'rca') && ($env{'request.role'}=~/^ca/)) ||
 1205:                     (($prt eq 'raa') && ($env{'request.role'}=~/^aa/)) || 
 1206:                     (($prt eq 'rau') && ($env{'request.role'}=~/^au/))) {
 1207:                     # Check that we are on the correct machine
 1208:                     my $cadom=$requested_domain;
 1209:                     my $caname=$env{'user.name'};
 1210:                     if (($prt eq 'rca') || ($prt eq 'raa')) {
 1211: 		       ($cadom,$caname)=
 1212:                                ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 1213:                     }                       
 1214:                     $act =~ s/\$caname/$caname/g;
 1215:                     $act =~ s/\$cadom/$cadom/g;
 1216:                     my $home = &Apache::lonnet::homeserver($caname,$cadom);
 1217: 		    my $allowed=0;
 1218: 		    my @ids=&Apache::lonnet::current_machine_ids();
 1219: 		    foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
 1220: 		    if ($allowed) {
 1221:                         $output.=&switch($caname,$cadom,
 1222:                                         $row,$col,$img,$top,$bot,$act,$desc,$cat);
 1223:                     }
 1224:                 }
 1225:             }
 1226:         } elsif ($pro eq 'tools') {
 1227:             my @tools = ('aboutme','blog','portfolio');
 1228:             if (grep(/^\Q$prt\E$/,@tools)) {
 1229:                 if (!&Apache::lonnet::usertools_access($env{'user.name'},
 1230:                                                        $env{'user.domain'},
 1231:                                                        $prt,undef,'tools')) {
 1232:                     $output.=&clear($row,$col);
 1233:                     next;
 1234:                 }
 1235:             } elsif (($prt eq 'reqcrsnsc') || ($prt eq 'reqcrsshc')) {
 1236:                 if (($prt eq 'reqcrsnsc') && ($show_course))   {
 1237:                     next;
 1238:                 }
 1239:                 if (($prt eq 'reqcrsshc') && (!$show_course)) {
 1240:                     next;
 1241:                 }
 1242:                 my $showreqcrs = &check_for_rcrs();
 1243:                 if (!$showreqcrs) {
 1244:                     $output.=&clear($row,$col);
 1245:                     next;
 1246:                 }
 1247:             }
 1248:             $prt='any';
 1249:             $output.=&secondlevel(
 1250:           $uname,$udom,$rol,$crs,$pub,$con,$row,$col,$prt,$img,$top,$bot,$act,$desc,$cat);
 1251:         }
 1252:     }
 1253:     return $output;
 1254: }
 1255: 
 1256: sub check_for_rcrs {
 1257:     my $showreqcrs = 0;
 1258:     my @reqtypes = ('official','unofficial','community');
 1259:     foreach my $type (@reqtypes) {
 1260:         if (&Apache::lonnet::usertools_access($env{'user.name'},
 1261:                                               $env{'user.domain'},
 1262:                                               $type,undef,'requestcourses')) {
 1263:             $showreqcrs = 1;
 1264:             last;
 1265:         }
 1266:     }
 1267:     if (!$showreqcrs) {
 1268:         foreach my $type (@reqtypes) {
 1269:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 1270:                 $showreqcrs = 1;
 1271:                 last;
 1272:             }
 1273:         }
 1274:     }
 1275:     return $showreqcrs;
 1276: }
 1277: 
 1278: # ======================================================================= Close
 1279: 
 1280: sub close {
 1281:     if ($env{'environment.remote'} eq 'off') { return ''; }
 1282:     my $menuname = &get_menu_name();
 1283:     return(<<ENDCLOSE);
 1284: <script type="text/javascript">
 1285: // <![CDATA[
 1286: window.status='Accessing Remote Control';
 1287: menu=window.open("/adm/rat/empty.html","$menuname",
 1288:                  "height=350,width=150,scrollbars=no,menubar=no");
 1289: window.status='Disabling Remote Control';
 1290: menu.active=0;
 1291: menu.autologout=0;
 1292: window.status='Closing Remote Control';
 1293: menu.close();
 1294: window.status='Done.';
 1295: // ]]>
 1296: </script>
 1297: ENDCLOSE
 1298: }
 1299: 
 1300: sub dc_popup_js {
 1301:     my %lt = &Apache::lonlocal::texthash(
 1302:                                           more => '(More ...)',
 1303:                                           less => '(Less ...)',
 1304:                                         );
 1305:     return <<"END";
 1306: 
 1307: function showCourseID() {
 1308:     document.getElementById('dccid').style.display='block';
 1309:     document.getElementById('dccid').style.textAlign='left';
 1310:     document.getElementById('dccid').style.textFace='normal';
 1311:     document.getElementById('dccidtext').innerHTML ='<a href="javascript:hideCourseID();" class="LC_menubuttons_link">$lt{'less'}</a>';
 1312:     return;
 1313: }
 1314: 
 1315: function hideCourseID() {
 1316:     document.getElementById('dccid').style.display='none';
 1317:     document.getElementById('dccidtext').innerHTML ='<a href="javascript:showCourseID()" class="LC_menubuttons_link">$lt{'more'}</a>';
 1318:     return;
 1319: }
 1320: 
 1321: END
 1322: 
 1323: }
 1324: 
 1325: sub utilityfunctions {
 1326:     my $currenturl=&Apache::lonnet::clutter(&Apache::lonnet::fixversion((split(/\?/,$env{'request.noversionuri'}))[0]));
 1327:     if ($currenturl =~ m{^/adm/wrapper/ext/}
 1328:         && $env{'request.external.querystring'} ) {
 1329:             $currenturl .= ($currenturl=~/\?/)?'&':'?'.$env{'request.external.querystring'};
 1330:     }
 1331:     $currenturl=&Apache::lonenc::check_encrypt(&unescape($currenturl));
 1332:     
 1333:     my $currentsymb=&Apache::lonenc::check_encrypt($env{'request.symb'});
 1334: 
 1335:     my $dc_popup_cid;
 1336:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 1337:                         $env{'course.'.$env{'request.course.id'}.
 1338:                                  '.domain'}.'/'})) {
 1339:         $dc_popup_cid = &dc_popup_js();
 1340:     }
 1341: 
 1342:     my $start_page_annotate = 
 1343:         &Apache::loncommon::start_page('Annotator',undef,
 1344: 				       {'only_body' => 1,
 1345: 					'js_ready'  => 1,
 1346: 					'bgcolor'   => '#BBBBBB',
 1347: 					'add_entries' => {
 1348: 					    'onload' => 'javascript:document.goannotate.submit();'}});
 1349: 
 1350:     my $end_page_annotate = 
 1351:         &Apache::loncommon::end_page({'js_ready' => 1});
 1352: 
 1353:     my $start_page_bookmark =
 1354:         &Apache::loncommon::start_page('Bookmarks',undef,
 1355:                                        {'only_body' => 1,
 1356:                                         'js_ready'  => 1,
 1357:                                         'bgcolor'   => '#BBBBBB',});
 1358: 
 1359:     my $end_page_bookmark =
 1360:         &Apache::loncommon::end_page({'js_ready' => 1});
 1361: 
 1362:     my $confirm_switch = &mt("Editing requires switching to the resource's home server.").'\n'.
 1363:                          &mt('Switch server?');
 1364: 
 1365:     my $esc_url=&escape($currenturl);
 1366:     my $esc_symb=&escape($currentsymb);
 1367: 
 1368: return (<<ENDUTILITY)
 1369: 
 1370:     var currentURL=unescape("$esc_url");
 1371:     var reloadURL=unescape("$esc_url");
 1372:     var currentSymb=unescape("$esc_symb");
 1373: 
 1374: $dc_popup_cid
 1375: 
 1376: function go(url) {
 1377:    if (url!='' && url!= null) {
 1378:        currentURL = null;
 1379:        currentSymb= null;
 1380:        window.location.href=url;
 1381:    }
 1382: }
 1383: 
 1384: function need_switchserver(url) {
 1385:     if (url!='' && url!= null) {
 1386:         if (confirm("$confirm_switch")) {
 1387:             go(url); 
 1388:         }
 1389:     }
 1390:     return;
 1391: }
 1392: 
 1393: function gopost(url,postdata) {
 1394:    if (url!='') {
 1395:       this.document.server.action=url;
 1396:       this.document.server.postdata.value=postdata;
 1397:       this.document.server.command.value='';
 1398:       this.document.server.url.value='';
 1399:       this.document.server.symb.value='';
 1400:       this.document.server.submit();
 1401:    }
 1402: }
 1403: 
 1404: function gocmd(url,cmd) {
 1405:    if (url!='') {
 1406:       this.document.server.action=url;
 1407:       this.document.server.postdata.value='';
 1408:       this.document.server.command.value=cmd;
 1409:       this.document.server.url.value=currentURL;
 1410:       this.document.server.symb.value=currentSymb;
 1411:       this.document.server.submit();
 1412:    }
 1413: }
 1414: 
 1415: function gocstr(url,filename) {
 1416:     if (url == '/adm/cfile?action=delete') {
 1417:         this.document.cstrdelete.filename.value = filename
 1418:         this.document.cstrdelete.submit();
 1419:         return;
 1420:     }
 1421:     if (url == '/adm/printout') {
 1422:         this.document.cstrprint.postdata.value = filename
 1423:         this.document.cstrprint.curseed.value = 0;
 1424:         this.document.cstrprint.problemtype.value = 0;
 1425:         if (this.document.lonhomework) {
 1426:             if ((this.document.lonhomework.rndseed) && (this.document.lonhomework.rndseed.value != null) && (this.document.lonhomework.rndseed.value != '')) {
 1427:                 this.document.cstrprint.curseed.value = this.document.lonhomework.rndseed.value
 1428:             }
 1429:             if (this.document.lonhomework.problemtype) {
 1430: 		if (this.document.lonhomework.problemtype.value) {
 1431: 		    this.document.cstrprint.problemtype.value = 
 1432: 			this.document.lonhomework.problemtype.value;
 1433: 		} else if (this.document.lonhomework.problemtype.options) {
 1434: 		    for (var i=0; i<this.document.lonhomework.problemtype.options.length; i++) {
 1435: 			if (this.document.lonhomework.problemtype.options[i].selected) {
 1436: 			    if (this.document.lonhomework.problemtype.options[i].value != null && this.document.lonhomework.problemtype.options[i].value != '') { 
 1437: 				this.document.cstrprint.problemtype.value = this.document.lonhomework.problemtype.options[i].value
 1438: 				}
 1439: 			}
 1440: 		    }
 1441: 		}
 1442: 	    }
 1443: 	}
 1444:         this.document.cstrprint.submit();
 1445:         return;
 1446:     }
 1447:     if (url !='') {
 1448:         this.document.constspace.filename.value = filename;
 1449:         this.document.constspace.action = url;
 1450:         this.document.constspace.submit();
 1451:     }
 1452: }
 1453: 
 1454: function golist(url) {
 1455:    if (url!='' && url!= null) {
 1456:        currentURL = null;
 1457:        currentSymb= null;
 1458:        top.location.href=url;
 1459:    }
 1460: }
 1461: 
 1462: 
 1463: 
 1464: function catalog_info() {
 1465:    openMyModal(window.location.pathname+'.meta',500,400,'yes');
 1466: }
 1467: 
 1468: function chat_win() {
 1469:    lonchat=window.open('/res/adm/pages/chatroom.html',"LONchat",'height=320,width=480,resizable=yes,location=no,menubar=no,toolbar=no');
 1470: }
 1471: 
 1472: function group_chat(group) {
 1473:    var url = '/adm/groupchat?group='+group;
 1474:    var winName = 'LONchat_'+group;
 1475:    grpchat=window.open(url,winName,'height=320,width=280,resizable=yes,location=no,menubar=no,toolbar=no');
 1476: }
 1477: 
 1478: function edit_bookmarks() {
 1479:    go('');
 1480:    w_BookmarkPal_flag=1;
 1481:    bookmarkpal=window.open("/adm/bookmarks",
 1482:                "BookmarkPal", "width=500,height=505,scrollbars=0");
 1483: }
 1484: 
 1485: function annotate() {
 1486:    w_Annotator_flag=1;
 1487:    annotator=window.open('','Annotator','width=365,height=265,scrollbars=0');
 1488:    annotator.document.write(
 1489:    '$start_page_annotate'
 1490:   +"<form name='goannotate' target='Annotator' method='post' "
 1491:   +"action='/adm/annotations'>"
 1492:   +"<input type='hidden' name='symbnew' value='"+currentSymb+"' />"
 1493:   +"<\\/form>"
 1494:   +'$end_page_annotate');
 1495:    annotator.document.close();
 1496: }
 1497: 
 1498: function set_bookmark() {
 1499:    go('');
 1500:    clienttitle=document.title;
 1501:    clienthref=location.pathname;
 1502:    w_bmquery_flag=1;
 1503:    bmquery=window.open('','bmquery','width=365,height=165,scrollbars=0');
 1504:    bmquery.document.write(
 1505:    '$start_page_bookmark'
 1506:    +'<center><form method="post"'
 1507:    +' name="newlink" action="/adm/bookmarks" target="bmquery" '
 1508:    +'> <table width="340" height="150" '
 1509:    +'bgcolor="#FFFFFF" align="center"><tr><td>Link Name:<br /><input '
 1510:    +'type="text" name="title" size="45" value="'+clienttitle+'" />'
 1511:    +'<br />Address:<br /><input type="text" name="address" size="45" '
 1512:    +'value="'+clienthref+'" /><br /><center><input type="submit" '
 1513:    +'value="Save" /> <input type="button" value="Close" '
 1514:    +'onclick="javascript:window.close();" /></center></td>'
 1515:    +'</tr></table></form></center>'
 1516:    +'$end_page_bookmark' );
 1517:    bmquery.document.close();
 1518: }
 1519: 
 1520: ENDUTILITY
 1521: }
 1522: 
 1523: sub serverform {
 1524:     return(<<ENDSERVERFORM);
 1525: <form name="server" action="/adm/logout" method="post" target="_top">
 1526: <input type="hidden" name="postdata" value="none" />
 1527: <input type="hidden" name="command" value="none" />
 1528: <input type="hidden" name="url" value="none" />
 1529: <input type="hidden" name="symb" value="none" />
 1530: </form>
 1531: ENDSERVERFORM
 1532: }
 1533: 
 1534: sub constspaceform {
 1535:     return(<<ENDCONSTSPACEFORM);
 1536: <form name="constspace" action="/adm/logout" method="post" target="_top">
 1537: <input type="hidden" name="filename" value="" />
 1538: </form>
 1539: <form name="cstrdelete" action="/adm/cfile" method="post" target="_top">
 1540: <input type="hidden" name="action" value="delete" /> 
 1541: <input type="hidden" name="filename" value="" />
 1542: </form>
 1543: <form name="cstrprint" action="/adm/printout" target="_parent" method="post">
 1544: <input type="hidden" name="postdata" value="" />
 1545: <input type="hidden" name="curseed" value="" />
 1546: <input type="hidden" name="problemtype" value="" />
 1547: </form>
 1548: 
 1549: ENDCONSTSPACEFORM
 1550: }
 1551: 
 1552: sub hidden_button_check {
 1553:     if ( $env{'request.course.id'} eq ''
 1554:          || $env{'request.role.adv'} ) {
 1555: 
 1556:         return;
 1557:     }
 1558:     my $buttonshide = &Apache::lonnet::EXT('resource.0.buttonshide');
 1559:     return $buttonshide; 
 1560: }
 1561: 
 1562: sub roles_selector {
 1563:     my ($cdom,$cnum) = @_;
 1564:     my $crstype = &Apache::loncommon::course_type();
 1565:     my $now = time;
 1566:     my (%courseroles,%seccount,%courseprivs);
 1567:     my $is_cc;
 1568:     my $role_selector;
 1569:     my $ccrole;
 1570:     if ($crstype eq 'Community') {
 1571:         $ccrole = 'co';
 1572:     } else {
 1573:         $ccrole = 'cc';
 1574:     }
 1575:     my $priv;
 1576:     my $destinationurl = $ENV{'REQUEST_URI'};
 1577:     my $reqprivs = &required_privs();
 1578:     if (ref($reqprivs) eq 'HASH') {
 1579:         my $destination = $destinationurl;
 1580:         $destination =~ s/(\?.*)$//;
 1581:         if (exists($reqprivs->{$destination})) {
 1582:             $priv = $reqprivs->{$destination};
 1583:         }
 1584:     }
 1585:     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
 1586:         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
 1587:         
 1588:         if ((($start) && ($start<0)) || 
 1589:             (($end) && ($end<$now))  ||
 1590:             (($start) && ($now<$start))) {
 1591:             $is_cc = 0;
 1592:         } else {
 1593:             $is_cc = 1;
 1594:         }
 1595:     }
 1596:     if ($is_cc) {
 1597:         &get_all_courseroles($cdom,$cnum,\%courseroles,\%seccount,\%courseprivs,$priv);
 1598:     } else {
 1599:         my %gotnosection;
 1600:         foreach my $item (keys(%env)) {
 1601:             if ($item =~ m-^user\.role\.([^.]+)\./\Q$cdom\E/\Q$cnum\E/?(\w*)$-) {
 1602:                 my $role = $1;
 1603:                 my $sec = $2;
 1604:                 next if ($role eq 'gr');
 1605:                 my ($start,$end) = split(/\./,$env{$item});
 1606:                 next if (($start && $start > $now) || ($end && $end < $now));
 1607:                 if ($sec eq '') {
 1608:                     if (!$gotnosection{$role}) {
 1609:                         $seccount{$role} ++;
 1610:                         $gotnosection{$role} = 1;
 1611:                     }
 1612:                 }
 1613:                 if ($priv ne '') {
 1614:                     my $cnumsec = $cnum;
 1615:                     if ($sec ne '') {
 1616:                         $cnumsec .= "/$sec";
 1617:                     }
 1618:                     $courseprivs{"$role./$cdom/$cnumsec./"} =
 1619:                         $env{"user.priv.$role./$cdom/$cnumsec./"};
 1620:                     $courseprivs{"$role./$cdom/$cnumsec./$cdom/"} =
 1621:                         $env{"user.priv.$role./$cdom/$cnumsec./$cdom/"};
 1622:                     $courseprivs{"$role./$cdom/$cnumsec./$cdom/$cnumsec"} =
 1623:                         $env{"user.priv.$role./$cdom/$cnumsec./$cdom/$cnumsec"};
 1624:                 }
 1625:                 if (ref($courseroles{$role}) eq 'ARRAY') {
 1626:                     if ($sec ne '') {
 1627:                         if (!grep(/^\Q$sec\E$/,@{$courseroles{$role}})) {
 1628:                             push(@{$courseroles{$role}},$sec);
 1629:                             $seccount{$role} ++;
 1630:                         }
 1631:                     }
 1632:                 } else {
 1633:                     @{$courseroles{$role}} = ();
 1634:                     if ($sec ne '') {
 1635:                         $seccount{$role} ++;
 1636:                         push(@{$courseroles{$role}},$sec);
 1637:                     }
 1638:                 }
 1639:             }
 1640:         }
 1641:     }
 1642:     my $switchtext;
 1643:     if ($crstype eq 'Community') {
 1644:         $switchtext = &mt('Switch community role to...')
 1645:     } else {
 1646:         $switchtext = &mt('Switch course role to...')
 1647:     }
 1648:     my @roles_order = ($ccrole,'in','ta','ep','ad','st');
 1649:     if (keys(%courseroles) > 1) {
 1650:         $role_selector = &jump_to_role($cdom,$cnum,\%seccount,\%courseroles,\%courseprivs,$priv);
 1651:         $role_selector .= '<form name="rolechooser" method="post" action="/adm/roles">
 1652:                           <select name="switchrole" onchange="javascript:adhocRole('."'switchrole'".')">';
 1653:         $role_selector .= '<option value="">'.$switchtext.'</option>';
 1654:         foreach my $role (@roles_order) {
 1655:             if (defined($courseroles{$role})) {
 1656:                 $role_selector .= "\n".'<option value="'.$role.'">'.&Apache::lonnet::plaintext($role,$crstype).'</option>'; 
 1657:             }
 1658:         }
 1659:         foreach my $role (sort(keys(%courseroles))) {
 1660:             if ($role =~ /^cr/) {
 1661:                 $role_selector .= "\n".'<option value="'.$role.'">'.&Apache::lonnet::plaintext($role).'</option>'; 
 1662:             }
 1663:         }
 1664:         $role_selector .= '</select>'."\n".
 1665:                '<input type="hidden" name="destinationurl" value="'.
 1666:                &HTML::Entities::encode($destinationurl).'" />'."\n".
 1667:                '<input type="hidden" name="gotorole" value="1" />'."\n".
 1668:                '<input type="hidden" name="selectrole" value="" />'."\n".
 1669:                '<input type="hidden" name="switch" value="1" />'."\n".
 1670:                '</form>';
 1671:     }
 1672:     return $role_selector;
 1673: }
 1674: 
 1675: sub get_all_courseroles {
 1676:     my ($cdom,$cnum,$courseroles,$seccount,$courseprivs) = @_;
 1677:     unless ((ref($courseroles) eq 'HASH') && (ref($seccount) eq 'HASH') &&
 1678:             (ref($courseprivs) eq 'HASH')) {
 1679:         return;
 1680:     }
 1681:     my ($result,$cached) = 
 1682:         &Apache::lonnet::is_cached_new('getcourseroles',$cdom.'_'.$cnum);
 1683:     if (defined($cached)) {
 1684:         if (ref($result) eq 'HASH') {
 1685:             if ((ref($result->{'roles'}) eq 'HASH') && 
 1686:                 (ref($result->{'seccount'}) eq 'HASH') && 
 1687:                 (ref($result->{'privs'}) eq 'HASH')) {
 1688:                 %{$courseroles} = %{$result->{'roles'}};
 1689:                 %{$seccount} = %{$result->{'seccount'}};
 1690:                 %{$courseprivs} = %{$result->{'privs'}};
 1691:                 return;
 1692:             }
 1693:         }
 1694:     }
 1695:     my %gotnosection;
 1696:     my %adv_roles =
 1697:          &Apache::lonnet::get_course_adv_roles($env{'request.course.id'},1);
 1698:     foreach my $role (keys(%adv_roles)) {
 1699:         my ($urole,$usec) = split(/:/,$role);
 1700:         if (!$gotnosection{$urole}) {
 1701:             $seccount->{$urole} ++;
 1702:             $gotnosection{$urole} = 1;
 1703:         }
 1704:         if (ref($courseroles->{$urole}) eq 'ARRAY') {
 1705:             if ($usec ne '') {
 1706:                 if (!grep(/^Q$usec\E$/,@{$courseroles->{$urole}})) {
 1707:                     push(@{$courseroles->{$urole}},$usec);
 1708:                     $seccount->{$urole} ++;
 1709:                 }
 1710:             }
 1711:         } else {
 1712:             @{$courseroles->{$urole}} = ();
 1713:             if ($usec ne '') {
 1714:                 $seccount->{$urole} ++;
 1715:                 push(@{$courseroles->{$urole}},$usec);
 1716:             }
 1717:         }
 1718:         my $area = '/'.$cdom.'/'.$cnum;
 1719:         if ($usec ne '') {
 1720:             $area .= '/'.$usec;
 1721:         }
 1722:         if ($role =~ /^cr\//) {
 1723:             &Apache::lonnet::custom_roleprivs($courseprivs,$urole,$cdom,$cnum,$urole.'.'.$area,$area);
 1724:         } else {
 1725:             &Apache::lonnet::standard_roleprivs($courseprivs,$urole,$cdom,$urole.'.'.$area,$cnum,$area);
 1726:         }
 1727:     }
 1728:     my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum,['st']);
 1729:     @{$courseroles->{'st'}} = ();
 1730:     &Apache::lonnet::standard_roleprivs($courseprivs,'st',$cdom,"st./$cdom/$cnum",$cnum,"/$cdom/$cnum");
 1731:     if (keys(%sections_count) > 0) {
 1732:         push(@{$courseroles->{'st'}},keys(%sections_count));
 1733:         $seccount->{'st'} = scalar(keys(%sections_count));
 1734:     }
 1735:     my $rolehash = {
 1736:                      'roles'    => $courseroles,
 1737:                      'seccount' => $seccount,
 1738:                      'privs'    => $courseprivs,
 1739:                    };
 1740:     &Apache::lonnet::do_cache_new('getcourseroles',$cdom.'_'.$cnum,$rolehash);
 1741:     return;
 1742: }
 1743: 
 1744: sub jump_to_role {
 1745:     my ($cdom,$cnum,$seccount,$courseroles,$courseprivs,$priv) = @_;
 1746:     my %lt = &Apache::lonlocal::texthash(
 1747:                 this => 'This role has section(s) associated with it.',
 1748:                 ente => 'Enter a specific section.',
 1749:                 orlb => 'Enter a specific section, or leave blank for no section.',
 1750:                 avai => 'Available sections are:',
 1751:                 youe => 'You entered an invalid section choice:',
 1752:                 plst => 'Please try again.',
 1753:                 role => 'The role you selected is not permitted to view the current page.',
 1754:                 swit => 'Switch role, but display Main Menu page instead?',
 1755:     );
 1756:     my $js;
 1757:     if (ref($courseroles) eq 'HASH') {
 1758:         $js = '    var secpick = new Array("'.$lt{'ente'}.'","'.$lt{'orlb'}.'");'."\n". 
 1759:               '    var numsec = new Array();'."\n".
 1760:               '    var rolesections = new Array();'."\n".
 1761:               '    var rolenames = new Array();'."\n".
 1762:               '    var roleseclist = new Array();'."\n";
 1763:         my @items = keys(%{$courseroles});
 1764:         for (my $i=0; $i<@items; $i++) {
 1765:             $js .= '    rolenames['.$i.'] = "'.$items[$i].'";'."\n";
 1766:             my ($secs,$secstr);
 1767:             if (ref($courseroles->{$items[$i]}) eq 'ARRAY') {
 1768:                 my @sections = sort { $a <=> $b } @{$courseroles->{$items[$i]}};
 1769:                 $secs = join('","',@sections);
 1770:                 $secstr = join(', ',@sections);
 1771:             }
 1772:             $js .= '    rolesections['.$i.'] = new Array("'.$secs.'");'."\n".
 1773:                    '    roleseclist['.$i.'] = "'.$secstr.'";'."\n".
 1774:                    '    numsec['.$i.'] = "'.$seccount->{$items[$i]}.'";'."\n";
 1775:         }
 1776:     }
 1777:     my $checkroles = 0;
 1778:     if ($priv && ref($courseprivs) eq 'HASH') {
 1779:         my (%disallowed,%allowed,@disallow);
 1780:         foreach my $role (sort(keys(%{$courseprivs}))) {
 1781:             my $trole;
 1782:             if ($role =~ m{^(.+?)\Q./$cdom/$cnum\E}) {
 1783:                 $trole = $1;
 1784:             }
 1785:             if (($trole ne '') && ($trole ne 'cm')) {
 1786:                 if ($courseprivs->{$role} =~ /\Q:$priv\E($|:|\&\w+)/) {
 1787:                     $allowed{$trole} = 1;
 1788:                 } else {
 1789:                     $disallowed{$trole} = 1;
 1790:                 }
 1791:             }
 1792:         }
 1793:         foreach my $trole (keys(%disallowed)) {
 1794:             unless ($allowed{$trole}) {
 1795:                 push(@disallow,$trole);
 1796:             }
 1797:         }
 1798:         if (@disallow > 0) {
 1799:             $checkroles = 1;
 1800:             $js .= "    var disallow = new Array('".join("','",@disallow)."');\n".
 1801:                    "    var rolecheck = 1;\n";
 1802:         }
 1803:     }
 1804:     if (!$checkroles) {
 1805:         $js .=  "    var disallow = new Array();\n".
 1806:                 "    rolecheck = 0;\n";
 1807:     }
 1808:     return <<"END";
 1809: <script type="text/javascript">
 1810: //<![CDATA[
 1811: function adhocRole(roleitem) {
 1812:     $js
 1813:     var newrole =  document.rolechooser.elements[roleitem].options[document.rolechooser.elements[roleitem].selectedIndex].value;
 1814:     if (newrole == '') {
 1815:         return;
 1816:     } 
 1817:     var fullrole = newrole+'./$cdom/$cnum';
 1818:     var selidx = '';
 1819:     for (var i=0; i<rolenames.length; i++) {
 1820:         if (rolenames[i] == newrole) {
 1821:             selidx = i;
 1822:         }
 1823:     }
 1824:     if (rolecheck > 0) {
 1825:         for (var i=0; i<disallow.length; i++) {
 1826:             if (disallow[i] == newrole) {
 1827:                 if (confirm("$lt{'role'}\\n$lt{'swit'}")) {
 1828:                     document.rolechooser.destinationurl.value = '/adm/menu';
 1829:                 } else {
 1830:                     document.rolechooser.elements[roleitem].selectedIndex = 0;
 1831:                     return;
 1832:                 }
 1833:             }
 1834:         }
 1835:     }
 1836:     var secok = 1;
 1837:     var secchoice = '';
 1838:     if (selidx >= 0) {
 1839:         if (numsec[selidx] > 1) {
 1840:             secok = 0;
 1841:             var numrolesec = rolesections[selidx].length;
 1842:             var msgidx = numsec[selidx] - numrolesec;
 1843:             secchoice = prompt("$lt{'this'} "+secpick[msgidx]+"\\n$lt{'avai'} "+roleseclist[selidx],"");
 1844:             if (secchoice == '') {
 1845:                 if (msgidx > 0) {
 1846:                     secok = 1;
 1847:                 }
 1848:             } else {
 1849:                 for (var j=0; j<rolesections[selidx].length; j++) {
 1850:                     if (rolesections[selidx][j] == secchoice) {
 1851:                         secok = 1;
 1852:                     }
 1853:                 }
 1854:             }
 1855:         } else {
 1856:             if (rolesections[selidx].length == 1) {
 1857:                 secchoice = rolesections[selidx][0];
 1858:             }
 1859:         }
 1860:     }
 1861:     if (secok == 1) {
 1862:         if (secchoice != '') {
 1863:             fullrole += '/'+secchoice;
 1864:         }
 1865:     } else {
 1866:         document.rolechooser.elements[roleitem].selectedIndex = 0;
 1867:         if (secchoice != null) {
 1868:             alert("$lt{'youe'} \\""+secchoice+"\\".\\n $lt{'plst'}");
 1869:         }
 1870:         return;
 1871:     }
 1872:     if (fullrole == "$env{'request.role'}") {
 1873:         document.rolechooser.elements[roleitem].selectedIndex = 0;
 1874:         return;
 1875:     }
 1876:     itemid = retrieveIndex('gotorole');
 1877:     if (itemid != -1) {
 1878:         document.rolechooser.elements[itemid].name = fullrole;
 1879:     }
 1880:     document.rolechooser.elements[roleitem].options[document.rolechooser.elements[roleitem].selectedIndex].value = fullrole;
 1881:     document.rolechooser.selectrole.value = '1';
 1882:     document.rolechooser.submit();
 1883:     return;
 1884: }
 1885: 
 1886: function retrieveIndex(item) {
 1887:     for (var i=0;i<document.rolechooser.elements.length;i++) {
 1888:         if (document.rolechooser.elements[i].name == item) {
 1889:             return i;
 1890:         }
 1891:     }
 1892:     return -1;
 1893: }
 1894: // ]]>
 1895: </script>
 1896: END
 1897: }
 1898: 
 1899: sub required_privs {
 1900:     my $privs =  {
 1901:              '/adm/parmset'      => 'opa',
 1902:              '/adm/courseprefs'  => 'opa',
 1903:              '/adm/whatsnew'     => 'whn',
 1904:              '/adm/populate'     => 'cst',
 1905:              '/adm/trackstudent' => 'vsa',
 1906:              '/adm/statistics'   => 'vgr',
 1907:              '/adm/setblock'     => 'dcm',
 1908:              '/adm/coursedocs'   => 'mdc',
 1909:            };
 1910:     unless ($env{'course.'.$env{'request.course.id'}.'.grading'} eq 'spreadsheet') {
 1911:         $privs->{'/adm/classcalc'}   = 'vgr',
 1912:         $privs->{'/adm/assesscalc'}  = 'vgr',
 1913:         $privs->{'/adm/studentcalc'} = 'vgr';
 1914:     }
 1915:     return $privs;
 1916: }
 1917: 
 1918: # ================================================================ Main Program
 1919: 
 1920: BEGIN {
 1921:     if (! defined($readdesk)) {
 1922:         {
 1923:             my $tabfile = $Apache::lonnet::perlvar{'lonTabDir'}.'/mydesk.tab';
 1924:             if ( CORE::open( my $config,"<$tabfile") ) {
 1925:                 while (my $configline=<$config>) {
 1926:                     $configline=(split(/\#/,$configline))[0];
 1927:                     $configline=~s/^\s+//;
 1928:                     chomp($configline);
 1929:                     if ($configline=~/^cat\:/) {
 1930:                         my @entries=split(/\:/,$configline);
 1931:                         $category_positions{$entries[2]}=$entries[1];
 1932:                         $category_names{$entries[2]}=$entries[3];
 1933:                     } elsif ($configline=~/^prim\:/) {
 1934:                         my @entries = (split(/\:/, $configline))[1..5];
 1935:                         push @primary_menu, \@entries;
 1936:                     } elsif ($configline=~/^primsub\:/) {
 1937:                         my ($parent,@entries) = (split(/\:/, $configline))[1..4];
 1938:                         push (@{$primary_submenu{$parent}},\@entries);
 1939:                     } elsif ($configline=~/^scnd\:/) {
 1940:                         my @entries = (split(/\:/, $configline))[1..5];
 1941:                         push @secondary_menu, \@entries; 
 1942:                     } elsif ($configline) {
 1943:                         push(@desklines,$configline);
 1944:                     }
 1945:                 }
 1946:                 CORE::close($config);
 1947:             }
 1948:         }
 1949:         $readdesk='done';
 1950:     }
 1951: }
 1952: 
 1953: 1;
 1954: __END__
 1955: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>