Annotation of loncom/interface/loncommon.pm, revision 1.1075.2.112

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1075.2.112! raeburn     4: # $Id: loncommon.pm,v 1.1075.2.111 2016/09/01 01:27:25 raeburn Exp $
1.10      albertel    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: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1075.2.25  raeburn    70: use Apache::lonuserutils();
1.1075.2.27  raeburn    71: use Apache::lonuserstate();
1.1075.2.69  raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    74: use DateTime::TimeZone;
1.1075.2.102  raeburn    75: use DateTime::Locale;
1.1075.2.94  raeburn    76: use Encode();
1.1075.2.14  raeburn    77: use Authen::Captcha;
                     78: use Captcha::reCAPTCHA;
1.1075.2.107  raeburn    79: use JSON::DWIW;
                     80: use LWP::UserAgent;
1.1075.2.64  raeburn    81: use Crypt::DES;
                     82: use DynaLoader; # for Crypt::DES version
1.117     www        83: 
1.517     raeburn    84: # ---------------------------------------------- Designs
                     85: use vars qw(%defaultdesign);
                     86: 
1.22      www        87: my $readit;
                     88: 
1.517     raeburn    89: 
1.157     matthew    90: ##
                     91: ## Global Variables
                     92: ##
1.46      matthew    93: 
1.643     foxr       94: 
                     95: # ----------------------------------------------- SSI with retries:
                     96: #
                     97: 
                     98: =pod
                     99: 
1.648     raeburn   100: =head1 Server Side include with retries:
1.643     foxr      101: 
                    102: =over 4
                    103: 
1.648     raeburn   104: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      105: 
                    106: Performs an ssi with some number of retries.  Retries continue either
                    107: until the result is ok or until the retry count supplied by the
                    108: caller is exhausted.  
                    109: 
                    110: Inputs:
1.648     raeburn   111: 
                    112: =over 4
                    113: 
1.643     foxr      114: resource   - Identifies the resource to insert.
1.648     raeburn   115: 
1.643     foxr      116: retries    - Count of the number of retries allowed.
1.648     raeburn   117: 
1.643     foxr      118: form       - Hash that identifies the rendering options.
                    119: 
1.648     raeburn   120: =back
                    121: 
                    122: Returns:
                    123: 
                    124: =over 4
                    125: 
1.643     foxr      126: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   127: 
1.643     foxr      128: response   - The response from the last attempt (which may or may not have been successful.
                    129: 
1.648     raeburn   130: =back
                    131: 
                    132: =back
                    133: 
1.643     foxr      134: =cut
                    135: 
                    136: sub ssi_with_retries {
                    137:     my ($resource, $retries, %form) = @_;
                    138: 
                    139: 
                    140:     my $ok = 0;			# True if we got a good response.
                    141:     my $content;
                    142:     my $response;
                    143: 
                    144:     # Try to get the ssi done. within the retries count:
                    145: 
                    146:     do {
                    147: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    148: 	$ok      = $response->is_success;
1.650     www       149:         if (!$ok) {
                    150:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    151:         }
1.643     foxr      152: 	$retries--;
                    153:     } while (!$ok && ($retries > 0));
                    154: 
                    155:     if (!$ok) {
                    156: 	$content = '';		# On error return an empty content.
                    157:     }
                    158:     return ($content, $response);
                    159: 
                    160: }
                    161: 
                    162: 
                    163: 
1.20      www       164: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  165: my %language;
1.124     www       166: my %supported_language;
1.1048    foxr      167: my %latex_language;		# For choosing hyphenation in <transl..>
                    168: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  169: my %cprtag;
1.192     taceyjo1  170: my %scprtag;
1.351     www       171: my %fe; my %fd; my %fm;
1.41      ng        172: my %category_extensions;
1.12      harris41  173: 
1.46      matthew   174: # ---------------------------------------------- Thesaurus variables
1.144     matthew   175: #
                    176: # %Keywords:
                    177: #      A hash used by &keyword to determine if a word is considered a keyword.
                    178: # $thesaurus_db_file 
                    179: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   180: 
                    181: my %Keywords;
                    182: my $thesaurus_db_file;
                    183: 
1.144     matthew   184: #
                    185: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    186: # thesaurus.tab, and filecategories.tab.
                    187: #
1.18      www       188: BEGIN {
1.46      matthew   189:     # Variable initialization
                    190:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    191:     #
1.22      www       192:     unless ($readit) {
1.12      harris41  193: # ------------------------------------------------------------------- languages
                    194:     {
1.158     raeburn   195:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    196:                                    '/language.tab';
                    197:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  198:             while (my $line = <$fh>) {
                    199:                 next if ($line=~/^\#/);
                    200:                 chomp($line);
1.1048    foxr      201:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   202:                 $language{$key}=$val.' - '.$enc;
                    203:                 if ($sup) {
                    204:                     $supported_language{$key}=$sup;
                    205:                 }
1.1048    foxr      206: 		if ($latex) {
                    207: 		    $latex_language_bykey{$key} = $latex;
                    208: 		    $latex_language{$two} = $latex;
                    209: 		}
1.158     raeburn   210:             }
                    211:             close($fh);
                    212:         }
1.12      harris41  213:     }
                    214: # ------------------------------------------------------------------ copyrights
                    215:     {
1.158     raeburn   216:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    217:                                   '/copyright.tab';
                    218:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  219:             while (my $line = <$fh>) {
                    220:                 next if ($line=~/^\#/);
                    221:                 chomp($line);
                    222:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   223:                 $cprtag{$key}=$val;
                    224:             }
                    225:             close($fh);
                    226:         }
1.12      harris41  227:     }
1.351     www       228: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  229:     {
                    230:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    231:                                   '/source_copyright.tab';
                    232:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  233:             while (my $line = <$fh>) {
                    234:                 next if ($line =~ /^\#/);
                    235:                 chomp($line);
                    236:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  237:                 $scprtag{$key}=$val;
                    238:             }
                    239:             close($fh);
                    240:         }
                    241:     }
1.63      www       242: 
1.517     raeburn   243: # -------------------------------------------------------------- default domain designs
1.63      www       244:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   245:     my $designfile = $designdir.'/default.tab';
                    246:     if ( open (my $fh,"<$designfile") ) {
                    247:         while (my $line = <$fh>) {
                    248:             next if ($line =~ /^\#/);
                    249:             chomp($line);
                    250:             my ($key,$val)=(split(/\=/,$line));
                    251:             if ($val) { $defaultdesign{$key}=$val; }
                    252:         }
                    253:         close($fh);
1.63      www       254:     }
                    255: 
1.15      harris41  256: # ------------------------------------------------------------- file categories
                    257:     {
1.158     raeburn   258:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    259:                                   '/filecategories.tab';
                    260:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  261: 	    while (my $line = <$fh>) {
                    262: 		next if ($line =~ /^\#/);
                    263: 		chomp($line);
                    264:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.158     raeburn   265:                 push @{$category_extensions{lc($category)}},$extension;
                    266:             }
                    267:             close($fh);
                    268:         }
                    269: 
1.15      harris41  270:     }
1.12      harris41  271: # ------------------------------------------------------------------ file types
                    272:     {
1.158     raeburn   273:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    274:                '/filetypes.tab';
                    275:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  276:             while (my $line = <$fh>) {
                    277: 		next if ($line =~ /^\#/);
                    278: 		chomp($line);
                    279:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   280:                 if ($descr ne '') {
                    281:                     $fe{$ending}=lc($emb);
                    282:                     $fd{$ending}=$descr;
1.351     www       283:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   284:                 }
                    285:             }
                    286:             close($fh);
                    287:         }
1.12      harris41  288:     }
1.22      www       289:     &Apache::lonnet::logthis(
1.705     tempelho  290:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       291:     $readit=1;
1.46      matthew   292:     }  # end of unless($readit) 
1.32      matthew   293:     
                    294: }
1.112     bowersj2  295: 
1.42      matthew   296: ###############################################################
                    297: ##           HTML and Javascript Helper Functions            ##
                    298: ###############################################################
                    299: 
                    300: =pod 
                    301: 
1.112     bowersj2  302: =head1 HTML and Javascript Functions
1.42      matthew   303: 
1.112     bowersj2  304: =over 4
                    305: 
1.648     raeburn   306: =item * &browser_and_searcher_javascript()
1.112     bowersj2  307: 
                    308: X<browsing, javascript>X<searching, javascript>Returns a string
                    309: containing javascript with two functions, C<openbrowser> and
                    310: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    311: tags.
1.42      matthew   312: 
1.648     raeburn   313: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   314: 
                    315: inputs: formname, elementname, only, omit
                    316: 
                    317: formname and elementname indicate the name of the html form and name of
                    318: the element that the results of the browsing selection are to be placed in. 
                    319: 
                    320: Specifying 'only' will restrict the browser to displaying only files
1.185     www       321: with the given extension.  Can be a comma separated list.
1.42      matthew   322: 
                    323: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       324: with the given extension.  Can be a comma separated list.
1.42      matthew   325: 
1.648     raeburn   326: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   327: 
                    328: Inputs: formname, elementname
                    329: 
                    330: formname and elementname specify the name of the html form and the name
                    331: of the element the selection from the search results will be placed in.
1.542     raeburn   332: 
1.42      matthew   333: =cut
                    334: 
                    335: sub browser_and_searcher_javascript {
1.199     albertel  336:     my ($mode)=@_;
                    337:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  338:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   339:     return <<END;
1.219     albertel  340: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   341:     var editbrowser = null;
1.135     albertel  342:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       343:         var url = '$resurl/?';
1.42      matthew   344:         if (editbrowser == null) {
                    345:             url += 'launch=1&';
                    346:         }
                    347:         url += 'catalogmode=interactive&';
1.199     albertel  348:         url += 'mode=$mode&';
1.611     albertel  349:         url += 'inhibitmenu=yes&';
1.42      matthew   350:         url += 'form=' + formname + '&';
                    351:         if (only != null) {
                    352:             url += 'only=' + only + '&';
1.217     albertel  353:         } else {
                    354:             url += 'only=&';
                    355: 	}
1.42      matthew   356:         if (omit != null) {
                    357:             url += 'omit=' + omit + '&';
1.217     albertel  358:         } else {
                    359:             url += 'omit=&';
                    360: 	}
1.135     albertel  361:         if (titleelement != null) {
                    362:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  363:         } else {
                    364: 	    url += 'titleelement=&';
                    365: 	}
1.42      matthew   366:         url += 'element=' + elementname + '';
                    367:         var title = 'Browser';
1.435     albertel  368:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   369:         options += ',width=700,height=600';
                    370:         editbrowser = open(url,title,options,'1');
                    371:         editbrowser.focus();
                    372:     }
                    373:     var editsearcher;
1.135     albertel  374:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   375:         var url = '/adm/searchcat?';
                    376:         if (editsearcher == null) {
                    377:             url += 'launch=1&';
                    378:         }
                    379:         url += 'catalogmode=interactive&';
1.199     albertel  380:         url += 'mode=$mode&';
1.42      matthew   381:         url += 'form=' + formname + '&';
1.135     albertel  382:         if (titleelement != null) {
                    383:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  384:         } else {
                    385: 	    url += 'titleelement=&';
                    386: 	}
1.42      matthew   387:         url += 'element=' + elementname + '';
                    388:         var title = 'Search';
1.435     albertel  389:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   390:         options += ',width=700,height=600';
                    391:         editsearcher = open(url,title,options,'1');
                    392:         editsearcher.focus();
                    393:     }
1.219     albertel  394: // END LON-CAPA Internal -->
1.42      matthew   395: END
1.170     www       396: }
                    397: 
                    398: sub lastresurl {
1.258     albertel  399:     if ($env{'environment.lastresurl'}) {
                    400: 	return $env{'environment.lastresurl'}
1.170     www       401:     } else {
                    402: 	return '/res';
                    403:     }
                    404: }
                    405: 
                    406: sub storeresurl {
                    407:     my $resurl=&Apache::lonnet::clutter(shift);
                    408:     unless ($resurl=~/^\/res/) { return 0; }
                    409:     $resurl=~s/\/$//;
                    410:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   411:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       412:     return 1;
1.42      matthew   413: }
                    414: 
1.74      www       415: sub studentbrowser_javascript {
1.111     www       416:    unless (
1.258     albertel  417:             (($env{'request.course.id'}) && 
1.302     albertel  418:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    419: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    420: 					  '/'.$env{'request.course.sec'})
                    421: 	      ))
1.258     albertel  422:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       423:           ) { return ''; }  
1.74      www       424:    return (<<'ENDSTDBRW');
1.776     bisitz    425: <script type="text/javascript" language="Javascript">
1.824     bisitz    426: // <![CDATA[
1.74      www       427:     var stdeditbrowser;
1.999     www       428:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       429:         var url = '/adm/pickstudent?';
                    430:         var filter;
1.558     albertel  431: 	if (!ignorefilter) {
                    432: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    433: 	}
1.74      www       434:         if (filter != null) {
                    435:            if (filter != '') {
                    436:                url += 'filter='+filter+'&';
                    437: 	   }
                    438:         }
                    439:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       440:                                     '&udomelement='+udom+
                    441:                                     '&clicker='+clicker;
1.111     www       442: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   443:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       444:         var title = 'Student_Browser';
1.74      www       445:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    446:         options += ',width=700,height=600';
                    447:         stdeditbrowser = open(url,title,options,'1');
                    448:         stdeditbrowser.focus();
                    449:     }
1.824     bisitz    450: // ]]>
1.74      www       451: </script>
                    452: ENDSTDBRW
                    453: }
1.42      matthew   454: 
1.1003    www       455: sub resourcebrowser_javascript {
                    456:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       457:    return (<<'ENDRESBRW');
1.1003    www       458: <script type="text/javascript" language="Javascript">
                    459: // <![CDATA[
                    460:     var reseditbrowser;
1.1004    www       461:     function openresbrowser(formname,reslink) {
1.1005    www       462:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       463:         var title = 'Resource_Browser';
                    464:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       465:         options += ',width=700,height=500';
1.1004    www       466:         reseditbrowser = open(url,title,options,'1');
                    467:         reseditbrowser.focus();
1.1003    www       468:     }
                    469: // ]]>
                    470: </script>
1.1004    www       471: ENDRESBRW
1.1003    www       472: }
                    473: 
1.74      www       474: sub selectstudent_link {
1.999     www       475:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    476:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    477:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    478:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  479:    if ($env{'request.course.id'}) {  
1.302     albertel  480:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    481: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    482: 					'/'.$env{'request.course.sec'})) {
1.111     www       483: 	   return '';
                    484:        }
1.999     www       485:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   486:        if ($courseadvonly)  {
                    487:            $callargs .= ",'',1,1";
                    488:        }
                    489:        return '<span class="LC_nobreak">'.
                    490:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    491:               &mt('Select User').'</a></span>';
1.74      www       492:    }
1.258     albertel  493:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       494:        $callargs .= ",'',1"; 
1.793     raeburn   495:        return '<span class="LC_nobreak">'.
                    496:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    497:               &mt('Select User').'</a></span>';
1.111     www       498:    }
                    499:    return '';
1.91      www       500: }
                    501: 
1.1004    www       502: sub selectresource_link {
                    503:    my ($form,$reslink,$arg)=@_;
                    504:    
                    505:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    506:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    507:    unless ($env{'request.course.id'}) { return $arg; }
                    508:    return '<span class="LC_nobreak">'.
                    509:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    510:               $arg.'</a></span>';
                    511: }
                    512: 
                    513: 
                    514: 
1.653     raeburn   515: sub authorbrowser_javascript {
                    516:     return <<"ENDAUTHORBRW";
1.776     bisitz    517: <script type="text/javascript" language="JavaScript">
1.824     bisitz    518: // <![CDATA[
1.653     raeburn   519: var stdeditbrowser;
                    520: 
                    521: function openauthorbrowser(formname,udom) {
                    522:     var url = '/adm/pickauthor?';
                    523:     url += 'form='+formname+'&roledom='+udom;
                    524:     var title = 'Author_Browser';
                    525:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    526:     options += ',width=700,height=600';
                    527:     stdeditbrowser = open(url,title,options,'1');
                    528:     stdeditbrowser.focus();
                    529: }
                    530: 
1.824     bisitz    531: // ]]>
1.653     raeburn   532: </script>
                    533: ENDAUTHORBRW
                    534: }
                    535: 
1.91      www       536: sub coursebrowser_javascript {
1.1075.2.31  raeburn   537:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1075.2.95  raeburn   538:         $credits_element,$instcode) = @_;
1.932     raeburn   539:     my $wintitle = 'Course_Browser';
1.931     raeburn   540:     if ($crstype eq 'Community') {
1.932     raeburn   541:         $wintitle = 'Community_Browser';
1.909     raeburn   542:     }
1.876     raeburn   543:     my $id_functions = &javascript_index_functions();
                    544:     my $output = '
1.776     bisitz    545: <script type="text/javascript" language="JavaScript">
1.824     bisitz    546: // <![CDATA[
1.468     raeburn   547:     var stdeditbrowser;'."\n";
1.876     raeburn   548: 
                    549:     $output .= <<"ENDSTDBRW";
1.909     raeburn   550:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       551:         var url = '/adm/pickcourse?';
1.895     raeburn   552:         var formid = getFormIdByName(formname);
1.876     raeburn   553:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  554:         if (domainfilter != null) {
                    555:            if (domainfilter != '') {
                    556:                url += 'domainfilter='+domainfilter+'&';
                    557: 	   }
                    558:         }
1.91      www       559:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  560: 	                            '&cdomelement='+udom+
                    561:                                     '&cnameelement='+desc;
1.468     raeburn   562:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   563:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   564:                 url += '&roleelement='+extra_element;
                    565:                 if (domainfilter == null || domainfilter == '') {
                    566:                     url += '&domainfilter='+extra_element;
                    567:                 }
1.234     raeburn   568:             }
1.468     raeburn   569:             else {
                    570:                 if (formname == 'portform') {
                    571:                     url += '&setroles='+extra_element;
1.800     raeburn   572:                 } else {
                    573:                     if (formname == 'rules') {
                    574:                         url += '&fixeddom='+extra_element; 
                    575:                     }
1.468     raeburn   576:                 }
                    577:             }     
1.230     raeburn   578:         }
1.909     raeburn   579:         if (type != null && type != '') {
                    580:             url += '&type='+type;
                    581:         }
                    582:         if (type_elem != null && type_elem != '') {
                    583:             url += '&typeelement='+type_elem;
                    584:         }
1.872     raeburn   585:         if (formname == 'ccrs') {
                    586:             var ownername = document.forms[formid].ccuname.value;
                    587:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1075.2.101  raeburn   588:             url += '&cloner='+ownername+':'+ownerdom;
                    589:             if (type == 'Course') {
                    590:                 url += '&crscode='+document.forms[formid].crscode.value;
                    591:             }
1.1075.2.95  raeburn   592:         }
                    593:         if (formname == 'requestcrs') {
                    594:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   595:         }
1.293     raeburn   596:         if (multflag !=null && multflag != '') {
                    597:             url += '&multiple='+multflag;
                    598:         }
1.909     raeburn   599:         var title = '$wintitle';
1.91      www       600:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    601:         options += ',width=700,height=600';
                    602:         stdeditbrowser = open(url,title,options,'1');
                    603:         stdeditbrowser.focus();
                    604:     }
1.876     raeburn   605: $id_functions
                    606: ENDSTDBRW
1.1075.2.31  raeburn   607:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    608:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    609:                                       $credits_element);
1.876     raeburn   610:     }
                    611:     $output .= '
                    612: // ]]>
                    613: </script>';
                    614:     return $output;
                    615: }
                    616: 
                    617: sub javascript_index_functions {
                    618:     return <<"ENDJS";
                    619: 
                    620: function getFormIdByName(formname) {
                    621:     for (var i=0;i<document.forms.length;i++) {
                    622:         if (document.forms[i].name == formname) {
                    623:             return i;
                    624:         }
                    625:     }
                    626:     return -1;
                    627: }
                    628: 
                    629: function getIndexByName(formid,item) {
                    630:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    631:         if (document.forms[formid].elements[i].name == item) {
                    632:             return i;
                    633:         }
                    634:     }
                    635:     return -1;
                    636: }
1.468     raeburn   637: 
1.876     raeburn   638: function getDomainFromSelectbox(formname,udom) {
                    639:     var userdom;
                    640:     var formid = getFormIdByName(formname);
                    641:     if (formid > -1) {
                    642:         var domid = getIndexByName(formid,udom);
                    643:         if (domid > -1) {
                    644:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    645:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    646:             }
                    647:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    648:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   649:             }
                    650:         }
                    651:     }
1.876     raeburn   652:     return userdom;
                    653: }
                    654: 
                    655: ENDJS
1.468     raeburn   656: 
1.876     raeburn   657: }
                    658: 
1.1017    raeburn   659: sub javascript_array_indexof {
1.1018    raeburn   660:     return <<ENDJS;
1.1017    raeburn   661: <script type="text/javascript" language="JavaScript">
                    662: // <![CDATA[
                    663: 
                    664: if (!Array.prototype.indexOf) {
                    665:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    666:         "use strict";
                    667:         if (this === void 0 || this === null) {
                    668:             throw new TypeError();
                    669:         }
                    670:         var t = Object(this);
                    671:         var len = t.length >>> 0;
                    672:         if (len === 0) {
                    673:             return -1;
                    674:         }
                    675:         var n = 0;
                    676:         if (arguments.length > 0) {
                    677:             n = Number(arguments[1]);
                    678:             if (n !== n) { // shortcut for verifying if it's NaN
                    679:                 n = 0;
                    680:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    681:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    682:             }
                    683:         }
                    684:         if (n >= len) {
                    685:             return -1;
                    686:         }
                    687:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    688:         for (; k < len; k++) {
                    689:             if (k in t && t[k] === searchElement) {
                    690:                 return k;
                    691:             }
                    692:         }
                    693:         return -1;
                    694:     }
                    695: }
                    696: 
                    697: // ]]>
                    698: </script>
                    699: 
                    700: ENDJS
                    701: 
                    702: }
                    703: 
1.876     raeburn   704: sub userbrowser_javascript {
                    705:     my $id_functions = &javascript_index_functions();
                    706:     return <<"ENDUSERBRW";
                    707: 
1.888     raeburn   708: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   709:     var url = '/adm/pickuser?';
                    710:     var userdom = getDomainFromSelectbox(formname,udom);
                    711:     if (userdom != null) {
                    712:        if (userdom != '') {
                    713:            url += 'srchdom='+userdom+'&';
                    714:        }
                    715:     }
                    716:     url += 'form=' + formname + '&unameelement='+uname+
                    717:                                 '&udomelement='+udom+
                    718:                                 '&ulastelement='+ulast+
                    719:                                 '&ufirstelement='+ufirst+
                    720:                                 '&uemailelement='+uemail+
1.881     raeburn   721:                                 '&hideudomelement='+hideudom+
                    722:                                 '&coursedom='+crsdom;
1.888     raeburn   723:     if ((caller != null) && (caller != undefined)) {
                    724:         url += '&caller='+caller;
                    725:     }
1.876     raeburn   726:     var title = 'User_Browser';
                    727:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    728:     options += ',width=700,height=600';
                    729:     var stdeditbrowser = open(url,title,options,'1');
                    730:     stdeditbrowser.focus();
                    731: }
                    732: 
1.888     raeburn   733: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   734:     var formid = getFormIdByName(formname);
                    735:     if (formid > -1) {
1.888     raeburn   736:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   737:         var domid = getIndexByName(formid,udom);
                    738:         var hidedomid = getIndexByName(formid,origdom);
                    739:         if (hidedomid > -1) {
                    740:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   741:             var unameval = document.forms[formid].elements[unameid].value;
                    742:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    743:                 if (domid > -1) {
                    744:                     var slct = document.forms[formid].elements[domid];
                    745:                     if (slct.type == 'select-one') {
                    746:                         var i;
                    747:                         for (i=0;i<slct.length;i++) {
                    748:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    749:                         }
                    750:                     }
                    751:                     if (slct.type == 'hidden') {
                    752:                         slct.value = fixeddom;
1.876     raeburn   753:                     }
                    754:                 }
1.468     raeburn   755:             }
                    756:         }
                    757:     }
1.876     raeburn   758:     return;
                    759: }
                    760: 
                    761: $id_functions
                    762: ENDUSERBRW
1.468     raeburn   763: }
                    764: 
                    765: sub setsec_javascript {
1.1075.2.31  raeburn   766:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   767:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    768:         $communityrolestr);
                    769:     if ($role_element ne '') {
                    770:         my @allroles = ('st','ta','ep','in','ad');
                    771:         foreach my $crstype ('Course','Community') {
                    772:             if ($crstype eq 'Community') {
                    773:                 foreach my $role (@allroles) {
                    774:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    775:                 }
                    776:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    777:             } else {
                    778:                 foreach my $role (@allroles) {
                    779:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    780:                 }
                    781:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    782:             }
                    783:         }
                    784:         $rolestr = '"'.join('","',@allroles).'"';
                    785:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    786:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    787:     }
1.468     raeburn   788:     my $setsections = qq|
                    789: function setSect(sectionlist) {
1.629     raeburn   790:     var sectionsArray = new Array();
                    791:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    792:         sectionsArray = sectionlist.split(",");
                    793:     }
1.468     raeburn   794:     var numSections = sectionsArray.length;
                    795:     document.$formname.$sec_element.length = 0;
                    796:     if (numSections == 0) {
                    797:         document.$formname.$sec_element.multiple=false;
                    798:         document.$formname.$sec_element.size=1;
                    799:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    800:     } else {
                    801:         if (numSections == 1) {
                    802:             document.$formname.$sec_element.multiple=false;
                    803:             document.$formname.$sec_element.size=1;
                    804:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    805:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    806:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    807:         } else {
                    808:             for (var i=0; i<numSections; i++) {
                    809:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    810:             }
                    811:             document.$formname.$sec_element.multiple=true
                    812:             if (numSections < 3) {
                    813:                 document.$formname.$sec_element.size=numSections;
                    814:             } else {
                    815:                 document.$formname.$sec_element.size=3;
                    816:             }
                    817:             document.$formname.$sec_element.options[0].selected = false
                    818:         }
                    819:     }
1.91      www       820: }
1.905     raeburn   821: 
                    822: function setRole(crstype) {
1.468     raeburn   823: |;
1.905     raeburn   824:     if ($role_element eq '') {
                    825:         $setsections .= '    return;
                    826: }
                    827: ';
                    828:     } else {
                    829:         $setsections .= qq|
                    830:     var elementLength = document.$formname.$role_element.length;
                    831:     var allroles = Array($rolestr);
                    832:     var courserolenames = Array($courserolestr);
                    833:     var communityrolenames = Array($communityrolestr);
                    834:     if (elementLength != undefined) {
                    835:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    836:             if (crstype == 'Course') {
                    837:                 return;
                    838:             } else {
                    839:                 allroles[5] = 'co';
                    840:                 for (var i=0; i<6; i++) {
                    841:                     document.$formname.$role_element.options[i].value = allroles[i];
                    842:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    843:                 }
                    844:             }
                    845:         } else {
                    846:             if (crstype == 'Community') {
                    847:                 return;
                    848:             } else {
                    849:                 allroles[5] = 'cc';
                    850:                 for (var i=0; i<6; i++) {
                    851:                     document.$formname.$role_element.options[i].value = allroles[i];
                    852:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    853:                 }
                    854:             }
                    855:         }
                    856:     }
                    857:     return;
                    858: }
                    859: |;
                    860:     }
1.1075.2.31  raeburn   861:     if ($credits_element) {
                    862:         $setsections .= qq|
                    863: function setCredits(defaultcredits) {
                    864:     document.$formname.$credits_element.value = defaultcredits;
                    865:     return;
                    866: }
                    867: |;
                    868:     }
1.468     raeburn   869:     return $setsections;
                    870: }
                    871: 
1.91      www       872: sub selectcourse_link {
1.909     raeburn   873:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    874:        $typeelement) = @_;
                    875:    my $type = $selecttype;
1.871     raeburn   876:    my $linktext = &mt('Select Course');
                    877:    if ($selecttype eq 'Community') {
1.909     raeburn   878:        $linktext = &mt('Select Community');
1.906     raeburn   879:    } elsif ($selecttype eq 'Course/Community') {
                    880:        $linktext = &mt('Select Course/Community');
1.909     raeburn   881:        $type = '';
1.1019    raeburn   882:    } elsif ($selecttype eq 'Select') {
                    883:        $linktext = &mt('Select');
                    884:        $type = '';
1.871     raeburn   885:    }
1.787     bisitz    886:    return '<span class="LC_nobreak">'
                    887:          ."<a href='"
                    888:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    889:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   890:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   891:          ."'>".$linktext.'</a>'
1.787     bisitz    892:          .'</span>';
1.74      www       893: }
1.42      matthew   894: 
1.653     raeburn   895: sub selectauthor_link {
                    896:    my ($form,$udom)=@_;
                    897:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    898:           &mt('Select Author').'</a>';
                    899: }
                    900: 
1.876     raeburn   901: sub selectuser_link {
1.881     raeburn   902:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   903:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   904:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   905:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   906:            ');">'.$linktext.'</a>';
1.876     raeburn   907: }
                    908: 
1.273     raeburn   909: sub check_uncheck_jscript {
                    910:     my $jscript = <<"ENDSCRT";
                    911: function checkAll(field) {
                    912:     if (field.length > 0) {
                    913:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   914:             if (!field[i].disabled) {
                    915:                 field[i].checked = true;
                    916:             }
1.273     raeburn   917:         }
                    918:     } else {
1.1075.2.14  raeburn   919:         if (!field.disabled) {
                    920:             field.checked = true;
                    921:         }
1.273     raeburn   922:     }
                    923: }
                    924:  
                    925: function uncheckAll(field) {
                    926:     if (field.length > 0) {
                    927:         for (i = 0; i < field.length; i++) {
                    928:             field[i].checked = false ;
1.543     albertel  929:         }
                    930:     } else {
1.273     raeburn   931:         field.checked = false ;
                    932:     }
                    933: }
                    934: ENDSCRT
                    935:     return $jscript;
                    936: }
                    937: 
1.656     www       938: sub select_timezone {
1.659     raeburn   939:    my ($name,$selected,$onchange,$includeempty)=@_;
                    940:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    941:    if ($includeempty) {
                    942:        $output .= '<option value=""';
                    943:        if (($selected eq '') || ($selected eq 'local')) {
                    944:            $output .= ' selected="selected" ';
                    945:        }
                    946:        $output .= '> </option>';
                    947:    }
1.657     raeburn   948:    my @timezones = DateTime::TimeZone->all_names;
                    949:    foreach my $tzone (@timezones) {
                    950:        $output.= '<option value="'.$tzone.'"';
                    951:        if ($tzone eq $selected) {
                    952:            $output.=' selected="selected"';
                    953:        }
                    954:        $output.=">$tzone</option>\n";
1.656     www       955:    }
                    956:    $output.="</select>";
                    957:    return $output;
                    958: }
1.273     raeburn   959: 
1.687     raeburn   960: sub select_datelocale {
                    961:     my ($name,$selected,$onchange,$includeempty)=@_;
                    962:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    963:     if ($includeempty) {
                    964:         $output .= '<option value=""';
                    965:         if ($selected eq '') {
                    966:             $output .= ' selected="selected" ';
                    967:         }
                    968:         $output .= '> </option>';
                    969:     }
1.1075.2.102  raeburn   970:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   971:     my (@possibles,%locale_names);
1.1075.2.102  raeburn   972:     my @locales = DateTime::Locale->ids();
                    973:     foreach my $id (@locales) {
                    974:         if ($id ne '') {
                    975:             my ($en_terr,$native_terr);
                    976:             my $loc = DateTime::Locale->load($id);
                    977:             if (ref($loc)) {
                    978:                 $en_terr = $loc->name();
                    979:                 $native_terr = $loc->native_name();
1.687     raeburn   980:                 if (grep(/^en$/,@languages) || !@languages) {
                    981:                     if ($en_terr ne '') {
                    982:                         $locale_names{$id} = '('.$en_terr.')';
                    983:                     } elsif ($native_terr ne '') {
                    984:                         $locale_names{$id} = $native_terr;
                    985:                     }
                    986:                 } else {
                    987:                     if ($native_terr ne '') {
                    988:                         $locale_names{$id} = $native_terr.' ';
                    989:                     } elsif ($en_terr ne '') {
                    990:                         $locale_names{$id} = '('.$en_terr.')';
                    991:                     }
                    992:                 }
1.1075.2.94  raeburn   993:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1075.2.102  raeburn   994:                 push(@possibles,$id);
1.687     raeburn   995:             }
                    996:         }
                    997:     }
                    998:     foreach my $item (sort(@possibles)) {
                    999:         $output.= '<option value="'.$item.'"';
                   1000:         if ($item eq $selected) {
                   1001:             $output.=' selected="selected"';
                   1002:         }
                   1003:         $output.=">$item";
                   1004:         if ($locale_names{$item} ne '') {
1.1075.2.94  raeburn  1005:             $output.='  '.$locale_names{$item};
1.687     raeburn  1006:         }
                   1007:         $output.="</option>\n";
                   1008:     }
                   1009:     $output.="</select>";
                   1010:     return $output;
                   1011: }
                   1012: 
1.792     raeburn  1013: sub select_language {
                   1014:     my ($name,$selected,$includeempty) = @_;
                   1015:     my %langchoices;
                   1016:     if ($includeempty) {
1.1075.2.32  raeburn  1017:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1018:     }
                   1019:     foreach my $id (&languageids()) {
                   1020:         my $code = &supportedlanguagecode($id);
                   1021:         if ($code) {
                   1022:             $langchoices{$code} = &plainlanguagedescription($id);
                   1023:         }
                   1024:     }
1.1075.2.32  raeburn  1025:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.970     raeburn  1026:     return &select_form($selected,$name,\%langchoices);
1.792     raeburn  1027: }
                   1028: 
1.42      matthew  1029: =pod
1.36      matthew  1030: 
1.648     raeburn  1031: =item * &linked_select_forms(...)
1.36      matthew  1032: 
                   1033: linked_select_forms returns a string containing a <script></script> block
                   1034: and html for two <select> menus.  The select menus will be linked in that
                   1035: changing the value of the first menu will result in new values being placed
                   1036: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1037: order unless a defined order is provided.
1.36      matthew  1038: 
                   1039: linked_select_forms takes the following ordered inputs:
                   1040: 
                   1041: =over 4
                   1042: 
1.112     bowersj2 1043: =item * $formname, the name of the <form> tag
1.36      matthew  1044: 
1.112     bowersj2 1045: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1046: 
1.112     bowersj2 1047: =item * $firstdefault, the default value for the first menu
1.36      matthew  1048: 
1.112     bowersj2 1049: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1050: 
1.112     bowersj2 1051: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1052: 
1.112     bowersj2 1053: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1054: 
1.609     raeburn  1055: =item * $menuorder, the order of values in the first menu
                   1056: 
1.1075.2.31  raeburn  1057: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1058:         event for the first <select> tag
                   1059: 
                   1060: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1061:         event for the second <select> tag
                   1062: 
1.41      ng       1063: =back 
                   1064: 
1.36      matthew  1065: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1066: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1067: values for the first select menu.  The text that coincides with the 
1.41      ng       1068: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1069: and text for the second menu are given in the hash pointed to by 
                   1070: $menu{$choice1}->{'select2'}.  
                   1071: 
1.112     bowersj2 1072:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1073:                        default => "B3",
                   1074:                        select2 => { 
                   1075:                            B1 => "Choice B1",
                   1076:                            B2 => "Choice B2",
                   1077:                            B3 => "Choice B3",
                   1078:                            B4 => "Choice B4"
1.609     raeburn  1079:                            },
                   1080:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1081:                    },
                   1082:                A2 => { text =>"Choice A2" ,
                   1083:                        default => "C2",
                   1084:                        select2 => { 
                   1085:                            C1 => "Choice C1",
                   1086:                            C2 => "Choice C2",
                   1087:                            C3 => "Choice C3"
1.609     raeburn  1088:                            },
                   1089:                        order => ['C2','C1','C3'],
1.112     bowersj2 1090:                    },
                   1091:                A3 => { text =>"Choice A3" ,
                   1092:                        default => "D6",
                   1093:                        select2 => { 
                   1094:                            D1 => "Choice D1",
                   1095:                            D2 => "Choice D2",
                   1096:                            D3 => "Choice D3",
                   1097:                            D4 => "Choice D4",
                   1098:                            D5 => "Choice D5",
                   1099:                            D6 => "Choice D6",
                   1100:                            D7 => "Choice D7"
1.609     raeburn  1101:                            },
                   1102:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1103:                    }
                   1104:                );
1.36      matthew  1105: 
                   1106: =cut
                   1107: 
                   1108: sub linked_select_forms {
                   1109:     my ($formname,
                   1110:         $middletext,
                   1111:         $firstdefault,
                   1112:         $firstselectname,
                   1113:         $secondselectname, 
1.609     raeburn  1114:         $hashref,
                   1115:         $menuorder,
1.1075.2.31  raeburn  1116:         $onchangefirst,
                   1117:         $onchangesecond
1.36      matthew  1118:         ) = @_;
                   1119:     my $second = "document.$formname.$secondselectname";
                   1120:     my $first = "document.$formname.$firstselectname";
                   1121:     # output the javascript to do the changing
                   1122:     my $result = '';
1.776     bisitz   1123:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1124:     $result.="// <![CDATA[\n";
1.36      matthew  1125:     $result.="var select2data = new Object();\n";
                   1126:     $" = '","';
                   1127:     my $debug = '';
                   1128:     foreach my $s1 (sort(keys(%$hashref))) {
                   1129:         $result.="select2data.d_$s1 = new Object();\n";        
                   1130:         $result.="select2data.d_$s1.def = new String('".
                   1131:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1132:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1133:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1134:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1135:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1136:         }
1.36      matthew  1137:         $result.="\"@s2values\");\n";
                   1138:         $result.="select2data.d_$s1.texts = new Array(";        
                   1139:         my @s2texts;
                   1140:         foreach my $value (@s2values) {
                   1141:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                   1142:         }
                   1143:         $result.="\"@s2texts\");\n";
                   1144:     }
                   1145:     $"=' ';
                   1146:     $result.= <<"END";
                   1147: 
                   1148: function select1_changed() {
                   1149:     // Determine new choice
                   1150:     var newvalue = "d_" + $first.value;
                   1151:     // update select2
                   1152:     var values     = select2data[newvalue].values;
                   1153:     var texts      = select2data[newvalue].texts;
                   1154:     var select2def = select2data[newvalue].def;
                   1155:     var i;
                   1156:     // out with the old
                   1157:     for (i = 0; i < $second.options.length; i++) {
                   1158:         $second.options[i] = null;
                   1159:     }
                   1160:     // in with the nuclear
                   1161:     for (i=0;i<values.length; i++) {
                   1162:         $second.options[i] = new Option(values[i]);
1.143     matthew  1163:         $second.options[i].value = values[i];
1.36      matthew  1164:         $second.options[i].text = texts[i];
                   1165:         if (values[i] == select2def) {
                   1166:             $second.options[i].selected = true;
                   1167:         }
                   1168:     }
                   1169: }
1.824     bisitz   1170: // ]]>
1.36      matthew  1171: </script>
                   1172: END
                   1173:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1174:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1175:     my @order = sort(keys(%{$hashref}));
                   1176:     if (ref($menuorder) eq 'ARRAY') {
                   1177:         @order = @{$menuorder};
                   1178:     }
                   1179:     foreach my $value (@order) {
1.36      matthew  1180:         $result.="    <option value=\"$value\" ";
1.253     albertel 1181:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1182:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1183:     }
                   1184:     $result .= "</select>\n";
                   1185:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1186:     $result .= $middletext;
1.1075.2.31  raeburn  1187:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1188:     if ($onchangesecond) {
                   1189:         $result .= ' onchange="'.$onchangesecond.'"';
                   1190:     }
                   1191:     $result .= ">\n";
1.36      matthew  1192:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1193:     
                   1194:     my @secondorder = sort(keys(%select2));
                   1195:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1196:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1197:     }
                   1198:     foreach my $value (@secondorder) {
1.36      matthew  1199:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1200:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1201:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1202:     }
                   1203:     $result .= "</select>\n";
                   1204:     #    return $debug;
                   1205:     return $result;
                   1206: }   #  end of sub linked_select_forms {
                   1207: 
1.45      matthew  1208: =pod
1.44      bowersj2 1209: 
1.973     raeburn  1210: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1211: 
1.112     bowersj2 1212: Returns a string corresponding to an HTML link to the given help
                   1213: $topic, where $topic corresponds to the name of a .tex file in
                   1214: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1215: spaces. 
                   1216: 
                   1217: $text will optionally be linked to the same topic, allowing you to
                   1218: link text in addition to the graphic. If you do not want to link
                   1219: text, but wish to specify one of the later parameters, pass an
                   1220: empty string. 
                   1221: 
                   1222: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1223: the link will not open a new window. If false, the link will open
                   1224: a new window using Javascript. (Default is false.) 
                   1225: 
                   1226: $width and $height are optional numerical parameters that will
                   1227: override the width and height of the popped up window, which may
1.973     raeburn  1228: be useful for certain help topics with big pictures included.
                   1229: 
                   1230: $imgid is the id of the img tag used for the help icon. This may be
                   1231: used in a javascript call to switch the image src.  See 
                   1232: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1233: 
                   1234: =cut
                   1235: 
                   1236: sub help_open_topic {
1.973     raeburn  1237:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1238:     $text = "" if (not defined $text);
1.44      bowersj2 1239:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1240:     $width = 500 if (not defined $width);
1.44      bowersj2 1241:     $height = 400 if (not defined $height);
                   1242:     my $filename = $topic;
                   1243:     $filename =~ s/ /_/g;
                   1244: 
1.48      bowersj2 1245:     my $template = "";
                   1246:     my $link;
1.572     banghart 1247:     
1.159     www      1248:     $topic=~s/\W/\_/g;
1.44      bowersj2 1249: 
1.572     banghart 1250:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1251:         if ($env{'browser.mobile'}) {
                   1252: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1253:         } else {
                   1254:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1255:         }
1.1037    www      1256:     } elsif ($stayOnPage eq 'popup') {
                   1257:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1.572     banghart 1258:     } else {
1.48      bowersj2 1259: 	$link = "/adm/help/${filename}.hlp";
                   1260:     }
                   1261: 
                   1262:     # Add the text
1.755     neumanie 1263:     if ($text ne "") {	
1.763     bisitz   1264: 	$template.='<span class="LC_help_open_topic">'
                   1265:                   .'<a target="_top" href="'.$link.'">'
                   1266:                   .$text.'</a>';
1.48      bowersj2 1267:     }
                   1268: 
1.763     bisitz   1269:     # (Always) Add the graphic
1.179     matthew  1270:     my $title = &mt('Online Help');
1.667     raeburn  1271:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1272:     if ($imgid ne '') {
                   1273:         $imgid = ' id="'.$imgid.'"';
                   1274:     }
1.763     bisitz   1275:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1276:               .'<img src="'.$helpicon.'" border="0"'
                   1277:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1278:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1279:               .' /></a>';
                   1280:     if ($text ne "") {	
                   1281:         $template.='</span>';
                   1282:     }
1.44      bowersj2 1283:     return $template;
                   1284: 
1.106     bowersj2 1285: }
                   1286: 
                   1287: # This is a quicky function for Latex cheatsheet editing, since it 
                   1288: # appears in at least four places
                   1289: sub helpLatexCheatsheet {
1.1037    www      1290:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1291:     my $out;
1.106     bowersj2 1292:     my $addOther = '';
1.732     raeburn  1293:     if ($topic) {
1.1037    www      1294: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1295:     }
                   1296:     $out = '<span>' # Start cheatsheet
                   1297: 	  .$addOther
                   1298:           .'<span>'
1.1037    www      1299: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1300: 	  .'</span> <span>'
1.1037    www      1301: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1302: 	  .'</span>';
1.732     raeburn  1303:     unless ($not_author) {
1.763     bisitz   1304:         $out .= ' <span>'
1.1037    www      1305: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1306: 	       .'</span> <span>'
1.1075.2.78  raeburn  1307:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1308:                .'</span>';
1.732     raeburn  1309:     }
1.763     bisitz   1310:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1311:     return $out;
1.172     www      1312: }
                   1313: 
1.430     albertel 1314: sub general_help {
                   1315:     my $helptopic='Student_Intro';
                   1316:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1317: 	$helptopic='Authoring_Intro';
1.907     raeburn  1318:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1319: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1320:     } elsif ($env{'request.role'}=~/^dc/) {
                   1321:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1322:     }
                   1323:     return $helptopic;
                   1324: }
                   1325: 
                   1326: sub update_help_link {
                   1327:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1328:     my $origurl = $ENV{'REQUEST_URI'};
                   1329:     $origurl=~s|^/~|/priv/|;
                   1330:     my $timestamp = time;
                   1331:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1332:         $$datum = &escape($$datum);
                   1333:     }
                   1334: 
                   1335:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
                   1336:     my $output .= <<"ENDOUTPUT";
                   1337: <script type="text/javascript">
1.824     bisitz   1338: // <![CDATA[
1.430     albertel 1339: banner_link = '$banner_link';
1.824     bisitz   1340: // ]]>
1.430     albertel 1341: </script>
                   1342: ENDOUTPUT
                   1343:     return $output;
                   1344: }
                   1345: 
                   1346: # now just updates the help link and generates a blue icon
1.193     raeburn  1347: sub help_open_menu {
1.430     albertel 1348:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1349: 	= @_;    
1.949     droeschl 1350:     $stayOnPage = 1;
1.430     albertel 1351:     my $output;
                   1352:     if ($component_help) {
                   1353: 	if (!$text) {
                   1354: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1355: 				       $width,$height);
                   1356: 	} else {
                   1357: 	    my $help_text;
                   1358: 	    $help_text=&unescape($topic);
                   1359: 	    $output='<table><tr><td>'.
                   1360: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1361: 				 $width,$height).'</td></tr></table>';
                   1362: 	}
                   1363:     }
                   1364:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1365:     return $output.$banner_link;
                   1366: }
                   1367: 
                   1368: sub top_nav_help {
                   1369:     my ($text) = @_;
1.436     albertel 1370:     $text = &mt($text);
1.1075.2.60  raeburn  1371:     my $stay_on_page;
                   1372:     unless ($env{'environment.remote'} eq 'on') {
                   1373:         $stay_on_page = 1;
                   1374:     }
1.1075.2.61  raeburn  1375:     my ($link,$banner_link);
                   1376:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1377:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1378: 	                         : "javascript:helpMenu('open')";
                   1379:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1380:     }
1.201     raeburn  1381:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1382:     if ($link) {
                   1383:         return <<"END";
1.436     albertel 1384: $banner_link
1.1075.2.56  raeburn  1385: <a href="$link" title="$title">$text</a>
1.436     albertel 1386: END
1.1075.2.61  raeburn  1387:     } else {
                   1388:         return '&nbsp;'.$text.'&nbsp;';
                   1389:     }
1.436     albertel 1390: }
                   1391: 
                   1392: sub help_menu_js {
1.1075.2.52  raeburn  1393:     my ($httphost) = @_;
1.949     droeschl 1394:     my $stayOnPage = 1;
1.436     albertel 1395:     my $width = 620;
                   1396:     my $height = 600;
1.430     albertel 1397:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1398:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1399:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1400:     my $start_page =
                   1401:         &Apache::loncommon::start_page('Help Menu', undef,
                   1402: 				       {'frameset'    => 1,
                   1403: 					'js_ready'    => 1,
1.1075.2.52  raeburn  1404:                                         'use_absolute' => $httphost, 
1.331     albertel 1405: 					'add_entries' => {
                   1406: 					    'border' => '0',
1.579     raeburn  1407: 					    'rows'   => "110,*",},});
1.331     albertel 1408:     my $end_page =
                   1409:         &Apache::loncommon::end_page({'frameset' => 1,
                   1410: 				      'js_ready' => 1,});
                   1411: 
1.436     albertel 1412:     my $template .= <<"ENDTEMPLATE";
                   1413: <script type="text/javascript">
1.877     bisitz   1414: // <![CDATA[
1.253     albertel 1415: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1416: var banner_link = '';
1.243     raeburn  1417: function helpMenu(target) {
                   1418:     var caller = this;
                   1419:     if (target == 'open') {
                   1420:         var newWindow = null;
                   1421:         try {
1.262     albertel 1422:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1423:         }
                   1424:         catch(error) {
                   1425:             writeHelp(caller);
                   1426:             return;
                   1427:         }
                   1428:         if (newWindow) {
                   1429:             caller = newWindow;
                   1430:         }
1.193     raeburn  1431:     }
1.243     raeburn  1432:     writeHelp(caller);
                   1433:     return;
                   1434: }
                   1435: function writeHelp(caller) {
1.1075.2.61  raeburn  1436:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1437:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1438:     caller.document.close();
                   1439:     caller.focus();
1.193     raeburn  1440: }
1.877     bisitz   1441: // END LON-CAPA Internal -->
1.253     albertel 1442: // ]]>
1.436     albertel 1443: </script>
1.193     raeburn  1444: ENDTEMPLATE
                   1445:     return $template;
                   1446: }
                   1447: 
1.172     www      1448: sub help_open_bug {
                   1449:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1450:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1451:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1452:     $text = "" if (not defined $text);
                   1453: 	$stayOnPage=1;
1.184     albertel 1454:     $width = 600 if (not defined $width);
                   1455:     $height = 600 if (not defined $height);
1.172     www      1456: 
                   1457:     $topic=~s/\W+/\+/g;
                   1458:     my $link='';
                   1459:     my $template='';
1.379     albertel 1460:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1461: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1462:     if (!$stayOnPage)
                   1463:     {
                   1464: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1465:     }
                   1466:     else
                   1467:     {
                   1468: 	$link = $url;
                   1469:     }
                   1470:     # Add the text
                   1471:     if ($text ne "")
                   1472:     {
                   1473: 	$template .= 
                   1474:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1475:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1476:     }
                   1477: 
                   1478:     # Add the graphic
1.179     matthew  1479:     my $title = &mt('Report a Bug');
1.215     albertel 1480:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1481:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1482:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1483: ENDTEMPLATE
                   1484:     if ($text ne '') { $template.='</td></tr></table>' };
                   1485:     return $template;
                   1486: 
                   1487: }
                   1488: 
                   1489: sub help_open_faq {
                   1490:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1491:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1492:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1493:     $text = "" if (not defined $text);
                   1494: 	$stayOnPage=1;
                   1495:     $width = 350 if (not defined $width);
                   1496:     $height = 400 if (not defined $height);
                   1497: 
                   1498:     $topic=~s/\W+/\+/g;
                   1499:     my $link='';
                   1500:     my $template='';
                   1501:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1502:     if (!$stayOnPage)
                   1503:     {
                   1504: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1505:     }
                   1506:     else
                   1507:     {
                   1508: 	$link = $url;
                   1509:     }
                   1510: 
                   1511:     # Add the text
                   1512:     if ($text ne "")
                   1513:     {
                   1514: 	$template .= 
1.173     www      1515:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1516:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1517:     }
                   1518: 
                   1519:     # Add the graphic
1.179     matthew  1520:     my $title = &mt('View the FAQ');
1.215     albertel 1521:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1522:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1523:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1524: ENDTEMPLATE
                   1525:     if ($text ne '') { $template.='</td></tr></table>' };
                   1526:     return $template;
                   1527: 
1.44      bowersj2 1528: }
1.37      matthew  1529: 
1.180     matthew  1530: ###############################################################
                   1531: ###############################################################
                   1532: 
1.45      matthew  1533: =pod
                   1534: 
1.648     raeburn  1535: =item * &change_content_javascript():
1.256     matthew  1536: 
                   1537: This and the next function allow you to create small sections of an
                   1538: otherwise static HTML page that you can update on the fly with
                   1539: Javascript, even in Netscape 4.
                   1540: 
                   1541: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1542: must be written to the HTML page once. It will prove the Javascript
                   1543: function "change(name, content)". Calling the change function with the
                   1544: name of the section 
                   1545: you want to update, matching the name passed to C<changable_area>, and
                   1546: the new content you want to put in there, will put the content into
                   1547: that area.
                   1548: 
                   1549: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1550: to contain room for the original contents. You need to "make space"
                   1551: for whatever changes you wish to make, and be B<sure> to check your
                   1552: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1553: it's adequate for updating a one-line status display, but little more.
                   1554: This script will set the space to 100% width, so you only need to
                   1555: worry about height in Netscape 4.
                   1556: 
                   1557: Modern browsers are much less limiting, and if you can commit to the
                   1558: user not using Netscape 4, this feature may be used freely with
                   1559: pretty much any HTML.
                   1560: 
                   1561: =cut
                   1562: 
                   1563: sub change_content_javascript {
                   1564:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1565:     if ($env{'browser.type'} eq 'netscape' &&
                   1566: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1567: 	return (<<NETSCAPE4);
                   1568: 	function change(name, content) {
                   1569: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1570: 	    doc.open();
                   1571: 	    doc.write(content);
                   1572: 	    doc.close();
                   1573: 	}
                   1574: NETSCAPE4
                   1575:     } else {
                   1576: 	# Otherwise, we need to use semi-standards-compliant code
                   1577: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1578: 	# is really scary, and every useful browser supports it
                   1579: 	return (<<DOMBASED);
                   1580: 	function change(name, content) {
                   1581: 	    element = document.getElementById(name);
                   1582: 	    element.innerHTML = content;
                   1583: 	}
                   1584: DOMBASED
                   1585:     }
                   1586: }
                   1587: 
                   1588: =pod
                   1589: 
1.648     raeburn  1590: =item * &changable_area($name,$origContent):
1.256     matthew  1591: 
                   1592: This provides a "changable area" that can be modified on the fly via
                   1593: the Javascript code provided in C<change_content_javascript>. $name is
                   1594: the name you will use to reference the area later; do not repeat the
                   1595: same name on a given HTML page more then once. $origContent is what
                   1596: the area will originally contain, which can be left blank.
                   1597: 
                   1598: =cut
                   1599: 
                   1600: sub changable_area {
                   1601:     my ($name, $origContent) = @_;
                   1602: 
1.258     albertel 1603:     if ($env{'browser.type'} eq 'netscape' &&
                   1604: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1605: 	# If this is netscape 4, we need to use the Layer tag
                   1606: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1607:     } else {
                   1608: 	return "<span id='$name'>$origContent</span>";
                   1609:     }
                   1610: }
                   1611: 
                   1612: =pod
                   1613: 
1.648     raeburn  1614: =item * &viewport_geometry_js 
1.590     raeburn  1615: 
                   1616: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1617: 
                   1618: =cut
                   1619: 
                   1620: 
                   1621: sub viewport_geometry_js { 
                   1622:     return <<"GEOMETRY";
                   1623: var Geometry = {};
                   1624: function init_geometry() {
                   1625:     if (Geometry.init) { return };
                   1626:     Geometry.init=1;
                   1627:     if (window.innerHeight) {
                   1628:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1629:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1630:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1631:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1632:     }
                   1633:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1634:         Geometry.getViewportHeight =
                   1635:             function() { return document.documentElement.clientHeight; };
                   1636:         Geometry.getViewportWidth =
                   1637:             function() { return document.documentElement.clientWidth; };
                   1638: 
                   1639:         Geometry.getHorizontalScroll =
                   1640:             function() { return document.documentElement.scrollLeft; };
                   1641:         Geometry.getVerticalScroll =
                   1642:             function() { return document.documentElement.scrollTop; };
                   1643:     }
                   1644:     else if (document.body.clientHeight) {
                   1645:         Geometry.getViewportHeight =
                   1646:             function() { return document.body.clientHeight; };
                   1647:         Geometry.getViewportWidth =
                   1648:             function() { return document.body.clientWidth; };
                   1649:         Geometry.getHorizontalScroll =
                   1650:             function() { return document.body.scrollLeft; };
                   1651:         Geometry.getVerticalScroll =
                   1652:             function() { return document.body.scrollTop; };
                   1653:     }
                   1654: }
                   1655: 
                   1656: GEOMETRY
                   1657: }
                   1658: 
                   1659: =pod
                   1660: 
1.648     raeburn  1661: =item * &viewport_size_js()
1.590     raeburn  1662: 
                   1663: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
                   1664: 
                   1665: =cut
                   1666: 
                   1667: sub viewport_size_js {
                   1668:     my $geometry = &viewport_geometry_js();
                   1669:     return <<"DIMS";
                   1670: 
                   1671: $geometry
                   1672: 
                   1673: function getViewportDims(width,height) {
                   1674:     init_geometry();
                   1675:     width.value = Geometry.getViewportWidth();
                   1676:     height.value = Geometry.getViewportHeight();
                   1677:     return;
                   1678: }
                   1679: 
                   1680: DIMS
                   1681: }
                   1682: 
                   1683: =pod
                   1684: 
1.648     raeburn  1685: =item * &resize_textarea_js()
1.565     albertel 1686: 
                   1687: emits the needed javascript to resize a textarea to be as big as possible
                   1688: 
                   1689: creates a function resize_textrea that takes two IDs first should be
                   1690: the id of the element to resize, second should be the id of a div that
                   1691: surrounds everything that comes after the textarea, this routine needs
                   1692: to be attached to the <body> for the onload and onresize events.
                   1693: 
1.648     raeburn  1694: =back
1.565     albertel 1695: 
                   1696: =cut
                   1697: 
                   1698: sub resize_textarea_js {
1.590     raeburn  1699:     my $geometry = &viewport_geometry_js();
1.565     albertel 1700:     return <<"RESIZE";
                   1701:     <script type="text/javascript">
1.824     bisitz   1702: // <![CDATA[
1.590     raeburn  1703: $geometry
1.565     albertel 1704: 
1.588     albertel 1705: function getX(element) {
                   1706:     var x = 0;
                   1707:     while (element) {
                   1708: 	x += element.offsetLeft;
                   1709: 	element = element.offsetParent;
                   1710:     }
                   1711:     return x;
                   1712: }
                   1713: function getY(element) {
                   1714:     var y = 0;
                   1715:     while (element) {
                   1716: 	y += element.offsetTop;
                   1717: 	element = element.offsetParent;
                   1718:     }
                   1719:     return y;
                   1720: }
                   1721: 
                   1722: 
1.565     albertel 1723: function resize_textarea(textarea_id,bottom_id) {
                   1724:     init_geometry();
                   1725:     var textarea        = document.getElementById(textarea_id);
                   1726:     //alert(textarea);
                   1727: 
1.588     albertel 1728:     var textarea_top    = getY(textarea);
1.565     albertel 1729:     var textarea_height = textarea.offsetHeight;
                   1730:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1731:     var bottom_top      = getY(bottom);
1.565     albertel 1732:     var bottom_height   = bottom.offsetHeight;
                   1733:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1734:     var fudge           = 23;
1.565     albertel 1735:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1736:     if (new_height < 300) {
                   1737: 	new_height = 300;
                   1738:     }
                   1739:     textarea.style.height=new_height+'px';
                   1740: }
1.824     bisitz   1741: // ]]>
1.565     albertel 1742: </script>
                   1743: RESIZE
                   1744: 
                   1745: }
                   1746: 
1.1075.2.112! raeburn  1747: sub colorfuleditor_js {
        !          1748:     return <<"COLORFULEDIT"
        !          1749: <script type="text/javascript">
        !          1750: // <![CDATA[>
        !          1751:     function fold_box(curDepth, lastresource){
        !          1752: 
        !          1753:     // we need a list because there can be several blocks you need to fold in one tag
        !          1754:         var block = document.getElementsByName('foldblock_'+curDepth);
        !          1755:     // but there is only one folding button per tag
        !          1756:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
        !          1757: 
        !          1758:         if(block.item(0).style.display == 'none'){
        !          1759: 
        !          1760:             foldbutton.value = '@{[&mt("Hide")]}';
        !          1761:             for (i = 0; i < block.length; i++){
        !          1762:                 block.item(i).style.display = '';
        !          1763:             }
        !          1764:         }else{
        !          1765: 
        !          1766:             foldbutton.value = '@{[&mt("Show")]}';
        !          1767:             for (i = 0; i < block.length; i++){
        !          1768:                 // block.item(i).style.visibility = 'collapse';
        !          1769:                 block.item(i).style.display = 'none';
        !          1770:             }
        !          1771:         };
        !          1772:         saveState(lastresource);
        !          1773:     }
        !          1774: 
        !          1775:     function saveState (lastresource) {
        !          1776: 
        !          1777:         var tag_list = getTagList();
        !          1778:         if(tag_list != null){
        !          1779:             var timestamp = new Date().getTime();
        !          1780:             var key = lastresource;
        !          1781: 
        !          1782:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
        !          1783:             // starting with timestamp
        !          1784:             var value = timestamp+';';
        !          1785: 
        !          1786:             // building the list of key-value pairs
        !          1787:             for(var i = 0; i < tag_list.length; i++){
        !          1788:                 value += tag_list[i]+',';
        !          1789:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
        !          1790:             }
        !          1791: 
        !          1792:             // only iterate whole storage if nothing to override
        !          1793:             if(localStorage.getItem(key) == null){
        !          1794: 
        !          1795:                 // prevent storage from growing large
        !          1796:                 if(localStorage.length > 50){
        !          1797:                     var regex_getTimestamp = /^(?:\d)+;/;
        !          1798:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
        !          1799:                     var oldest_key;
        !          1800: 
        !          1801:                     for(var i = 1; i < localStorage.length; i++){
        !          1802:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
        !          1803:                             oldest_key = localStorage.key(i);
        !          1804:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
        !          1805:                         }
        !          1806:                     }
        !          1807:                     localStorage.removeItem(oldest_key);
        !          1808:                 }
        !          1809:             }
        !          1810:             localStorage.setItem(key,value);
        !          1811:         }
        !          1812:     }
        !          1813: 
        !          1814:     // restore folding status of blocks (on page load)
        !          1815:     function restoreState (lastresource) {
        !          1816:         if(localStorage.getItem(lastresource) != null){
        !          1817:             var key = lastresource;
        !          1818:             var value = localStorage.getItem(key);
        !          1819:             var regex_delTimestamp = /^\d+;/;
        !          1820: 
        !          1821:             value.replace(regex_delTimestamp, '');
        !          1822: 
        !          1823:             var valueArr = value.split(';');
        !          1824:             var pairs;
        !          1825:             var elements;
        !          1826:             for (var i = 0; i < valueArr.length; i++){
        !          1827:                 pairs = valueArr[i].split(',');
        !          1828:                 elements = document.getElementsByName(pairs[0]);
        !          1829: 
        !          1830:                 for (var j = 0; j < elements.length; j++){
        !          1831:                     elements[j].style.display = pairs[1];
        !          1832:                     if (pairs[1] == "none"){
        !          1833:                         var regex_id = /([_\\d]+)\$/;
        !          1834:                         regex_id.exec(pairs[0]);
        !          1835:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
        !          1836:                     }
        !          1837:                 }
        !          1838:             }
        !          1839:         }
        !          1840:     }
        !          1841: 
        !          1842:     function getTagList () {
        !          1843: 
        !          1844:         var stringToSearch = document.lonhomework.innerHTML;
        !          1845: 
        !          1846:         var ret = new Array();
        !          1847:         var regex_findBlock = /(foldblock_.*?)"/g;
        !          1848:         var tag_list = stringToSearch.match(regex_findBlock);
        !          1849: 
        !          1850:         if(tag_list != null){
        !          1851:             for(var i = 0; i < tag_list.length; i++){
        !          1852:                 ret.push(tag_list[i].replace(/"/, ''));
        !          1853:             }
        !          1854:         }
        !          1855:         return ret;
        !          1856:     }
        !          1857: 
        !          1858:     function saveScrollPosition (resource) {
        !          1859:         var tag_list = getTagList();
        !          1860: 
        !          1861:         // we dont always want to jump to the first block
        !          1862:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
        !          1863:         if(\$(window).scrollTop() > 170){
        !          1864:             if(tag_list != null){
        !          1865:                 var result;
        !          1866:                 for(var i = 0; i < tag_list.length; i++){
        !          1867:                     if(isElementInViewport(tag_list[i])){
        !          1868:                         result += tag_list[i]+';';
        !          1869:                     }
        !          1870:                 }
        !          1871:                 sessionStorage.setItem('anchor_'+resource, result);
        !          1872:             }
        !          1873:         } else {
        !          1874:             // we dont need to save zero, just delete the item to leave everything tidy
        !          1875:             sessionStorage.removeItem('anchor_'+resource);
        !          1876:         }
        !          1877:     }
        !          1878: 
        !          1879:     function restoreScrollPosition(resource){
        !          1880: 
        !          1881:         var elem = sessionStorage.getItem('anchor_'+resource);
        !          1882:         if(elem != null){
        !          1883:             var tag_list = elem.split(';');
        !          1884:             var elem_list;
        !          1885: 
        !          1886:             for(var i = 0; i < tag_list.length; i++){
        !          1887:                 elem_list = document.getElementsByName(tag_list[i]);
        !          1888: 
        !          1889:                 if(elem_list.length > 0){
        !          1890:                     elem = elem_list[0];
        !          1891:                     break;
        !          1892:                 }
        !          1893:             }
        !          1894:             elem.scrollIntoView();
        !          1895:         }
        !          1896:     }
        !          1897: 
        !          1898:     function isElementInViewport(el) {
        !          1899: 
        !          1900:         // change to last element instead of first
        !          1901:         var elem = document.getElementsByName(el);
        !          1902:         var rect = elem[0].getBoundingClientRect();
        !          1903: 
        !          1904:         return (
        !          1905:             rect.top >= 0 &&
        !          1906:             rect.left >= 0 &&
        !          1907:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
        !          1908:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
        !          1909:         );
        !          1910:     }
        !          1911: 
        !          1912:     function autosize(depth){
        !          1913:         var cmInst = window['cm'+depth];
        !          1914:         var fitsizeButton = document.getElementById('fitsize'+depth);
        !          1915: 
        !          1916:         // is fixed size, switching to dynamic
        !          1917:         if (sessionStorage.getItem("autosized_"+depth) == null) {
        !          1918:             cmInst.setSize("","auto");
        !          1919:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
        !          1920:             sessionStorage.setItem("autosized_"+depth, "yes");
        !          1921: 
        !          1922:         // is dynamic size, switching to fixed
        !          1923:         } else {
        !          1924:             cmInst.setSize("","300px");
        !          1925:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
        !          1926:             sessionStorage.removeItem("autosized_"+depth);
        !          1927:         }
        !          1928:     }
        !          1929: 
        !          1930: 
        !          1931: 
        !          1932: // ]]>
        !          1933: </script>
        !          1934: COLORFULEDIT
        !          1935: }
        !          1936: 
        !          1937: sub xmleditor_js {
        !          1938:     return <<XMLEDIT
        !          1939: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
        !          1940: <script type="text/javascript">
        !          1941: // <![CDATA[>
        !          1942: 
        !          1943:     function saveScrollPosition (resource) {
        !          1944: 
        !          1945:         var scrollPos = \$(window).scrollTop();
        !          1946:         sessionStorage.setItem(resource,scrollPos);
        !          1947:     }
        !          1948: 
        !          1949:     function restoreScrollPosition(resource){
        !          1950: 
        !          1951:         var scrollPos = sessionStorage.getItem(resource);
        !          1952:         \$(window).scrollTop(scrollPos);
        !          1953:     }
        !          1954: 
        !          1955:     // unless internet explorer
        !          1956:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
        !          1957: 
        !          1958:         \$(document).ready(function() {
        !          1959:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
        !          1960:         });
        !          1961:     }
        !          1962: 
        !          1963:     // inserts text at cursor position into codemirror (xml editor only)
        !          1964:     function insertText(text){
        !          1965:         cm.focus();
        !          1966:         var curPos = cm.getCursor();
        !          1967:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
        !          1968:     }
        !          1969: // ]]>
        !          1970: </script>
        !          1971: XMLEDIT
        !          1972: }
        !          1973: 
        !          1974: sub insert_folding_button {
        !          1975:     my $curDepth = $Apache::lonxml::curdepth;
        !          1976:     my $lastresource = $env{'request.ambiguous'};
        !          1977: 
        !          1978:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
        !          1979:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
        !          1980: }
        !          1981: 
        !          1982: 
1.565     albertel 1983: =pod
                   1984: 
1.256     matthew  1985: =head1 Excel and CSV file utility routines
                   1986: 
                   1987: =cut
                   1988: 
                   1989: ###############################################################
                   1990: ###############################################################
                   1991: 
                   1992: =pod
                   1993: 
1.1075.2.56  raeburn  1994: =over 4
                   1995: 
1.648     raeburn  1996: =item * &csv_translate($text) 
1.37      matthew  1997: 
1.185     www      1998: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  1999: format.
                   2000: 
                   2001: =cut
                   2002: 
1.180     matthew  2003: ###############################################################
                   2004: ###############################################################
1.37      matthew  2005: sub csv_translate {
                   2006:     my $text = shift;
                   2007:     $text =~ s/\"/\"\"/g;
1.209     albertel 2008:     $text =~ s/\n/ /g;
1.37      matthew  2009:     return $text;
                   2010: }
1.180     matthew  2011: 
                   2012: ###############################################################
                   2013: ###############################################################
                   2014: 
                   2015: =pod
                   2016: 
1.648     raeburn  2017: =item * &define_excel_formats()
1.180     matthew  2018: 
                   2019: Define some commonly used Excel cell formats.
                   2020: 
                   2021: Currently supported formats:
                   2022: 
                   2023: =over 4
                   2024: 
                   2025: =item header
                   2026: 
                   2027: =item bold
                   2028: 
                   2029: =item h1
                   2030: 
                   2031: =item h2
                   2032: 
                   2033: =item h3
                   2034: 
1.256     matthew  2035: =item h4
                   2036: 
                   2037: =item i
                   2038: 
1.180     matthew  2039: =item date
                   2040: 
                   2041: =back
                   2042: 
                   2043: Inputs: $workbook
                   2044: 
                   2045: Returns: $format, a hash reference.
                   2046: 
1.1057    foxr     2047: 
1.180     matthew  2048: =cut
                   2049: 
                   2050: ###############################################################
                   2051: ###############################################################
                   2052: sub define_excel_formats {
                   2053:     my ($workbook) = @_;
                   2054:     my $format;
                   2055:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2056:                                                 bottom    => 1,
                   2057:                                                 align     => 'center');
                   2058:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2059:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2060:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2061:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2062:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2063:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2064:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2065:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2066:     return $format;
                   2067: }
                   2068: 
                   2069: ###############################################################
                   2070: ###############################################################
1.113     bowersj2 2071: 
                   2072: =pod
                   2073: 
1.648     raeburn  2074: =item * &create_workbook()
1.255     matthew  2075: 
                   2076: Create an Excel worksheet.  If it fails, output message on the
                   2077: request object and return undefs.
                   2078: 
                   2079: Inputs: Apache request object
                   2080: 
                   2081: Returns (undef) on failure, 
                   2082:     Excel worksheet object, scalar with filename, and formats 
                   2083:     from &Apache::loncommon::define_excel_formats on success
                   2084: 
                   2085: =cut
                   2086: 
                   2087: ###############################################################
                   2088: ###############################################################
                   2089: sub create_workbook {
                   2090:     my ($r) = @_;
                   2091:         #
                   2092:     # Create the excel spreadsheet
                   2093:     my $filename = '/prtspool/'.
1.258     albertel 2094:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2095:         time.'_'.rand(1000000000).'.xls';
                   2096:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2097:     if (! defined($workbook)) {
                   2098:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2099:         $r->print(
                   2100:             '<p class="LC_error">'
                   2101:            .&mt('Problems occurred in creating the new Excel file.')
                   2102:            .' '.&mt('This error has been logged.')
                   2103:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2104:            .'</p>'
                   2105:         );
1.255     matthew  2106:         return (undef);
                   2107:     }
                   2108:     #
1.1014    foxr     2109:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2110:     #
                   2111:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2112:     return ($workbook,$filename,$format);
                   2113: }
                   2114: 
                   2115: ###############################################################
                   2116: ###############################################################
                   2117: 
                   2118: =pod
                   2119: 
1.648     raeburn  2120: =item * &create_text_file()
1.113     bowersj2 2121: 
1.542     raeburn  2122: Create a file to write to and eventually make available to the user.
1.256     matthew  2123: If file creation fails, outputs an error message on the request object and 
                   2124: return undefs.
1.113     bowersj2 2125: 
1.256     matthew  2126: Inputs: Apache request object, and file suffix
1.113     bowersj2 2127: 
1.256     matthew  2128: Returns (undef) on failure, 
                   2129:     Filehandle and filename on success.
1.113     bowersj2 2130: 
                   2131: =cut
                   2132: 
1.256     matthew  2133: ###############################################################
                   2134: ###############################################################
                   2135: sub create_text_file {
                   2136:     my ($r,$suffix) = @_;
                   2137:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2138:     my $fh;
                   2139:     my $filename = '/prtspool/'.
1.258     albertel 2140:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2141:         time.'_'.rand(1000000000).'.'.$suffix;
                   2142:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2143:     if (! defined($fh)) {
                   2144:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2145:         $r->print(
                   2146:             '<p class="LC_error">'
                   2147:            .&mt('Problems occurred in creating the output file.')
                   2148:            .' '.&mt('This error has been logged.')
                   2149:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2150:            .'</p>'
                   2151:         );
1.113     bowersj2 2152:     }
1.256     matthew  2153:     return ($fh,$filename)
1.113     bowersj2 2154: }
                   2155: 
                   2156: 
1.256     matthew  2157: =pod 
1.113     bowersj2 2158: 
                   2159: =back
                   2160: 
                   2161: =cut
1.37      matthew  2162: 
                   2163: ###############################################################
1.33      matthew  2164: ##        Home server <option> list generating code          ##
                   2165: ###############################################################
1.35      matthew  2166: 
1.169     www      2167: # ------------------------------------------
                   2168: 
                   2169: sub domain_select {
                   2170:     my ($name,$value,$multiple)=@_;
                   2171:     my %domains=map { 
1.514     albertel 2172: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2173:     } &Apache::lonnet::all_domains();
1.169     www      2174:     if ($multiple) {
                   2175: 	$domains{''}=&mt('Any domain');
1.550     albertel 2176: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2177: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2178:     } else {
1.550     albertel 2179: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2180: 	return &select_form($name,$value,\%domains);
1.169     www      2181:     }
                   2182: }
                   2183: 
1.282     albertel 2184: #-------------------------------------------
                   2185: 
                   2186: =pod
                   2187: 
1.519     raeburn  2188: =head1 Routines for form select boxes
                   2189: 
                   2190: =over 4
                   2191: 
1.648     raeburn  2192: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2193: 
                   2194: Returns a string containing a <select> element int multiple mode
                   2195: 
                   2196: 
                   2197: Args:
                   2198:   $name - name of the <select> element
1.506     raeburn  2199:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2200:   $size - number of rows long the select element is
1.283     albertel 2201:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2202:           (shown text should already have been &mt())
1.506     raeburn  2203:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2204: 
1.282     albertel 2205: =cut
                   2206: 
                   2207: #-------------------------------------------
1.169     www      2208: sub multiple_select_form {
1.284     albertel 2209:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2210:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2211:     my $output='';
1.191     matthew  2212:     if (! defined($size)) {
                   2213:         $size = 4;
1.283     albertel 2214:         if (scalar(keys(%$hash))<4) {
                   2215:             $size = scalar(keys(%$hash));
1.191     matthew  2216:         }
                   2217:     }
1.734     bisitz   2218:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2219:     my @order;
1.506     raeburn  2220:     if (ref($order) eq 'ARRAY')  {
                   2221:         @order = @{$order};
                   2222:     } else {
                   2223:         @order = sort(keys(%$hash));
1.501     banghart 2224:     }
                   2225:     if (exists($$hash{'select_form_order'})) {
                   2226:         @order = @{$$hash{'select_form_order'}};
                   2227:     }
                   2228:         
1.284     albertel 2229:     foreach my $key (@order) {
1.356     albertel 2230:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2231:         $output.='selected="selected" ' if ($selected{$key});
                   2232:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2233:     }
                   2234:     $output.="</select>\n";
                   2235:     return $output;
                   2236: }
                   2237: 
1.88      www      2238: #-------------------------------------------
                   2239: 
                   2240: =pod
                   2241: 
1.970     raeburn  2242: =item * &select_form($defdom,$name,$hashref,$onchange)
1.88      www      2243: 
                   2244: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2245: allow a user to select options from a ref to a hash containing:
                   2246: option_name => displayed text. An optional $onchange can include
                   2247: a javascript onchange item, e.g., onchange="this.form.submit();"  
                   2248: 
1.88      www      2249: See lonrights.pm for an example invocation and use.
                   2250: 
                   2251: =cut
                   2252: 
                   2253: #-------------------------------------------
                   2254: sub select_form {
1.970     raeburn  2255:     my ($def,$name,$hashref,$onchange) = @_;
                   2256:     return unless (ref($hashref) eq 'HASH');
                   2257:     if ($onchange) {
                   2258:         $onchange = ' onchange="'.$onchange.'"';
                   2259:     }
                   2260:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.128     albertel 2261:     my @keys;
1.970     raeburn  2262:     if (exists($hashref->{'select_form_order'})) {
                   2263: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2264:     } else {
1.970     raeburn  2265: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2266:     }
1.356     albertel 2267:     foreach my $key (@keys) {
                   2268:         $selectform.=
                   2269: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2270:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2271:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2272:     }
                   2273:     $selectform.="</select>";
                   2274:     return $selectform;
                   2275: }
                   2276: 
1.475     www      2277: # For display filters
                   2278: 
                   2279: sub display_filter {
1.1074    raeburn  2280:     my ($context) = @_;
1.475     www      2281:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2282:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2283:     my $phraseinput = 'hidden';
                   2284:     my $includeinput = 'hidden';
                   2285:     my ($checked,$includetypestext);
                   2286:     if ($env{'form.displayfilter'} eq 'containing') {
                   2287:         $phraseinput = 'text'; 
                   2288:         if ($context eq 'parmslog') {
                   2289:             $includeinput = 'checkbox';
                   2290:             if ($env{'form.includetypes'}) {
                   2291:                 $checked = ' checked="checked"';
                   2292:             }
                   2293:             $includetypestext = &mt('Include parameter types');
                   2294:         }
                   2295:     } else {
                   2296:         $includetypestext = '&nbsp;';
                   2297:     }
                   2298:     my ($additional,$secondid,$thirdid);
                   2299:     if ($context eq 'parmslog') {
                   2300:         $additional = 
                   2301:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2302:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2303:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2304:             '</label>';
                   2305:         $secondid = 'includetypes';
                   2306:         $thirdid = 'includetypestext';
                   2307:     }
                   2308:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2309:                                                     '$secondid','$thirdid')";
                   2310:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2311: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2312: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2313: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2314:            &mt('Filter: [_1]',
1.477     www      2315: 	   &select_form($env{'form.displayfilter'},
                   2316: 			'displayfilter',
1.970     raeburn  2317: 			{'currentfolder' => 'Current folder/page',
1.477     www      2318: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2319: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2320: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2321:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2322:                          '" />'.$additional;
                   2323: }
                   2324: 
                   2325: sub display_filter_js {
                   2326:     my $includetext = &mt('Include parameter types');
                   2327:     return <<"ENDJS";
                   2328:   
                   2329: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2330:     var firstType = 'hidden';
                   2331:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2332:         firstType = 'text';
                   2333:     }
                   2334:     firstObject = document.getElementById(firstid);
                   2335:     if (typeof(firstObject) == 'object') {
                   2336:         if (firstObject.type != firstType) {
                   2337:             changeInputType(firstObject,firstType);
                   2338:         }
                   2339:     }
                   2340:     if (context == 'parmslog') {
                   2341:         var secondType = 'hidden';
                   2342:         if (firstType == 'text') {
                   2343:             secondType = 'checkbox';
                   2344:         }
                   2345:         secondObject = document.getElementById(secondid);  
                   2346:         if (typeof(secondObject) == 'object') {
                   2347:             if (secondObject.type != secondType) {
                   2348:                 changeInputType(secondObject,secondType);
                   2349:             }
                   2350:         }
                   2351:         var textItem = document.getElementById(thirdid);
                   2352:         var currtext = textItem.innerHTML;
                   2353:         var newtext;
                   2354:         if (firstType == 'text') {
                   2355:             newtext = '$includetext';
                   2356:         } else {
                   2357:             newtext = '&nbsp;';
                   2358:         }
                   2359:         if (currtext != newtext) {
                   2360:             textItem.innerHTML = newtext;
                   2361:         }
                   2362:     }
                   2363:     return;
                   2364: }
                   2365: 
                   2366: function changeInputType(oldObject,newType) {
                   2367:     var newObject = document.createElement('input');
                   2368:     newObject.type = newType;
                   2369:     if (oldObject.size) {
                   2370:         newObject.size = oldObject.size;
                   2371:     }
                   2372:     if (oldObject.value) {
                   2373:         newObject.value = oldObject.value;
                   2374:     }
                   2375:     if (oldObject.name) {
                   2376:         newObject.name = oldObject.name;
                   2377:     }
                   2378:     if (oldObject.id) {
                   2379:         newObject.id = oldObject.id;
                   2380:     }
                   2381:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2382:     return;
                   2383: }
                   2384: 
                   2385: ENDJS
1.475     www      2386: }
                   2387: 
1.167     www      2388: sub gradeleveldescription {
                   2389:     my $gradelevel=shift;
                   2390:     my %gradelevels=(0 => 'Not specified',
                   2391: 		     1 => 'Grade 1',
                   2392: 		     2 => 'Grade 2',
                   2393: 		     3 => 'Grade 3',
                   2394: 		     4 => 'Grade 4',
                   2395: 		     5 => 'Grade 5',
                   2396: 		     6 => 'Grade 6',
                   2397: 		     7 => 'Grade 7',
                   2398: 		     8 => 'Grade 8',
                   2399: 		     9 => 'Grade 9',
                   2400: 		     10 => 'Grade 10',
                   2401: 		     11 => 'Grade 11',
                   2402: 		     12 => 'Grade 12',
                   2403: 		     13 => 'Grade 13',
                   2404: 		     14 => '100 Level',
                   2405: 		     15 => '200 Level',
                   2406: 		     16 => '300 Level',
                   2407: 		     17 => '400 Level',
                   2408: 		     18 => 'Graduate Level');
                   2409:     return &mt($gradelevels{$gradelevel});
                   2410: }
                   2411: 
1.163     www      2412: sub select_level_form {
                   2413:     my ($deflevel,$name)=@_;
                   2414:     unless ($deflevel) { $deflevel=0; }
1.167     www      2415:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2416:     for (my $i=0; $i<=18; $i++) {
                   2417:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2418:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2419:                 ">".&gradeleveldescription($i)."</option>\n";
                   2420:     }
                   2421:     $selectform.="</select>";
                   2422:     return $selectform;
1.163     www      2423: }
1.167     www      2424: 
1.35      matthew  2425: #-------------------------------------------
                   2426: 
1.45      matthew  2427: =pod
                   2428: 
1.1075.2.42  raeburn  2429: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
1.35      matthew  2430: 
                   2431: Returns a string containing a <select name='$name' size='1'> form to 
                   2432: allow a user to select the domain to preform an operation in.  
                   2433: See loncreateuser.pm for an example invocation and use.
                   2434: 
1.90      www      2435: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2436: selected");
                   2437: 
1.743     raeburn  2438: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2439: 
1.910     raeburn  2440: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
                   2441: 
1.1075.2.36  raeburn  2442: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2443: 
                   2444: The optional $excdoms is a reference to an array of domains which will be excluded from the available options. 
1.563     raeburn  2445: 
1.35      matthew  2446: =cut
                   2447: 
                   2448: #-------------------------------------------
1.34      matthew  2449: sub select_dom_form {
1.1075.2.36  raeburn  2450:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
1.872     raeburn  2451:     if ($onchange) {
1.874     raeburn  2452:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2453:     }
1.1075.2.36  raeburn  2454:     my (@domains,%exclude);
1.910     raeburn  2455:     if (ref($incdoms) eq 'ARRAY') {
                   2456:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2457:     } else {
                   2458:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2459:     }
1.90      www      2460:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2461:     if (ref($excdoms) eq 'ARRAY') {
                   2462:         map { $exclude{$_} = 1; } @{$excdoms};
                   2463:     }
1.743     raeburn  2464:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.356     albertel 2465:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2466:         next if ($exclude{$dom});
1.356     albertel 2467:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2468:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2469:         if ($showdomdesc) {
                   2470:             if ($dom ne '') {
                   2471:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2472:                 if ($domdesc ne '') {
                   2473:                     $selectdomain .= ' ('.$domdesc.')';
                   2474:                 }
                   2475:             } 
                   2476:         }
                   2477:         $selectdomain .= "</option>\n";
1.34      matthew  2478:     }
                   2479:     $selectdomain.="</select>";
                   2480:     return $selectdomain;
                   2481: }
                   2482: 
1.35      matthew  2483: #-------------------------------------------
                   2484: 
1.45      matthew  2485: =pod
                   2486: 
1.648     raeburn  2487: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2488: 
1.586     raeburn  2489: input: 4 arguments (two required, two optional) - 
                   2490:     $domain - domain of new user
                   2491:     $name - name of form element
                   2492:     $default - Value of 'default' causes a default item to be first 
                   2493:                             option, and selected by default. 
                   2494:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2495:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2496: output: returns 2 items: 
1.586     raeburn  2497: (a) form element which contains either:
                   2498:    (i) <select name="$name">
                   2499:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2500:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2501:        </select>
                   2502:        form item if there are multiple library servers in $domain, or
                   2503:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2504:        if there is only one library server in $domain.
                   2505: 
                   2506: (b) number of library servers found.
                   2507: 
                   2508: See loncreateuser.pm for example of use.
1.35      matthew  2509: 
                   2510: =cut
                   2511: 
                   2512: #-------------------------------------------
1.586     raeburn  2513: sub home_server_form_item {
                   2514:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2515:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2516:     my $result;
                   2517:     my $numlib = keys(%servers);
                   2518:     if ($numlib > 1) {
                   2519:         $result .= '<select name="'.$name.'" />'."\n";
                   2520:         if ($default) {
1.804     bisitz   2521:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2522:                        '</option>'."\n";
                   2523:         }
                   2524:         foreach my $hostid (sort(keys(%servers))) {
                   2525:             $result.= '<option value="'.$hostid.'">'.
                   2526: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2527:         }
                   2528:         $result .= '</select>'."\n";
                   2529:     } elsif ($numlib == 1) {
                   2530:         my $hostid;
                   2531:         foreach my $item (keys(%servers)) {
                   2532:             $hostid = $item;
                   2533:         }
                   2534:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2535:                    $hostid.'" />';
                   2536:                    if (!$hide) {
                   2537:                        $result .= $hostid.' '.$servers{$hostid};
                   2538:                    }
                   2539:                    $result .= "\n";
                   2540:     } elsif ($default) {
                   2541:         $result .= '<input type="hidden" name="'.$name.
                   2542:                    '" value="default" />';
                   2543:                    if (!$hide) {
                   2544:                        $result .= &mt('default');
                   2545:                    }
                   2546:                    $result .= "\n";
1.33      matthew  2547:     }
1.586     raeburn  2548:     return ($result,$numlib);
1.33      matthew  2549: }
1.112     bowersj2 2550: 
                   2551: =pod
                   2552: 
1.534     albertel 2553: =back 
                   2554: 
1.112     bowersj2 2555: =cut
1.87      matthew  2556: 
                   2557: ###############################################################
1.112     bowersj2 2558: ##                  Decoding User Agent                      ##
1.87      matthew  2559: ###############################################################
                   2560: 
                   2561: =pod
                   2562: 
1.112     bowersj2 2563: =head1 Decoding the User Agent
                   2564: 
                   2565: =over 4
                   2566: 
                   2567: =item * &decode_user_agent()
1.87      matthew  2568: 
                   2569: Inputs: $r
                   2570: 
                   2571: Outputs:
                   2572: 
                   2573: =over 4
                   2574: 
1.112     bowersj2 2575: =item * $httpbrowser
1.87      matthew  2576: 
1.112     bowersj2 2577: =item * $clientbrowser
1.87      matthew  2578: 
1.112     bowersj2 2579: =item * $clientversion
1.87      matthew  2580: 
1.112     bowersj2 2581: =item * $clientmathml
1.87      matthew  2582: 
1.112     bowersj2 2583: =item * $clientunicode
1.87      matthew  2584: 
1.112     bowersj2 2585: =item * $clientos
1.87      matthew  2586: 
1.1075.2.42  raeburn  2587: =item * $clientmobile
                   2588: 
                   2589: =item * $clientinfo
                   2590: 
1.1075.2.77  raeburn  2591: =item * $clientosversion
                   2592: 
1.87      matthew  2593: =back
                   2594: 
1.157     matthew  2595: =back 
                   2596: 
1.87      matthew  2597: =cut
                   2598: 
                   2599: ###############################################################
                   2600: ###############################################################
                   2601: sub decode_user_agent {
1.247     albertel 2602:     my ($r)=@_;
1.87      matthew  2603:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2604:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2605:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2606:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2607:     my $clientbrowser='unknown';
                   2608:     my $clientversion='0';
                   2609:     my $clientmathml='';
                   2610:     my $clientunicode='0';
1.1075.2.42  raeburn  2611:     my $clientmobile=0;
1.1075.2.77  raeburn  2612:     my $clientosversion='';
1.87      matthew  2613:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1075.2.76  raeburn  2614:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2615: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2616: 	    $clientbrowser=$bname;
                   2617:             $httpbrowser=~/$vreg/i;
                   2618: 	    $clientversion=$1;
                   2619:             $clientmathml=($clientversion>=$minv);
                   2620:             $clientunicode=($clientversion>=$univ);
                   2621: 	}
                   2622:     }
                   2623:     my $clientos='unknown';
1.1075.2.42  raeburn  2624:     my $clientinfo;
1.87      matthew  2625:     if (($httpbrowser=~/linux/i) ||
                   2626:         ($httpbrowser=~/unix/i) ||
                   2627:         ($httpbrowser=~/ux/i) ||
                   2628:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2629:     if (($httpbrowser=~/vax/i) ||
                   2630:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2631:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2632:     if (($httpbrowser=~/mac/i) ||
                   2633:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1075.2.77  raeburn  2634:     if ($httpbrowser=~/win/i) {
                   2635:         $clientos='win';
                   2636:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2637:             $clientosversion = $1;
                   2638:         }
                   2639:     }
1.87      matthew  2640:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2641:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2642:         $clientmobile=lc($1);
                   2643:     }
                   2644:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2645:         $clientinfo = 'firefox-'.$1;
                   2646:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2647:         $clientinfo = 'chromeframe-'.$1;
                   2648:     }
1.87      matthew  2649:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.77  raeburn  2650:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2651:             $clientosversion);
1.87      matthew  2652: }
                   2653: 
1.32      matthew  2654: ###############################################################
                   2655: ##    Authentication changing form generation subroutines    ##
                   2656: ###############################################################
                   2657: ##
                   2658: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2659: ## hash, and have reasonable default values.
                   2660: ##
                   2661: ##    formname = the name given in the <form> tag.
1.35      matthew  2662: #-------------------------------------------
                   2663: 
1.45      matthew  2664: =pod
                   2665: 
1.112     bowersj2 2666: =head1 Authentication Routines
                   2667: 
                   2668: =over 4
                   2669: 
1.648     raeburn  2670: =item * &authform_xxxxxx()
1.35      matthew  2671: 
                   2672: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2673: handle some of the conveniences required for authentication forms.  
                   2674: This is not an optimal method, but it works.  
                   2675: 
                   2676: =over 4
                   2677: 
1.112     bowersj2 2678: =item * authform_header
1.35      matthew  2679: 
1.112     bowersj2 2680: =item * authform_authorwarning
1.35      matthew  2681: 
1.112     bowersj2 2682: =item * authform_nochange
1.35      matthew  2683: 
1.112     bowersj2 2684: =item * authform_kerberos
1.35      matthew  2685: 
1.112     bowersj2 2686: =item * authform_internal
1.35      matthew  2687: 
1.112     bowersj2 2688: =item * authform_filesystem
1.35      matthew  2689: 
                   2690: =back
                   2691: 
1.648     raeburn  2692: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2693: 
1.35      matthew  2694: =cut
                   2695: 
                   2696: #-------------------------------------------
1.32      matthew  2697: sub authform_header{  
                   2698:     my %in = (
                   2699:         formname => 'cu',
1.80      albertel 2700:         kerb_def_dom => '',
1.32      matthew  2701:         @_,
                   2702:     );
                   2703:     $in{'formname'} = 'document.' . $in{'formname'};
                   2704:     my $result='';
1.80      albertel 2705: 
                   2706: #---------------------------------------------- Code for upper case translation
                   2707:     my $Javascript_toUpperCase;
                   2708:     unless ($in{kerb_def_dom}) {
                   2709:         $Javascript_toUpperCase =<<"END";
                   2710:         switch (choice) {
                   2711:            case 'krb': currentform.elements[choicearg].value =
                   2712:                currentform.elements[choicearg].value.toUpperCase();
                   2713:                break;
                   2714:            default:
                   2715:         }
                   2716: END
                   2717:     } else {
                   2718:         $Javascript_toUpperCase = "";
                   2719:     }
                   2720: 
1.165     raeburn  2721:     my $radioval = "'nochange'";
1.591     raeburn  2722:     if (defined($in{'curr_authtype'})) {
                   2723:         if ($in{'curr_authtype'} ne '') {
                   2724:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2725:         }
1.174     matthew  2726:     }
1.165     raeburn  2727:     my $argfield = 'null';
1.591     raeburn  2728:     if (defined($in{'mode'})) {
1.165     raeburn  2729:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2730:             if (defined($in{'curr_autharg'})) {
                   2731:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2732:                     $argfield = "'$in{'curr_autharg'}'";
                   2733:                 }
                   2734:             }
                   2735:         }
                   2736:     }
                   2737: 
1.32      matthew  2738:     $result.=<<"END";
                   2739: var current = new Object();
1.165     raeburn  2740: current.radiovalue = $radioval;
                   2741: current.argfield = $argfield;
1.32      matthew  2742: 
                   2743: function changed_radio(choice,currentform) {
                   2744:     var choicearg = choice + 'arg';
                   2745:     // If a radio button in changed, we need to change the argfield
                   2746:     if (current.radiovalue != choice) {
                   2747:         current.radiovalue = choice;
                   2748:         if (current.argfield != null) {
                   2749:             currentform.elements[current.argfield].value = '';
                   2750:         }
                   2751:         if (choice == 'nochange') {
                   2752:             current.argfield = null;
                   2753:         } else {
                   2754:             current.argfield = choicearg;
                   2755:             switch(choice) {
                   2756:                 case 'krb': 
                   2757:                     currentform.elements[current.argfield].value = 
                   2758:                         "$in{'kerb_def_dom'}";
                   2759:                 break;
                   2760:               default:
                   2761:                 break;
                   2762:             }
                   2763:         }
                   2764:     }
                   2765:     return;
                   2766: }
1.22      www      2767: 
1.32      matthew  2768: function changed_text(choice,currentform) {
                   2769:     var choicearg = choice + 'arg';
                   2770:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2771:         $Javascript_toUpperCase
1.32      matthew  2772:         // clear old field
                   2773:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2774:             currentform.elements[current.argfield].value = '';
                   2775:         }
                   2776:         current.argfield = choicearg;
                   2777:     }
                   2778:     set_auth_radio_buttons(choice,currentform);
                   2779:     return;
1.20      www      2780: }
1.32      matthew  2781: 
                   2782: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2783:     var numauthchoices = currentform.login.length;
                   2784:     if (typeof numauthchoices  == "undefined") {
                   2785:         return;
                   2786:     } 
1.32      matthew  2787:     var i=0;
1.986     raeburn  2788:     while (i < numauthchoices) {
1.32      matthew  2789:         if (currentform.login[i].value == newvalue) { break; }
                   2790:         i++;
                   2791:     }
1.986     raeburn  2792:     if (i == numauthchoices) {
1.32      matthew  2793:         return;
                   2794:     }
                   2795:     current.radiovalue = newvalue;
                   2796:     currentform.login[i].checked = true;
                   2797:     return;
                   2798: }
                   2799: END
                   2800:     return $result;
                   2801: }
                   2802: 
1.1075.2.20  raeburn  2803: sub authform_authorwarning {
1.32      matthew  2804:     my $result='';
1.144     matthew  2805:     $result='<i>'.
                   2806:         &mt('As a general rule, only authors or co-authors should be '.
                   2807:             'filesystem authenticated '.
                   2808:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2809:     return $result;
                   2810: }
                   2811: 
1.1075.2.20  raeburn  2812: sub authform_nochange {
1.32      matthew  2813:     my %in = (
                   2814:               formname => 'document.cu',
                   2815:               kerb_def_dom => 'MSU.EDU',
                   2816:               @_,
                   2817:           );
1.1075.2.20  raeburn  2818:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2819:     my $result;
1.1075.2.20  raeburn  2820:     if (!$authnum) {
                   2821:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2822:     } else {
                   2823:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2824:                   '<input type="radio" name="login" value="nochange" '.
                   2825:                   'checked="checked" onclick="'.
1.281     albertel 2826:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2827: 	    '</label>';
1.586     raeburn  2828:     }
1.32      matthew  2829:     return $result;
                   2830: }
                   2831: 
1.591     raeburn  2832: sub authform_kerberos {
1.32      matthew  2833:     my %in = (
                   2834:               formname => 'document.cu',
                   2835:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2836:               kerb_def_auth => 'krb4',
1.32      matthew  2837:               @_,
                   2838:               );
1.586     raeburn  2839:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   2840:         $autharg,$jscall);
1.1075.2.20  raeburn  2841:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2842:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2843:        $check5 = ' checked="checked"';
1.80      albertel 2844:     } else {
1.772     bisitz   2845:        $check4 = ' checked="checked"';
1.80      albertel 2846:     }
1.165     raeburn  2847:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2848:     if (defined($in{'curr_authtype'})) {
                   2849:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2850:             $krbcheck = ' checked="checked"';
1.623     raeburn  2851:             if (defined($in{'mode'})) {
                   2852:                 if ($in{'mode'} eq 'modifyuser') {
                   2853:                     $krbcheck = '';
                   2854:                 }
                   2855:             }
1.591     raeburn  2856:             if (defined($in{'curr_kerb_ver'})) {
                   2857:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2858:                     $check5 = ' checked="checked"';
1.591     raeburn  2859:                     $check4 = '';
                   2860:                 } else {
1.772     bisitz   2861:                     $check4 = ' checked="checked"';
1.591     raeburn  2862:                     $check5 = '';
                   2863:                 }
1.586     raeburn  2864:             }
1.591     raeburn  2865:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2866:                 $krbarg = $in{'curr_autharg'};
                   2867:             }
1.586     raeburn  2868:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2869:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2870:                     $result = 
                   2871:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2872:         $in{'curr_autharg'},$krbver);
                   2873:                 } else {
                   2874:                     $result =
                   2875:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2876:                 }
                   2877:                 return $result; 
                   2878:             }
                   2879:         }
                   2880:     } else {
                   2881:         if ($authnum == 1) {
1.784     bisitz   2882:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2883:         }
                   2884:     }
1.586     raeburn  2885:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2886:         return;
1.587     raeburn  2887:     } elsif ($authtype eq '') {
1.591     raeburn  2888:         if (defined($in{'mode'})) {
1.587     raeburn  2889:             if ($in{'mode'} eq 'modifycourse') {
                   2890:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2891:                     $authtype = '<input type="radio" name="login" value="krb" />';
1.587     raeburn  2892:                 }
                   2893:             }
                   2894:         }
1.586     raeburn  2895:     }
                   2896:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2897:     if ($authtype eq '') {
                   2898:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2899:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   2900:                     $krbcheck.' />';
                   2901:     }
                   2902:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2903:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2904:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2905:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2906:          $in{'curr_authtype'} eq 'krb4')) {
                   2907:         $result .= &mt
1.144     matthew  2908:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2909:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2910:          '<label>'.$authtype,
1.281     albertel 2911:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2912:              'value="'.$krbarg.'" '.
1.144     matthew  2913:              'onchange="'.$jscall.'" />',
1.281     albertel 2914:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   2915:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   2916: 	 '</label>');
1.586     raeburn  2917:     } elsif ($can_assign{'krb4'}) {
                   2918:         $result .= &mt
                   2919:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2920:          '[_3] Version 4 [_4]',
                   2921:          '<label>'.$authtype,
                   2922:          '</label><input type="text" size="10" name="krbarg" '.
                   2923:              'value="'.$krbarg.'" '.
                   2924:              'onchange="'.$jscall.'" />',
                   2925:          '<label><input type="hidden" name="krbver" value="4" />',
                   2926:          '</label>');
                   2927:     } elsif ($can_assign{'krb5'}) {
                   2928:         $result .= &mt
                   2929:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2930:          '[_3] Version 5 [_4]',
                   2931:          '<label>'.$authtype,
                   2932:          '</label><input type="text" size="10" name="krbarg" '.
                   2933:              'value="'.$krbarg.'" '.
                   2934:              'onchange="'.$jscall.'" />',
                   2935:          '<label><input type="hidden" name="krbver" value="5" />',
                   2936:          '</label>');
                   2937:     }
1.32      matthew  2938:     return $result;
                   2939: }
                   2940: 
1.1075.2.20  raeburn  2941: sub authform_internal {
1.586     raeburn  2942:     my %in = (
1.32      matthew  2943:                 formname => 'document.cu',
                   2944:                 kerb_def_dom => 'MSU.EDU',
                   2945:                 @_,
                   2946:                 );
1.586     raeburn  2947:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
1.1075.2.20  raeburn  2948:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2949:     if (defined($in{'curr_authtype'})) {
                   2950:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2951:             if ($can_assign{'int'}) {
1.772     bisitz   2952:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2953:                 if (defined($in{'mode'})) {
                   2954:                     if ($in{'mode'} eq 'modifyuser') {
                   2955:                         $intcheck = '';
                   2956:                     }
                   2957:                 }
1.591     raeburn  2958:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2959:                     $intarg = $in{'curr_autharg'};
                   2960:                 }
                   2961:             } else {
                   2962:                 $result = &mt('Currently internally authenticated.');
                   2963:                 return $result;
1.165     raeburn  2964:             }
                   2965:         }
1.586     raeburn  2966:     } else {
                   2967:         if ($authnum == 1) {
1.784     bisitz   2968:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2969:         }
                   2970:     }
                   2971:     if (!$can_assign{'int'}) {
                   2972:         return;
1.587     raeburn  2973:     } elsif ($authtype eq '') {
1.591     raeburn  2974:         if (defined($in{'mode'})) {
1.587     raeburn  2975:             if ($in{'mode'} eq 'modifycourse') {
                   2976:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2977:                     $authtype = '<input type="radio" name="login" value="int" />';
1.587     raeburn  2978:                 }
                   2979:             }
                   2980:         }
1.165     raeburn  2981:     }
1.586     raeburn  2982:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2983:     if ($authtype eq '') {
                   2984:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   2985:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   2986:     }
1.605     bisitz   2987:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  2988:                $intarg.'" onchange="'.$jscall.'" />';
                   2989:     $result = &mt
1.144     matthew  2990:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  2991:          '<label>'.$authtype,'</label>'.$autharg);
1.824     bisitz   2992:     $result.="<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
1.32      matthew  2993:     return $result;
                   2994: }
                   2995: 
1.1075.2.20  raeburn  2996: sub authform_local {
1.32      matthew  2997:     my %in = (
                   2998:               formname => 'document.cu',
                   2999:               kerb_def_dom => 'MSU.EDU',
                   3000:               @_,
                   3001:               );
1.586     raeburn  3002:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
1.1075.2.20  raeburn  3003:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  3004:     if (defined($in{'curr_authtype'})) {
                   3005:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3006:             if ($can_assign{'loc'}) {
1.772     bisitz   3007:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3008:                 if (defined($in{'mode'})) {
                   3009:                     if ($in{'mode'} eq 'modifyuser') {
                   3010:                         $loccheck = '';
                   3011:                     }
                   3012:                 }
1.591     raeburn  3013:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3014:                     $locarg = $in{'curr_autharg'};
                   3015:                 }
                   3016:             } else {
                   3017:                 $result = &mt('Currently using local (institutional) authentication.');
                   3018:                 return $result;
1.165     raeburn  3019:             }
                   3020:         }
1.586     raeburn  3021:     } else {
                   3022:         if ($authnum == 1) {
1.784     bisitz   3023:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3024:         }
                   3025:     }
                   3026:     if (!$can_assign{'loc'}) {
                   3027:         return;
1.587     raeburn  3028:     } elsif ($authtype eq '') {
1.591     raeburn  3029:         if (defined($in{'mode'})) {
1.587     raeburn  3030:             if ($in{'mode'} eq 'modifycourse') {
                   3031:                 if ($authnum == 1) {
1.1075.2.20  raeburn  3032:                     $authtype = '<input type="radio" name="login" value="loc" />';
1.587     raeburn  3033:                 }
                   3034:             }
                   3035:         }
1.165     raeburn  3036:     }
1.586     raeburn  3037:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3038:     if ($authtype eq '') {
                   3039:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3040:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   3041:                     $jscall.'" />';
                   3042:     }
                   3043:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   3044:                $locarg.'" onchange="'.$jscall.'" />';
                   3045:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3046:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3047:     return $result;
                   3048: }
                   3049: 
1.1075.2.20  raeburn  3050: sub authform_filesystem {
1.32      matthew  3051:     my %in = (
                   3052:               formname => 'document.cu',
                   3053:               kerb_def_dom => 'MSU.EDU',
                   3054:               @_,
                   3055:               );
1.586     raeburn  3056:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
1.1075.2.20  raeburn  3057:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  3058:     if (defined($in{'curr_authtype'})) {
                   3059:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3060:             if ($can_assign{'fsys'}) {
1.772     bisitz   3061:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3062:                 if (defined($in{'mode'})) {
                   3063:                     if ($in{'mode'} eq 'modifyuser') {
                   3064:                         $fsyscheck = '';
                   3065:                     }
                   3066:                 }
1.586     raeburn  3067:             } else {
                   3068:                 $result = &mt('Currently Filesystem Authenticated.');
                   3069:                 return $result;
                   3070:             }           
                   3071:         }
                   3072:     } else {
                   3073:         if ($authnum == 1) {
1.784     bisitz   3074:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3075:         }
                   3076:     }
                   3077:     if (!$can_assign{'fsys'}) {
                   3078:         return;
1.587     raeburn  3079:     } elsif ($authtype eq '') {
1.591     raeburn  3080:         if (defined($in{'mode'})) {
1.587     raeburn  3081:             if ($in{'mode'} eq 'modifycourse') {
                   3082:                 if ($authnum == 1) {
1.1075.2.20  raeburn  3083:                     $authtype = '<input type="radio" name="login" value="fsys" />';
1.587     raeburn  3084:                 }
                   3085:             }
                   3086:         }
1.586     raeburn  3087:     }
                   3088:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3089:     if ($authtype eq '') {
                   3090:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3091:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   3092:                     $jscall.'" />';
                   3093:     }
                   3094:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   3095:                ' onchange="'.$jscall.'" />';
                   3096:     $result = &mt
1.144     matthew  3097:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3098:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  3099:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   3100:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  3101:                   'onchange="'.$jscall.'" />');
1.32      matthew  3102:     return $result;
                   3103: }
                   3104: 
1.586     raeburn  3105: sub get_assignable_auth {
                   3106:     my ($dom) = @_;
                   3107:     if ($dom eq '') {
                   3108:         $dom = $env{'request.role.domain'};
                   3109:     }
                   3110:     my %can_assign = (
                   3111:                           krb4 => 1,
                   3112:                           krb5 => 1,
                   3113:                           int  => 1,
                   3114:                           loc  => 1,
                   3115:                      );
                   3116:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3117:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3118:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3119:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3120:             my $context;
                   3121:             if ($env{'request.role'} =~ /^au/) {
                   3122:                 $context = 'author';
                   3123:             } elsif ($env{'request.role'} =~ /^dc/) {
                   3124:                 $context = 'domain';
                   3125:             } elsif ($env{'request.course.id'}) {
                   3126:                 $context = 'course';
                   3127:             }
                   3128:             if ($context) {
                   3129:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3130:                    %can_assign = %{$authhash->{$context}}; 
                   3131:                 }
                   3132:             }
                   3133:         }
                   3134:     }
                   3135:     my $authnum = 0;
                   3136:     foreach my $key (keys(%can_assign)) {
                   3137:         if ($can_assign{$key}) {
                   3138:             $authnum ++;
                   3139:         }
                   3140:     }
                   3141:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3142:         $authnum --;
                   3143:     }
                   3144:     return ($authnum,%can_assign);
                   3145: }
                   3146: 
1.80      albertel 3147: ###############################################################
                   3148: ##    Get Kerberos Defaults for Domain                 ##
                   3149: ###############################################################
                   3150: ##
                   3151: ## Returns default kerberos version and an associated argument
                   3152: ## as listed in file domain.tab. If not listed, provides
                   3153: ## appropriate default domain and kerberos version.
                   3154: ##
                   3155: #-------------------------------------------
                   3156: 
                   3157: =pod
                   3158: 
1.648     raeburn  3159: =item * &get_kerberos_defaults()
1.80      albertel 3160: 
                   3161: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3162: version and domain. If not found, it defaults to version 4 and the 
                   3163: domain of the server.
1.80      albertel 3164: 
1.648     raeburn  3165: =over 4
                   3166: 
1.80      albertel 3167: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3168: 
1.648     raeburn  3169: =back
                   3170: 
                   3171: =back
                   3172: 
1.80      albertel 3173: =cut
                   3174: 
                   3175: #-------------------------------------------
                   3176: sub get_kerberos_defaults {
                   3177:     my $domain=shift;
1.641     raeburn  3178:     my ($krbdef,$krbdefdom);
                   3179:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3180:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3181:         $krbdef = $domdefaults{'auth_def'};
                   3182:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3183:     } else {
1.80      albertel 3184:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3185:         my $krbdefdom=$1;
                   3186:         $krbdefdom=~tr/a-z/A-Z/;
                   3187:         $krbdef = "krb4";
                   3188:     }
                   3189:     return ($krbdef,$krbdefdom);
                   3190: }
1.112     bowersj2 3191: 
1.32      matthew  3192: 
1.46      matthew  3193: ###############################################################
                   3194: ##                Thesaurus Functions                        ##
                   3195: ###############################################################
1.20      www      3196: 
1.46      matthew  3197: =pod
1.20      www      3198: 
1.112     bowersj2 3199: =head1 Thesaurus Functions
                   3200: 
                   3201: =over 4
                   3202: 
1.648     raeburn  3203: =item * &initialize_keywords()
1.46      matthew  3204: 
                   3205: Initializes the package variable %Keywords if it is empty.  Uses the
                   3206: package variable $thesaurus_db_file.
                   3207: 
                   3208: =cut
                   3209: 
                   3210: ###################################################
                   3211: 
                   3212: sub initialize_keywords {
                   3213:     return 1 if (scalar keys(%Keywords));
                   3214:     # If we are here, %Keywords is empty, so fill it up
                   3215:     #   Make sure the file we need exists...
                   3216:     if (! -e $thesaurus_db_file) {
                   3217:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3218:                                  " failed because it does not exist");
                   3219:         return 0;
                   3220:     }
                   3221:     #   Set up the hash as a database
                   3222:     my %thesaurus_db;
                   3223:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3224:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3225:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3226:                                  $thesaurus_db_file);
                   3227:         return 0;
                   3228:     } 
                   3229:     #  Get the average number of appearances of a word.
                   3230:     my $avecount = $thesaurus_db{'average.count'};
                   3231:     #  Put keywords (those that appear > average) into %Keywords
                   3232:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3233:         my ($count,undef) = split /:/,$data;
                   3234:         $Keywords{$word}++ if ($count > $avecount);
                   3235:     }
                   3236:     untie %thesaurus_db;
                   3237:     # Remove special values from %Keywords.
1.356     albertel 3238:     foreach my $value ('total.count','average.count') {
                   3239:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3240:   }
1.46      matthew  3241:     return 1;
                   3242: }
                   3243: 
                   3244: ###################################################
                   3245: 
                   3246: =pod
                   3247: 
1.648     raeburn  3248: =item * &keyword($word)
1.46      matthew  3249: 
                   3250: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3251: than the average number of times in the thesaurus database.  Calls 
                   3252: &initialize_keywords
                   3253: 
                   3254: =cut
                   3255: 
                   3256: ###################################################
1.20      www      3257: 
                   3258: sub keyword {
1.46      matthew  3259:     return if (!&initialize_keywords());
                   3260:     my $word=lc(shift());
                   3261:     $word=~s/\W//g;
                   3262:     return exists($Keywords{$word});
1.20      www      3263: }
1.46      matthew  3264: 
                   3265: ###############################################################
                   3266: 
                   3267: =pod 
1.20      www      3268: 
1.648     raeburn  3269: =item * &get_related_words()
1.46      matthew  3270: 
1.160     matthew  3271: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3272: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3273: will be returned.  The order of the words returned is determined by the
                   3274: database which holds them.
                   3275: 
                   3276: Uses global $thesaurus_db_file.
                   3277: 
1.1057    foxr     3278: 
1.46      matthew  3279: =cut
                   3280: 
                   3281: ###############################################################
                   3282: sub get_related_words {
                   3283:     my $keyword = shift;
                   3284:     my %thesaurus_db;
                   3285:     if (! -e $thesaurus_db_file) {
                   3286:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3287:                                  "failed because the file does not exist");
                   3288:         return ();
                   3289:     }
                   3290:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3291:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3292:         return ();
                   3293:     } 
                   3294:     my @Words=();
1.429     www      3295:     my $count=0;
1.46      matthew  3296:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3297: 	# The first element is the number of times
                   3298: 	# the word appears.  We do not need it now.
1.429     www      3299: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3300: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3301: 	my $threshold=$mostfrequentcount/10;
                   3302:         foreach my $possibleword (@RelatedWords) {
                   3303:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3304:             if ($wordcount>$threshold) {
                   3305: 		push(@Words,$word);
                   3306:                 $count++;
                   3307:                 if ($count>10) { last; }
                   3308: 	    }
1.20      www      3309:         }
                   3310:     }
1.46      matthew  3311:     untie %thesaurus_db;
                   3312:     return @Words;
1.14      harris41 3313: }
1.46      matthew  3314: 
1.112     bowersj2 3315: =pod
                   3316: 
                   3317: =back
                   3318: 
                   3319: =cut
1.61      www      3320: 
                   3321: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3322: =pod
                   3323: 
1.112     bowersj2 3324: =head1 User Name Functions
                   3325: 
                   3326: =over 4
                   3327: 
1.648     raeburn  3328: =item * &plainname($uname,$udom,$first)
1.81      albertel 3329: 
1.112     bowersj2 3330: Takes a users logon name and returns it as a string in
1.226     albertel 3331: "first middle last generation" form 
                   3332: if $first is set to 'lastname' then it returns it as
                   3333: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3334: 
                   3335: =cut
1.61      www      3336: 
1.295     www      3337: 
1.81      albertel 3338: ###############################################################
1.61      www      3339: sub plainname {
1.226     albertel 3340:     my ($uname,$udom,$first)=@_;
1.537     albertel 3341:     return if (!defined($uname) || !defined($udom));
1.295     www      3342:     my %names=&getnames($uname,$udom);
1.226     albertel 3343:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3344: 					  $names{'middlename'},
                   3345: 					  $names{'lastname'},
                   3346: 					  $names{'generation'},$first);
                   3347:     $name=~s/^\s+//;
1.62      www      3348:     $name=~s/\s+$//;
                   3349:     $name=~s/\s+/ /g;
1.353     albertel 3350:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3351:     return $name;
1.61      www      3352: }
1.66      www      3353: 
                   3354: # -------------------------------------------------------------------- Nickname
1.81      albertel 3355: =pod
                   3356: 
1.648     raeburn  3357: =item * &nickname($uname,$udom)
1.81      albertel 3358: 
                   3359: Gets a users name and returns it as a string as
                   3360: 
                   3361: "&quot;nickname&quot;"
1.66      www      3362: 
1.81      albertel 3363: if the user has a nickname or
                   3364: 
                   3365: "first middle last generation"
                   3366: 
                   3367: if the user does not
                   3368: 
                   3369: =cut
1.66      www      3370: 
                   3371: sub nickname {
                   3372:     my ($uname,$udom)=@_;
1.537     albertel 3373:     return if (!defined($uname) || !defined($udom));
1.295     www      3374:     my %names=&getnames($uname,$udom);
1.68      albertel 3375:     my $name=$names{'nickname'};
1.66      www      3376:     if ($name) {
                   3377:        $name='&quot;'.$name.'&quot;'; 
                   3378:     } else {
                   3379:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3380: 	     $names{'lastname'}.' '.$names{'generation'};
                   3381:        $name=~s/\s+$//;
                   3382:        $name=~s/\s+/ /g;
                   3383:     }
                   3384:     return $name;
                   3385: }
                   3386: 
1.295     www      3387: sub getnames {
                   3388:     my ($uname,$udom)=@_;
1.537     albertel 3389:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3390:     if ($udom eq 'public' && $uname eq 'public') {
                   3391: 	return ('lastname' => &mt('Public'));
                   3392:     }
1.295     www      3393:     my $id=$uname.':'.$udom;
                   3394:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3395:     if ($cached) {
                   3396: 	return %{$names};
                   3397:     } else {
                   3398: 	my %loadnames=&Apache::lonnet::get('environment',
                   3399:                     ['firstname','middlename','lastname','generation','nickname'],
                   3400: 					 $udom,$uname);
                   3401: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3402: 	return %loadnames;
                   3403:     }
                   3404: }
1.61      www      3405: 
1.542     raeburn  3406: # -------------------------------------------------------------------- getemails
1.648     raeburn  3407: 
1.542     raeburn  3408: =pod
                   3409: 
1.648     raeburn  3410: =item * &getemails($uname,$udom)
1.542     raeburn  3411: 
                   3412: Gets a user's email information and returns it as a hash with keys:
                   3413: notification, critnotification, permanentemail
                   3414: 
                   3415: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3416: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3417:  
1.648     raeburn  3418: 
1.542     raeburn  3419: =cut
                   3420: 
1.648     raeburn  3421: 
1.466     albertel 3422: sub getemails {
                   3423:     my ($uname,$udom)=@_;
                   3424:     if ($udom eq 'public' && $uname eq 'public') {
                   3425: 	return;
                   3426:     }
1.467     www      3427:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3428:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3429:     my $id=$uname.':'.$udom;
                   3430:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3431:     if ($cached) {
                   3432: 	return %{$names};
                   3433:     } else {
                   3434: 	my %loadnames=&Apache::lonnet::get('environment',
                   3435:                     			   ['notification','critnotification',
                   3436: 					    'permanentemail'],
                   3437: 					   $udom,$uname);
                   3438: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3439: 	return %loadnames;
                   3440:     }
                   3441: }
                   3442: 
1.551     albertel 3443: sub flush_email_cache {
                   3444:     my ($uname,$udom)=@_;
                   3445:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3446:     if (!$uname) { $uname=$env{'user.name'};   }
                   3447:     return if ($udom eq 'public' && $uname eq 'public');
                   3448:     my $id=$uname.':'.$udom;
                   3449:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3450: }
                   3451: 
1.728     raeburn  3452: # -------------------------------------------------------------------- getlangs
                   3453: 
                   3454: =pod
                   3455: 
                   3456: =item * &getlangs($uname,$udom)
                   3457: 
                   3458: Gets a user's language preference and returns it as a hash with key:
                   3459: language.
                   3460: 
                   3461: =cut
                   3462: 
                   3463: 
                   3464: sub getlangs {
                   3465:     my ($uname,$udom) = @_;
                   3466:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3467:     if (!$uname) { $uname=$env{'user.name'};   }
                   3468:     my $id=$uname.':'.$udom;
                   3469:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3470:     if ($cached) {
                   3471:         return %{$langs};
                   3472:     } else {
                   3473:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3474:                                            $udom,$uname);
                   3475:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3476:         return %loadlangs;
                   3477:     }
                   3478: }
                   3479: 
                   3480: sub flush_langs_cache {
                   3481:     my ($uname,$udom)=@_;
                   3482:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3483:     if (!$uname) { $uname=$env{'user.name'};   }
                   3484:     return if ($udom eq 'public' && $uname eq 'public');
                   3485:     my $id=$uname.':'.$udom;
                   3486:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3487: }
                   3488: 
1.61      www      3489: # ------------------------------------------------------------------ Screenname
1.81      albertel 3490: 
                   3491: =pod
                   3492: 
1.648     raeburn  3493: =item * &screenname($uname,$udom)
1.81      albertel 3494: 
                   3495: Gets a users screenname and returns it as a string
                   3496: 
                   3497: =cut
1.61      www      3498: 
                   3499: sub screenname {
                   3500:     my ($uname,$udom)=@_;
1.258     albertel 3501:     if ($uname eq $env{'user.name'} &&
                   3502: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3503:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3504:     return $names{'screenname'};
1.62      www      3505: }
                   3506: 
1.212     albertel 3507: 
1.802     bisitz   3508: # ------------------------------------------------------------- Confirm Wrapper
                   3509: =pod
                   3510: 
1.1075.2.42  raeburn  3511: =item * &confirmwrapper($message)
1.802     bisitz   3512: 
                   3513: Wrap messages about completion of operation in box
                   3514: 
                   3515: =cut
                   3516: 
                   3517: sub confirmwrapper {
                   3518:     my ($message)=@_;
                   3519:     if ($message) {
                   3520:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3521:                .$message."\n"
                   3522:                .'</div>'."\n";
                   3523:     } else {
                   3524:         return $message;
                   3525:     }
                   3526: }
                   3527: 
1.62      www      3528: # ------------------------------------------------------------- Message Wrapper
                   3529: 
                   3530: sub messagewrapper {
1.369     www      3531:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3532:     return 
1.441     albertel 3533:         '<a href="/adm/email?compose=individual&amp;'.
                   3534:         'recname='.$username.'&amp;recdom='.$domain.
                   3535: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3536:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3537: }
1.802     bisitz   3538: 
1.74      www      3539: # --------------------------------------------------------------- Notes Wrapper
                   3540: 
                   3541: sub noteswrapper {
                   3542:     my ($link,$un,$do)=@_;
                   3543:     return 
1.896     amueller 3544: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3545: }
1.802     bisitz   3546: 
1.62      www      3547: # ------------------------------------------------------------- Aboutme Wrapper
                   3548: 
                   3549: sub aboutmewrapper {
1.1070    raeburn  3550:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3551:     if (!defined($username)  && !defined($domain)) {
                   3552:         return;
                   3553:     }
1.1075.2.15  raeburn  3554:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3555: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3556: }
                   3557: 
                   3558: # ------------------------------------------------------------ Syllabus Wrapper
                   3559: 
                   3560: sub syllabuswrapper {
1.707     bisitz   3561:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3562:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3563: }
1.14      harris41 3564: 
1.802     bisitz   3565: # -----------------------------------------------------------------------------
                   3566: 
1.208     matthew  3567: sub track_student_link {
1.887     raeburn  3568:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3569:     my $link ="/adm/trackstudent?";
1.208     matthew  3570:     my $title = 'View recent activity';
                   3571:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3572:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3573:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3574:         $title .= ' of this student';
1.268     albertel 3575:     } 
1.208     matthew  3576:     if (defined($target) && $target !~ /^\s*$/) {
                   3577:         $target = qq{target="$target"};
                   3578:     } else {
                   3579:         $target = '';
                   3580:     }
1.268     albertel 3581:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3582:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3583:     $title = &mt($title);
                   3584:     $linktext = &mt($linktext);
1.448     albertel 3585:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3586: 	&help_open_topic('View_recent_activity');
1.208     matthew  3587: }
                   3588: 
1.781     raeburn  3589: sub slot_reservations_link {
                   3590:     my ($linktext,$sname,$sdom,$target) = @_;
                   3591:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3592:     my $title = 'View slot reservation history';
                   3593:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3594:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3595:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3596:         $title .= ' of this student';
                   3597:     }
                   3598:     if (defined($target) && $target !~ /^\s*$/) {
                   3599:         $target = qq{target="$target"};
                   3600:     } else {
                   3601:         $target = '';
                   3602:     }
                   3603:     $title = &mt($title);
                   3604:     $linktext = &mt($linktext);
                   3605:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3606: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3607: 
                   3608: }
                   3609: 
1.508     www      3610: # ===================================================== Display a student photo
                   3611: 
                   3612: 
1.509     albertel 3613: sub student_image_tag {
1.508     www      3614:     my ($domain,$user)=@_;
                   3615:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3616:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3617: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3618:     } else {
                   3619: 	return '';
                   3620:     }
                   3621: }
                   3622: 
1.112     bowersj2 3623: =pod
                   3624: 
                   3625: =back
                   3626: 
                   3627: =head1 Access .tab File Data
                   3628: 
                   3629: =over 4
                   3630: 
1.648     raeburn  3631: =item * &languageids() 
1.112     bowersj2 3632: 
                   3633: returns list of all language ids
                   3634: 
                   3635: =cut
                   3636: 
1.14      harris41 3637: sub languageids {
1.16      harris41 3638:     return sort(keys(%language));
1.14      harris41 3639: }
                   3640: 
1.112     bowersj2 3641: =pod
                   3642: 
1.648     raeburn  3643: =item * &languagedescription() 
1.112     bowersj2 3644: 
                   3645: returns description of a specified language id
                   3646: 
                   3647: =cut
                   3648: 
1.14      harris41 3649: sub languagedescription {
1.125     www      3650:     my $code=shift;
                   3651:     return  ($supported_language{$code}?'* ':'').
                   3652:             $language{$code}.
1.126     www      3653: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3654: }
                   3655: 
1.1048    foxr     3656: =pod
                   3657: 
                   3658: =item * &plainlanguagedescription
                   3659: 
                   3660: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3661: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3662: 
                   3663: =cut
                   3664: 
1.145     www      3665: sub plainlanguagedescription {
                   3666:     my $code=shift;
                   3667:     return $language{$code};
                   3668: }
                   3669: 
1.1048    foxr     3670: =pod
                   3671: 
                   3672: =item * &supportedlanguagecode
                   3673: 
                   3674: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3675: code.
                   3676: 
                   3677: =cut
                   3678: 
1.145     www      3679: sub supportedlanguagecode {
                   3680:     my $code=shift;
                   3681:     return $supported_language{$code};
1.97      www      3682: }
                   3683: 
1.112     bowersj2 3684: =pod
                   3685: 
1.1048    foxr     3686: =item * &latexlanguage()
                   3687: 
                   3688: Given a language key code returns the correspondnig language to use
                   3689: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3690: is no supported hyphenation for the language code.
                   3691: 
                   3692: =cut
                   3693: 
                   3694: sub latexlanguage {
                   3695:     my $code = shift;
                   3696:     return $latex_language{$code};
                   3697: }
                   3698: 
                   3699: =pod
                   3700: 
                   3701: =item * &latexhyphenation()
                   3702: 
                   3703: Same as above but what's supplied is the language as it might be stored
                   3704: in the metadata.
                   3705: 
                   3706: =cut
                   3707: 
                   3708: sub latexhyphenation {
                   3709:     my $key = shift;
                   3710:     return $latex_language_bykey{$key};
                   3711: }
                   3712: 
                   3713: =pod
                   3714: 
1.648     raeburn  3715: =item * &copyrightids() 
1.112     bowersj2 3716: 
                   3717: returns list of all copyrights
                   3718: 
                   3719: =cut
                   3720: 
                   3721: sub copyrightids {
                   3722:     return sort(keys(%cprtag));
                   3723: }
                   3724: 
                   3725: =pod
                   3726: 
1.648     raeburn  3727: =item * &copyrightdescription() 
1.112     bowersj2 3728: 
                   3729: returns description of a specified copyright id
                   3730: 
                   3731: =cut
                   3732: 
                   3733: sub copyrightdescription {
1.166     www      3734:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3735: }
1.197     matthew  3736: 
                   3737: =pod
                   3738: 
1.648     raeburn  3739: =item * &source_copyrightids() 
1.192     taceyjo1 3740: 
                   3741: returns list of all source copyrights
                   3742: 
                   3743: =cut
                   3744: 
                   3745: sub source_copyrightids {
                   3746:     return sort(keys(%scprtag));
                   3747: }
                   3748: 
                   3749: =pod
                   3750: 
1.648     raeburn  3751: =item * &source_copyrightdescription() 
1.192     taceyjo1 3752: 
                   3753: returns description of a specified source copyright id
                   3754: 
                   3755: =cut
                   3756: 
                   3757: sub source_copyrightdescription {
                   3758:     return &mt($scprtag{shift(@_)});
                   3759: }
1.112     bowersj2 3760: 
                   3761: =pod
                   3762: 
1.648     raeburn  3763: =item * &filecategories() 
1.112     bowersj2 3764: 
                   3765: returns list of all file categories
                   3766: 
                   3767: =cut
                   3768: 
                   3769: sub filecategories {
                   3770:     return sort(keys(%category_extensions));
                   3771: }
                   3772: 
                   3773: =pod
                   3774: 
1.648     raeburn  3775: =item * &filecategorytypes() 
1.112     bowersj2 3776: 
                   3777: returns list of file types belonging to a given file
                   3778: category
                   3779: 
                   3780: =cut
                   3781: 
                   3782: sub filecategorytypes {
1.356     albertel 3783:     my ($cat) = @_;
                   3784:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3785: }
                   3786: 
                   3787: =pod
                   3788: 
1.648     raeburn  3789: =item * &fileembstyle() 
1.112     bowersj2 3790: 
                   3791: returns embedding style for a specified file type
                   3792: 
                   3793: =cut
                   3794: 
                   3795: sub fileembstyle {
                   3796:     return $fe{lc(shift(@_))};
1.169     www      3797: }
                   3798: 
1.351     www      3799: sub filemimetype {
                   3800:     return $fm{lc(shift(@_))};
                   3801: }
                   3802: 
1.169     www      3803: 
                   3804: sub filecategoryselect {
                   3805:     my ($name,$value)=@_;
1.189     matthew  3806:     return &select_form($value,$name,
1.970     raeburn  3807:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3808: }
                   3809: 
                   3810: =pod
                   3811: 
1.648     raeburn  3812: =item * &filedescription() 
1.112     bowersj2 3813: 
                   3814: returns description for a specified file type
                   3815: 
                   3816: =cut
                   3817: 
                   3818: sub filedescription {
1.188     matthew  3819:     my $file_description = $fd{lc(shift())};
                   3820:     $file_description =~ s:([\[\]]):~$1:g;
                   3821:     return &mt($file_description);
1.112     bowersj2 3822: }
                   3823: 
                   3824: =pod
                   3825: 
1.648     raeburn  3826: =item * &filedescriptionex() 
1.112     bowersj2 3827: 
                   3828: returns description for a specified file type with
                   3829: extra formatting
                   3830: 
                   3831: =cut
                   3832: 
                   3833: sub filedescriptionex {
                   3834:     my $ex=shift;
1.188     matthew  3835:     my $file_description = $fd{lc($ex)};
                   3836:     $file_description =~ s:([\[\]]):~$1:g;
                   3837:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3838: }
                   3839: 
                   3840: # End of .tab access
                   3841: =pod
                   3842: 
                   3843: =back
                   3844: 
                   3845: =cut
                   3846: 
                   3847: # ------------------------------------------------------------------ File Types
                   3848: sub fileextensions {
                   3849:     return sort(keys(%fe));
                   3850: }
                   3851: 
1.97      www      3852: # ----------------------------------------------------------- Display Languages
                   3853: # returns a hash with all desired display languages
                   3854: #
                   3855: 
                   3856: sub display_languages {
                   3857:     my %languages=();
1.695     raeburn  3858:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3859: 	$languages{$lang}=1;
1.97      www      3860:     }
                   3861:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3862:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3863: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3864: 	    $languages{$lang}=1;
1.97      www      3865:         }
                   3866:     }
                   3867:     return %languages;
1.14      harris41 3868: }
                   3869: 
1.582     albertel 3870: sub languages {
                   3871:     my ($possible_langs) = @_;
1.695     raeburn  3872:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3873:     if (!ref($possible_langs)) {
                   3874: 	if( wantarray ) {
                   3875: 	    return @preferred_langs;
                   3876: 	} else {
                   3877: 	    return $preferred_langs[0];
                   3878: 	}
                   3879:     }
                   3880:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3881:     my @preferred_possibilities;
                   3882:     foreach my $preferred_lang (@preferred_langs) {
                   3883: 	if (exists($possibilities{$preferred_lang})) {
                   3884: 	    push(@preferred_possibilities, $preferred_lang);
                   3885: 	}
                   3886:     }
                   3887:     if( wantarray ) {
                   3888: 	return @preferred_possibilities;
                   3889:     }
                   3890:     return $preferred_possibilities[0];
                   3891: }
                   3892: 
1.742     raeburn  3893: sub user_lang {
                   3894:     my ($touname,$toudom,$fromcid) = @_;
                   3895:     my @userlangs;
                   3896:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3897:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3898:                     $env{'course.'.$fromcid.'.languages'}));
                   3899:     } else {
                   3900:         my %langhash = &getlangs($touname,$toudom);
                   3901:         if ($langhash{'languages'} ne '') {
                   3902:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3903:         } else {
                   3904:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3905:             if ($domdefs{'lang_def'} ne '') {
                   3906:                 @userlangs = ($domdefs{'lang_def'});
                   3907:             }
                   3908:         }
                   3909:     }
                   3910:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3911:     my $user_lh = Apache::localize->get_handle(@languages);
                   3912:     return $user_lh;
                   3913: }
                   3914: 
                   3915: 
1.112     bowersj2 3916: ###############################################################
                   3917: ##               Student Answer Attempts                     ##
                   3918: ###############################################################
                   3919: 
                   3920: =pod
                   3921: 
                   3922: =head1 Alternate Problem Views
                   3923: 
                   3924: =over 4
                   3925: 
1.648     raeburn  3926: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  3927:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 3928: 
                   3929: Return string with previous attempt on problem. Arguments:
                   3930: 
                   3931: =over 4
                   3932: 
                   3933: =item * $symb: Problem, including path
                   3934: 
                   3935: =item * $username: username of the desired student
                   3936: 
                   3937: =item * $domain: domain of the desired student
1.14      harris41 3938: 
1.112     bowersj2 3939: =item * $course: Course ID
1.14      harris41 3940: 
1.112     bowersj2 3941: =item * $getattempt: Leave blank for all attempts, otherwise put
                   3942:     something
1.14      harris41 3943: 
1.112     bowersj2 3944: =item * $regexp: if string matches this regexp, the string will be
                   3945:     sent to $gradesub
1.14      harris41 3946: 
1.112     bowersj2 3947: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 3948: 
1.1075.2.86  raeburn  3949: =item * $usec: section of the desired student
                   3950: 
                   3951: =item * $identifier: counter for student (multiple students one problem) or
                   3952:     problem (one student; whole sequence).
                   3953: 
1.112     bowersj2 3954: =back
1.14      harris41 3955: 
1.112     bowersj2 3956: The output string is a table containing all desired attempts, if any.
1.16      harris41 3957: 
1.112     bowersj2 3958: =cut
1.1       albertel 3959: 
                   3960: sub get_previous_attempt {
1.1075.2.86  raeburn  3961:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 3962:   my $prevattempts='';
1.43      ng       3963:   no strict 'refs';
1.1       albertel 3964:   if ($symb) {
1.3       albertel 3965:     my (%returnhash)=
                   3966:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 3967:     if ($returnhash{'version'}) {
                   3968:       my %lasthash=();
                   3969:       my $version;
                   3970:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  3971:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   3972:             if ($key =~ /\.rawrndseed$/) {
                   3973:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   3974:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   3975:             } else {
                   3976:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   3977:             }
1.19      harris41 3978:         }
1.1       albertel 3979:       }
1.596     albertel 3980:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   3981:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  3982:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  3983:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 3984:       foreach my $key (sort(keys(%lasthash))) {
                   3985: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       3986: 	if ($#parts > 0) {
1.31      albertel 3987: 	  my $data=$parts[-1];
1.989     raeburn  3988:           next if ($data eq 'foilorder');
1.31      albertel 3989: 	  pop(@parts);
1.1010    www      3990:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  3991:           if ($data eq 'type') {
                   3992:               unless ($showsurv) {
                   3993:                   my $id = join(',',@parts);
                   3994:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  3995:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   3996:                       $lasthidden{$ign.'.'.$id} = 1;
                   3997:                   }
1.945     raeburn  3998:               }
1.1075.2.86  raeburn  3999:               if ($identifier ne '') {
                   4000:                   my $id = join(',',@parts);
                   4001:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4002:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4003:                       $hidestatus{$ign.'.'.$id} = 1;
                   4004:                   }
                   4005:               }
                   4006:           } elsif ($data eq 'regrader') {
                   4007:               if (($identifier ne '') && (@parts)) {
                   4008:                   my $id = join(',',@parts);
                   4009:                   $regraded{$ign.'.'.$id} = 1;
                   4010:               }
1.1010    www      4011:           } 
1.31      albertel 4012: 	} else {
1.41      ng       4013: 	  if ($#parts == 0) {
                   4014: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4015: 	  } else {
                   4016: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4017: 	  }
1.31      albertel 4018: 	}
1.16      harris41 4019:       }
1.596     albertel 4020:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4021:       if ($getattempt eq '') {
1.1075.2.86  raeburn  4022:         my (%solved,%resets,%probstatus);
                   4023:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4024:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4025:                 foreach my $id (keys(%regraded)) {
                   4026:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4027:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4028:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4029:                         push(@{$resets{$id}},$version);
                   4030:                     }
                   4031:                 }
                   4032:             }
                   4033:         }
1.40      ng       4034: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  4035:             my (@hidden,@unsolved);
1.945     raeburn  4036:             if (%typeparts) {
                   4037:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  4038:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   4039:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4040:                         push(@hidden,$id);
1.1075.2.86  raeburn  4041:                     } elsif ($identifier ne '') {
                   4042:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4043:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4044:                                 ($hidestatus{$id})) {
                   4045:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   4046:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4047:                                 push(@{$solved{$id}},$version);
                   4048:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4049:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4050:                                 my $skip;
                   4051:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4052:                                     foreach my $reset (@{$resets{$id}}) {
                   4053:                                         if ($reset > $solved{$id}[-1]) {
                   4054:                                             $skip=1;
                   4055:                                             last;
                   4056:                                         }
                   4057:                                     }
                   4058:                                 }
                   4059:                                 unless ($skip) {
                   4060:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4061:                                     push(@unsolved,$partslist);
                   4062:                                 }
                   4063:                             }
                   4064:                         }
1.945     raeburn  4065:                     }
                   4066:                 }
                   4067:             }
                   4068:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  4069:                            '<td>'.&mt('Transaction [_1]',$version);
                   4070:             if (@unsolved) {
                   4071:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4072:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4073:                                  &mt('Hide').'</label></span>';
                   4074:             }
                   4075:             $prevattempts .= '</td>';
1.945     raeburn  4076:             if (@hidden) {
                   4077:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4078:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4079:                     my $hide;
                   4080:                     foreach my $id (@hidden) {
                   4081:                         if ($key =~ /^\Q$id\E/) {
                   4082:                             $hide = 1;
                   4083:                             last;
                   4084:                         }
                   4085:                     }
                   4086:                     if ($hide) {
                   4087:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4088:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4089:                             my $value = &format_previous_attempt_value($key,
                   4090:                                              $returnhash{$version.':'.$key});
                   4091:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4092:                         } else {
                   4093:                             $prevattempts.='<td>&nbsp;</td>';
                   4094:                         }
                   4095:                     } else {
                   4096:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  4097:                             my $value = $returnhash{$version.':'.$key};
                   4098:                             if ($key =~ /\.rndseed$/) {
                   4099:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4100:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4101:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4102:                                 }
                   4103:                             }
                   4104:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4105:                                            '&nbsp;</td>';
1.945     raeburn  4106:                         } else {
                   4107:                             $prevattempts.='<td>&nbsp;</td>';
                   4108:                         }
                   4109:                     }
                   4110:                 }
                   4111:             } else {
                   4112: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4113:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  4114:                     my $value = $returnhash{$version.':'.$key};
                   4115:                     if ($key =~ /\.rndseed$/) {
                   4116:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4117:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4118:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4119:                         }
                   4120:                     }
                   4121:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4122:                                    '&nbsp;</td>';
1.945     raeburn  4123: 	        }
                   4124:             }
                   4125: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4126: 	 }
1.1       albertel 4127:       }
1.945     raeburn  4128:       my @currhidden = keys(%lasthidden);
1.596     albertel 4129:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4130:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4131:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4132:           if (%typeparts) {
                   4133:               my $hidden;
                   4134:               foreach my $id (@currhidden) {
                   4135:                   if ($key =~ /^\Q$id\E/) {
                   4136:                       $hidden = 1;
                   4137:                       last;
                   4138:                   }
                   4139:               }
                   4140:               if ($hidden) {
                   4141:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4142:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4143:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4144:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4145:                           $value = &$gradesub($value);
                   4146:                       }
                   4147:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4148:                   } else {
                   4149:                       $prevattempts.='<td>&nbsp;</td>';
                   4150:                   }
                   4151:               } else {
                   4152:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4153:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4154:                       $value = &$gradesub($value);
                   4155:                   }
                   4156:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4157:               }
                   4158:           } else {
                   4159: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4160: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4161:                   $value = &$gradesub($value);
                   4162:               }
                   4163: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4164:           }
1.16      harris41 4165:       }
1.596     albertel 4166:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4167:     } else {
1.596     albertel 4168:       $prevattempts=
                   4169: 	  &start_data_table().&start_data_table_row().
                   4170: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4171: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4172:     }
                   4173:   } else {
1.596     albertel 4174:     $prevattempts=
                   4175: 	  &start_data_table().&start_data_table_row().
                   4176: 	  '<td>'.&mt('No data.').'</td>'.
                   4177: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4178:   }
1.10      albertel 4179: }
                   4180: 
1.581     albertel 4181: sub format_previous_attempt_value {
                   4182:     my ($key,$value) = @_;
1.1011    www      4183:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 4184: 	$value = &Apache::lonlocal::locallocaltime($value);
                   4185:     } elsif (ref($value) eq 'ARRAY') {
                   4186: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  4187:     } elsif ($key =~ /answerstring$/) {
                   4188:         my %answers = &Apache::lonnet::str2hash($value);
                   4189:         my @anskeys = sort(keys(%answers));
                   4190:         if (@anskeys == 1) {
                   4191:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4192:             if ($answer =~ m{\0}) {
                   4193:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4194:             }
                   4195:             my $tag_internal_answer_name = 'INTERNAL';
                   4196:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4197:                 $value = $answer; 
                   4198:             } else {
                   4199:                 $value = $anskeys[0].'='.$answer;
                   4200:             }
                   4201:         } else {
                   4202:             foreach my $ans (@anskeys) {
                   4203:                 my $answer = $answers{$ans};
1.1001    raeburn  4204:                 if ($answer =~ m{\0}) {
                   4205:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4206:                 }
                   4207:                 $value .=  $ans.'='.$answer.'<br />';;
                   4208:             } 
                   4209:         }
1.581     albertel 4210:     } else {
                   4211: 	$value = &unescape($value);
                   4212:     }
                   4213:     return $value;
                   4214: }
                   4215: 
                   4216: 
1.107     albertel 4217: sub relative_to_absolute {
                   4218:     my ($url,$output)=@_;
                   4219:     my $parser=HTML::TokeParser->new(\$output);
                   4220:     my $token;
                   4221:     my $thisdir=$url;
                   4222:     my @rlinks=();
                   4223:     while ($token=$parser->get_token) {
                   4224: 	if ($token->[0] eq 'S') {
                   4225: 	    if ($token->[1] eq 'a') {
                   4226: 		if ($token->[2]->{'href'}) {
                   4227: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4228: 		}
                   4229: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4230: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4231: 	    } elsif ($token->[1] eq 'base') {
                   4232: 		$thisdir=$token->[2]->{'href'};
                   4233: 	    }
                   4234: 	}
                   4235:     }
                   4236:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4237:     foreach my $link (@rlinks) {
1.726     raeburn  4238: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4239: 		($link=~/^\//) ||
                   4240: 		($link=~/^javascript:/i) ||
                   4241: 		($link=~/^mailto:/i) ||
                   4242: 		($link=~/^\#/)) {
                   4243: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4244: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4245: 	}
                   4246:     }
                   4247: # -------------------------------------------------- Deal with Applet codebases
                   4248:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4249:     return $output;
                   4250: }
                   4251: 
1.112     bowersj2 4252: =pod
                   4253: 
1.648     raeburn  4254: =item * &get_student_view()
1.112     bowersj2 4255: 
                   4256: show a snapshot of what student was looking at
                   4257: 
                   4258: =cut
                   4259: 
1.10      albertel 4260: sub get_student_view {
1.186     albertel 4261:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4262:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4263:   my (%form);
1.10      albertel 4264:   my @elements=('symb','courseid','domain','username');
                   4265:   foreach my $element (@elements) {
1.186     albertel 4266:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4267:   }
1.186     albertel 4268:   if (defined($moreenv)) {
                   4269:       %form=(%form,%{$moreenv});
                   4270:   }
1.236     albertel 4271:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4272:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4273:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4274:   $userview=~s/\<body[^\>]*\>//gi;
                   4275:   $userview=~s/\<\/body\>//gi;
                   4276:   $userview=~s/\<html\>//gi;
                   4277:   $userview=~s/\<\/html\>//gi;
                   4278:   $userview=~s/\<head\>//gi;
                   4279:   $userview=~s/\<\/head\>//gi;
                   4280:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4281:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4282:   if (wantarray) {
                   4283:      return ($userview,$response);
                   4284:   } else {
                   4285:      return $userview;
                   4286:   }
                   4287: }
                   4288: 
                   4289: sub get_student_view_with_retries {
                   4290:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4291: 
                   4292:     my $ok = 0;                 # True if we got a good response.
                   4293:     my $content;
                   4294:     my $response;
                   4295: 
                   4296:     # Try to get the student_view done. within the retries count:
                   4297:     
                   4298:     do {
                   4299:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4300:          $ok      = $response->is_success;
                   4301:          if (!$ok) {
                   4302:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4303:          }
                   4304:          $retries--;
                   4305:     } while (!$ok && ($retries > 0));
                   4306:     
                   4307:     if (!$ok) {
                   4308:        $content = '';          # On error return an empty content.
                   4309:     }
1.651     www      4310:     if (wantarray) {
                   4311:        return ($content, $response);
                   4312:     } else {
                   4313:        return $content;
                   4314:     }
1.11      albertel 4315: }
                   4316: 
1.112     bowersj2 4317: =pod
                   4318: 
1.648     raeburn  4319: =item * &get_student_answers() 
1.112     bowersj2 4320: 
                   4321: show a snapshot of how student was answering problem
                   4322: 
                   4323: =cut
                   4324: 
1.11      albertel 4325: sub get_student_answers {
1.100     sakharuk 4326:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4327:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4328:   my (%moreenv);
1.11      albertel 4329:   my @elements=('symb','courseid','domain','username');
                   4330:   foreach my $element (@elements) {
1.186     albertel 4331:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4332:   }
1.186     albertel 4333:   $moreenv{'grade_target'}='answer';
                   4334:   %moreenv=(%form,%moreenv);
1.497     raeburn  4335:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4336:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4337:   return $userview;
1.1       albertel 4338: }
1.116     albertel 4339: 
                   4340: =pod
                   4341: 
                   4342: =item * &submlink()
                   4343: 
1.242     albertel 4344: Inputs: $text $uname $udom $symb $target
1.116     albertel 4345: 
                   4346: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4347: 
                   4348: =cut
                   4349: 
                   4350: ###############################################
                   4351: sub submlink {
1.242     albertel 4352:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4353:     if (!($uname && $udom)) {
                   4354: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4355: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4356: 	if (!$symb) { $symb=$cursymb; }
                   4357:     }
1.254     matthew  4358:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4359:     $symb=&escape($symb);
1.960     bisitz   4360:     if ($target) { $target=" target=\"$target\""; }
                   4361:     return
                   4362:         '<a href="/adm/grades?command=submission'.
                   4363:         '&amp;symb='.$symb.
                   4364:         '&amp;student='.$uname.
                   4365:         '&amp;userdom='.$udom.'"'.
                   4366:         $target.'>'.$text.'</a>';
1.242     albertel 4367: }
                   4368: ##############################################
                   4369: 
                   4370: =pod
                   4371: 
                   4372: =item * &pgrdlink()
                   4373: 
                   4374: Inputs: $text $uname $udom $symb $target
                   4375: 
                   4376: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4377: 
                   4378: =cut
                   4379: 
                   4380: ###############################################
                   4381: sub pgrdlink {
                   4382:     my $link=&submlink(@_);
                   4383:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4384:     return $link;
                   4385: }
                   4386: ##############################################
                   4387: 
                   4388: =pod
                   4389: 
                   4390: =item * &pprmlink()
                   4391: 
                   4392: Inputs: $text $uname $udom $symb $target
                   4393: 
                   4394: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4395: student and a specific resource
1.242     albertel 4396: 
                   4397: =cut
                   4398: 
                   4399: ###############################################
                   4400: sub pprmlink {
                   4401:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4402:     if (!($uname && $udom)) {
                   4403: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4404: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4405: 	if (!$symb) { $symb=$cursymb; }
                   4406:     }
1.254     matthew  4407:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4408:     $symb=&escape($symb);
1.242     albertel 4409:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4410:     return '<a href="/adm/parmset?command=set&amp;'.
                   4411: 	'symb='.$symb.'&amp;uname='.$uname.
                   4412: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4413: }
                   4414: ##############################################
1.37      matthew  4415: 
1.112     bowersj2 4416: =pod
                   4417: 
                   4418: =back
                   4419: 
                   4420: =cut
                   4421: 
1.37      matthew  4422: ###############################################
1.51      www      4423: 
                   4424: 
                   4425: sub timehash {
1.687     raeburn  4426:     my ($thistime) = @_;
                   4427:     my $timezone = &Apache::lonlocal::gettimezone();
                   4428:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4429:                      ->set_time_zone($timezone);
                   4430:     my $wday = $dt->day_of_week();
                   4431:     if ($wday == 7) { $wday = 0; }
                   4432:     return ( 'second' => $dt->second(),
                   4433:              'minute' => $dt->minute(),
                   4434:              'hour'   => $dt->hour(),
                   4435:              'day'     => $dt->day_of_month(),
                   4436:              'month'   => $dt->month(),
                   4437:              'year'    => $dt->year(),
                   4438:              'weekday' => $wday,
                   4439:              'dayyear' => $dt->day_of_year(),
                   4440:              'dlsav'   => $dt->is_dst() );
1.51      www      4441: }
                   4442: 
1.370     www      4443: sub utc_string {
                   4444:     my ($date)=@_;
1.371     www      4445:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4446: }
                   4447: 
1.51      www      4448: sub maketime {
                   4449:     my %th=@_;
1.687     raeburn  4450:     my ($epoch_time,$timezone,$dt);
                   4451:     $timezone = &Apache::lonlocal::gettimezone();
                   4452:     eval {
                   4453:         $dt = DateTime->new( year   => $th{'year'},
                   4454:                              month  => $th{'month'},
                   4455:                              day    => $th{'day'},
                   4456:                              hour   => $th{'hour'},
                   4457:                              minute => $th{'minute'},
                   4458:                              second => $th{'second'},
                   4459:                              time_zone => $timezone,
                   4460:                          );
                   4461:     };
                   4462:     if (!$@) {
                   4463:         $epoch_time = $dt->epoch;
                   4464:         if ($epoch_time) {
                   4465:             return $epoch_time;
                   4466:         }
                   4467:     }
1.51      www      4468:     return POSIX::mktime(
                   4469:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4470:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4471: }
                   4472: 
                   4473: #########################################
1.51      www      4474: 
                   4475: sub findallcourses {
1.482     raeburn  4476:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4477:     my %roles;
                   4478:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4479:     my %courses;
1.51      www      4480:     my $now=time;
1.482     raeburn  4481:     if (!defined($uname)) {
                   4482:         $uname = $env{'user.name'};
                   4483:     }
                   4484:     if (!defined($udom)) {
                   4485:         $udom = $env{'user.domain'};
                   4486:     }
                   4487:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4488:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4489:         if (!%roles) {
                   4490:             %roles = (
                   4491:                        cc => 1,
1.907     raeburn  4492:                        co => 1,
1.482     raeburn  4493:                        in => 1,
                   4494:                        ep => 1,
                   4495:                        ta => 1,
                   4496:                        cr => 1,
                   4497:                        st => 1,
                   4498:              );
                   4499:         }
                   4500:         foreach my $entry (keys(%roleshash)) {
                   4501:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4502:             if ($trole =~ /^cr/) { 
                   4503:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4504:             } else {
                   4505:                 next if (!exists($roles{$trole}));
                   4506:             }
                   4507:             if ($tend) {
                   4508:                 next if ($tend < $now);
                   4509:             }
                   4510:             if ($tstart) {
                   4511:                 next if ($tstart > $now);
                   4512:             }
1.1058    raeburn  4513:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4514:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4515:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4516:             if ($secpart eq '') {
                   4517:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4518:                 $sec = 'none';
1.1058    raeburn  4519:                 $value .= $cnum.'/';
1.482     raeburn  4520:             } else {
                   4521:                 $cnum = $cnumpart;
                   4522:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4523:                 $value .= $cnum.'/'.$sec;
                   4524:             }
                   4525:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4526:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4527:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4528:                 }
                   4529:             } else {
                   4530:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4531:             }
1.482     raeburn  4532:         }
                   4533:     } else {
                   4534:         foreach my $key (keys(%env)) {
1.483     albertel 4535: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4536:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4537: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4538: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4539: 	        next if (%roles && !exists($roles{$role}));
                   4540: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4541:                 my $active=1;
                   4542:                 if ($starttime) {
                   4543: 		    if ($now<$starttime) { $active=0; }
                   4544:                 }
                   4545:                 if ($endtime) {
                   4546:                     if ($now>$endtime) { $active=0; }
                   4547:                 }
                   4548:                 if ($active) {
1.1058    raeburn  4549:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4550:                     if ($sec eq '') {
                   4551:                         $sec = 'none';
1.1058    raeburn  4552:                     } else {
                   4553:                         $value .= $sec;
                   4554:                     }
                   4555:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4556:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4557:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4558:                         }
                   4559:                     } else {
                   4560:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4561:                     }
1.474     raeburn  4562:                 }
                   4563:             }
1.51      www      4564:         }
                   4565:     }
1.474     raeburn  4566:     return %courses;
1.51      www      4567: }
1.37      matthew  4568: 
1.54      www      4569: ###############################################
1.474     raeburn  4570: 
                   4571: sub blockcheck {
1.1075.2.73  raeburn  4572:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4573: 
1.1075.2.73  raeburn  4574:     if (defined($udom) && defined($uname)) {
                   4575:         # If uname and udom are for a course, check for blocks in the course.
                   4576:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4577:             my ($startblock,$endblock,$triggerblock) =
                   4578:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4579:             return ($startblock,$endblock,$triggerblock);
                   4580:         }
                   4581:     } else {
1.490     raeburn  4582:         $udom = $env{'user.domain'};
                   4583:         $uname = $env{'user.name'};
                   4584:     }
                   4585: 
1.502     raeburn  4586:     my $startblock = 0;
                   4587:     my $endblock = 0;
1.1062    raeburn  4588:     my $triggerblock = '';
1.482     raeburn  4589:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4590: 
1.490     raeburn  4591:     # If uname is for a user, and activity is course-specific, i.e.,
                   4592:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4593: 
1.490     raeburn  4594:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.73  raeburn  4595:          $activity eq 'groups' || $activity eq 'printout') &&
                   4596:         ($env{'request.course.id'})) {
1.490     raeburn  4597:         foreach my $key (keys(%live_courses)) {
                   4598:             if ($key ne $env{'request.course.id'}) {
                   4599:                 delete($live_courses{$key});
                   4600:             }
                   4601:         }
                   4602:     }
                   4603: 
                   4604:     my $otheruser = 0;
                   4605:     my %own_courses;
                   4606:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4607:         # Resource belongs to user other than current user.
                   4608:         $otheruser = 1;
                   4609:         # Gather courses for current user
                   4610:         %own_courses = 
                   4611:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4612:     }
                   4613: 
                   4614:     # Gather active course roles - course coordinator, instructor, 
                   4615:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4616: 
                   4617:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4618:         my ($cdom,$cnum);
                   4619:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4620:             $cdom = $env{'course.'.$course.'.domain'};
                   4621:             $cnum = $env{'course.'.$course.'.num'};
                   4622:         } else {
1.490     raeburn  4623:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4624:         }
                   4625:         my $no_ownblock = 0;
                   4626:         my $no_userblock = 0;
1.533     raeburn  4627:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4628:             # Check if current user has 'evb' priv for this
                   4629:             if (defined($own_courses{$course})) {
                   4630:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4631:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4632:                     if ($sec ne 'none') {
                   4633:                         $checkrole .= '/'.$sec;
                   4634:                     }
                   4635:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4636:                         $no_ownblock = 1;
                   4637:                         last;
                   4638:                     }
                   4639:                 }
                   4640:             }
                   4641:             # if they have 'evb' priv and are currently not playing student
                   4642:             next if (($no_ownblock) &&
                   4643:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4644:         }
1.474     raeburn  4645:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4646:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4647:             if ($sec ne 'none') {
1.482     raeburn  4648:                 $checkrole .= '/'.$sec;
1.474     raeburn  4649:             }
1.490     raeburn  4650:             if ($otheruser) {
                   4651:                 # Resource belongs to user other than current user.
                   4652:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4653:                 my (%allroles,%userroles);
                   4654:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4655:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4656:                         my ($trole,$tdom,$tnum,$tsec);
                   4657:                         if ($entry =~ /^cr/) {
                   4658:                             ($trole,$tdom,$tnum,$tsec) = 
                   4659:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4660:                         } else {
                   4661:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4662:                         }
                   4663:                         my ($spec,$area,$trest);
                   4664:                         $area = '/'.$tdom.'/'.$tnum;
                   4665:                         $trest = $tnum;
                   4666:                         if ($tsec ne '') {
                   4667:                             $area .= '/'.$tsec;
                   4668:                             $trest .= '/'.$tsec;
                   4669:                         }
                   4670:                         $spec = $trole.'.'.$area;
                   4671:                         if ($trole =~ /^cr/) {
                   4672:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4673:                                                               $tdom,$spec,$trest,$area);
                   4674:                         } else {
                   4675:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4676:                                                                 $tdom,$spec,$trest,$area);
                   4677:                         }
                   4678:                     }
                   4679:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
                   4680:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4681:                         if ($1) {
                   4682:                             $no_userblock = 1;
                   4683:                             last;
                   4684:                         }
1.486     raeburn  4685:                     }
                   4686:                 }
1.490     raeburn  4687:             } else {
                   4688:                 # Resource belongs to current user
                   4689:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4690:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4691:                     $no_ownblock = 1;
                   4692:                     last;
                   4693:                 }
1.474     raeburn  4694:             }
                   4695:         }
                   4696:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4697:         next if (($no_ownblock) &&
1.491     albertel 4698:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4699:         next if ($no_userblock);
1.474     raeburn  4700: 
1.866     kalberla 4701:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  4702:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4703:         
1.1062    raeburn  4704:         my ($start,$end,$trigger) = 
                   4705:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4706:         if (($start != 0) && 
                   4707:             (($startblock == 0) || ($startblock > $start))) {
                   4708:             $startblock = $start;
1.1062    raeburn  4709:             if ($trigger ne '') {
                   4710:                 $triggerblock = $trigger;
                   4711:             }
1.502     raeburn  4712:         }
                   4713:         if (($end != 0)  &&
                   4714:             (($endblock == 0) || ($endblock < $end))) {
                   4715:             $endblock = $end;
1.1062    raeburn  4716:             if ($trigger ne '') {
                   4717:                 $triggerblock = $trigger;
                   4718:             }
1.502     raeburn  4719:         }
1.490     raeburn  4720:     }
1.1062    raeburn  4721:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4722: }
                   4723: 
                   4724: sub get_blocks {
1.1062    raeburn  4725:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4726:     my $startblock = 0;
                   4727:     my $endblock = 0;
1.1062    raeburn  4728:     my $triggerblock = '';
1.490     raeburn  4729:     my $course = $cdom.'_'.$cnum;
                   4730:     $setters->{$course} = {};
                   4731:     $setters->{$course}{'staff'} = [];
                   4732:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4733:     $setters->{$course}{'triggers'} = [];
                   4734:     my (@blockers,%triggered);
                   4735:     my $now = time;
                   4736:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4737:     if ($activity eq 'docs') {
                   4738:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4739:         foreach my $block (@blockers) {
                   4740:             if ($block =~ /^firstaccess____(.+)$/) {
                   4741:                 my $item = $1;
                   4742:                 my $type = 'map';
                   4743:                 my $timersymb = $item;
                   4744:                 if ($item eq 'course') {
                   4745:                     $type = 'course';
                   4746:                 } elsif ($item =~ /___\d+___/) {
                   4747:                     $type = 'resource';
                   4748:                 } else {
                   4749:                     $timersymb = &Apache::lonnet::symbread($item);
                   4750:                 }
                   4751:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4752:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4753:                 $triggered{$block} = {
                   4754:                                        start => $start,
                   4755:                                        end   => $end,
                   4756:                                        type  => $type,
                   4757:                                      };
                   4758:             }
                   4759:         }
                   4760:     } else {
                   4761:         foreach my $block (keys(%commblocks)) {
                   4762:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4763:                 my ($start,$end) = ($1,$2);
                   4764:                 if ($start <= time && $end >= time) {
                   4765:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4766:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4767:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4768:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4769:                                     push(@blockers,$block);
                   4770:                                 }
                   4771:                             }
                   4772:                         }
                   4773:                     }
                   4774:                 }
                   4775:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4776:                 my $item = $1;
                   4777:                 my $timersymb = $item; 
                   4778:                 my $type = 'map';
                   4779:                 if ($item eq 'course') {
                   4780:                     $type = 'course';
                   4781:                 } elsif ($item =~ /___\d+___/) {
                   4782:                     $type = 'resource';
                   4783:                 } else {
                   4784:                     $timersymb = &Apache::lonnet::symbread($item);
                   4785:                 }
                   4786:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4787:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4788:                 if ($start && $end) {
                   4789:                     if (($start <= time) && ($end >= time)) {
                   4790:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4791:                             push(@blockers,$block);
                   4792:                             $triggered{$block} = {
                   4793:                                                    start => $start,
                   4794:                                                    end   => $end,
                   4795:                                                    type  => $type,
                   4796:                                                  };
                   4797:                         }
                   4798:                     }
1.490     raeburn  4799:                 }
1.1062    raeburn  4800:             }
                   4801:         }
                   4802:     }
                   4803:     foreach my $blocker (@blockers) {
                   4804:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4805:             &parse_block_record($commblocks{$blocker});
                   4806:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4807:         my ($start,$end,$triggertype);
                   4808:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4809:             ($start,$end) = ($1,$2);
                   4810:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4811:             $start = $triggered{$blocker}{'start'};
                   4812:             $end = $triggered{$blocker}{'end'};
                   4813:             $triggertype = $triggered{$blocker}{'type'};
                   4814:         }
                   4815:         if ($start) {
                   4816:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4817:             if ($triggertype) {
                   4818:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4819:             } else {
                   4820:                 push(@{$$setters{$course}{'triggers'}},0);
                   4821:             }
                   4822:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4823:                 $startblock = $start;
                   4824:                 if ($triggertype) {
                   4825:                     $triggerblock = $blocker;
1.474     raeburn  4826:                 }
                   4827:             }
1.1062    raeburn  4828:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4829:                $endblock = $end;
                   4830:                if ($triggertype) {
                   4831:                    $triggerblock = $blocker;
                   4832:                }
                   4833:             }
1.474     raeburn  4834:         }
                   4835:     }
1.1062    raeburn  4836:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4837: }
                   4838: 
                   4839: sub parse_block_record {
                   4840:     my ($record) = @_;
                   4841:     my ($setuname,$setudom,$title,$blocks);
                   4842:     if (ref($record) eq 'HASH') {
                   4843:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4844:         $title = &unescape($record->{'event'});
                   4845:         $blocks = $record->{'blocks'};
                   4846:     } else {
                   4847:         my @data = split(/:/,$record,3);
                   4848:         if (scalar(@data) eq 2) {
                   4849:             $title = $data[1];
                   4850:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4851:         } else {
                   4852:             ($setuname,$setudom,$title) = @data;
                   4853:         }
                   4854:         $blocks = { 'com' => 'on' };
                   4855:     }
                   4856:     return ($setuname,$setudom,$title,$blocks);
                   4857: }
                   4858: 
1.854     kalberla 4859: sub blocking_status {
1.1075.2.73  raeburn  4860:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  4861:     my %setters;
1.890     droeschl 4862: 
1.1061    raeburn  4863: # check for active blocking
1.1062    raeburn  4864:     my ($startblock,$endblock,$triggerblock) = 
1.1075.2.73  raeburn  4865:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  4866:     my $blocked = 0;
                   4867:     if ($startblock && $endblock) {
                   4868:         $blocked = 1;
                   4869:     }
1.890     droeschl 4870: 
1.1061    raeburn  4871: # caller just wants to know whether a block is active
                   4872:     if (!wantarray) { return $blocked; }
                   4873: 
                   4874: # build a link to a popup window containing the details
                   4875:     my $querystring  = "?activity=$activity";
                   4876: # $uname and $udom decide whose portfolio the user is trying to look at
1.1075.2.97  raeburn  4877:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   4878:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
                   4879:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  4880:     } elsif ($activity eq 'docs') {
                   4881:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4882:     }
1.1061    raeburn  4883: 
                   4884:     my $output .= <<'END_MYBLOCK';
                   4885: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4886:     var options = "width=" + w + ",height=" + h + ",";
                   4887:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4888:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   4889:     var newWin = window.open(url, wdwName, options);
                   4890:     newWin.focus();
                   4891: }
1.890     droeschl 4892: END_MYBLOCK
1.854     kalberla 4893: 
1.1061    raeburn  4894:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 4895:   
1.1061    raeburn  4896:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  4897:     my $text = &mt('Communication Blocked');
1.1075.2.93  raeburn  4898:     my $class = 'LC_comblock';
1.1062    raeburn  4899:     if ($activity eq 'docs') {
                   4900:         $text = &mt('Content Access Blocked');
1.1075.2.93  raeburn  4901:         $class = '';
1.1063    raeburn  4902:     } elsif ($activity eq 'printout') {
                   4903:         $text = &mt('Printing Blocked');
1.1075.2.97  raeburn  4904:     } elsif ($activity eq 'passwd') {
                   4905:         $text = &mt('Password Changing Blocked');
1.1062    raeburn  4906:     }
1.1061    raeburn  4907:     $output .= <<"END_BLOCK";
1.1075.2.93  raeburn  4908: <div class='$class'>
1.869     kalberla 4909:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 4910:   title='$text'>
                   4911:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 4912:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 4913:   title='$text'>$text</a>
1.867     kalberla 4914: </div>
                   4915: 
                   4916: END_BLOCK
1.474     raeburn  4917: 
1.1061    raeburn  4918:     return ($blocked, $output);
1.854     kalberla 4919: }
1.490     raeburn  4920: 
1.60      matthew  4921: ###############################################
                   4922: 
1.682     raeburn  4923: sub check_ip_acc {
1.1075.2.105  raeburn  4924:     my ($acc,$clientip)=@_;
1.682     raeburn  4925:     &Apache::lonxml::debug("acc is $acc");
                   4926:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4927:         return 1;
                   4928:     }
                   4929:     my $allowed=0;
1.1075.2.111  raeburn  4930:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
1.682     raeburn  4931: 
                   4932:     my $name;
                   4933:     foreach my $pattern (split(',',$acc)) {
                   4934:         $pattern =~ s/^\s*//;
                   4935:         $pattern =~ s/\s*$//;
                   4936:         if ($pattern =~ /\*$/) {
                   4937:             #35.8.*
                   4938:             $pattern=~s/\*//;
                   4939:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4940:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   4941:             #35.8.3.[34-56]
                   4942:             my $low=$2;
                   4943:             my $high=$3;
                   4944:             $pattern=$1;
                   4945:             if ($ip =~ /^\Q$pattern\E/) {
                   4946:                 my $last=(split(/\./,$ip))[3];
                   4947:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   4948:             }
                   4949:         } elsif ($pattern =~ /^\*/) {
                   4950:             #*.msu.edu
                   4951:             $pattern=~s/\*//;
                   4952:             if (!defined($name)) {
                   4953:                 use Socket;
                   4954:                 my $netaddr=inet_aton($ip);
                   4955:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4956:             }
                   4957:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4958:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   4959:             #127.0.0.1
                   4960:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4961:         } else {
                   4962:             #some.name.com
                   4963:             if (!defined($name)) {
                   4964:                 use Socket;
                   4965:                 my $netaddr=inet_aton($ip);
                   4966:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4967:             }
                   4968:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4969:         }
                   4970:         if ($allowed) { last; }
                   4971:     }
                   4972:     return $allowed;
                   4973: }
                   4974: 
                   4975: ###############################################
                   4976: 
1.60      matthew  4977: =pod
                   4978: 
1.112     bowersj2 4979: =head1 Domain Template Functions
                   4980: 
                   4981: =over 4
                   4982: 
                   4983: =item * &determinedomain()
1.60      matthew  4984: 
                   4985: Inputs: $domain (usually will be undef)
                   4986: 
1.63      www      4987: Returns: Determines which domain should be used for designs
1.60      matthew  4988: 
                   4989: =cut
1.54      www      4990: 
1.60      matthew  4991: ###############################################
1.63      www      4992: sub determinedomain {
                   4993:     my $domain=shift;
1.531     albertel 4994:     if (! $domain) {
1.60      matthew  4995:         # Determine domain if we have not been given one
1.893     raeburn  4996:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 4997:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   4998:         if ($env{'request.role.domain'}) { 
                   4999:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5000:         }
                   5001:     }
1.63      www      5002:     return $domain;
                   5003: }
                   5004: ###############################################
1.517     raeburn  5005: 
1.518     albertel 5006: sub devalidate_domconfig_cache {
                   5007:     my ($udom)=@_;
                   5008:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5009: }
                   5010: 
                   5011: # ---------------------- Get domain configuration for a domain
                   5012: sub get_domainconf {
                   5013:     my ($udom) = @_;
                   5014:     my $cachetime=1800;
                   5015:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5016:     if (defined($cached)) { return %{$result}; }
                   5017: 
                   5018:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5019: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5020:     my (%designhash,%legacy);
1.518     albertel 5021:     if (keys(%domconfig) > 0) {
                   5022:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5023:             if (keys(%{$domconfig{'login'}})) {
                   5024:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5025:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  5026:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5027:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5028:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5029:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5030:                                         if ($key eq 'loginvia') {
                   5031:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5032:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5033:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5034:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5035:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5036:                                                 } else {
                   5037:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5038:                                                 }
1.948     raeburn  5039:                                             }
1.1075.2.87  raeburn  5040:                                         } elsif ($key eq 'headtag') {
                   5041:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5042:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5043:                                             }
1.946     raeburn  5044:                                         }
1.1075.2.87  raeburn  5045:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5046:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5047:                                         }
1.946     raeburn  5048:                                     }
                   5049:                                 }
                   5050:                             }
                   5051:                         } else {
                   5052:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5053:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5054:                                     $domconfig{'login'}{$key}{$img};
                   5055:                             }
1.699     raeburn  5056:                         }
                   5057:                     } else {
                   5058:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5059:                     }
1.632     raeburn  5060:                 }
                   5061:             } else {
                   5062:                 $legacy{'login'} = 1;
1.518     albertel 5063:             }
1.632     raeburn  5064:         } else {
                   5065:             $legacy{'login'} = 1;
1.518     albertel 5066:         }
                   5067:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5068:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5069:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5070:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5071:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5072:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5073:                         }
1.518     albertel 5074:                     }
                   5075:                 }
1.632     raeburn  5076:             } else {
                   5077:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5078:             }
1.632     raeburn  5079:         } else {
                   5080:             $legacy{'rolecolors'} = 1;
1.518     albertel 5081:         }
1.948     raeburn  5082:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5083:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5084:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5085:             }
                   5086:         }
1.632     raeburn  5087:         if (keys(%legacy) > 0) {
                   5088:             my %legacyhash = &get_legacy_domconf($udom);
                   5089:             foreach my $item (keys(%legacyhash)) {
                   5090:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5091:                     if ($legacy{'login'}) { 
                   5092:                         $designhash{$item} = $legacyhash{$item};
                   5093:                     }
                   5094:                 } else {
                   5095:                     if ($legacy{'rolecolors'}) {
                   5096:                         $designhash{$item} = $legacyhash{$item};
                   5097:                     }
1.518     albertel 5098:                 }
                   5099:             }
                   5100:         }
1.632     raeburn  5101:     } else {
                   5102:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5103:     }
                   5104:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5105: 				  $cachetime);
                   5106:     return %designhash;
                   5107: }
                   5108: 
1.632     raeburn  5109: sub get_legacy_domconf {
                   5110:     my ($udom) = @_;
                   5111:     my %legacyhash;
                   5112:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5113:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5114:     if (-e $designfile) {
                   5115:         if ( open (my $fh,"<$designfile") ) {
                   5116:             while (my $line = <$fh>) {
                   5117:                 next if ($line =~ /^\#/);
                   5118:                 chomp($line);
                   5119:                 my ($key,$val)=(split(/\=/,$line));
                   5120:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5121:             }
                   5122:             close($fh);
                   5123:         }
                   5124:     }
1.1026    raeburn  5125:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5126:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5127:     }
                   5128:     return %legacyhash;
                   5129: }
                   5130: 
1.63      www      5131: =pod
                   5132: 
1.112     bowersj2 5133: =item * &domainlogo()
1.63      www      5134: 
                   5135: Inputs: $domain (usually will be undef)
                   5136: 
                   5137: Returns: A link to a domain logo, if the domain logo exists.
                   5138: If the domain logo does not exist, a description of the domain.
                   5139: 
                   5140: =cut
1.112     bowersj2 5141: 
1.63      www      5142: ###############################################
                   5143: sub domainlogo {
1.517     raeburn  5144:     my $domain = &determinedomain(shift);
1.518     albertel 5145:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5146:     # See if there is a logo
                   5147:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5148:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5149:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5150: 	    if ($imgsrc =~ m{^/res/}) {
                   5151: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5152: 		&Apache::lonnet::repcopy($local_name);
                   5153: 	    }
                   5154: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5155:         } 
                   5156:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5157:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5158:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5159:     } else {
1.60      matthew  5160:         return '';
1.59      www      5161:     }
                   5162: }
1.63      www      5163: ##############################################
                   5164: 
                   5165: =pod
                   5166: 
1.112     bowersj2 5167: =item * &designparm()
1.63      www      5168: 
                   5169: Inputs: $which parameter; $domain (usually will be undef)
                   5170: 
                   5171: Returns: value of designparamter $which
                   5172: 
                   5173: =cut
1.112     bowersj2 5174: 
1.397     albertel 5175: 
1.400     albertel 5176: ##############################################
1.397     albertel 5177: sub designparm {
                   5178:     my ($which,$domain)=@_;
                   5179:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5180:         return $env{'environment.color.'.$which};
1.96      www      5181:     }
1.63      www      5182:     $domain=&determinedomain($domain);
1.1016    raeburn  5183:     my %domdesign;
                   5184:     unless ($domain eq 'public') {
                   5185:         %domdesign = &get_domainconf($domain);
                   5186:     }
1.520     raeburn  5187:     my $output;
1.517     raeburn  5188:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5189:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5190:     } else {
1.520     raeburn  5191:         $output = $defaultdesign{$which};
                   5192:     }
                   5193:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5194:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5195:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5196:             if ($output =~ m{^/res/}) {
                   5197:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5198:                 &Apache::lonnet::repcopy($local_name);
                   5199:             }
1.520     raeburn  5200:             $output = &lonhttpdurl($output);
                   5201:         }
1.63      www      5202:     }
1.520     raeburn  5203:     return $output;
1.63      www      5204: }
1.59      www      5205: 
1.822     bisitz   5206: ##############################################
                   5207: =pod
                   5208: 
1.832     bisitz   5209: =item * &authorspace()
                   5210: 
1.1028    raeburn  5211: Inputs: $url (usually will be undef).
1.832     bisitz   5212: 
1.1075.2.40  raeburn  5213: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5214:          directory being viewed (or for which action is being taken). 
                   5215:          If $url is provided, and begins /priv/<domain>/<uname>
                   5216:          the path will be that portion of the $context argument.
                   5217:          Otherwise the path will be for the author space of the current
                   5218:          user when the current role is author, or for that of the 
                   5219:          co-author/assistant co-author space when the current role 
                   5220:          is co-author or assistant co-author.
1.832     bisitz   5221: 
                   5222: =cut
                   5223: 
                   5224: sub authorspace {
1.1028    raeburn  5225:     my ($url) = @_;
                   5226:     if ($url ne '') {
                   5227:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5228:            return $1;
                   5229:         }
                   5230:     }
1.832     bisitz   5231:     my $caname = '';
1.1024    www      5232:     my $cadom = '';
1.1028    raeburn  5233:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5234:         ($cadom,$caname) =
1.832     bisitz   5235:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5236:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5237:         $caname = $env{'user.name'};
1.1024    www      5238:         $cadom = $env{'user.domain'};
1.832     bisitz   5239:     }
1.1028    raeburn  5240:     if (($caname ne '') && ($cadom ne '')) {
                   5241:         return "/priv/$cadom/$caname/";
                   5242:     }
                   5243:     return;
1.832     bisitz   5244: }
                   5245: 
                   5246: ##############################################
                   5247: =pod
                   5248: 
1.822     bisitz   5249: =item * &head_subbox()
                   5250: 
                   5251: Inputs: $content (contains HTML code with page functions, etc.)
                   5252: 
                   5253: Returns: HTML div with $content
                   5254:          To be included in page header
                   5255: 
                   5256: =cut
                   5257: 
                   5258: sub head_subbox {
                   5259:     my ($content)=@_;
                   5260:     my $output =
1.993     raeburn  5261:         '<div class="LC_head_subbox">'
1.822     bisitz   5262:        .$content
                   5263:        .'</div>'
                   5264: }
                   5265: 
                   5266: ##############################################
                   5267: =pod
                   5268: 
                   5269: =item * &CSTR_pageheader()
                   5270: 
1.1026    raeburn  5271: Input: (optional) filename from which breadcrumb trail is built.
                   5272:        In most cases no input as needed, as $env{'request.filename'}
                   5273:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5274: 
                   5275: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5276:          To be included on Authoring Space pages
1.822     bisitz   5277: 
                   5278: =cut
                   5279: 
                   5280: sub CSTR_pageheader {
1.1026    raeburn  5281:     my ($trailfile) = @_;
                   5282:     if ($trailfile eq '') {
                   5283:         $trailfile = $env{'request.filename'};
                   5284:     }
                   5285: 
                   5286: # this is for resources; directories have customtitle, and crumbs
                   5287: # and select recent are created in lonpubdir.pm
                   5288: 
                   5289:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5290:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5291:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5292:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5293:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5294: 
                   5295:     my $parentpath = '';
                   5296:     my $lastitem = '';
                   5297:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5298:         $parentpath = $1;
                   5299:         $lastitem = $2;
                   5300:     } else {
                   5301:         $lastitem = $thisdisfn;
                   5302:     }
1.921     bisitz   5303: 
                   5304:     my $output =
1.822     bisitz   5305:          '<div>'
                   5306:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  5307:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5308:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5309:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5310:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5311: 
                   5312:     if ($lastitem) {
                   5313:         $output .=
                   5314:              '<span class="LC_filename">'
                   5315:             .$lastitem
                   5316:             .'</span>';
                   5317:     }
                   5318:     $output .=
                   5319:          '<br />'
1.822     bisitz   5320:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5321:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5322:         .'</form>'
                   5323:         .&Apache::lonmenu::constspaceform()
                   5324:         .'</div>';
1.921     bisitz   5325: 
                   5326:     return $output;
1.822     bisitz   5327: }
                   5328: 
1.60      matthew  5329: ###############################################
                   5330: ###############################################
                   5331: 
                   5332: =pod
                   5333: 
1.112     bowersj2 5334: =back
                   5335: 
1.549     albertel 5336: =head1 HTML Helpers
1.112     bowersj2 5337: 
                   5338: =over 4
                   5339: 
                   5340: =item * &bodytag()
1.60      matthew  5341: 
                   5342: Returns a uniform header for LON-CAPA web pages.
                   5343: 
                   5344: Inputs: 
                   5345: 
1.112     bowersj2 5346: =over 4
                   5347: 
                   5348: =item * $title, A title to be displayed on the page.
                   5349: 
                   5350: =item * $function, the current role (can be undef).
                   5351: 
                   5352: =item * $addentries, extra parameters for the <body> tag.
                   5353: 
                   5354: =item * $bodyonly, if defined, only return the <body> tag.
                   5355: 
                   5356: =item * $domain, if defined, force a given domain.
                   5357: 
                   5358: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5359:             text interface only)
1.60      matthew  5360: 
1.814     bisitz   5361: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5362:                      navigational links
1.317     albertel 5363: 
1.338     albertel 5364: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5365: 
1.1075.2.12  raeburn  5366: =item * $no_inline_link, if true and in remote mode, don't show the
                   5367:          'Switch To Inline Menu' link
                   5368: 
1.460     albertel 5369: =item * $args, optional argument valid values are
                   5370:             no_auto_mt_title -> prevents &mt()ing the title arg
                   5371: 
1.1075.2.15  raeburn  5372: =item * $advtoolsref, optional argument, ref to an array containing
                   5373:             inlineremote items to be added in "Functions" menu below
                   5374:             breadcrumbs.
                   5375: 
1.112     bowersj2 5376: =back
                   5377: 
1.60      matthew  5378: Returns: A uniform header for LON-CAPA web pages.  
                   5379: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5380: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5381: other decorations will be returned.
                   5382: 
                   5383: =cut
                   5384: 
1.54      www      5385: sub bodytag {
1.831     bisitz   5386:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.15  raeburn  5387:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
1.339     albertel 5388: 
1.954     raeburn  5389:     my $public;
                   5390:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5391:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5392:         $public = 1;
                   5393:     }
1.460     albertel 5394:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5395:     my $httphost = $args->{'use_absolute'};
1.339     albertel 5396: 
1.183     matthew  5397:     $function = &get_users_function() if (!$function);
1.339     albertel 5398:     my $img =    &designparm($function.'.img',$domain);
                   5399:     my $font =   &designparm($function.'.font',$domain);
                   5400:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5401: 
1.803     bisitz   5402:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5403: 		   'bgcolor' => $pgbg,
1.339     albertel 5404: 		   'text'    => $font,
                   5405:                    'alink'   => &designparm($function.'.alink',$domain),
                   5406: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5407: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5408:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5409: 
1.63      www      5410:  # role and realm
1.1075.2.68  raeburn  5411:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5412:     if ($realm) {
                   5413:         $realm = '/'.$realm;
                   5414:     }
1.378     raeburn  5415:     if ($role  eq 'ca') {
1.479     albertel 5416:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5417:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5418:     } 
1.55      www      5419: # realm
1.258     albertel 5420:     if ($env{'request.course.id'}) {
1.378     raeburn  5421:         if ($env{'request.role'} !~ /^cr/) {
                   5422:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   5423:         }
1.898     raeburn  5424:         if ($env{'request.course.sec'}) {
                   5425:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5426:         }   
1.359     albertel 5427: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5428:     } else {
                   5429:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5430:     }
1.433     albertel 5431: 
1.359     albertel 5432:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5433: 
1.438     albertel 5434:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5435: 
1.101     www      5436: # construct main body tag
1.359     albertel 5437:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  5438: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5439: 
1.1075.2.38  raeburn  5440:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5441: 
                   5442:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5443:         return $bodytag;
1.1075.2.38  raeburn  5444:     }
1.359     albertel 5445: 
1.954     raeburn  5446:     if ($public) {
1.433     albertel 5447: 	undef($role);
                   5448:     }
1.359     albertel 5449:     
1.762     bisitz   5450:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5451:     #
                   5452:     # Extra info if you are the DC
                   5453:     my $dc_info = '';
                   5454:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5455:                         $env{'course.'.$env{'request.course.id'}.
                   5456:                                  '.domain'}.'/'})) {
                   5457:         my $cid = $env{'request.course.id'};
1.917     raeburn  5458:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5459:         $dc_info =~ s/\s+$//;
1.359     albertel 5460:     }
                   5461: 
1.1075.2.108  raeburn  5462:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 5463: 
1.1075.2.13  raeburn  5464:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5465: 
1.1075.2.38  raeburn  5466: 
                   5467: 
1.1075.2.21  raeburn  5468:     my $funclist;
                   5469:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  5470:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  5471:                     Apache::lonmenu::serverform();
                   5472:         my $forbodytag;
                   5473:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5474:                                             $forcereg,$args->{'group'},
                   5475:                                             $args->{'bread_crumbs'},
                   5476:                                             $advtoolsref,'',\$forbodytag);
                   5477:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5478:             $funclist = $forbodytag;
                   5479:         }
                   5480:     } else {
1.903     droeschl 5481: 
                   5482:         #    if ($env{'request.state'} eq 'construct') {
                   5483:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5484:         #    }
                   5485: 
1.1075.2.38  raeburn  5486:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5487:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5488: 
1.1075.2.38  raeburn  5489:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.1075.2.2  raeburn  5490: 
1.916     droeschl 5491:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.1075.2.22  raeburn  5492:             if ($dc_info) {
                   5493:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
1.1075.2.1  raeburn  5494:             }
1.1075.2.38  raeburn  5495:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.1075.2.22  raeburn  5496:                            <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5497:             return $bodytag;
                   5498:         }
1.894     droeschl 5499: 
1.927     raeburn  5500:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1075.2.38  raeburn  5501:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5502:         }
1.916     droeschl 5503: 
1.1075.2.38  raeburn  5504:         $bodytag .= $right;
1.852     droeschl 5505: 
1.917     raeburn  5506:         if ($dc_info) {
                   5507:             $dc_info = &dc_courseid_toggle($dc_info);
                   5508:         }
                   5509:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5510: 
1.1075.2.61  raeburn  5511:         #if directed to not display the secondary menu, don't.
                   5512:         if ($args->{'no_secondary_menu'}) {
                   5513:             return $bodytag;
                   5514:         }
1.903     droeschl 5515:         #don't show menus for public users
1.954     raeburn  5516:         if (!$public){
1.1075.2.52  raeburn  5517:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5518:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5519:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5520:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5521:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5522:                                 $args->{'bread_crumbs'});
                   5523:             } elsif ($forcereg) { 
1.1075.2.22  raeburn  5524:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
                   5525:                                                             $args->{'group'});
1.1075.2.15  raeburn  5526:             } else {
1.1075.2.21  raeburn  5527:                 my $forbodytag;
                   5528:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5529:                                                     $forcereg,$args->{'group'},
                   5530:                                                     $args->{'bread_crumbs'},
                   5531:                                                     $advtoolsref,'',\$forbodytag);
                   5532:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5533:                     $bodytag .= $forbodytag;
                   5534:                 }
1.920     raeburn  5535:             }
1.903     droeschl 5536:         }else{
                   5537:             # this is to seperate menu from content when there's no secondary
                   5538:             # menu. Especially needed for public accessible ressources.
                   5539:             $bodytag .= '<hr style="clear:both" />';
                   5540:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5541:         }
1.903     droeschl 5542: 
1.235     raeburn  5543:         return $bodytag;
1.1075.2.12  raeburn  5544:     }
                   5545: 
                   5546: #
                   5547: # Top frame rendering, Remote is up
                   5548: #
                   5549: 
                   5550:     my $imgsrc = $img;
                   5551:     if ($img =~ /^\/adm/) {
                   5552:         $imgsrc = &lonhttpdurl($img);
                   5553:     }
                   5554:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5555: 
1.1075.2.60  raeburn  5556:     my $help=($no_inline_link?''
                   5557:               :&Apache::loncommon::top_nav_help('Help'));
                   5558: 
1.1075.2.12  raeburn  5559:     # Explicit link to get inline menu
                   5560:     my $menu= ($no_inline_link?''
                   5561:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5562: 
                   5563:     if ($dc_info) {
                   5564:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5565:     }
                   5566: 
1.1075.2.38  raeburn  5567:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   5568:     unless ($public) {
                   5569:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5570:                                 undef,'LC_menubuttons_link');
                   5571:     }
                   5572: 
1.1075.2.12  raeburn  5573:     unless ($env{'form.inhibitmenu'}) {
                   5574:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  5575:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  5576:                        <li>$help</li>
1.1075.2.12  raeburn  5577:                        <li>$menu</li>
                   5578:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5579:     }
1.1075.2.13  raeburn  5580:     if ($env{'request.state'} eq 'construct') {
                   5581:         if (!$public){
                   5582:             if ($env{'request.state'} eq 'construct') {
                   5583:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5584:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  5585:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5586:                             &Apache::lonmenu::innerregister($forcereg,
                   5587:                                                             $args->{'bread_crumbs'});
                   5588:             }
                   5589:         }
                   5590:     }
1.1075.2.21  raeburn  5591:     return $bodytag."\n".$funclist;
1.182     matthew  5592: }
                   5593: 
1.917     raeburn  5594: sub dc_courseid_toggle {
                   5595:     my ($dc_info) = @_;
1.980     raeburn  5596:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5597:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5598:            &mt('(More ...)').'</a></span>'.
                   5599:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5600: }
                   5601: 
1.330     albertel 5602: sub make_attr_string {
                   5603:     my ($register,$attr_ref) = @_;
                   5604: 
                   5605:     if ($attr_ref && !ref($attr_ref)) {
                   5606: 	die("addentries Must be a hash ref ".
                   5607: 	    join(':',caller(1))." ".
                   5608: 	    join(':',caller(0))." ");
                   5609:     }
                   5610: 
                   5611:     if ($register) {
1.339     albertel 5612: 	my ($on_load,$on_unload);
                   5613: 	foreach my $key (keys(%{$attr_ref})) {
                   5614: 	    if      (lc($key) eq 'onload') {
                   5615: 		$on_load.=$attr_ref->{$key}.';';
                   5616: 		delete($attr_ref->{$key});
                   5617: 
                   5618: 	    } elsif (lc($key) eq 'onunload') {
                   5619: 		$on_unload.=$attr_ref->{$key}.';';
                   5620: 		delete($attr_ref->{$key});
                   5621: 	    }
                   5622: 	}
1.1075.2.12  raeburn  5623:         if ($env{'environment.remote'} eq 'on') {
                   5624:             $attr_ref->{'onload'}  =
                   5625:                 &Apache::lonmenu::loadevents().  $on_load;
                   5626:             $attr_ref->{'onunload'}=
                   5627:                 &Apache::lonmenu::unloadevents().$on_unload;
                   5628:         } else {  
                   5629: 	    $attr_ref->{'onload'}  = $on_load;
                   5630: 	    $attr_ref->{'onunload'}= $on_unload;
                   5631:         }
1.330     albertel 5632:     }
1.339     albertel 5633: 
1.330     albertel 5634:     my $attr_string;
1.1075.2.56  raeburn  5635:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5636: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5637:     }
                   5638:     return $attr_string;
                   5639: }
                   5640: 
                   5641: 
1.182     matthew  5642: ###############################################
1.251     albertel 5643: ###############################################
                   5644: 
                   5645: =pod
                   5646: 
                   5647: =item * &endbodytag()
                   5648: 
                   5649: Returns a uniform footer for LON-CAPA web pages.
                   5650: 
1.635     raeburn  5651: Inputs: 1 - optional reference to an args hash
                   5652: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5653: a 'Continue' link is not displayed if the page contains an
                   5654: internal redirect in the <head></head> section,
                   5655: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5656: 
                   5657: =cut
                   5658: 
                   5659: sub endbodytag {
1.635     raeburn  5660:     my ($args) = @_;
1.1075.2.6  raeburn  5661:     my $endbodytag;
                   5662:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5663:         $endbodytag='</body>';
                   5664:     }
1.315     albertel 5665:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5666:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5667: 	    $endbodytag=
                   5668: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5669: 	        &mt('Continue').'</a>'.
                   5670: 	        $endbodytag;
                   5671:         }
1.315     albertel 5672:     }
1.251     albertel 5673:     return $endbodytag;
                   5674: }
                   5675: 
1.352     albertel 5676: =pod
                   5677: 
                   5678: =item * &standard_css()
                   5679: 
                   5680: Returns a style sheet
                   5681: 
                   5682: Inputs: (all optional)
                   5683:             domain         -> force to color decorate a page for a specific
                   5684:                                domain
                   5685:             function       -> force usage of a specific rolish color scheme
                   5686:             bgcolor        -> override the default page bgcolor
                   5687: 
                   5688: =cut
                   5689: 
1.343     albertel 5690: sub standard_css {
1.345     albertel 5691:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5692:     $function  = &get_users_function() if (!$function);
                   5693:     my $img    = &designparm($function.'.img',   $domain);
                   5694:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5695:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5696:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5697: #second colour for later usage
1.345     albertel 5698:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5699:     my $pgbg_or_bgcolor =
                   5700: 	         $bgcolor ||
1.352     albertel 5701: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5702:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5703:     my $alink  = &designparm($function.'.alink', $domain);
                   5704:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5705:     my $link   = &designparm($function.'.link',  $domain);
                   5706: 
1.602     albertel 5707:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5708:     my $mono                 = 'monospace';
1.850     bisitz   5709:     my $data_table_head      = $sidebg;
                   5710:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5711:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5712:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5713:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5714:     my $mail_new             = '#FFBB77';
                   5715:     my $mail_new_hover       = '#DD9955';
                   5716:     my $mail_read            = '#BBBB77';
                   5717:     my $mail_read_hover      = '#999944';
                   5718:     my $mail_replied         = '#AAAA88';
                   5719:     my $mail_replied_hover   = '#888855';
                   5720:     my $mail_other           = '#99BBBB';
                   5721:     my $mail_other_hover     = '#669999';
1.391     albertel 5722:     my $table_header         = '#DDDDDD';
1.489     raeburn  5723:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5724:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5725:     my $button_hover         = '#BF2317';
1.392     albertel 5726: 
1.608     albertel 5727:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5728:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5729:                                              : '0 3px 0 4px';
1.448     albertel 5730: 
1.523     albertel 5731: 
1.343     albertel 5732:     return <<END;
1.947     droeschl 5733: 
                   5734: /* needed for iframe to allow 100% height in FF */
                   5735: body, html { 
                   5736:     margin: 0;
                   5737:     padding: 0 0.5%;
                   5738:     height: 99%; /* to avoid scrollbars */
                   5739: }
                   5740: 
1.795     www      5741: body {
1.911     bisitz   5742:   font-family: $sans;
                   5743:   line-height:130%;
                   5744:   font-size:0.83em;
                   5745:   color:$font;
1.795     www      5746: }
                   5747: 
1.959     onken    5748: a:focus,
                   5749: a:focus img {
1.795     www      5750:   color: red;
                   5751: }
1.698     harmsja  5752: 
1.911     bisitz   5753: form, .inline {
                   5754:   display: inline;
1.795     www      5755: }
1.721     harmsja  5756: 
1.795     www      5757: .LC_right {
1.911     bisitz   5758:   text-align:right;
1.795     www      5759: }
                   5760: 
                   5761: .LC_middle {
1.911     bisitz   5762:   vertical-align:middle;
1.795     www      5763: }
1.721     harmsja  5764: 
1.1075.2.38  raeburn  5765: .LC_floatleft {
                   5766:   float: left;
                   5767: }
                   5768: 
                   5769: .LC_floatright {
                   5770:   float: right;
                   5771: }
                   5772: 
1.911     bisitz   5773: .LC_400Box {
                   5774:   width:400px;
                   5775: }
1.721     harmsja  5776: 
1.947     droeschl 5777: .LC_iframecontainer {
                   5778:     width: 98%;
                   5779:     margin: 0;
                   5780:     position: fixed;
                   5781:     top: 8.5em;
                   5782:     bottom: 0;
                   5783: }
                   5784: 
                   5785: .LC_iframecontainer iframe{
                   5786:     border: none;
                   5787:     width: 100%;
                   5788:     height: 100%;
                   5789: }
                   5790: 
1.778     bisitz   5791: .LC_filename {
                   5792:   font-family: $mono;
                   5793:   white-space:pre;
1.921     bisitz   5794:   font-size: 120%;
1.778     bisitz   5795: }
                   5796: 
                   5797: .LC_fileicon {
                   5798:   border: none;
                   5799:   height: 1.3em;
                   5800:   vertical-align: text-bottom;
                   5801:   margin-right: 0.3em;
                   5802:   text-decoration:none;
                   5803: }
                   5804: 
1.1008    www      5805: .LC_setting {
                   5806:   text-decoration:underline;
                   5807: }
                   5808: 
1.350     albertel 5809: .LC_error {
                   5810:   color: red;
                   5811: }
1.795     www      5812: 
1.1075.2.15  raeburn  5813: .LC_warning {
                   5814:   color: darkorange;
                   5815: }
                   5816: 
1.457     albertel 5817: .LC_diff_removed {
1.733     bisitz   5818:   color: red;
1.394     albertel 5819: }
1.532     albertel 5820: 
                   5821: .LC_info,
1.457     albertel 5822: .LC_success,
                   5823: .LC_diff_added {
1.350     albertel 5824:   color: green;
                   5825: }
1.795     www      5826: 
1.802     bisitz   5827: div.LC_confirm_box {
                   5828:   background-color: #FAFAFA;
                   5829:   border: 1px solid $lg_border_color;
                   5830:   margin-right: 0;
                   5831:   padding: 5px;
                   5832: }
                   5833: 
                   5834: div.LC_confirm_box .LC_error img,
                   5835: div.LC_confirm_box .LC_success img {
                   5836:   vertical-align: middle;
                   5837: }
                   5838: 
1.1075.2.108  raeburn  5839: .LC_maxwidth {
                   5840:   max-width: 100%;
                   5841:   height: auto;
                   5842: }
                   5843: 
                   5844: .LC_textsize_mobile {
                   5845:   \@media only screen and (max-device-width: 480px) {
                   5846:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   5847:   }
                   5848: }
                   5849: 
1.440     albertel 5850: .LC_icon {
1.771     droeschl 5851:   border: none;
1.790     droeschl 5852:   vertical-align: middle;
1.771     droeschl 5853: }
                   5854: 
1.543     albertel 5855: .LC_docs_spacer {
                   5856:   width: 25px;
                   5857:   height: 1px;
1.771     droeschl 5858:   border: none;
1.543     albertel 5859: }
1.346     albertel 5860: 
1.532     albertel 5861: .LC_internal_info {
1.735     bisitz   5862:   color: #999999;
1.532     albertel 5863: }
                   5864: 
1.794     www      5865: .LC_discussion {
1.1050    www      5866:   background: $data_table_dark;
1.911     bisitz   5867:   border: 1px solid black;
                   5868:   margin: 2px;
1.794     www      5869: }
                   5870: 
                   5871: .LC_disc_action_left {
1.1050    www      5872:   background: $sidebg;
1.911     bisitz   5873:   text-align: left;
1.1050    www      5874:   padding: 4px;
                   5875:   margin: 2px;
1.794     www      5876: }
                   5877: 
                   5878: .LC_disc_action_right {
1.1050    www      5879:   background: $sidebg;
1.911     bisitz   5880:   text-align: right;
1.1050    www      5881:   padding: 4px;
                   5882:   margin: 2px;
1.794     www      5883: }
                   5884: 
                   5885: .LC_disc_new_item {
1.911     bisitz   5886:   background: white;
                   5887:   border: 2px solid red;
1.1050    www      5888:   margin: 4px;
                   5889:   padding: 4px;
1.794     www      5890: }
                   5891: 
                   5892: .LC_disc_old_item {
1.911     bisitz   5893:   background: white;
1.1050    www      5894:   margin: 4px;
                   5895:   padding: 4px;
1.794     www      5896: }
                   5897: 
1.458     albertel 5898: table.LC_pastsubmission {
                   5899:   border: 1px solid black;
                   5900:   margin: 2px;
                   5901: }
                   5902: 
1.924     bisitz   5903: table#LC_menubuttons {
1.345     albertel 5904:   width: 100%;
                   5905:   background: $pgbg;
1.392     albertel 5906:   border: 2px;
1.402     albertel 5907:   border-collapse: separate;
1.803     bisitz   5908:   padding: 0;
1.345     albertel 5909: }
1.392     albertel 5910: 
1.801     tempelho 5911: table#LC_title_bar a {
                   5912:   color: $fontmenu;
                   5913: }
1.836     bisitz   5914: 
1.807     droeschl 5915: table#LC_title_bar {
1.819     tempelho 5916:   clear: both;
1.836     bisitz   5917:   display: none;
1.807     droeschl 5918: }
                   5919: 
1.795     www      5920: table#LC_title_bar,
1.933     droeschl 5921: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5922: table#LC_title_bar.LC_with_remote {
1.359     albertel 5923:   width: 100%;
1.392     albertel 5924:   border-color: $pgbg;
                   5925:   border-style: solid;
                   5926:   border-width: $border;
1.379     albertel 5927:   background: $pgbg;
1.801     tempelho 5928:   color: $fontmenu;
1.392     albertel 5929:   border-collapse: collapse;
1.803     bisitz   5930:   padding: 0;
1.819     tempelho 5931:   margin: 0;
1.359     albertel 5932: }
1.795     www      5933: 
1.933     droeschl 5934: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5935:     margin: 0;
                   5936:     padding: 0;
1.933     droeschl 5937:     position: relative;
                   5938:     list-style: none;
1.913     droeschl 5939: }
1.933     droeschl 5940: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5941:     display: inline;
                   5942: }
1.933     droeschl 5943: 
                   5944: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5945:     padding: 0;
1.933     droeschl 5946:     margin: 0;
                   5947:     float: left;
1.913     droeschl 5948: }
1.933     droeschl 5949: .LC_breadcrumb_tools_tools {
                   5950:     padding: 0;
                   5951:     margin: 0;
1.913     droeschl 5952:     float: right;
                   5953: }
                   5954: 
1.359     albertel 5955: table#LC_title_bar td {
                   5956:   background: $tabbg;
                   5957: }
1.795     www      5958: 
1.911     bisitz   5959: table#LC_menubuttons img {
1.803     bisitz   5960:   border: none;
1.346     albertel 5961: }
1.795     www      5962: 
1.842     droeschl 5963: .LC_breadcrumbs_component {
1.911     bisitz   5964:   float: right;
                   5965:   margin: 0 1em;
1.357     albertel 5966: }
1.842     droeschl 5967: .LC_breadcrumbs_component img {
1.911     bisitz   5968:   vertical-align: middle;
1.777     tempelho 5969: }
1.795     www      5970: 
1.1075.2.108  raeburn  5971: .LC_breadcrumbs_hoverable {
                   5972:   background: $sidebg;
                   5973: }
                   5974: 
1.383     albertel 5975: td.LC_table_cell_checkbox {
                   5976:   text-align: center;
                   5977: }
1.795     www      5978: 
                   5979: .LC_fontsize_small {
1.911     bisitz   5980:   font-size: 70%;
1.705     tempelho 5981: }
                   5982: 
1.844     bisitz   5983: #LC_breadcrumbs {
1.911     bisitz   5984:   clear:both;
                   5985:   background: $sidebg;
                   5986:   border-bottom: 1px solid $lg_border_color;
                   5987:   line-height: 2.5em;
1.933     droeschl 5988:   overflow: hidden;
1.911     bisitz   5989:   margin: 0;
                   5990:   padding: 0;
1.995     raeburn  5991:   text-align: left;
1.819     tempelho 5992: }
1.862     bisitz   5993: 
1.1075.2.16  raeburn  5994: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   5995:   clear:both;
                   5996:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 5997:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  5998:   margin: 0 0 10px 0;
1.966     bisitz   5999:   padding: 3px;
1.995     raeburn  6000:   text-align: left;
1.822     bisitz   6001: }
                   6002: 
1.795     www      6003: .LC_fontsize_medium {
1.911     bisitz   6004:   font-size: 85%;
1.705     tempelho 6005: }
                   6006: 
1.795     www      6007: .LC_fontsize_large {
1.911     bisitz   6008:   font-size: 120%;
1.705     tempelho 6009: }
                   6010: 
1.346     albertel 6011: .LC_menubuttons_inline_text {
                   6012:   color: $font;
1.698     harmsja  6013:   font-size: 90%;
1.701     harmsja  6014:   padding-left:3px;
1.346     albertel 6015: }
                   6016: 
1.934     droeschl 6017: .LC_menubuttons_inline_text img{
                   6018:   vertical-align: middle;
                   6019: }
                   6020: 
1.1051    www      6021: li.LC_menubuttons_inline_text img {
1.951     onken    6022:   cursor:pointer;
1.1002    droeschl 6023:   text-decoration: none;
1.951     onken    6024: }
                   6025: 
1.526     www      6026: .LC_menubuttons_link {
                   6027:   text-decoration: none;
                   6028: }
1.795     www      6029: 
1.522     albertel 6030: .LC_menubuttons_category {
1.521     www      6031:   color: $font;
1.526     www      6032:   background: $pgbg;
1.521     www      6033:   font-size: larger;
                   6034:   font-weight: bold;
                   6035: }
                   6036: 
1.346     albertel 6037: td.LC_menubuttons_text {
1.911     bisitz   6038:   color: $font;
1.346     albertel 6039: }
1.706     harmsja  6040: 
1.346     albertel 6041: .LC_current_location {
                   6042:   background: $tabbg;
                   6043: }
1.795     www      6044: 
1.938     bisitz   6045: table.LC_data_table {
1.347     albertel 6046:   border: 1px solid #000000;
1.402     albertel 6047:   border-collapse: separate;
1.426     albertel 6048:   border-spacing: 1px;
1.610     albertel 6049:   background: $pgbg;
1.347     albertel 6050: }
1.795     www      6051: 
1.422     albertel 6052: .LC_data_table_dense {
                   6053:   font-size: small;
                   6054: }
1.795     www      6055: 
1.507     raeburn  6056: table.LC_nested_outer {
                   6057:   border: 1px solid #000000;
1.589     raeburn  6058:   border-collapse: collapse;
1.803     bisitz   6059:   border-spacing: 0;
1.507     raeburn  6060:   width: 100%;
                   6061: }
1.795     www      6062: 
1.879     raeburn  6063: table.LC_innerpickbox,
1.507     raeburn  6064: table.LC_nested {
1.803     bisitz   6065:   border: none;
1.589     raeburn  6066:   border-collapse: collapse;
1.803     bisitz   6067:   border-spacing: 0;
1.507     raeburn  6068:   width: 100%;
                   6069: }
1.795     www      6070: 
1.911     bisitz   6071: table.LC_data_table tr th,
                   6072: table.LC_calendar tr th,
1.879     raeburn  6073: table.LC_prior_tries tr th,
                   6074: table.LC_innerpickbox tr th {
1.349     albertel 6075:   font-weight: bold;
                   6076:   background-color: $data_table_head;
1.801     tempelho 6077:   color:$fontmenu;
1.701     harmsja  6078:   font-size:90%;
1.347     albertel 6079: }
1.795     www      6080: 
1.879     raeburn  6081: table.LC_innerpickbox tr th,
                   6082: table.LC_innerpickbox tr td {
                   6083:   vertical-align: top;
                   6084: }
                   6085: 
1.711     raeburn  6086: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6087:   background-color: #CCCCCC;
1.711     raeburn  6088:   font-weight: bold;
                   6089:   text-align: left;
                   6090: }
1.795     www      6091: 
1.912     bisitz   6092: table.LC_data_table tr.LC_odd_row > td {
                   6093:   background-color: $data_table_light;
                   6094:   padding: 2px;
                   6095:   vertical-align: top;
                   6096: }
                   6097: 
1.809     bisitz   6098: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6099:   background-color: $data_table_light;
1.912     bisitz   6100:   vertical-align: top;
                   6101: }
                   6102: 
                   6103: table.LC_data_table tr.LC_even_row > td {
                   6104:   background-color: $data_table_dark;
1.425     albertel 6105:   padding: 2px;
1.900     bisitz   6106:   vertical-align: top;
1.347     albertel 6107: }
1.795     www      6108: 
1.809     bisitz   6109: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6110:   background-color: $data_table_dark;
1.900     bisitz   6111:   vertical-align: top;
1.347     albertel 6112: }
1.795     www      6113: 
1.425     albertel 6114: table.LC_data_table tr.LC_data_table_highlight td {
                   6115:   background-color: $data_table_darker;
                   6116: }
1.795     www      6117: 
1.639     raeburn  6118: table.LC_data_table tr td.LC_leftcol_header {
                   6119:   background-color: $data_table_head;
                   6120:   font-weight: bold;
                   6121: }
1.795     www      6122: 
1.451     albertel 6123: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6124: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6125:   font-weight: bold;
                   6126:   font-style: italic;
                   6127:   text-align: center;
                   6128:   padding: 8px;
1.347     albertel 6129: }
1.795     www      6130: 
1.1075.2.30  raeburn  6131: table.LC_data_table tr.LC_empty_row td,
                   6132: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6133:   background-color: $sidebg;
                   6134: }
                   6135: 
                   6136: table.LC_nested tr.LC_empty_row td {
                   6137:   background-color: #FFFFFF;
                   6138: }
                   6139: 
1.890     droeschl 6140: table.LC_caption {
                   6141: }
                   6142: 
1.507     raeburn  6143: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6144:   padding: 4ex
                   6145: }
1.795     www      6146: 
1.507     raeburn  6147: table.LC_nested_outer tr th {
                   6148:   font-weight: bold;
1.801     tempelho 6149:   color:$fontmenu;
1.507     raeburn  6150:   background-color: $data_table_head;
1.701     harmsja  6151:   font-size: small;
1.507     raeburn  6152:   border-bottom: 1px solid #000000;
                   6153: }
1.795     www      6154: 
1.507     raeburn  6155: table.LC_nested_outer tr td.LC_subheader {
                   6156:   background-color: $data_table_head;
                   6157:   font-weight: bold;
                   6158:   font-size: small;
                   6159:   border-bottom: 1px solid #000000;
                   6160:   text-align: right;
1.451     albertel 6161: }
1.795     www      6162: 
1.507     raeburn  6163: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6164:   background-color: #CCCCCC;
1.451     albertel 6165:   font-weight: bold;
                   6166:   font-size: small;
1.507     raeburn  6167:   text-align: center;
                   6168: }
1.795     www      6169: 
1.589     raeburn  6170: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6171: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6172:   text-align: left;
1.451     albertel 6173: }
1.795     www      6174: 
1.507     raeburn  6175: table.LC_nested td {
1.735     bisitz   6176:   background-color: #FFFFFF;
1.451     albertel 6177:   font-size: small;
1.507     raeburn  6178: }
1.795     www      6179: 
1.507     raeburn  6180: table.LC_nested_outer tr th.LC_right_item,
                   6181: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6182: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6183: table.LC_nested tr td.LC_right_item {
1.451     albertel 6184:   text-align: right;
                   6185: }
                   6186: 
1.507     raeburn  6187: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6188:   background-color: #EEEEEE;
1.451     albertel 6189: }
                   6190: 
1.473     raeburn  6191: table.LC_createuser {
                   6192: }
                   6193: 
                   6194: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6195:   font-size: small;
1.473     raeburn  6196: }
                   6197: 
                   6198: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6199:   background-color: #CCCCCC;
1.473     raeburn  6200:   font-weight: bold;
                   6201:   text-align: center;
                   6202: }
                   6203: 
1.349     albertel 6204: table.LC_calendar {
                   6205:   border: 1px solid #000000;
                   6206:   border-collapse: collapse;
1.917     raeburn  6207:   width: 98%;
1.349     albertel 6208: }
1.795     www      6209: 
1.349     albertel 6210: table.LC_calendar_pickdate {
                   6211:   font-size: xx-small;
                   6212: }
1.795     www      6213: 
1.349     albertel 6214: table.LC_calendar tr td {
                   6215:   border: 1px solid #000000;
                   6216:   vertical-align: top;
1.917     raeburn  6217:   width: 14%;
1.349     albertel 6218: }
1.795     www      6219: 
1.349     albertel 6220: table.LC_calendar tr td.LC_calendar_day_empty {
                   6221:   background-color: $data_table_dark;
                   6222: }
1.795     www      6223: 
1.779     bisitz   6224: table.LC_calendar tr td.LC_calendar_day_current {
                   6225:   background-color: $data_table_highlight;
1.777     tempelho 6226: }
1.795     www      6227: 
1.938     bisitz   6228: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6229:   background-color: $mail_new;
                   6230: }
1.795     www      6231: 
1.938     bisitz   6232: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6233:   background-color: $mail_new_hover;
                   6234: }
1.795     www      6235: 
1.938     bisitz   6236: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6237:   background-color: $mail_read;
                   6238: }
1.795     www      6239: 
1.938     bisitz   6240: /*
                   6241: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6242:   background-color: $mail_read_hover;
                   6243: }
1.938     bisitz   6244: */
1.795     www      6245: 
1.938     bisitz   6246: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6247:   background-color: $mail_replied;
                   6248: }
1.795     www      6249: 
1.938     bisitz   6250: /*
                   6251: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6252:   background-color: $mail_replied_hover;
                   6253: }
1.938     bisitz   6254: */
1.795     www      6255: 
1.938     bisitz   6256: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6257:   background-color: $mail_other;
                   6258: }
1.795     www      6259: 
1.938     bisitz   6260: /*
                   6261: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6262:   background-color: $mail_other_hover;
                   6263: }
1.938     bisitz   6264: */
1.494     raeburn  6265: 
1.777     tempelho 6266: table.LC_data_table tr > td.LC_browser_file,
                   6267: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6268:   background: #AAEE77;
1.389     albertel 6269: }
1.795     www      6270: 
1.777     tempelho 6271: table.LC_data_table tr > td.LC_browser_file_locked,
                   6272: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6273:   background: #FFAA99;
1.387     albertel 6274: }
1.795     www      6275: 
1.777     tempelho 6276: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6277:   background: #888888;
1.779     bisitz   6278: }
1.795     www      6279: 
1.777     tempelho 6280: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6281: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6282:   background: #F8F866;
1.777     tempelho 6283: }
1.795     www      6284: 
1.696     bisitz   6285: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6286:   background: #E0E8FF;
1.387     albertel 6287: }
1.696     bisitz   6288: 
1.707     bisitz   6289: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6290:   /* background: #77FF77; */
1.707     bisitz   6291: }
1.795     www      6292: 
1.707     bisitz   6293: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6294:   border-right: 8px solid #FFFF77;
1.707     bisitz   6295: }
1.795     www      6296: 
1.707     bisitz   6297: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6298:   border-right: 8px solid #FFAA77;
1.707     bisitz   6299: }
1.795     www      6300: 
1.707     bisitz   6301: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6302:   border-right: 8px solid #FF7777;
1.707     bisitz   6303: }
1.795     www      6304: 
1.707     bisitz   6305: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6306:   border-right: 8px solid #AAFF77;
1.707     bisitz   6307: }
1.795     www      6308: 
1.707     bisitz   6309: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6310:   border-right: 8px solid #11CC55;
1.707     bisitz   6311: }
                   6312: 
1.388     albertel 6313: span.LC_current_location {
1.701     harmsja  6314:   font-size:larger;
1.388     albertel 6315:   background: $pgbg;
                   6316: }
1.387     albertel 6317: 
1.1029    www      6318: span.LC_current_nav_location {
                   6319:   font-weight:bold;
                   6320:   background: $sidebg;
                   6321: }
                   6322: 
1.395     albertel 6323: span.LC_parm_menu_item {
                   6324:   font-size: larger;
                   6325: }
1.795     www      6326: 
1.395     albertel 6327: span.LC_parm_scope_all {
                   6328:   color: red;
                   6329: }
1.795     www      6330: 
1.395     albertel 6331: span.LC_parm_scope_folder {
                   6332:   color: green;
                   6333: }
1.795     www      6334: 
1.395     albertel 6335: span.LC_parm_scope_resource {
                   6336:   color: orange;
                   6337: }
1.795     www      6338: 
1.395     albertel 6339: span.LC_parm_part {
                   6340:   color: blue;
                   6341: }
1.795     www      6342: 
1.911     bisitz   6343: span.LC_parm_folder,
                   6344: span.LC_parm_symb {
1.395     albertel 6345:   font-size: x-small;
                   6346:   font-family: $mono;
                   6347:   color: #AAAAAA;
                   6348: }
                   6349: 
1.977     bisitz   6350: ul.LC_parm_parmlist li {
                   6351:   display: inline-block;
                   6352:   padding: 0.3em 0.8em;
                   6353:   vertical-align: top;
                   6354:   width: 150px;
                   6355:   border-top:1px solid $lg_border_color;
                   6356: }
                   6357: 
1.795     www      6358: td.LC_parm_overview_level_menu,
                   6359: td.LC_parm_overview_map_menu,
                   6360: td.LC_parm_overview_parm_selectors,
                   6361: td.LC_parm_overview_restrictions  {
1.396     albertel 6362:   border: 1px solid black;
                   6363:   border-collapse: collapse;
                   6364: }
1.795     www      6365: 
1.396     albertel 6366: table.LC_parm_overview_restrictions td {
                   6367:   border-width: 1px 4px 1px 4px;
                   6368:   border-style: solid;
                   6369:   border-color: $pgbg;
                   6370:   text-align: center;
                   6371: }
1.795     www      6372: 
1.396     albertel 6373: table.LC_parm_overview_restrictions th {
                   6374:   background: $tabbg;
                   6375:   border-width: 1px 4px 1px 4px;
                   6376:   border-style: solid;
                   6377:   border-color: $pgbg;
                   6378: }
1.795     www      6379: 
1.398     albertel 6380: table#LC_helpmenu {
1.803     bisitz   6381:   border: none;
1.398     albertel 6382:   height: 55px;
1.803     bisitz   6383:   border-spacing: 0;
1.398     albertel 6384: }
                   6385: 
                   6386: table#LC_helpmenu fieldset legend {
                   6387:   font-size: larger;
                   6388: }
1.795     www      6389: 
1.397     albertel 6390: table#LC_helpmenu_links {
                   6391:   width: 100%;
                   6392:   border: 1px solid black;
                   6393:   background: $pgbg;
1.803     bisitz   6394:   padding: 0;
1.397     albertel 6395:   border-spacing: 1px;
                   6396: }
1.795     www      6397: 
1.397     albertel 6398: table#LC_helpmenu_links tr td {
                   6399:   padding: 1px;
                   6400:   background: $tabbg;
1.399     albertel 6401:   text-align: center;
                   6402:   font-weight: bold;
1.397     albertel 6403: }
1.396     albertel 6404: 
1.795     www      6405: table#LC_helpmenu_links a:link,
                   6406: table#LC_helpmenu_links a:visited,
1.397     albertel 6407: table#LC_helpmenu_links a:active {
                   6408:   text-decoration: none;
                   6409:   color: $font;
                   6410: }
1.795     www      6411: 
1.397     albertel 6412: table#LC_helpmenu_links a:hover {
                   6413:   text-decoration: underline;
                   6414:   color: $vlink;
                   6415: }
1.396     albertel 6416: 
1.417     albertel 6417: .LC_chrt_popup_exists {
                   6418:   border: 1px solid #339933;
                   6419:   margin: -1px;
                   6420: }
1.795     www      6421: 
1.417     albertel 6422: .LC_chrt_popup_up {
                   6423:   border: 1px solid yellow;
                   6424:   margin: -1px;
                   6425: }
1.795     www      6426: 
1.417     albertel 6427: .LC_chrt_popup {
                   6428:   border: 1px solid #8888FF;
                   6429:   background: #CCCCFF;
                   6430: }
1.795     www      6431: 
1.421     albertel 6432: table.LC_pick_box {
                   6433:   border-collapse: separate;
                   6434:   background: white;
                   6435:   border: 1px solid black;
                   6436:   border-spacing: 1px;
                   6437: }
1.795     www      6438: 
1.421     albertel 6439: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6440:   background: $sidebg;
1.421     albertel 6441:   font-weight: bold;
1.900     bisitz   6442:   text-align: left;
1.740     bisitz   6443:   vertical-align: top;
1.421     albertel 6444:   width: 184px;
                   6445:   padding: 8px;
                   6446: }
1.795     www      6447: 
1.579     raeburn  6448: table.LC_pick_box td.LC_pick_box_value {
                   6449:   text-align: left;
                   6450:   padding: 8px;
                   6451: }
1.795     www      6452: 
1.579     raeburn  6453: table.LC_pick_box td.LC_pick_box_select {
                   6454:   text-align: left;
                   6455:   padding: 8px;
                   6456: }
1.795     www      6457: 
1.424     albertel 6458: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6459:   padding: 0;
1.421     albertel 6460:   height: 1px;
                   6461:   background: black;
                   6462: }
1.795     www      6463: 
1.421     albertel 6464: table.LC_pick_box td.LC_pick_box_submit {
                   6465:   text-align: right;
                   6466: }
1.795     www      6467: 
1.579     raeburn  6468: table.LC_pick_box td.LC_evenrow_value {
                   6469:   text-align: left;
                   6470:   padding: 8px;
                   6471:   background-color: $data_table_light;
                   6472: }
1.795     www      6473: 
1.579     raeburn  6474: table.LC_pick_box td.LC_oddrow_value {
                   6475:   text-align: left;
                   6476:   padding: 8px;
                   6477:   background-color: $data_table_light;
                   6478: }
1.795     www      6479: 
1.579     raeburn  6480: span.LC_helpform_receipt_cat {
                   6481:   font-weight: bold;
                   6482: }
1.795     www      6483: 
1.424     albertel 6484: table.LC_group_priv_box {
                   6485:   background: white;
                   6486:   border: 1px solid black;
                   6487:   border-spacing: 1px;
                   6488: }
1.795     www      6489: 
1.424     albertel 6490: table.LC_group_priv_box td.LC_pick_box_title {
                   6491:   background: $tabbg;
                   6492:   font-weight: bold;
                   6493:   text-align: right;
                   6494:   width: 184px;
                   6495: }
1.795     www      6496: 
1.424     albertel 6497: table.LC_group_priv_box td.LC_groups_fixed {
                   6498:   background: $data_table_light;
                   6499:   text-align: center;
                   6500: }
1.795     www      6501: 
1.424     albertel 6502: table.LC_group_priv_box td.LC_groups_optional {
                   6503:   background: $data_table_dark;
                   6504:   text-align: center;
                   6505: }
1.795     www      6506: 
1.424     albertel 6507: table.LC_group_priv_box td.LC_groups_functionality {
                   6508:   background: $data_table_darker;
                   6509:   text-align: center;
                   6510:   font-weight: bold;
                   6511: }
1.795     www      6512: 
1.424     albertel 6513: table.LC_group_priv td {
                   6514:   text-align: left;
1.803     bisitz   6515:   padding: 0;
1.424     albertel 6516: }
                   6517: 
                   6518: .LC_navbuttons {
                   6519:   margin: 2ex 0ex 2ex 0ex;
                   6520: }
1.795     www      6521: 
1.423     albertel 6522: .LC_topic_bar {
                   6523:   font-weight: bold;
                   6524:   background: $tabbg;
1.918     wenzelju 6525:   margin: 1em 0em 1em 2em;
1.805     bisitz   6526:   padding: 3px;
1.918     wenzelju 6527:   font-size: 1.2em;
1.423     albertel 6528: }
1.795     www      6529: 
1.423     albertel 6530: .LC_topic_bar span {
1.918     wenzelju 6531:   left: 0.5em;
                   6532:   position: absolute;
1.423     albertel 6533:   vertical-align: middle;
1.918     wenzelju 6534:   font-size: 1.2em;
1.423     albertel 6535: }
1.795     www      6536: 
1.423     albertel 6537: table.LC_course_group_status {
                   6538:   margin: 20px;
                   6539: }
1.795     www      6540: 
1.423     albertel 6541: table.LC_status_selector td {
                   6542:   vertical-align: top;
                   6543:   text-align: center;
1.424     albertel 6544:   padding: 4px;
                   6545: }
1.795     www      6546: 
1.599     albertel 6547: div.LC_feedback_link {
1.616     albertel 6548:   clear: both;
1.829     kalberla 6549:   background: $sidebg;
1.779     bisitz   6550:   width: 100%;
1.829     kalberla 6551:   padding-bottom: 10px;
                   6552:   border: 1px $tabbg solid;
1.833     kalberla 6553:   height: 22px;
                   6554:   line-height: 22px;
                   6555:   padding-top: 5px;
                   6556: }
                   6557: 
                   6558: div.LC_feedback_link img {
                   6559:   height: 22px;
1.867     kalberla 6560:   vertical-align:middle;
1.829     kalberla 6561: }
                   6562: 
1.911     bisitz   6563: div.LC_feedback_link a {
1.829     kalberla 6564:   text-decoration: none;
1.489     raeburn  6565: }
1.795     www      6566: 
1.867     kalberla 6567: div.LC_comblock {
1.911     bisitz   6568:   display:inline;
1.867     kalberla 6569:   color:$font;
                   6570:   font-size:90%;
                   6571: }
                   6572: 
                   6573: div.LC_feedback_link div.LC_comblock {
                   6574:   padding-left:5px;
                   6575: }
                   6576: 
                   6577: div.LC_feedback_link div.LC_comblock a {
                   6578:   color:$font;
                   6579: }
                   6580: 
1.489     raeburn  6581: span.LC_feedback_link {
1.858     bisitz   6582:   /* background: $feedback_link_bg; */
1.599     albertel 6583:   font-size: larger;
                   6584: }
1.795     www      6585: 
1.599     albertel 6586: span.LC_message_link {
1.858     bisitz   6587:   /* background: $feedback_link_bg; */
1.599     albertel 6588:   font-size: larger;
                   6589:   position: absolute;
                   6590:   right: 1em;
1.489     raeburn  6591: }
1.421     albertel 6592: 
1.515     albertel 6593: table.LC_prior_tries {
1.524     albertel 6594:   border: 1px solid #000000;
                   6595:   border-collapse: separate;
                   6596:   border-spacing: 1px;
1.515     albertel 6597: }
1.523     albertel 6598: 
1.515     albertel 6599: table.LC_prior_tries td {
1.524     albertel 6600:   padding: 2px;
1.515     albertel 6601: }
1.523     albertel 6602: 
                   6603: .LC_answer_correct {
1.795     www      6604:   background: lightgreen;
                   6605:   color: darkgreen;
                   6606:   padding: 6px;
1.523     albertel 6607: }
1.795     www      6608: 
1.523     albertel 6609: .LC_answer_charged_try {
1.797     www      6610:   background: #FFAAAA;
1.795     www      6611:   color: darkred;
                   6612:   padding: 6px;
1.523     albertel 6613: }
1.795     www      6614: 
1.779     bisitz   6615: .LC_answer_not_charged_try,
1.523     albertel 6616: .LC_answer_no_grade,
                   6617: .LC_answer_late {
1.795     www      6618:   background: lightyellow;
1.523     albertel 6619:   color: black;
1.795     www      6620:   padding: 6px;
1.523     albertel 6621: }
1.795     www      6622: 
1.523     albertel 6623: .LC_answer_previous {
1.795     www      6624:   background: lightblue;
                   6625:   color: darkblue;
                   6626:   padding: 6px;
1.523     albertel 6627: }
1.795     www      6628: 
1.779     bisitz   6629: .LC_answer_no_message {
1.777     tempelho 6630:   background: #FFFFFF;
                   6631:   color: black;
1.795     www      6632:   padding: 6px;
1.779     bisitz   6633: }
1.795     www      6634: 
1.779     bisitz   6635: .LC_answer_unknown {
                   6636:   background: orange;
                   6637:   color: black;
1.795     www      6638:   padding: 6px;
1.777     tempelho 6639: }
1.795     www      6640: 
1.529     albertel 6641: span.LC_prior_numerical,
                   6642: span.LC_prior_string,
                   6643: span.LC_prior_custom,
                   6644: span.LC_prior_reaction,
                   6645: span.LC_prior_math {
1.925     bisitz   6646:   font-family: $mono;
1.523     albertel 6647:   white-space: pre;
                   6648: }
                   6649: 
1.525     albertel 6650: span.LC_prior_string {
1.925     bisitz   6651:   font-family: $mono;
1.525     albertel 6652:   white-space: pre;
                   6653: }
                   6654: 
1.523     albertel 6655: table.LC_prior_option {
                   6656:   width: 100%;
                   6657:   border-collapse: collapse;
                   6658: }
1.795     www      6659: 
1.911     bisitz   6660: table.LC_prior_rank,
1.795     www      6661: table.LC_prior_match {
1.528     albertel 6662:   border-collapse: collapse;
                   6663: }
1.795     www      6664: 
1.528     albertel 6665: table.LC_prior_option tr td,
                   6666: table.LC_prior_rank tr td,
                   6667: table.LC_prior_match tr td {
1.524     albertel 6668:   border: 1px solid #000000;
1.515     albertel 6669: }
                   6670: 
1.855     bisitz   6671: .LC_nobreak {
1.544     albertel 6672:   white-space: nowrap;
1.519     raeburn  6673: }
                   6674: 
1.576     raeburn  6675: span.LC_cusr_emph {
                   6676:   font-style: italic;
                   6677: }
                   6678: 
1.633     raeburn  6679: span.LC_cusr_subheading {
                   6680:   font-weight: normal;
                   6681:   font-size: 85%;
                   6682: }
                   6683: 
1.861     bisitz   6684: div.LC_docs_entry_move {
1.859     bisitz   6685:   border: 1px solid #BBBBBB;
1.545     albertel 6686:   background: #DDDDDD;
1.861     bisitz   6687:   width: 22px;
1.859     bisitz   6688:   padding: 1px;
                   6689:   margin: 0;
1.545     albertel 6690: }
                   6691: 
1.861     bisitz   6692: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6693: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6694:   font-size: x-small;
                   6695: }
1.795     www      6696: 
1.861     bisitz   6697: .LC_docs_entry_parameter {
                   6698:   white-space: nowrap;
                   6699: }
                   6700: 
1.544     albertel 6701: .LC_docs_copy {
1.545     albertel 6702:   color: #000099;
1.544     albertel 6703: }
1.795     www      6704: 
1.544     albertel 6705: .LC_docs_cut {
1.545     albertel 6706:   color: #550044;
1.544     albertel 6707: }
1.795     www      6708: 
1.544     albertel 6709: .LC_docs_rename {
1.545     albertel 6710:   color: #009900;
1.544     albertel 6711: }
1.795     www      6712: 
1.544     albertel 6713: .LC_docs_remove {
1.545     albertel 6714:   color: #990000;
                   6715: }
                   6716: 
1.547     albertel 6717: .LC_docs_reinit_warn,
                   6718: .LC_docs_ext_edit {
                   6719:   font-size: x-small;
                   6720: }
                   6721: 
1.545     albertel 6722: table.LC_docs_adddocs td,
                   6723: table.LC_docs_adddocs th {
                   6724:   border: 1px solid #BBBBBB;
                   6725:   padding: 4px;
                   6726:   background: #DDDDDD;
1.543     albertel 6727: }
                   6728: 
1.584     albertel 6729: table.LC_sty_begin {
                   6730:   background: #BBFFBB;
                   6731: }
1.795     www      6732: 
1.584     albertel 6733: table.LC_sty_end {
                   6734:   background: #FFBBBB;
                   6735: }
                   6736: 
1.589     raeburn  6737: table.LC_double_column {
1.803     bisitz   6738:   border-width: 0;
1.589     raeburn  6739:   border-collapse: collapse;
                   6740:   width: 100%;
                   6741:   padding: 2px;
                   6742: }
                   6743: 
                   6744: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6745:   top: 2px;
1.589     raeburn  6746:   left: 2px;
                   6747:   width: 47%;
                   6748:   vertical-align: top;
                   6749: }
                   6750: 
                   6751: table.LC_double_column tr td.LC_right_col {
                   6752:   top: 2px;
1.779     bisitz   6753:   right: 2px;
1.589     raeburn  6754:   width: 47%;
                   6755:   vertical-align: top;
                   6756: }
                   6757: 
1.591     raeburn  6758: div.LC_left_float {
                   6759:   float: left;
                   6760:   padding-right: 5%;
1.597     albertel 6761:   padding-bottom: 4px;
1.591     raeburn  6762: }
                   6763: 
                   6764: div.LC_clear_float_header {
1.597     albertel 6765:   padding-bottom: 2px;
1.591     raeburn  6766: }
                   6767: 
                   6768: div.LC_clear_float_footer {
1.597     albertel 6769:   padding-top: 10px;
1.591     raeburn  6770:   clear: both;
                   6771: }
                   6772: 
1.597     albertel 6773: div.LC_grade_show_user {
1.941     bisitz   6774: /*  border-left: 5px solid $sidebg; */
                   6775:   border-top: 5px solid #000000;
                   6776:   margin: 50px 0 0 0;
1.936     bisitz   6777:   padding: 15px 0 5px 10px;
1.597     albertel 6778: }
1.795     www      6779: 
1.936     bisitz   6780: div.LC_grade_show_user_odd_row {
1.941     bisitz   6781: /*  border-left: 5px solid #000000; */
                   6782: }
                   6783: 
                   6784: div.LC_grade_show_user div.LC_Box {
                   6785:   margin-right: 50px;
1.597     albertel 6786: }
                   6787: 
                   6788: div.LC_grade_submissions,
                   6789: div.LC_grade_message_center,
1.936     bisitz   6790: div.LC_grade_info_links {
1.597     albertel 6791:   margin: 5px;
                   6792:   width: 99%;
                   6793:   background: #FFFFFF;
                   6794: }
1.795     www      6795: 
1.597     albertel 6796: div.LC_grade_submissions_header,
1.936     bisitz   6797: div.LC_grade_message_center_header {
1.705     tempelho 6798:   font-weight: bold;
                   6799:   font-size: large;
1.597     albertel 6800: }
1.795     www      6801: 
1.597     albertel 6802: div.LC_grade_submissions_body,
1.936     bisitz   6803: div.LC_grade_message_center_body {
1.597     albertel 6804:   border: 1px solid black;
                   6805:   width: 99%;
                   6806:   background: #FFFFFF;
                   6807: }
1.795     www      6808: 
1.613     albertel 6809: table.LC_scantron_action {
                   6810:   width: 100%;
                   6811: }
1.795     www      6812: 
1.613     albertel 6813: table.LC_scantron_action tr th {
1.698     harmsja  6814:   font-weight:bold;
                   6815:   font-style:normal;
1.613     albertel 6816: }
1.795     www      6817: 
1.779     bisitz   6818: .LC_edit_problem_header,
1.614     albertel 6819: div.LC_edit_problem_footer {
1.705     tempelho 6820:   font-weight: normal;
                   6821:   font-size:  medium;
1.602     albertel 6822:   margin: 2px;
1.1060    bisitz   6823:   background-color: $sidebg;
1.600     albertel 6824: }
1.795     www      6825: 
1.600     albertel 6826: div.LC_edit_problem_header,
1.602     albertel 6827: div.LC_edit_problem_header div,
1.614     albertel 6828: div.LC_edit_problem_footer,
                   6829: div.LC_edit_problem_footer div,
1.602     albertel 6830: div.LC_edit_problem_editxml_header,
                   6831: div.LC_edit_problem_editxml_header div {
1.1075.2.112! raeburn  6832:   z-index: 100;
1.600     albertel 6833: }
1.795     www      6834: 
1.600     albertel 6835: div.LC_edit_problem_header_title {
1.705     tempelho 6836:   font-weight: bold;
                   6837:   font-size: larger;
1.602     albertel 6838:   background: $tabbg;
                   6839:   padding: 3px;
1.1060    bisitz   6840:   margin: 0 0 5px 0;
1.602     albertel 6841: }
1.795     www      6842: 
1.602     albertel 6843: table.LC_edit_problem_header_title {
                   6844:   width: 100%;
1.600     albertel 6845:   background: $tabbg;
1.602     albertel 6846: }
                   6847: 
1.1075.2.112! raeburn  6848: div.LC_edit_actionbar {
        !          6849:     background-color: $sidebg;
        !          6850:     margin: 0;
        !          6851:     padding: 0;
        !          6852:     line-height: 200%;
1.602     albertel 6853: }
1.795     www      6854: 
1.1075.2.112! raeburn  6855: div.LC_edit_actionbar div{
        !          6856:     padding: 0;
        !          6857:     margin: 0;
        !          6858:     display: inline-block;
1.600     albertel 6859: }
1.795     www      6860: 
1.1075.2.34  raeburn  6861: .LC_edit_opt {
                   6862:   padding-left: 1em;
                   6863:   white-space: nowrap;
                   6864: }
                   6865: 
1.1075.2.57  raeburn  6866: .LC_edit_problem_latexhelper{
                   6867:     text-align: right;
                   6868: }
                   6869: 
                   6870: #LC_edit_problem_colorful div{
                   6871:     margin-left: 40px;
                   6872: }
                   6873: 
1.1075.2.112! raeburn  6874: #LC_edit_problem_codemirror div{
        !          6875:     margin-left: 0px;
        !          6876: }
        !          6877: 
1.911     bisitz   6878: img.stift {
1.803     bisitz   6879:   border-width: 0;
                   6880:   vertical-align: middle;
1.677     riegler  6881: }
1.680     riegler  6882: 
1.923     bisitz   6883: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6884:   vertical-align: top;
1.777     tempelho 6885: }
1.795     www      6886: 
1.716     raeburn  6887: div.LC_createcourse {
1.911     bisitz   6888:   margin: 10px 10px 10px 10px;
1.716     raeburn  6889: }
                   6890: 
1.917     raeburn  6891: .LC_dccid {
1.1075.2.38  raeburn  6892:   float: right;
1.917     raeburn  6893:   margin: 0.2em 0 0 0;
                   6894:   padding: 0;
                   6895:   font-size: 90%;
                   6896:   display:none;
                   6897: }
                   6898: 
1.897     wenzelju 6899: ol.LC_primary_menu a:hover,
1.721     harmsja  6900: ol#LC_MenuBreadcrumbs a:hover,
                   6901: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6902: ul#LC_secondary_menu a:hover,
1.721     harmsja  6903: .LC_FormSectionClearButton input:hover
1.795     www      6904: ul.LC_TabContent   li:hover a {
1.952     onken    6905:   color:$button_hover;
1.911     bisitz   6906:   text-decoration:none;
1.693     droeschl 6907: }
                   6908: 
1.779     bisitz   6909: h1 {
1.911     bisitz   6910:   padding: 0;
                   6911:   line-height:130%;
1.693     droeschl 6912: }
1.698     harmsja  6913: 
1.911     bisitz   6914: h2,
                   6915: h3,
                   6916: h4,
                   6917: h5,
                   6918: h6 {
                   6919:   margin: 5px 0 5px 0;
                   6920:   padding: 0;
                   6921:   line-height:130%;
1.693     droeschl 6922: }
1.795     www      6923: 
                   6924: .LC_hcell {
1.911     bisitz   6925:   padding:3px 15px 3px 15px;
                   6926:   margin: 0;
                   6927:   background-color:$tabbg;
                   6928:   color:$fontmenu;
                   6929:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6930: }
1.795     www      6931: 
1.840     bisitz   6932: .LC_Box > .LC_hcell {
1.911     bisitz   6933:   margin: 0 -10px 10px -10px;
1.835     bisitz   6934: }
                   6935: 
1.721     harmsja  6936: .LC_noBorder {
1.911     bisitz   6937:   border: 0;
1.698     harmsja  6938: }
1.693     droeschl 6939: 
1.721     harmsja  6940: .LC_FormSectionClearButton input {
1.911     bisitz   6941:   background-color:transparent;
                   6942:   border: none;
                   6943:   cursor:pointer;
                   6944:   text-decoration:underline;
1.693     droeschl 6945: }
1.763     bisitz   6946: 
                   6947: .LC_help_open_topic {
1.911     bisitz   6948:   color: #FFFFFF;
                   6949:   background-color: #EEEEFF;
                   6950:   margin: 1px;
                   6951:   padding: 4px;
                   6952:   border: 1px solid #000033;
                   6953:   white-space: nowrap;
                   6954:   /* vertical-align: middle; */
1.759     neumanie 6955: }
1.693     droeschl 6956: 
1.911     bisitz   6957: dl,
                   6958: ul,
                   6959: div,
                   6960: fieldset {
                   6961:   margin: 10px 10px 10px 0;
                   6962:   /* overflow: hidden; */
1.693     droeschl 6963: }
1.795     www      6964: 
1.1075.2.90  raeburn  6965: article.geogebraweb div {
                   6966:     margin: 0;
                   6967: }
                   6968: 
1.838     bisitz   6969: fieldset > legend {
1.911     bisitz   6970:   font-weight: bold;
                   6971:   padding: 0 5px 0 5px;
1.838     bisitz   6972: }
                   6973: 
1.813     bisitz   6974: #LC_nav_bar {
1.911     bisitz   6975:   float: left;
1.995     raeburn  6976:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   6977:   margin: 0 0 2px 0;
1.807     droeschl 6978: }
                   6979: 
1.916     droeschl 6980: #LC_realm {
                   6981:   margin: 0.2em 0 0 0;
                   6982:   padding: 0;
                   6983:   font-weight: bold;
                   6984:   text-align: center;
1.995     raeburn  6985:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 6986: }
                   6987: 
1.911     bisitz   6988: #LC_nav_bar em {
                   6989:   font-weight: bold;
                   6990:   font-style: normal;
1.807     droeschl 6991: }
                   6992: 
1.897     wenzelju 6993: ol.LC_primary_menu {
1.934     droeschl 6994:   margin: 0;
1.1075.2.2  raeburn  6995:   padding: 0;
1.995     raeburn  6996:   background-color: $pgbg_or_bgcolor;
1.807     droeschl 6997: }
                   6998: 
1.852     droeschl 6999: ol#LC_PathBreadcrumbs {
1.911     bisitz   7000:   margin: 0;
1.693     droeschl 7001: }
                   7002: 
1.897     wenzelju 7003: ol.LC_primary_menu li {
1.1075.2.2  raeburn  7004:   color: RGB(80, 80, 80);
                   7005:   vertical-align: middle;
                   7006:   text-align: left;
                   7007:   list-style: none;
1.1075.2.112! raeburn  7008:   position: relative;
1.1075.2.2  raeburn  7009:   float: left;
1.1075.2.112! raeburn  7010:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
        !          7011:   line-height: 1.5em;
1.1075.2.2  raeburn  7012: }
                   7013: 
1.1075.2.112! raeburn  7014: ol.LC_primary_menu li a 
        !          7015: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  7016:   display: block;
                   7017:   margin: 0;
                   7018:   padding: 0 5px 0 10px;
                   7019:   text-decoration: none;
                   7020: }
                   7021: 
1.1075.2.112! raeburn  7022: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
        !          7023:   display: inline-block;
        !          7024:   width: 95%;
        !          7025:   text-align: left;
        !          7026: }
        !          7027: 
        !          7028: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
        !          7029:   display: inline-block;
        !          7030:   width: 5%;
        !          7031:   float: right;
        !          7032:   text-align: right;
        !          7033:   font-size: 70%;
        !          7034: }
        !          7035: 
        !          7036: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  7037:   display: none;
1.1075.2.112! raeburn  7038:   width: 15em;
1.1075.2.2  raeburn  7039:   background-color: $data_table_light;
1.1075.2.112! raeburn  7040:   position: absolute;
        !          7041:   top: 100%;
        !          7042: }
        !          7043: 
        !          7044: ol.LC_primary_menu ul ul {
        !          7045:   left: 100%;
        !          7046:   top: 0;
1.1075.2.2  raeburn  7047: }
                   7048: 
1.1075.2.112! raeburn  7049: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  7050:   display: block;
                   7051:   position: absolute;
                   7052:   margin: 0;
                   7053:   padding: 0;
1.1075.2.5  raeburn  7054:   z-index: 2;
1.1075.2.2  raeburn  7055: }
                   7056: 
                   7057: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112! raeburn  7058: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  7059:   font-size: 90%;
1.911     bisitz   7060:   vertical-align: top;
1.1075.2.2  raeburn  7061:   float: none;
1.1075.2.5  raeburn  7062:   border-left: 1px solid black;
                   7063:   border-right: 1px solid black;
1.1075.2.112! raeburn  7064: /* A dark bottom border to visualize different menu options;
        !          7065: overwritten in the create_submenu routine for the last border-bottom of the menu */
        !          7066:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  7067: }
                   7068: 
1.1075.2.112! raeburn  7069: ol.LC_primary_menu li li p:hover {
        !          7070:   color:$button_hover;
        !          7071:   text-decoration:none;
        !          7072:   background-color:$data_table_dark;
1.1075.2.2  raeburn  7073: }
                   7074: 
                   7075: ol.LC_primary_menu li li a:hover {
                   7076:    color:$button_hover;
                   7077:    background-color:$data_table_dark;
1.693     droeschl 7078: }
                   7079: 
1.1075.2.112! raeburn  7080: /* Font-size equal to the size of the predecessors*/
        !          7081: ol.LC_primary_menu li:hover li li {
        !          7082:   font-size: 100%;
        !          7083: }
        !          7084: 
1.897     wenzelju 7085: ol.LC_primary_menu li img {
1.911     bisitz   7086:   vertical-align: bottom;
1.934     droeschl 7087:   height: 1.1em;
1.1075.2.3  raeburn  7088:   margin: 0.2em 0 0 0;
1.693     droeschl 7089: }
                   7090: 
1.897     wenzelju 7091: ol.LC_primary_menu a {
1.911     bisitz   7092:   color: RGB(80, 80, 80);
                   7093:   text-decoration: none;
1.693     droeschl 7094: }
1.795     www      7095: 
1.949     droeschl 7096: ol.LC_primary_menu a.LC_new_message {
                   7097:   font-weight:bold;
                   7098:   color: darkred;
                   7099: }
                   7100: 
1.975     raeburn  7101: ol.LC_docs_parameters {
                   7102:   margin-left: 0;
                   7103:   padding: 0;
                   7104:   list-style: none;
                   7105: }
                   7106: 
                   7107: ol.LC_docs_parameters li {
                   7108:   margin: 0;
                   7109:   padding-right: 20px;
                   7110:   display: inline;
                   7111: }
                   7112: 
1.976     raeburn  7113: ol.LC_docs_parameters li:before {
                   7114:   content: "\\002022 \\0020";
                   7115: }
                   7116: 
                   7117: li.LC_docs_parameters_title {
                   7118:   font-weight: bold;
                   7119: }
                   7120: 
                   7121: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7122:   content: "";
                   7123: }
                   7124: 
1.897     wenzelju 7125: ul#LC_secondary_menu {
1.1075.2.23  raeburn  7126:   clear: right;
1.911     bisitz   7127:   color: $fontmenu;
                   7128:   background: $tabbg;
                   7129:   list-style: none;
                   7130:   padding: 0;
                   7131:   margin: 0;
                   7132:   width: 100%;
1.995     raeburn  7133:   text-align: left;
1.1075.2.4  raeburn  7134:   float: left;
1.808     droeschl 7135: }
                   7136: 
1.897     wenzelju 7137: ul#LC_secondary_menu li {
1.911     bisitz   7138:   font-weight: bold;
                   7139:   line-height: 1.8em;
                   7140:   border-right: 1px solid black;
                   7141:   vertical-align: middle;
1.1075.2.4  raeburn  7142:   float: left;
                   7143: }
                   7144: 
                   7145: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7146:   background-color: $data_table_light;
                   7147: }
                   7148: 
                   7149: ul#LC_secondary_menu li a {
                   7150:   padding: 0 0.8em;
                   7151: }
                   7152: 
                   7153: ul#LC_secondary_menu li ul {
                   7154:   display: none;
                   7155: }
                   7156: 
                   7157: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7158:   display: block;
                   7159:   position: absolute;
                   7160:   margin: 0;
                   7161:   padding: 0;
                   7162:   list-style:none;
                   7163:   float: none;
                   7164:   background-color: $data_table_light;
1.1075.2.5  raeburn  7165:   z-index: 2;
1.1075.2.10  raeburn  7166:   margin-left: -1px;
1.1075.2.4  raeburn  7167: }
                   7168: 
                   7169: ul#LC_secondary_menu li ul li {
                   7170:   font-size: 90%;
                   7171:   vertical-align: top;
                   7172:   border-left: 1px solid black;
                   7173:   border-right: 1px solid black;
1.1075.2.33  raeburn  7174:   background-color: $data_table_light;
1.1075.2.4  raeburn  7175:   list-style:none;
                   7176:   float: none;
                   7177: }
                   7178: 
                   7179: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7180:   background-color: $data_table_dark;
1.807     droeschl 7181: }
                   7182: 
1.847     tempelho 7183: ul.LC_TabContent {
1.911     bisitz   7184:   display:block;
                   7185:   background: $sidebg;
                   7186:   border-bottom: solid 1px $lg_border_color;
                   7187:   list-style:none;
1.1020    raeburn  7188:   margin: -1px -10px 0 -10px;
1.911     bisitz   7189:   padding: 0;
1.693     droeschl 7190: }
                   7191: 
1.795     www      7192: ul.LC_TabContent li,
                   7193: ul.LC_TabContentBigger li {
1.911     bisitz   7194:   float:left;
1.741     harmsja  7195: }
1.795     www      7196: 
1.897     wenzelju 7197: ul#LC_secondary_menu li a {
1.911     bisitz   7198:   color: $fontmenu;
                   7199:   text-decoration: none;
1.693     droeschl 7200: }
1.795     www      7201: 
1.721     harmsja  7202: ul.LC_TabContent {
1.952     onken    7203:   min-height:20px;
1.721     harmsja  7204: }
1.795     www      7205: 
                   7206: ul.LC_TabContent li {
1.911     bisitz   7207:   vertical-align:middle;
1.959     onken    7208:   padding: 0 16px 0 10px;
1.911     bisitz   7209:   background-color:$tabbg;
                   7210:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7211:   border-left: solid 1px $font;
1.721     harmsja  7212: }
1.795     www      7213: 
1.847     tempelho 7214: ul.LC_TabContent .right {
1.911     bisitz   7215:   float:right;
1.847     tempelho 7216: }
                   7217: 
1.911     bisitz   7218: ul.LC_TabContent li a,
                   7219: ul.LC_TabContent li {
                   7220:   color:rgb(47,47,47);
                   7221:   text-decoration:none;
                   7222:   font-size:95%;
                   7223:   font-weight:bold;
1.952     onken    7224:   min-height:20px;
                   7225: }
                   7226: 
1.959     onken    7227: ul.LC_TabContent li a:hover,
                   7228: ul.LC_TabContent li a:focus {
1.952     onken    7229:   color: $button_hover;
1.959     onken    7230:   background:none;
                   7231:   outline:none;
1.952     onken    7232: }
                   7233: 
                   7234: ul.LC_TabContent li:hover {
                   7235:   color: $button_hover;
                   7236:   cursor:pointer;
1.721     harmsja  7237: }
1.795     www      7238: 
1.911     bisitz   7239: ul.LC_TabContent li.active {
1.952     onken    7240:   color: $font;
1.911     bisitz   7241:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7242:   border-bottom:solid 1px #FFFFFF;
                   7243:   cursor: default;
1.744     ehlerst  7244: }
1.795     www      7245: 
1.959     onken    7246: ul.LC_TabContent li.active a {
                   7247:   color:$font;
                   7248:   background:#FFFFFF;
                   7249:   outline: none;
                   7250: }
1.1047    raeburn  7251: 
                   7252: ul.LC_TabContent li.goback {
                   7253:   float: left;
                   7254:   border-left: none;
                   7255: }
                   7256: 
1.870     tempelho 7257: #maincoursedoc {
1.911     bisitz   7258:   clear:both;
1.870     tempelho 7259: }
                   7260: 
                   7261: ul.LC_TabContentBigger {
1.911     bisitz   7262:   display:block;
                   7263:   list-style:none;
                   7264:   padding: 0;
1.870     tempelho 7265: }
                   7266: 
1.795     www      7267: ul.LC_TabContentBigger li {
1.911     bisitz   7268:   vertical-align:bottom;
                   7269:   height: 30px;
                   7270:   font-size:110%;
                   7271:   font-weight:bold;
                   7272:   color: #737373;
1.841     tempelho 7273: }
                   7274: 
1.957     onken    7275: ul.LC_TabContentBigger li.active {
                   7276:   position: relative;
                   7277:   top: 1px;
                   7278: }
                   7279: 
1.870     tempelho 7280: ul.LC_TabContentBigger li a {
1.911     bisitz   7281:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7282:   height: 30px;
                   7283:   line-height: 30px;
                   7284:   text-align: center;
                   7285:   display: block;
                   7286:   text-decoration: none;
1.958     onken    7287:   outline: none;  
1.741     harmsja  7288: }
1.795     www      7289: 
1.870     tempelho 7290: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7291:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7292:   color:$font;
1.744     ehlerst  7293: }
1.795     www      7294: 
1.870     tempelho 7295: ul.LC_TabContentBigger li b {
1.911     bisitz   7296:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7297:   display: block;
                   7298:   float: left;
                   7299:   padding: 0 30px;
1.957     onken    7300:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7301: }
                   7302: 
1.956     onken    7303: ul.LC_TabContentBigger li:hover b {
                   7304:   color:$button_hover;
                   7305: }
                   7306: 
1.870     tempelho 7307: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7308:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7309:   color:$font;
1.957     onken    7310:   border: 0;
1.741     harmsja  7311: }
1.693     droeschl 7312: 
1.870     tempelho 7313: 
1.862     bisitz   7314: ul.LC_CourseBreadcrumbs {
                   7315:   background: $sidebg;
1.1020    raeburn  7316:   height: 2em;
1.862     bisitz   7317:   padding-left: 10px;
1.1020    raeburn  7318:   margin: 0;
1.862     bisitz   7319:   list-style-position: inside;
                   7320: }
                   7321: 
1.911     bisitz   7322: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7323: ol#LC_PathBreadcrumbs {
1.911     bisitz   7324:   padding-left: 10px;
                   7325:   margin: 0;
1.933     droeschl 7326:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7327: }
                   7328: 
1.911     bisitz   7329: ol#LC_MenuBreadcrumbs li,
                   7330: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7331: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7332:   display: inline;
1.933     droeschl 7333:   white-space: normal;  
1.693     droeschl 7334: }
                   7335: 
1.823     bisitz   7336: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7337: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7338:   text-decoration: none;
                   7339:   font-size:90%;
1.693     droeschl 7340: }
1.795     www      7341: 
1.969     droeschl 7342: ol#LC_MenuBreadcrumbs h1 {
                   7343:   display: inline;
                   7344:   font-size: 90%;
                   7345:   line-height: 2.5em;
                   7346:   margin: 0;
                   7347:   padding: 0;
                   7348: }
                   7349: 
1.795     www      7350: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7351:   text-decoration:none;
                   7352:   font-size:100%;
                   7353:   font-weight:bold;
1.693     droeschl 7354: }
1.795     www      7355: 
1.840     bisitz   7356: .LC_Box {
1.911     bisitz   7357:   border: solid 1px $lg_border_color;
                   7358:   padding: 0 10px 10px 10px;
1.746     neumanie 7359: }
1.795     www      7360: 
1.1020    raeburn  7361: .LC_DocsBox {
                   7362:   border: solid 1px $lg_border_color;
                   7363:   padding: 0 0 10px 10px;
                   7364: }
                   7365: 
1.795     www      7366: .LC_AboutMe_Image {
1.911     bisitz   7367:   float:left;
                   7368:   margin-right:10px;
1.747     neumanie 7369: }
1.795     www      7370: 
                   7371: .LC_Clear_AboutMe_Image {
1.911     bisitz   7372:   clear:left;
1.747     neumanie 7373: }
1.795     www      7374: 
1.721     harmsja  7375: dl.LC_ListStyleClean dt {
1.911     bisitz   7376:   padding-right: 5px;
                   7377:   display: table-header-group;
1.693     droeschl 7378: }
                   7379: 
1.721     harmsja  7380: dl.LC_ListStyleClean dd {
1.911     bisitz   7381:   display: table-row;
1.693     droeschl 7382: }
                   7383: 
1.721     harmsja  7384: .LC_ListStyleClean,
                   7385: .LC_ListStyleSimple,
                   7386: .LC_ListStyleNormal,
1.795     www      7387: .LC_ListStyleSpecial {
1.911     bisitz   7388:   /* display:block; */
                   7389:   list-style-position: inside;
                   7390:   list-style-type: none;
                   7391:   overflow: hidden;
                   7392:   padding: 0;
1.693     droeschl 7393: }
                   7394: 
1.721     harmsja  7395: .LC_ListStyleSimple li,
                   7396: .LC_ListStyleSimple dd,
                   7397: .LC_ListStyleNormal li,
                   7398: .LC_ListStyleNormal dd,
                   7399: .LC_ListStyleSpecial li,
1.795     www      7400: .LC_ListStyleSpecial dd {
1.911     bisitz   7401:   margin: 0;
                   7402:   padding: 5px 5px 5px 10px;
                   7403:   clear: both;
1.693     droeschl 7404: }
                   7405: 
1.721     harmsja  7406: .LC_ListStyleClean li,
                   7407: .LC_ListStyleClean dd {
1.911     bisitz   7408:   padding-top: 0;
                   7409:   padding-bottom: 0;
1.693     droeschl 7410: }
                   7411: 
1.721     harmsja  7412: .LC_ListStyleSimple dd,
1.795     www      7413: .LC_ListStyleSimple li {
1.911     bisitz   7414:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7415: }
                   7416: 
1.721     harmsja  7417: .LC_ListStyleSpecial li,
                   7418: .LC_ListStyleSpecial dd {
1.911     bisitz   7419:   list-style-type: none;
                   7420:   background-color: RGB(220, 220, 220);
                   7421:   margin-bottom: 4px;
1.693     droeschl 7422: }
                   7423: 
1.721     harmsja  7424: table.LC_SimpleTable {
1.911     bisitz   7425:   margin:5px;
                   7426:   border:solid 1px $lg_border_color;
1.795     www      7427: }
1.693     droeschl 7428: 
1.721     harmsja  7429: table.LC_SimpleTable tr {
1.911     bisitz   7430:   padding: 0;
                   7431:   border:solid 1px $lg_border_color;
1.693     droeschl 7432: }
1.795     www      7433: 
                   7434: table.LC_SimpleTable thead {
1.911     bisitz   7435:   background:rgb(220,220,220);
1.693     droeschl 7436: }
                   7437: 
1.721     harmsja  7438: div.LC_columnSection {
1.911     bisitz   7439:   display: block;
                   7440:   clear: both;
                   7441:   overflow: hidden;
                   7442:   margin: 0;
1.693     droeschl 7443: }
                   7444: 
1.721     harmsja  7445: div.LC_columnSection>* {
1.911     bisitz   7446:   float: left;
                   7447:   margin: 10px 20px 10px 0;
                   7448:   overflow:hidden;
1.693     droeschl 7449: }
1.721     harmsja  7450: 
1.795     www      7451: table em {
1.911     bisitz   7452:   font-weight: bold;
                   7453:   font-style: normal;
1.748     schulted 7454: }
1.795     www      7455: 
1.779     bisitz   7456: table.LC_tableBrowseRes,
1.795     www      7457: table.LC_tableOfContent {
1.911     bisitz   7458:   border:none;
                   7459:   border-spacing: 1px;
                   7460:   padding: 3px;
                   7461:   background-color: #FFFFFF;
                   7462:   font-size: 90%;
1.753     droeschl 7463: }
1.789     droeschl 7464: 
1.911     bisitz   7465: table.LC_tableOfContent {
                   7466:   border-collapse: collapse;
1.789     droeschl 7467: }
                   7468: 
1.771     droeschl 7469: table.LC_tableBrowseRes a,
1.768     schulted 7470: table.LC_tableOfContent a {
1.911     bisitz   7471:   background-color: transparent;
                   7472:   text-decoration: none;
1.753     droeschl 7473: }
                   7474: 
1.795     www      7475: table.LC_tableOfContent img {
1.911     bisitz   7476:   border: none;
                   7477:   height: 1.3em;
                   7478:   vertical-align: text-bottom;
                   7479:   margin-right: 0.3em;
1.753     droeschl 7480: }
1.757     schulted 7481: 
1.795     www      7482: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7483:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7484: }
                   7485: 
1.795     www      7486: a#LC_content_toolbar_everything {
1.911     bisitz   7487:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7488: }
                   7489: 
1.795     www      7490: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7491:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7492: }
                   7493: 
1.795     www      7494: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7495:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7496: }
                   7497: 
1.795     www      7498: a#LC_content_toolbar_changefolder {
1.911     bisitz   7499:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7500: }
                   7501: 
1.795     www      7502: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7503:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7504: }
                   7505: 
1.1043    raeburn  7506: a#LC_content_toolbar_edittoplevel {
                   7507:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7508: }
                   7509: 
1.795     www      7510: ul#LC_toolbar li a:hover {
1.911     bisitz   7511:   background-position: bottom center;
1.757     schulted 7512: }
                   7513: 
1.795     www      7514: ul#LC_toolbar {
1.911     bisitz   7515:   padding: 0;
                   7516:   margin: 2px;
                   7517:   list-style:none;
                   7518:   position:relative;
                   7519:   background-color:white;
1.1075.2.9  raeburn  7520:   overflow: auto;
1.757     schulted 7521: }
                   7522: 
1.795     www      7523: ul#LC_toolbar li {
1.911     bisitz   7524:   border:1px solid white;
                   7525:   padding: 0;
                   7526:   margin: 0;
                   7527:   float: left;
                   7528:   display:inline;
                   7529:   vertical-align:middle;
1.1075.2.9  raeburn  7530:   white-space: nowrap;
1.911     bisitz   7531: }
1.757     schulted 7532: 
1.783     amueller 7533: 
1.795     www      7534: a.LC_toolbarItem {
1.911     bisitz   7535:   display:block;
                   7536:   padding: 0;
                   7537:   margin: 0;
                   7538:   height: 32px;
                   7539:   width: 32px;
                   7540:   color:white;
                   7541:   border: none;
                   7542:   background-repeat:no-repeat;
                   7543:   background-color:transparent;
1.757     schulted 7544: }
                   7545: 
1.915     droeschl 7546: ul.LC_funclist {
                   7547:     margin: 0;
                   7548:     padding: 0.5em 1em 0.5em 0;
                   7549: }
                   7550: 
1.933     droeschl 7551: ul.LC_funclist > li:first-child {
                   7552:     font-weight:bold; 
                   7553:     margin-left:0.8em;
                   7554: }
                   7555: 
1.915     droeschl 7556: ul.LC_funclist + ul.LC_funclist {
                   7557:     /* 
                   7558:        left border as a seperator if we have more than
                   7559:        one list 
                   7560:     */
                   7561:     border-left: 1px solid $sidebg;
                   7562:     /* 
                   7563:        this hides the left border behind the border of the 
                   7564:        outer box if element is wrapped to the next 'line' 
                   7565:     */
                   7566:     margin-left: -1px;
                   7567: }
                   7568: 
1.843     bisitz   7569: ul.LC_funclist li {
1.915     droeschl 7570:   display: inline;
1.782     bisitz   7571:   white-space: nowrap;
1.915     droeschl 7572:   margin: 0 0 0 25px;
                   7573:   line-height: 150%;
1.782     bisitz   7574: }
                   7575: 
1.974     wenzelju 7576: .LC_hidden {
                   7577:   display: none;
                   7578: }
                   7579: 
1.1030    www      7580: .LCmodal-overlay {
                   7581: 		position:fixed;
                   7582: 		top:0;
                   7583: 		right:0;
                   7584: 		bottom:0;
                   7585: 		left:0;
                   7586: 		height:100%;
                   7587: 		width:100%;
                   7588: 		margin:0;
                   7589: 		padding:0;
                   7590: 		background:#999;
                   7591: 		opacity:.75;
                   7592: 		filter: alpha(opacity=75);
                   7593: 		-moz-opacity: 0.75;
                   7594: 		z-index:101;
                   7595: }
                   7596: 
                   7597: * html .LCmodal-overlay {   
                   7598: 		position: absolute;
                   7599: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7600: }
                   7601: 
                   7602: .LCmodal-window {
                   7603: 		position:fixed;
                   7604: 		top:50%;
                   7605: 		left:50%;
                   7606: 		margin:0;
                   7607: 		padding:0;
                   7608: 		z-index:102;
                   7609: 	}
                   7610: 
                   7611: * html .LCmodal-window {
                   7612: 		position:absolute;
                   7613: }
                   7614: 
                   7615: .LCclose-window {
                   7616: 		position:absolute;
                   7617: 		width:32px;
                   7618: 		height:32px;
                   7619: 		right:8px;
                   7620: 		top:8px;
                   7621: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7622: 		text-indent:-99999px;
                   7623: 		overflow:hidden;
                   7624: 		cursor:pointer;
                   7625: }
                   7626: 
1.1075.2.17  raeburn  7627: /*
                   7628:   styles used by TTH when "Default set of options to pass to tth/m
                   7629:   when converting TeX" in course settings has been set
                   7630: 
                   7631:   option passed: -t
                   7632: 
                   7633: */
                   7634: 
                   7635: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7636: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7637: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7638: td div.norm {line-height:normal;}
                   7639: 
                   7640: /*
                   7641:   option passed -y3
                   7642: */
                   7643: 
                   7644: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7645: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7646: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7647: 
1.343     albertel 7648: END
                   7649: }
                   7650: 
1.306     albertel 7651: =pod
                   7652: 
                   7653: =item * &headtag()
                   7654: 
                   7655: Returns a uniform footer for LON-CAPA web pages.
                   7656: 
1.307     albertel 7657: Inputs: $title - optional title for the head
                   7658:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7659:         $args - optional arguments
1.319     albertel 7660:             force_register - if is true call registerurl so the remote is 
                   7661:                              informed
1.415     albertel 7662:             redirect       -> array ref of
                   7663:                                    1- seconds before redirect occurs
                   7664:                                    2- url to redirect to
                   7665:                                    3- whether the side effect should occur
1.315     albertel 7666:                            (side effect of setting 
                   7667:                                $env{'internal.head.redirect'} to the url 
                   7668:                                redirected too)
1.352     albertel 7669:             domain         -> force to color decorate a page for a specific
                   7670:                                domain
                   7671:             function       -> force usage of a specific rolish color scheme
                   7672:             bgcolor        -> override the default page bgcolor
1.460     albertel 7673:             no_auto_mt_title
                   7674:                            -> prevent &mt()ing the title arg
1.464     albertel 7675: 
1.306     albertel 7676: =cut
                   7677: 
                   7678: sub headtag {
1.313     albertel 7679:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7680:     
1.363     albertel 7681:     my $function = $args->{'function'} || &get_users_function();
                   7682:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7683:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  7684:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7685:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7686: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7687: 		   #time(),
1.418     albertel 7688: 		   $env{'environment.color.timestamp'},
1.363     albertel 7689: 		   $function,$domain,$bgcolor);
                   7690: 
1.369     www      7691:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7692: 
1.308     albertel 7693:     my $result =
                   7694: 	'<head>'.
1.1075.2.56  raeburn  7695: 	&font_settings($args);
1.319     albertel 7696: 
1.1075.2.72  raeburn  7697:     my $inhibitprint;
                   7698:     if ($args->{'print_suppress'}) {
                   7699:         $inhibitprint = &print_suppression();
                   7700:     }
1.1064    raeburn  7701: 
1.461     albertel 7702:     if (!$args->{'frameset'}) {
                   7703: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7704:     }
1.1075.2.12  raeburn  7705:     if ($args->{'force_register'}) {
                   7706:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 7707:     }
1.436     albertel 7708:     if (!$args->{'no_nav_bar'} 
                   7709: 	&& !$args->{'only_body'}
                   7710: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  7711: 	$result .= &help_menu_js($httphost);
1.1032    www      7712:         $result.=&modal_window();
1.1038    www      7713:         $result.=&togglebox_script();
1.1034    www      7714:         $result.=&wishlist_window();
1.1041    www      7715:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7716:     } else {
                   7717:         if ($args->{'add_modal'}) {
                   7718:            $result.=&modal_window();
                   7719:         }
                   7720:         if ($args->{'add_wishlist'}) {
                   7721:            $result.=&wishlist_window();
                   7722:         }
1.1038    www      7723:         if ($args->{'add_togglebox'}) {
                   7724:            $result.=&togglebox_script();
                   7725:         }
1.1041    www      7726:         if ($args->{'add_progressbar'}) {
                   7727:            $result.=&LCprogressbarUpdate_script();
                   7728:         }
1.436     albertel 7729:     }
1.314     albertel 7730:     if (ref($args->{'redirect'})) {
1.414     albertel 7731: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7732: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7733: 	if (!$inhibit_continue) {
                   7734: 	    $env{'internal.head.redirect'} = $url;
                   7735: 	}
1.313     albertel 7736: 	$result.=<<ADDMETA
                   7737: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7738: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7739: ADDMETA
1.1075.2.89  raeburn  7740:     } else {
                   7741:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7742:             my $requrl = $env{'request.uri'};
                   7743:             if ($requrl eq '') {
                   7744:                 $requrl = $ENV{'REQUEST_URI'};
                   7745:                 $requrl =~ s/\?.+$//;
                   7746:             }
                   7747:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7748:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7749:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7750:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7751:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7752:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   7753:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7754:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7755:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   7756:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   7757:                             if (($newserver) && ($newserver ne $lonhost)) {
                   7758:                                 my $numsec = 5;
                   7759:                                 my $timeout = $numsec * 1000;
                   7760:                                 my ($newurl,$locknum,%locks,$msg);
                   7761:                                 if ($env{'request.role.adv'}) {
                   7762:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   7763:                                 }
                   7764:                                 my $disable_submit = 0;
                   7765:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   7766:                                     $disable_submit = 1;
                   7767:                                 }
                   7768:                                 if ($locknum) {
                   7769:                                     my @lockinfo = sort(values(%locks));
                   7770:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   7771:                                            join(", ",sort(values(%locks)))."\\n".
                   7772:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   7773:                                 } else {
                   7774:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   7775:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   7776:                                     }
                   7777:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   7778:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   7779:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   7780:                                         $newurl .= '&role='.$env{'request.role'};
                   7781:                                     }
                   7782:                                     if ($env{'request.symb'}) {
                   7783:                                         $newurl .= '&symb='.$env{'request.symb'};
                   7784:                                     } else {
                   7785:                                         $newurl .= '&origurl='.$requrl;
                   7786:                                     }
                   7787:                                 }
1.1075.2.98  raeburn  7788:                                 &js_escape(\$msg);
1.1075.2.89  raeburn  7789:                                 $result.=<<OFFLOAD
                   7790: <meta http-equiv="pragma" content="no-cache" />
                   7791: <script type="text/javascript">
1.1075.2.92  raeburn  7792: // <![CDATA[
1.1075.2.89  raeburn  7793: function LC_Offload_Now() {
                   7794:     var dest = "$newurl";
                   7795:     if (dest != '') {
                   7796:         window.location.href="$newurl";
                   7797:     }
                   7798: }
1.1075.2.92  raeburn  7799: \$(document).ready(function () {
                   7800:     window.alert('$msg');
                   7801:     if ($disable_submit) {
1.1075.2.89  raeburn  7802:         \$(".LC_hwk_submit").prop("disabled", true);
                   7803:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  7804:     }
                   7805:     setTimeout('LC_Offload_Now()', $timeout);
                   7806: });
                   7807: // ]]>
1.1075.2.89  raeburn  7808: </script>
                   7809: OFFLOAD
                   7810:                             }
                   7811:                         }
                   7812:                     }
                   7813:                 }
                   7814:             }
                   7815:         }
1.313     albertel 7816:     }
1.306     albertel 7817:     if (!defined($title)) {
                   7818: 	$title = 'The LearningOnline Network with CAPA';
                   7819:     }
1.460     albertel 7820:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7821:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  7822: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   7823:     if (!$args->{'frameset'}) {
                   7824:         $result .= ' /';
                   7825:     }
                   7826:     $result .= '>'
1.1064    raeburn  7827:         .$inhibitprint
1.414     albertel 7828: 	.$head_extra;
1.1075.2.108  raeburn  7829:     my $clientmobile;
                   7830:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   7831:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   7832:     } else {
                   7833:         $clientmobile = $env{'browser.mobile'};
                   7834:     }
                   7835:     if ($clientmobile) {
1.1075.2.42  raeburn  7836:         $result .= '
                   7837: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   7838: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   7839:     }
1.962     droeschl 7840:     return $result.'</head>';
1.306     albertel 7841: }
                   7842: 
                   7843: =pod
                   7844: 
1.340     albertel 7845: =item * &font_settings()
                   7846: 
                   7847: Returns neccessary <meta> to set the proper encoding
                   7848: 
1.1075.2.56  raeburn  7849: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 7850: 
                   7851: =cut
                   7852: 
                   7853: sub font_settings {
1.1075.2.56  raeburn  7854:     my ($args) = @_;
1.340     albertel 7855:     my $headerstring='';
1.1075.2.56  raeburn  7856:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   7857:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 7858: 	$headerstring.=
1.1075.2.61  raeburn  7859: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   7860:         if (!$args->{'frameset'}) {
                   7861:             $headerstring.= ' /';
                   7862:         }
                   7863:         $headerstring .= '>'."\n";
1.340     albertel 7864:     }
                   7865:     return $headerstring;
                   7866: }
                   7867: 
1.341     albertel 7868: =pod
                   7869: 
1.1064    raeburn  7870: =item * &print_suppression()
                   7871: 
                   7872: In course context returns css which causes the body to be blank when media="print",
                   7873: if printout generation is unavailable for the current resource.
                   7874: 
                   7875: This could be because:
                   7876: 
                   7877: (a) printstartdate is in the future
                   7878: 
                   7879: (b) printenddate is in the past
                   7880: 
                   7881: (c) there is an active exam block with "printout"
                   7882: functionality blocked
                   7883: 
                   7884: Users with pav, pfo or evb privileges are exempt.
                   7885: 
                   7886: Inputs: none
                   7887: 
                   7888: =cut
                   7889: 
                   7890: 
                   7891: sub print_suppression {
                   7892:     my $noprint;
                   7893:     if ($env{'request.course.id'}) {
                   7894:         my $scope = $env{'request.course.id'};
                   7895:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7896:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7897:             return;
                   7898:         }
                   7899:         if ($env{'request.course.sec'} ne '') {
                   7900:             $scope .= "/$env{'request.course.sec'}";
                   7901:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7902:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7903:                 return;
1.1064    raeburn  7904:             }
                   7905:         }
                   7906:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7907:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.73  raeburn  7908:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  7909:         if ($blocked) {
                   7910:             my $checkrole = "cm./$cdom/$cnum";
                   7911:             if ($env{'request.course.sec'} ne '') {
                   7912:                 $checkrole .= "/$env{'request.course.sec'}";
                   7913:             }
                   7914:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7915:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7916:                 $noprint = 1;
                   7917:             }
                   7918:         }
                   7919:         unless ($noprint) {
                   7920:             my $symb = &Apache::lonnet::symbread();
                   7921:             if ($symb ne '') {
                   7922:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7923:                 if (ref($navmap)) {
                   7924:                     my $res = $navmap->getBySymb($symb);
                   7925:                     if (ref($res)) {
                   7926:                         if (!$res->resprintable()) {
                   7927:                             $noprint = 1;
                   7928:                         }
                   7929:                     }
                   7930:                 }
                   7931:             }
                   7932:         }
                   7933:         if ($noprint) {
                   7934:             return <<"ENDSTYLE";
                   7935: <style type="text/css" media="print">
                   7936:     body { display:none }
                   7937: </style>
                   7938: ENDSTYLE
                   7939:         }
                   7940:     }
                   7941:     return;
                   7942: }
                   7943: 
                   7944: =pod
                   7945: 
1.341     albertel 7946: =item * &xml_begin()
                   7947: 
                   7948: Returns the needed doctype and <html>
                   7949: 
                   7950: Inputs: none
                   7951: 
                   7952: =cut
                   7953: 
                   7954: sub xml_begin {
1.1075.2.61  raeburn  7955:     my ($is_frameset) = @_;
1.341     albertel 7956:     my $output='';
                   7957: 
                   7958:     if ($env{'browser.mathml'}) {
                   7959: 	$output='<?xml version="1.0"?>'
                   7960:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   7961: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   7962:             
                   7963: #	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" [<!ENTITY mathns "http://www.w3.org/1998/Math/MathML">] >'
                   7964: 	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">'
                   7965:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   7966: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  7967:     } elsif ($is_frameset) {
                   7968:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   7969:                 '<html>'."\n";
1.341     albertel 7970:     } else {
1.1075.2.61  raeburn  7971: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   7972:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 7973:     }
                   7974:     return $output;
                   7975: }
1.340     albertel 7976: 
                   7977: =pod
                   7978: 
1.306     albertel 7979: =item * &start_page()
                   7980: 
                   7981: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   7982: 
1.648     raeburn  7983: Inputs:
                   7984: 
                   7985: =over 4
                   7986: 
                   7987: $title - optional title for the page
                   7988: 
                   7989: $head_extra - optional extra HTML to incude inside the <head>
                   7990: 
                   7991: $args - additional optional args supported are:
                   7992: 
                   7993: =over 8
                   7994: 
                   7995:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 7996:                                     arg on
1.814     bisitz   7997:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  7998:              add_entries    -> additional attributes to add to the  <body>
                   7999:              domain         -> force to color decorate a page for a 
1.317     albertel 8000:                                     specific domain
1.648     raeburn  8001:              function       -> force usage of a specific rolish color
1.317     albertel 8002:                                     scheme
1.648     raeburn  8003:              redirect       -> see &headtag()
                   8004:              bgcolor        -> override the default page bg color
                   8005:              js_ready       -> return a string ready for being used in 
1.317     albertel 8006:                                     a javascript writeln
1.648     raeburn  8007:              html_encode    -> return a string ready for being used in 
1.320     albertel 8008:                                     a html attribute
1.648     raeburn  8009:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8010:                                     $forcereg arg
1.648     raeburn  8011:              frameset       -> if true will start with a <frameset>
1.330     albertel 8012:                                     rather than <body>
1.648     raeburn  8013:              skip_phases    -> hash ref of 
1.338     albertel 8014:                                     head -> skip the <html><head> generation
                   8015:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  8016:              no_inline_link -> if true and in remote mode, don't show the
                   8017:                                     'Switch To Inline Menu' link
1.648     raeburn  8018:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8019:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8020:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.15  raeburn  8021:              group          -> includes the current group, if page is for a
                   8022:                                specific group
1.361     albertel 8023: 
1.648     raeburn  8024: =back
1.460     albertel 8025: 
1.648     raeburn  8026: =back
1.562     albertel 8027: 
1.306     albertel 8028: =cut
                   8029: 
                   8030: sub start_page {
1.309     albertel 8031:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8032:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8033: 
1.315     albertel 8034:     $env{'internal.start_page'}++;
1.1075.2.15  raeburn  8035:     my ($result,@advtools);
1.964     droeschl 8036: 
1.338     albertel 8037:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  8038:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8039:     }
                   8040:     
                   8041:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8042: 	if ($args->{'frameset'}) {
                   8043: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8044: 						$args->{'add_entries'});
                   8045: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8046:         } else {
                   8047:             $result .=
                   8048:                 &bodytag($title, 
                   8049:                          $args->{'function'},       $args->{'add_entries'},
                   8050:                          $args->{'only_body'},      $args->{'domain'},
                   8051:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  8052:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.15  raeburn  8053:                          $args,                     \@advtools);
1.831     bisitz   8054:         }
1.330     albertel 8055:     }
1.338     albertel 8056: 
1.315     albertel 8057:     if ($args->{'js_ready'}) {
1.713     kaisler  8058: 		$result = &js_ready($result);
1.315     albertel 8059:     }
1.320     albertel 8060:     if ($args->{'html_encode'}) {
1.713     kaisler  8061: 		$result = &html_encode($result);
                   8062:     }
                   8063: 
1.813     bisitz   8064:     # Preparation for new and consistent functionlist at top of screen
                   8065:     # if ($args->{'functionlist'}) {
                   8066:     #            $result .= &build_functionlist();
                   8067:     #}
                   8068: 
1.964     droeschl 8069:     # Don't add anything more if only_body wanted or in const space
                   8070:     return $result if    $args->{'only_body'} 
                   8071:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8072: 
                   8073:     #Breadcrumbs
1.758     kaisler  8074:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8075: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8076: 		#if any br links exists, add them to the breadcrumbs
                   8077: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8078: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8079: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8080: 			}
                   8081: 		}
1.1075.2.19  raeburn  8082:                 # if @advtools array contains items add then to the breadcrumbs
                   8083:                 if (@advtools > 0) {
                   8084:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8085:                 }
1.758     kaisler  8086: 
                   8087: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8088: 		if(exists($args->{'bread_crumbs_component'})){
                   8089: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   8090: 		}else{
                   8091: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   8092: 		}
1.1075.2.24  raeburn  8093:     } elsif (($env{'environment.remote'} eq 'on') &&
                   8094:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   8095:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   8096:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  8097:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 8098:     }
1.315     albertel 8099:     return $result;
1.306     albertel 8100: }
                   8101: 
                   8102: sub end_page {
1.315     albertel 8103:     my ($args) = @_;
                   8104:     $env{'internal.end_page'}++;
1.330     albertel 8105:     my $result;
1.335     albertel 8106:     if ($args->{'discussion'}) {
                   8107: 	my ($target,$parser);
                   8108: 	if (ref($args->{'discussion'})) {
                   8109: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8110: 				$args->{'discussion'}{'parser'});
                   8111: 	}
                   8112: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8113:     }
1.330     albertel 8114:     if ($args->{'frameset'}) {
                   8115: 	$result .= '</frameset>';
                   8116:     } else {
1.635     raeburn  8117: 	$result .= &endbodytag($args);
1.330     albertel 8118:     }
1.1075.2.6  raeburn  8119:     unless ($args->{'notbody'}) {
                   8120:         $result .= "\n</html>";
                   8121:     }
1.330     albertel 8122: 
1.315     albertel 8123:     if ($args->{'js_ready'}) {
1.317     albertel 8124: 	$result = &js_ready($result);
1.315     albertel 8125:     }
1.335     albertel 8126: 
1.320     albertel 8127:     if ($args->{'html_encode'}) {
                   8128: 	$result = &html_encode($result);
                   8129:     }
1.335     albertel 8130: 
1.315     albertel 8131:     return $result;
                   8132: }
                   8133: 
1.1034    www      8134: sub wishlist_window {
                   8135:     return(<<'ENDWISHLIST');
1.1046    raeburn  8136: <script type="text/javascript">
1.1034    www      8137: // <![CDATA[
                   8138: // <!-- BEGIN LON-CAPA Internal
                   8139: function set_wishlistlink(title, path) {
                   8140:     if (!title) {
                   8141:         title = document.title;
                   8142:         title = title.replace(/^LON-CAPA /,'');
                   8143:     }
1.1075.2.65  raeburn  8144:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  8145:     title = title.replace("'","\\\'");
1.1034    www      8146:     if (!path) {
                   8147:         path = location.pathname;
                   8148:     }
1.1075.2.65  raeburn  8149:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  8150:     path = path.replace("'","\\\'");
1.1034    www      8151:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8152:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8153: }
                   8154: // END LON-CAPA Internal -->
                   8155: // ]]>
                   8156: </script>
                   8157: ENDWISHLIST
                   8158: }
                   8159: 
1.1030    www      8160: sub modal_window {
                   8161:     return(<<'ENDMODAL');
1.1046    raeburn  8162: <script type="text/javascript">
1.1030    www      8163: // <![CDATA[
                   8164: // <!-- BEGIN LON-CAPA Internal
                   8165: var modalWindow = {
                   8166: 	parent:"body",
                   8167: 	windowId:null,
                   8168: 	content:null,
                   8169: 	width:null,
                   8170: 	height:null,
                   8171: 	close:function()
                   8172: 	{
                   8173: 	        $(".LCmodal-window").remove();
                   8174: 	        $(".LCmodal-overlay").remove();
                   8175: 	},
                   8176: 	open:function()
                   8177: 	{
                   8178: 		var modal = "";
                   8179: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8180: 		modal += "<div id=\"" + this.windowId + "\" class=\"LCmodal-window\" style=\"width:" + this.width + "px; height:" + this.height + "px; margin-top:-" + (this.height / 2) + "px; margin-left:-" + (this.width / 2) + "px;\">";
                   8181: 		modal += this.content;
                   8182: 		modal += "</div>";	
                   8183: 
                   8184: 		$(this.parent).append(modal);
                   8185: 
                   8186: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8187: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8188: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8189: 	}
                   8190: };
1.1075.2.42  raeburn  8191: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8192: 	{
1.1075.2.83  raeburn  8193:                 source = source.replace("'","&#39;");
1.1030    www      8194: 		modalWindow.windowId = "myModal";
                   8195: 		modalWindow.width = width;
                   8196: 		modalWindow.height = height;
1.1075.2.80  raeburn  8197: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8198: 		modalWindow.open();
1.1075.2.87  raeburn  8199: 	};
1.1030    www      8200: // END LON-CAPA Internal -->
                   8201: // ]]>
                   8202: </script>
                   8203: ENDMODAL
                   8204: }
                   8205: 
                   8206: sub modal_link {
1.1075.2.42  raeburn  8207:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8208:     unless ($width) { $width=480; }
                   8209:     unless ($height) { $height=400; }
1.1031    www      8210:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  8211:     unless ($transparency) { $transparency='true'; }
                   8212: 
1.1074    raeburn  8213:     my $target_attr;
                   8214:     if (defined($target)) {
                   8215:         $target_attr = 'target="'.$target.'"';
                   8216:     }
                   8217:     return <<"ENDLINK";
1.1075.2.42  raeburn  8218: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8219:            $linktext</a>
                   8220: ENDLINK
1.1030    www      8221: }
                   8222: 
1.1032    www      8223: sub modal_adhoc_script {
                   8224:     my ($funcname,$width,$height,$content)=@_;
                   8225:     return (<<ENDADHOC);
1.1046    raeburn  8226: <script type="text/javascript">
1.1032    www      8227: // <![CDATA[
                   8228:         var $funcname = function()
                   8229:         {
                   8230:                 modalWindow.windowId = "myModal";
                   8231:                 modalWindow.width = $width;
                   8232:                 modalWindow.height = $height;
                   8233:                 modalWindow.content = '$content';
                   8234:                 modalWindow.open();
                   8235:         };  
                   8236: // ]]>
                   8237: </script>
                   8238: ENDADHOC
                   8239: }
                   8240: 
1.1041    www      8241: sub modal_adhoc_inner {
                   8242:     my ($funcname,$width,$height,$content)=@_;
                   8243:     my $innerwidth=$width-20;
                   8244:     $content=&js_ready(
1.1042    www      8245:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  8246:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8247:                  $content.
1.1041    www      8248:                  &end_scrollbox().
1.1075.2.42  raeburn  8249:                  &end_page()
1.1041    www      8250:              );
                   8251:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8252: }
                   8253: 
                   8254: sub modal_adhoc_window {
                   8255:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8256:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8257:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8258: }
                   8259: 
                   8260: sub modal_adhoc_launch {
                   8261:     my ($funcname,$width,$height,$content)=@_;
                   8262:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8263: <script type="text/javascript">
                   8264: // <![CDATA[
                   8265: $funcname();
                   8266: // ]]>
                   8267: </script>
                   8268: ENDLAUNCH
                   8269: }
                   8270: 
                   8271: sub modal_adhoc_close {
                   8272:     return (<<ENDCLOSE);
                   8273: <script type="text/javascript">
                   8274: // <![CDATA[
                   8275: modalWindow.close();
                   8276: // ]]>
                   8277: </script>
                   8278: ENDCLOSE
                   8279: }
                   8280: 
1.1038    www      8281: sub togglebox_script {
                   8282:    return(<<ENDTOGGLE);
                   8283: <script type="text/javascript"> 
                   8284: // <![CDATA[
                   8285: function LCtoggleDisplay(id,hidetext,showtext) {
                   8286:    link = document.getElementById(id + "link").childNodes[0];
                   8287:    with (document.getElementById(id).style) {
                   8288:       if (display == "none" ) {
                   8289:           display = "inline";
                   8290:           link.nodeValue = hidetext;
                   8291:         } else {
                   8292:           display = "none";
                   8293:           link.nodeValue = showtext;
                   8294:        }
                   8295:    }
                   8296: }
                   8297: // ]]>
                   8298: </script>
                   8299: ENDTOGGLE
                   8300: }
                   8301: 
1.1039    www      8302: sub start_togglebox {
                   8303:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8304:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8305:     unless ($showtext) { $showtext=&mt('show'); }
                   8306:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8307:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8308:     return &start_data_table().
                   8309:            &start_data_table_header_row().
                   8310:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8311:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8312:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8313:            &end_data_table_header_row().
                   8314:            '<tr id="'.$id.'" style="display:none""><td>';
                   8315: }
                   8316: 
                   8317: sub end_togglebox {
                   8318:     return '</td></tr>'.&end_data_table();
                   8319: }
                   8320: 
1.1041    www      8321: sub LCprogressbar_script {
1.1045    www      8322:    my ($id)=@_;
1.1041    www      8323:    return(<<ENDPROGRESS);
                   8324: <script type="text/javascript">
                   8325: // <![CDATA[
1.1045    www      8326: \$('#progressbar$id').progressbar({
1.1041    www      8327:   value: 0,
                   8328:   change: function(event, ui) {
                   8329:     var newVal = \$(this).progressbar('option', 'value');
                   8330:     \$('.pblabel', this).text(LCprogressTxt);
                   8331:   }
                   8332: });
                   8333: // ]]>
                   8334: </script>
                   8335: ENDPROGRESS
                   8336: }
                   8337: 
                   8338: sub LCprogressbarUpdate_script {
                   8339:    return(<<ENDPROGRESSUPDATE);
                   8340: <style type="text/css">
                   8341: .ui-progressbar { position:relative; }
                   8342: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8343: </style>
                   8344: <script type="text/javascript">
                   8345: // <![CDATA[
1.1045    www      8346: var LCprogressTxt='---';
                   8347: 
                   8348: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8349:    LCprogressTxt=progresstext;
1.1045    www      8350:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8351: }
                   8352: // ]]>
                   8353: </script>
                   8354: ENDPROGRESSUPDATE
                   8355: }
                   8356: 
1.1042    www      8357: my $LClastpercent;
1.1045    www      8358: my $LCidcnt;
                   8359: my $LCcurrentid;
1.1042    www      8360: 
1.1041    www      8361: sub LCprogressbar {
1.1042    www      8362:     my ($r)=(@_);
                   8363:     $LClastpercent=0;
1.1045    www      8364:     $LCidcnt++;
                   8365:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8366:     my $starting=&mt('Starting');
                   8367:     my $content=(<<ENDPROGBAR);
1.1045    www      8368:   <div id="progressbar$LCcurrentid">
1.1041    www      8369:     <span class="pblabel">$starting</span>
                   8370:   </div>
                   8371: ENDPROGBAR
1.1045    www      8372:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8373: }
                   8374: 
                   8375: sub LCprogressbarUpdate {
1.1042    www      8376:     my ($r,$val,$text)=@_;
                   8377:     unless ($val) { 
                   8378:        if ($LClastpercent) {
                   8379:            $val=$LClastpercent;
                   8380:        } else {
                   8381:            $val=0;
                   8382:        }
                   8383:     }
1.1041    www      8384:     if ($val<0) { $val=0; }
                   8385:     if ($val>100) { $val=0; }
1.1042    www      8386:     $LClastpercent=$val;
1.1041    www      8387:     unless ($text) { $text=$val.'%'; }
                   8388:     $text=&js_ready($text);
1.1044    www      8389:     &r_print($r,<<ENDUPDATE);
1.1041    www      8390: <script type="text/javascript">
                   8391: // <![CDATA[
1.1045    www      8392: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8393: // ]]>
                   8394: </script>
                   8395: ENDUPDATE
1.1035    www      8396: }
                   8397: 
1.1042    www      8398: sub LCprogressbarClose {
                   8399:     my ($r)=@_;
                   8400:     $LClastpercent=0;
1.1044    www      8401:     &r_print($r,<<ENDCLOSE);
1.1042    www      8402: <script type="text/javascript">
                   8403: // <![CDATA[
1.1045    www      8404: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8405: // ]]>
                   8406: </script>
                   8407: ENDCLOSE
1.1044    www      8408: }
                   8409: 
                   8410: sub r_print {
                   8411:     my ($r,$to_print)=@_;
                   8412:     if ($r) {
                   8413:       $r->print($to_print);
                   8414:       $r->rflush();
                   8415:     } else {
                   8416:       print($to_print);
                   8417:     }
1.1042    www      8418: }
                   8419: 
1.320     albertel 8420: sub html_encode {
                   8421:     my ($result) = @_;
                   8422: 
1.322     albertel 8423:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8424:     
                   8425:     return $result;
                   8426: }
1.1044    www      8427: 
1.317     albertel 8428: sub js_ready {
                   8429:     my ($result) = @_;
                   8430: 
1.323     albertel 8431:     $result =~ s/[\n\r]/ /xmsg;
                   8432:     $result =~ s/\\/\\\\/xmsg;
                   8433:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8434:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8435:     
                   8436:     return $result;
                   8437: }
                   8438: 
1.315     albertel 8439: sub validate_page {
                   8440:     if (  exists($env{'internal.start_page'})
1.316     albertel 8441: 	  &&     $env{'internal.start_page'} > 1) {
                   8442: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8443: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8444: 				 $ENV{'request.filename'});
1.315     albertel 8445:     }
                   8446:     if (  exists($env{'internal.end_page'})
1.316     albertel 8447: 	  &&     $env{'internal.end_page'} > 1) {
                   8448: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8449: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8450: 				 $env{'request.filename'});
1.315     albertel 8451:     }
                   8452:     if (     exists($env{'internal.start_page'})
                   8453: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8454: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8455: 				 $env{'request.filename'});
1.315     albertel 8456:     }
                   8457:     if (   ! exists($env{'internal.start_page'})
                   8458: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8459: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8460: 				 $env{'request.filename'});
1.315     albertel 8461:     }
1.306     albertel 8462: }
1.315     albertel 8463: 
1.996     www      8464: 
                   8465: sub start_scrollbox {
1.1075.2.56  raeburn  8466:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8467:     unless ($outerwidth) { $outerwidth='520px'; }
                   8468:     unless ($width) { $width='500px'; }
                   8469:     unless ($height) { $height='200px'; }
1.1075    raeburn  8470:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8471:     if ($id ne '') {
1.1075.2.42  raeburn  8472:         $table_id = ' id="table_'.$id.'"';
                   8473:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8474:     }
1.1075    raeburn  8475:     if ($bgcolor ne '') {
                   8476:         $tdcol = "background-color: $bgcolor;";
                   8477:     }
1.1075.2.42  raeburn  8478:     my $nicescroll_js;
                   8479:     if ($env{'browser.mobile'}) {
                   8480:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8481:     }
1.1075    raeburn  8482:     return <<"END";
1.1075.2.42  raeburn  8483: $nicescroll_js
                   8484: 
                   8485: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  8486: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  8487: END
1.996     www      8488: }
                   8489: 
                   8490: sub end_scrollbox {
1.1036    www      8491:     return '</div></td></tr></table>';
1.996     www      8492: }
                   8493: 
1.1075.2.42  raeburn  8494: sub nicescroll_javascript {
                   8495:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8496:     my %options;
                   8497:     if (ref($cursor) eq 'HASH') {
                   8498:         %options = %{$cursor};
                   8499:     }
                   8500:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8501:         $options{'railalign'} = 'left';
                   8502:     }
                   8503:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8504:         my $function  = &get_users_function();
                   8505:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   8506:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8507:             $options{'cursorcolor'} = '#00F';
                   8508:         }
                   8509:     }
                   8510:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8511:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   8512:             $options{'cursoropacity'}='1.0';
                   8513:         }
                   8514:     } else {
                   8515:         $options{'cursoropacity'}='1.0';
                   8516:     }
                   8517:     if ($options{'cursorfixedheight'} eq 'none') {
                   8518:         delete($options{'cursorfixedheight'});
                   8519:     } else {
                   8520:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8521:     }
                   8522:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8523:         delete($options{'railoffset'});
                   8524:     }
                   8525:     my @niceoptions;
                   8526:     while (my($key,$value) = each(%options)) {
                   8527:         if ($value =~ /^\{.+\}$/) {
                   8528:             push(@niceoptions,$key.':'.$value);
                   8529:         } else {
                   8530:             push(@niceoptions,$key.':"'.$value.'"');
                   8531:         }
                   8532:     }
                   8533:     my $nicescroll_js = '
                   8534: $(document).ready(
                   8535:       function() {
                   8536:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8537:       }
                   8538: );
                   8539: ';
                   8540:     if ($framecheck) {
                   8541:         $nicescroll_js .= '
                   8542: function expand_div(caller) {
                   8543:     if (top === self) {
                   8544:         document.getElementById("'.$id.'").style.width = "auto";
                   8545:         document.getElementById("'.$id.'").style.height = "auto";
                   8546:     } else {
                   8547:         try {
                   8548:             if (parent.frames) {
                   8549:                 if (parent.frames.length > 1) {
                   8550:                     var framesrc = parent.frames[1].location.href;
                   8551:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8552:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8553:                         document.getElementById("'.$id.'").style.width = "auto";
                   8554:                         document.getElementById("'.$id.'").style.height = "auto";
                   8555:                     }
                   8556:                 }
                   8557:             }
                   8558:         } catch (e) {
                   8559:             return;
                   8560:         }
                   8561:     }
                   8562:     return;
                   8563: }
                   8564: ';
                   8565:     }
                   8566:     if ($needjsready) {
                   8567:         $nicescroll_js = '
                   8568: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8569:     } else {
                   8570:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8571:     }
                   8572:     return $nicescroll_js;
                   8573: }
                   8574: 
1.318     albertel 8575: sub simple_error_page {
1.1075.2.49  raeburn  8576:     my ($r,$title,$msg,$args) = @_;
                   8577:     if (ref($args) eq 'HASH') {
                   8578:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8579:     } else {
                   8580:         $msg = &mt($msg);
                   8581:     }
                   8582: 
1.318     albertel 8583:     my $page =
                   8584: 	&Apache::loncommon::start_page($title).
1.1075.2.49  raeburn  8585: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8586: 	&Apache::loncommon::end_page();
                   8587:     if (ref($r)) {
                   8588: 	$r->print($page);
1.327     albertel 8589: 	return;
1.318     albertel 8590:     }
                   8591:     return $page;
                   8592: }
1.347     albertel 8593: 
                   8594: {
1.610     albertel 8595:     my @row_count;
1.961     onken    8596: 
                   8597:     sub start_data_table_count {
                   8598:         unshift(@row_count, 0);
                   8599:         return;
                   8600:     }
                   8601: 
                   8602:     sub end_data_table_count {
                   8603:         shift(@row_count);
                   8604:         return;
                   8605:     }
                   8606: 
1.347     albertel 8607:     sub start_data_table {
1.1018    raeburn  8608: 	my ($add_class,$id) = @_;
1.422     albertel 8609: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8610:         my $table_id;
                   8611:         if (defined($id)) {
                   8612:             $table_id = ' id="'.$id.'"';
                   8613:         }
1.961     onken    8614: 	&start_data_table_count();
1.1018    raeburn  8615: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8616:     }
                   8617: 
                   8618:     sub end_data_table {
1.961     onken    8619: 	&end_data_table_count();
1.389     albertel 8620: 	return '</table>'."\n";;
1.347     albertel 8621:     }
                   8622: 
                   8623:     sub start_data_table_row {
1.974     wenzelju 8624: 	my ($add_class, $id) = @_;
1.610     albertel 8625: 	$row_count[0]++;
                   8626: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8627: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8628:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8629:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8630:     }
1.471     banghart 8631:     
                   8632:     sub continue_data_table_row {
1.974     wenzelju 8633: 	my ($add_class, $id) = @_;
1.610     albertel 8634: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8635: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8636:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8637:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8638:     }
1.347     albertel 8639: 
                   8640:     sub end_data_table_row {
1.389     albertel 8641: 	return '</tr>'."\n";;
1.347     albertel 8642:     }
1.367     www      8643: 
1.421     albertel 8644:     sub start_data_table_empty_row {
1.707     bisitz   8645: #	$row_count[0]++;
1.421     albertel 8646: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8647:     }
                   8648: 
                   8649:     sub end_data_table_empty_row {
                   8650: 	return '</tr>'."\n";;
                   8651:     }
                   8652: 
1.367     www      8653:     sub start_data_table_header_row {
1.389     albertel 8654: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8655:     }
                   8656: 
                   8657:     sub end_data_table_header_row {
1.389     albertel 8658: 	return '</tr>'."\n";;
1.367     www      8659:     }
1.890     droeschl 8660: 
                   8661:     sub data_table_caption {
                   8662:         my $caption = shift;
                   8663:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8664:     }
1.347     albertel 8665: }
                   8666: 
1.548     albertel 8667: =pod
                   8668: 
                   8669: =item * &inhibit_menu_check($arg)
                   8670: 
                   8671: Checks for a inhibitmenu state and generates output to preserve it
                   8672: 
                   8673: Inputs:         $arg - can be any of
                   8674:                      - undef - in which case the return value is a string 
                   8675:                                to add  into arguments list of a uri
                   8676:                      - 'input' - in which case the return value is a HTML
                   8677:                                  <form> <input> field of type hidden to
                   8678:                                  preserve the value
                   8679:                      - a url - in which case the return value is the url with
                   8680:                                the neccesary cgi args added to preserve the
                   8681:                                inhibitmenu state
                   8682:                      - a ref to a url - no return value, but the string is
                   8683:                                         updated to include the neccessary cgi
                   8684:                                         args to preserve the inhibitmenu state
                   8685: 
                   8686: =cut
                   8687: 
                   8688: sub inhibit_menu_check {
                   8689:     my ($arg) = @_;
                   8690:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8691:     if ($arg eq 'input') {
                   8692: 	if ($env{'form.inhibitmenu'}) {
                   8693: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8694: 	} else {
                   8695: 	    return
                   8696: 	}
                   8697:     }
                   8698:     if ($env{'form.inhibitmenu'}) {
                   8699: 	if (ref($arg)) {
                   8700: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8701: 	} elsif ($arg eq '') {
                   8702: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8703: 	} else {
                   8704: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8705: 	}
                   8706:     }
                   8707:     if (!ref($arg)) {
                   8708: 	return $arg;
                   8709:     }
                   8710: }
                   8711: 
1.251     albertel 8712: ###############################################
1.182     matthew  8713: 
                   8714: =pod
                   8715: 
1.549     albertel 8716: =back
                   8717: 
                   8718: =head1 User Information Routines
                   8719: 
                   8720: =over 4
                   8721: 
1.405     albertel 8722: =item * &get_users_function()
1.182     matthew  8723: 
                   8724: Used by &bodytag to determine the current users primary role.
                   8725: Returns either 'student','coordinator','admin', or 'author'.
                   8726: 
                   8727: =cut
                   8728: 
                   8729: ###############################################
                   8730: sub get_users_function {
1.815     tempelho 8731:     my $function = 'norole';
1.818     tempelho 8732:     if ($env{'request.role'}=~/^(st)/) {
                   8733:         $function='student';
                   8734:     }
1.907     raeburn  8735:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8736:         $function='coordinator';
                   8737:     }
1.258     albertel 8738:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8739:         $function='admin';
                   8740:     }
1.826     bisitz   8741:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8742:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8743:         $function='author';
                   8744:     }
                   8745:     return $function;
1.54      www      8746: }
1.99      www      8747: 
                   8748: ###############################################
                   8749: 
1.233     raeburn  8750: =pod
                   8751: 
1.821     raeburn  8752: =item * &show_course()
                   8753: 
                   8754: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8755: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8756: 
                   8757: Inputs:
                   8758: None
                   8759: 
                   8760: Outputs:
                   8761: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8762: 
                   8763: =cut
                   8764: 
                   8765: ###############################################
                   8766: sub show_course {
                   8767:     my $course = !$env{'user.adv'};
                   8768:     if (!$env{'user.adv'}) {
                   8769:         foreach my $env (keys(%env)) {
                   8770:             next if ($env !~ m/^user\.priv\./);
                   8771:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8772:                 $course = 0;
                   8773:                 last;
                   8774:             }
                   8775:         }
                   8776:     }
                   8777:     return $course;
                   8778: }
                   8779: 
                   8780: ###############################################
                   8781: 
                   8782: =pod
                   8783: 
1.542     raeburn  8784: =item * &check_user_status()
1.274     raeburn  8785: 
                   8786: Determines current status of supplied role for a
                   8787: specific user. Roles can be active, previous or future.
                   8788: 
                   8789: Inputs: 
                   8790: user's domain, user's username, course's domain,
1.375     raeburn  8791: course's number, optional section ID.
1.274     raeburn  8792: 
                   8793: Outputs:
                   8794: role status: active, previous or future. 
                   8795: 
                   8796: =cut
                   8797: 
                   8798: sub check_user_status {
1.412     raeburn  8799:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8800:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  8801:     my @uroles = keys(%userinfo);
1.274     raeburn  8802:     my $srchstr;
                   8803:     my $active_chk = 'none';
1.412     raeburn  8804:     my $now = time;
1.274     raeburn  8805:     if (@uroles > 0) {
1.908     raeburn  8806:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8807:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8808:         } else {
1.412     raeburn  8809:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8810:         }
                   8811:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8812:             my $role_end = 0;
                   8813:             my $role_start = 0;
                   8814:             $active_chk = 'active';
1.412     raeburn  8815:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8816:                 $role_end = $1;
                   8817:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8818:                     $role_start = $1;
1.274     raeburn  8819:                 }
                   8820:             }
                   8821:             if ($role_start > 0) {
1.412     raeburn  8822:                 if ($now < $role_start) {
1.274     raeburn  8823:                     $active_chk = 'future';
                   8824:                 }
                   8825:             }
                   8826:             if ($role_end > 0) {
1.412     raeburn  8827:                 if ($now > $role_end) {
1.274     raeburn  8828:                     $active_chk = 'previous';
                   8829:                 }
                   8830:             }
                   8831:         }
                   8832:     }
                   8833:     return $active_chk;
                   8834: }
                   8835: 
                   8836: ###############################################
                   8837: 
                   8838: =pod
                   8839: 
1.405     albertel 8840: =item * &get_sections()
1.233     raeburn  8841: 
                   8842: Determines all the sections for a course including
                   8843: sections with students and sections containing other roles.
1.419     raeburn  8844: Incoming parameters: 
                   8845: 
                   8846: 1. domain
                   8847: 2. course number 
                   8848: 3. reference to array containing roles for which sections should 
                   8849: be gathered (optional).
                   8850: 4. reference to array containing status types for which sections 
                   8851: should be gathered (optional).
                   8852: 
                   8853: If the third argument is undefined, sections are gathered for any role. 
                   8854: If the fourth argument is undefined, sections are gathered for any status.
                   8855: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8856:  
1.374     raeburn  8857: Returns section hash (keys are section IDs, values are
                   8858: number of users in each section), subject to the
1.419     raeburn  8859: optional roles filter, optional status filter 
1.233     raeburn  8860: 
                   8861: =cut
                   8862: 
                   8863: ###############################################
                   8864: sub get_sections {
1.419     raeburn  8865:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8866:     if (!defined($cdom) || !defined($cnum)) {
                   8867:         my $cid =  $env{'request.course.id'};
                   8868: 
                   8869: 	return if (!defined($cid));
                   8870: 
                   8871:         $cdom = $env{'course.'.$cid.'.domain'};
                   8872:         $cnum = $env{'course.'.$cid.'.num'};
                   8873:     }
                   8874: 
                   8875:     my %sectioncount;
1.419     raeburn  8876:     my $now = time;
1.240     albertel 8877: 
1.1075.2.33  raeburn  8878:     my $check_students = 1;
                   8879:     my $only_students = 0;
                   8880:     if (ref($possible_roles) eq 'ARRAY') {
                   8881:         if (grep(/^st$/,@{$possible_roles})) {
                   8882:             if (@{$possible_roles} == 1) {
                   8883:                 $only_students = 1;
                   8884:             }
                   8885:         } else {
                   8886:             $check_students = 0;
                   8887:         }
                   8888:     }
                   8889: 
                   8890:     if ($check_students) {
1.276     albertel 8891: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8892: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8893: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8894:         my $start_index = &Apache::loncoursedata::CL_START();
                   8895:         my $end_index = &Apache::loncoursedata::CL_END();
                   8896:         my $status;
1.366     albertel 8897: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8898: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8899: 				                     $data->[$status_index],
                   8900:                                                      $data->[$start_index],
                   8901:                                                      $data->[$end_index]);
                   8902:             if ($stu_status eq 'Active') {
                   8903:                 $status = 'active';
                   8904:             } elsif ($end < $now) {
                   8905:                 $status = 'previous';
                   8906:             } elsif ($start > $now) {
                   8907:                 $status = 'future';
                   8908:             } 
                   8909: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8910:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8911:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8912: 		    $sectioncount{$section}++;
                   8913:                 }
1.240     albertel 8914: 	    }
                   8915: 	}
                   8916:     }
1.1075.2.33  raeburn  8917:     if ($only_students) {
                   8918:         return %sectioncount;
                   8919:     }
1.240     albertel 8920:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8921:     foreach my $user (sort(keys(%courseroles))) {
                   8922: 	if ($user !~ /^(\w{2})/) { next; }
                   8923: 	my ($role) = ($user =~ /^(\w{2})/);
                   8924: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  8925: 	my ($section,$status);
1.240     albertel 8926: 	if ($role eq 'cr' &&
                   8927: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   8928: 	    $section=$1;
                   8929: 	}
                   8930: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   8931: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  8932:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   8933:         if ($end == -1 && $start == -1) {
                   8934:             next; #deleted role
                   8935:         }
                   8936:         if (!defined($possible_status)) { 
                   8937:             $sectioncount{$section}++;
                   8938:         } else {
                   8939:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   8940:                 $status = 'active';
                   8941:             } elsif ($end < $now) {
                   8942:                 $status = 'future';
                   8943:             } elsif ($start > $now) {
                   8944:                 $status = 'previous';
                   8945:             }
                   8946:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   8947:                 $sectioncount{$section}++;
                   8948:             }
                   8949:         }
1.233     raeburn  8950:     }
1.366     albertel 8951:     return %sectioncount;
1.233     raeburn  8952: }
                   8953: 
1.274     raeburn  8954: ###############################################
1.294     raeburn  8955: 
                   8956: =pod
1.405     albertel 8957: 
                   8958: =item * &get_course_users()
                   8959: 
1.275     raeburn  8960: Retrieves usernames:domains for users in the specified course
                   8961: with specific role(s), and access status. 
                   8962: 
                   8963: Incoming parameters:
1.277     albertel 8964: 1. course domain
                   8965: 2. course number
                   8966: 3. access status: users must have - either active, 
1.275     raeburn  8967: previous, future, or all.
1.277     albertel 8968: 4. reference to array of permissible roles
1.288     raeburn  8969: 5. reference to array of section restrictions (optional)
                   8970: 6. reference to results object (hash of hashes).
                   8971: 7. reference to optional userdata hash
1.609     raeburn  8972: 8. reference to optional statushash
1.630     raeburn  8973: 9. flag if privileged users (except those set to unhide in
                   8974:    course settings) should be excluded    
1.609     raeburn  8975: Keys of top level results hash are roles.
1.275     raeburn  8976: Keys of inner hashes are username:domain, with 
                   8977: values set to access type.
1.288     raeburn  8978: Optional userdata hash returns an array with arguments in the 
                   8979: same order as loncoursedata::get_classlist() for student data.
                   8980: 
1.609     raeburn  8981: Optional statushash returns
                   8982: 
1.288     raeburn  8983: Entries for end, start, section and status are blank because
                   8984: of the possibility of multiple values for non-student roles.
                   8985: 
1.275     raeburn  8986: =cut
1.405     albertel 8987: 
1.275     raeburn  8988: ###############################################
1.405     albertel 8989: 
1.275     raeburn  8990: sub get_course_users {
1.630     raeburn  8991:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  8992:     my %idx = ();
1.419     raeburn  8993:     my %seclists;
1.288     raeburn  8994: 
                   8995:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   8996:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   8997:     $idx{end} = &Apache::loncoursedata::CL_END();
                   8998:     $idx{start} = &Apache::loncoursedata::CL_START();
                   8999:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9000:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9001:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9002:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9003: 
1.290     albertel 9004:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9005:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9006:         my $now = time;
1.277     albertel 9007:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9008:             my $match = 0;
1.412     raeburn  9009:             my $secmatch = 0;
1.419     raeburn  9010:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9011:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9012:             if ($section eq '') {
                   9013:                 $section = 'none';
                   9014:             }
1.291     albertel 9015:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9016:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9017:                     $secmatch = 1;
                   9018:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9019:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9020:                         $secmatch = 1;
                   9021:                     }
                   9022:                 } else {  
1.419     raeburn  9023: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9024: 		        $secmatch = 1;
                   9025:                     }
1.290     albertel 9026: 		}
1.412     raeburn  9027:                 if (!$secmatch) {
                   9028:                     next;
                   9029:                 }
1.419     raeburn  9030:             }
1.275     raeburn  9031:             if (defined($$types{'active'})) {
1.288     raeburn  9032:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9033:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9034:                     $match = 1;
1.275     raeburn  9035:                 }
                   9036:             }
                   9037:             if (defined($$types{'previous'})) {
1.609     raeburn  9038:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9039:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9040:                     $match = 1;
1.275     raeburn  9041:                 }
                   9042:             }
                   9043:             if (defined($$types{'future'})) {
1.609     raeburn  9044:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9045:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9046:                     $match = 1;
1.275     raeburn  9047:                 }
                   9048:             }
1.609     raeburn  9049:             if ($match) {
                   9050:                 push(@{$seclists{$student}},$section);
                   9051:                 if (ref($userdata) eq 'HASH') {
                   9052:                     $$userdata{$student} = $$classlist{$student};
                   9053:                 }
                   9054:                 if (ref($statushash) eq 'HASH') {
                   9055:                     $statushash->{$student}{'st'}{$section} = $status;
                   9056:                 }
1.288     raeburn  9057:             }
1.275     raeburn  9058:         }
                   9059:     }
1.412     raeburn  9060:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9061:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9062:         my $now = time;
1.609     raeburn  9063:         my %displaystatus = ( previous => 'Expired',
                   9064:                               active   => 'Active',
                   9065:                               future   => 'Future',
                   9066:                             );
1.1075.2.36  raeburn  9067:         my (%nothide,@possdoms);
1.630     raeburn  9068:         if ($hidepriv) {
                   9069:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9070:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9071:                 if ($user !~ /:/) {
                   9072:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9073:                 } else {
                   9074:                     $nothide{$user} = 1;
                   9075:                 }
                   9076:             }
1.1075.2.36  raeburn  9077:             my @possdoms = ($cdom);
                   9078:             if ($coursehash{'checkforpriv'}) {
                   9079:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9080:             }
1.630     raeburn  9081:         }
1.439     raeburn  9082:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9083:             my $match = 0;
1.412     raeburn  9084:             my $secmatch = 0;
1.439     raeburn  9085:             my $status;
1.412     raeburn  9086:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9087:             $user =~ s/:$//;
1.439     raeburn  9088:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9089:             if ($end == -1 || $start == -1) {
                   9090:                 next;
                   9091:             }
                   9092:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9093:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9094:                 my ($uname,$udom) = split(/:/,$user);
                   9095:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9096:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9097:                         $secmatch = 1;
                   9098:                     } elsif ($usec eq '') {
1.420     albertel 9099:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9100:                             $secmatch = 1;
                   9101:                         }
                   9102:                     } else {
                   9103:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9104:                             $secmatch = 1;
                   9105:                         }
                   9106:                     }
                   9107:                     if (!$secmatch) {
                   9108:                         next;
                   9109:                     }
1.288     raeburn  9110:                 }
1.419     raeburn  9111:                 if ($usec eq '') {
                   9112:                     $usec = 'none';
                   9113:                 }
1.275     raeburn  9114:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9115:                     if ($hidepriv) {
1.1075.2.36  raeburn  9116:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9117:                             (!$nothide{$uname.':'.$udom})) {
                   9118:                             next;
                   9119:                         }
                   9120:                     }
1.503     raeburn  9121:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9122:                         $status = 'previous';
                   9123:                     } elsif ($start > $now) {
                   9124:                         $status = 'future';
                   9125:                     } else {
                   9126:                         $status = 'active';
                   9127:                     }
1.277     albertel 9128:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9129:                         if ($status eq $type) {
1.420     albertel 9130:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9131:                                 push(@{$$users{$role}{$user}},$type);
                   9132:                             }
1.288     raeburn  9133:                             $match = 1;
                   9134:                         }
                   9135:                     }
1.419     raeburn  9136:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9137:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9138: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9139:                         }
1.420     albertel 9140:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9141:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9142:                         }
1.609     raeburn  9143:                         if (ref($statushash) eq 'HASH') {
                   9144:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9145:                         }
1.275     raeburn  9146:                     }
                   9147:                 }
                   9148:             }
                   9149:         }
1.290     albertel 9150:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9151:             if ((defined($cdom)) && (defined($cnum))) {
                   9152:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9153:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9154:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9155:                     next if ($owner eq '');
                   9156:                     my ($ownername,$ownerdom);
                   9157:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9158:                         $ownername = $1;
                   9159:                         $ownerdom = $2;
                   9160:                     } else {
                   9161:                         $ownername = $owner;
                   9162:                         $ownerdom = $cdom;
                   9163:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9164:                     }
                   9165:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9166:                     if (defined($userdata) && 
1.609     raeburn  9167: 			!exists($$userdata{$owner})) {
                   9168: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9169:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9170:                             push(@{$seclists{$owner}},'none');
                   9171:                         }
                   9172:                         if (ref($statushash) eq 'HASH') {
                   9173:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9174:                         }
1.290     albertel 9175: 		    }
1.279     raeburn  9176:                 }
                   9177:             }
                   9178:         }
1.419     raeburn  9179:         foreach my $user (keys(%seclists)) {
                   9180:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9181:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9182:         }
1.275     raeburn  9183:     }
                   9184:     return;
                   9185: }
                   9186: 
1.288     raeburn  9187: sub get_user_info {
                   9188:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9189:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9190: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9191:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9192:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9193:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9194:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9195:     return;
                   9196: }
1.275     raeburn  9197: 
1.472     raeburn  9198: ###############################################
                   9199: 
                   9200: =pod
                   9201: 
                   9202: =item * &get_user_quota()
                   9203: 
1.1075.2.41  raeburn  9204: Retrieves quota assigned for storage of user files.
                   9205: Default is to report quota for portfolio files.
1.472     raeburn  9206: 
                   9207: Incoming parameters:
                   9208: 1. user's username
                   9209: 2. user's domain
1.1075.2.41  raeburn  9210: 3. quota name - portfolio, author, or course
                   9211:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  9212: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  9213:    course
1.472     raeburn  9214: 
                   9215: Returns:
1.1075.2.58  raeburn  9216: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9217: 2. (Optional) Type of setting: custom or default
                   9218:    (individually assigned or default for user's 
                   9219:    institutional status).
                   9220: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9221:    or student - types as defined in localenroll::inst_usertypes 
                   9222:    for user's domain, which determines default quota for user.
                   9223: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9224: 
                   9225: If a value has been stored in the user's environment, 
1.536     raeburn  9226: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  9227: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9228: 
                   9229: =cut
                   9230: 
                   9231: ###############################################
                   9232: 
                   9233: 
                   9234: sub get_user_quota {
1.1075.2.42  raeburn  9235:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9236:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9237:     if (!defined($udom)) {
                   9238:         $udom = $env{'user.domain'};
                   9239:     }
                   9240:     if (!defined($uname)) {
                   9241:         $uname = $env{'user.name'};
                   9242:     }
                   9243:     if (($udom eq '' || $uname eq '') ||
                   9244:         ($udom eq 'public') && ($uname eq 'public')) {
                   9245:         $quota = 0;
1.536     raeburn  9246:         $quotatype = 'default';
                   9247:         $defquota = 0; 
1.472     raeburn  9248:     } else {
1.536     raeburn  9249:         my $inststatus;
1.1075.2.41  raeburn  9250:         if ($quotaname eq 'course') {
                   9251:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9252:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9253:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9254:             } else {
                   9255:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9256:                 $quota = $cenv{'internal.uploadquota'};
                   9257:             }
1.536     raeburn  9258:         } else {
1.1075.2.41  raeburn  9259:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9260:                 if ($quotaname eq 'author') {
                   9261:                     $quota = $env{'environment.authorquota'};
                   9262:                 } else {
                   9263:                     $quota = $env{'environment.portfolioquota'};
                   9264:                 }
                   9265:                 $inststatus = $env{'environment.inststatus'};
                   9266:             } else {
                   9267:                 my %userenv = 
                   9268:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9269:                                          'authorquota','inststatus'],$udom,$uname);
                   9270:                 my ($tmp) = keys(%userenv);
                   9271:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9272:                     if ($quotaname eq 'author') {
                   9273:                         $quota = $userenv{'authorquota'};
                   9274:                     } else {
                   9275:                         $quota = $userenv{'portfolioquota'};
                   9276:                     }
                   9277:                     $inststatus = $userenv{'inststatus'};
                   9278:                 } else {
                   9279:                     undef(%userenv);
                   9280:                 }
                   9281:             }
                   9282:         }
                   9283:         if ($quota eq '' || wantarray) {
                   9284:             if ($quotaname eq 'course') {
                   9285:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  9286:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   9287:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  9288:                     $defquota = $domdefs{$crstype.'quota'};
                   9289:                 }
                   9290:                 if ($defquota eq '') {
                   9291:                     $defquota = 500;
                   9292:                 }
1.1075.2.41  raeburn  9293:             } else {
                   9294:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9295:             }
                   9296:             if ($quota eq '') {
                   9297:                 $quota = $defquota;
                   9298:                 $quotatype = 'default';
                   9299:             } else {
                   9300:                 $quotatype = 'custom';
                   9301:             }
1.472     raeburn  9302:         }
                   9303:     }
1.536     raeburn  9304:     if (wantarray) {
                   9305:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9306:     } else {
                   9307:         return $quota;
                   9308:     }
1.472     raeburn  9309: }
                   9310: 
                   9311: ###############################################
                   9312: 
                   9313: =pod
                   9314: 
                   9315: =item * &default_quota()
                   9316: 
1.536     raeburn  9317: Retrieves default quota assigned for storage of user portfolio files,
                   9318: given an (optional) user's institutional status.
1.472     raeburn  9319: 
                   9320: Incoming parameters:
1.1075.2.42  raeburn  9321: 
1.472     raeburn  9322: 1. domain
1.536     raeburn  9323: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9324:    status types (e.g., faculty, staff, student etc.)
                   9325:    which apply to the user for whom the default is being retrieved.
                   9326:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  9327:    default quota will be returned.
                   9328: 3.  quota name - portfolio, author, or course
                   9329:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9330: 
                   9331: Returns:
1.1075.2.42  raeburn  9332: 
1.1075.2.58  raeburn  9333: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9334: 2. (Optional) institutional type which determined the value of the
                   9335:    default quota.
1.472     raeburn  9336: 
                   9337: If a value has been stored in the domain's configuration db,
                   9338: it will return that, otherwise it returns 20 (for backwards 
                   9339: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  9340: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9341: 
1.536     raeburn  9342: If the user's status includes multiple types (e.g., staff and student),
                   9343: the largest default quota which applies to the user determines the
                   9344: default quota returned.
                   9345: 
1.472     raeburn  9346: =cut
                   9347: 
                   9348: ###############################################
                   9349: 
                   9350: 
                   9351: sub default_quota {
1.1075.2.41  raeburn  9352:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9353:     my ($defquota,$settingstatus);
                   9354:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9355:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  9356:     my $key = 'defaultquota';
                   9357:     if ($quotaname eq 'author') {
                   9358:         $key = 'authorquota';
                   9359:     }
1.622     raeburn  9360:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9361:         if ($inststatus ne '') {
1.765     raeburn  9362:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9363:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  9364:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9365:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9366:                         if ($defquota eq '') {
1.1075.2.41  raeburn  9367:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9368:                             $settingstatus = $item;
1.1075.2.41  raeburn  9369:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9370:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9371:                             $settingstatus = $item;
                   9372:                         }
                   9373:                     }
1.1075.2.41  raeburn  9374:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9375:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9376:                         if ($defquota eq '') {
                   9377:                             $defquota = $quotahash{'quotas'}{$item};
                   9378:                             $settingstatus = $item;
                   9379:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9380:                             $defquota = $quotahash{'quotas'}{$item};
                   9381:                             $settingstatus = $item;
                   9382:                         }
1.536     raeburn  9383:                     }
                   9384:                 }
                   9385:             }
                   9386:         }
                   9387:         if ($defquota eq '') {
1.1075.2.41  raeburn  9388:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9389:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9390:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9391:                 $defquota = $quotahash{'quotas'}{'default'};
                   9392:             }
1.536     raeburn  9393:             $settingstatus = 'default';
1.1075.2.42  raeburn  9394:             if ($defquota eq '') {
                   9395:                 if ($quotaname eq 'author') {
                   9396:                     $defquota = 500;
                   9397:                 }
                   9398:             }
1.536     raeburn  9399:         }
                   9400:     } else {
                   9401:         $settingstatus = 'default';
1.1075.2.41  raeburn  9402:         if ($quotaname eq 'author') {
                   9403:             $defquota = 500;
                   9404:         } else {
                   9405:             $defquota = 20;
                   9406:         }
1.536     raeburn  9407:     }
                   9408:     if (wantarray) {
                   9409:         return ($defquota,$settingstatus);
1.472     raeburn  9410:     } else {
1.536     raeburn  9411:         return $defquota;
1.472     raeburn  9412:     }
                   9413: }
                   9414: 
1.1075.2.41  raeburn  9415: ###############################################
                   9416: 
                   9417: =pod
                   9418: 
1.1075.2.42  raeburn  9419: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  9420: 
                   9421: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  9422: of existing file within authoring space will cause quota for the authoring
                   9423: space to be exceeded.
                   9424: 
                   9425: Same, if upload of a file directly to a course/community via Course Editor
                   9426: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  9427: 
1.1075.2.61  raeburn  9428: Inputs: 7 
1.1075.2.42  raeburn  9429: 1. username or coursenum
1.1075.2.41  raeburn  9430: 2. domain
1.1075.2.42  raeburn  9431: 3. context ('author' or 'course')
1.1075.2.41  raeburn  9432: 4. filename of file for which action is being requested
                   9433: 5. filesize (kB) of file
                   9434: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  9435: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  9436: 
                   9437: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   9438:          otherwise return null.
                   9439: 
1.1075.2.42  raeburn  9440: =back
                   9441: 
1.1075.2.41  raeburn  9442: =cut
                   9443: 
1.1075.2.42  raeburn  9444: sub excess_filesize_warning {
1.1075.2.59  raeburn  9445:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  9446:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  9447:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  9448:     if ($context eq 'author') {
                   9449:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9450:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9451:     } else {
                   9452:         foreach my $subdir ('docs','supplemental') {
                   9453:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9454:         }
                   9455:     }
1.1075.2.41  raeburn  9456:     $disk_quota = int($disk_quota * 1000);
                   9457:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  9458:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  9459:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  9460:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9461:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  9462:                             $disk_quota,$current_disk_usage).
                   9463:                '</p>';
                   9464:     }
                   9465:     return;
                   9466: }
                   9467: 
                   9468: ###############################################
                   9469: 
                   9470: 
1.384     raeburn  9471: sub get_secgrprole_info {
                   9472:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9473:     my %sections_count = &get_sections($cdom,$cnum);
                   9474:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9475:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9476:     my @groups = sort(keys(%curr_groups));
                   9477:     my $allroles = [];
                   9478:     my $rolehash;
                   9479:     my $accesshash = {
                   9480:                      active => 'Currently has access',
                   9481:                      future => 'Will have future access',
                   9482:                      previous => 'Previously had access',
                   9483:                   };
                   9484:     if ($needroles) {
                   9485:         $rolehash = {'all' => 'all'};
1.385     albertel 9486:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9487: 	if (&Apache::lonnet::error(%user_roles)) {
                   9488: 	    undef(%user_roles);
                   9489: 	}
                   9490:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9491:             my ($role)=split(/\:/,$item,2);
                   9492:             if ($role eq 'cr') { next; }
                   9493:             if ($role =~ /^cr/) {
                   9494:                 $$rolehash{$role} = (split('/',$role))[3];
                   9495:             } else {
                   9496:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9497:             }
                   9498:         }
                   9499:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9500:             push(@{$allroles},$key);
                   9501:         }
                   9502:         push (@{$allroles},'st');
                   9503:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9504:     }
                   9505:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9506: }
                   9507: 
1.555     raeburn  9508: sub user_picker {
1.994     raeburn  9509:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  9510:     my $currdom = $dom;
                   9511:     my %curr_selected = (
                   9512:                         srchin => 'dom',
1.580     raeburn  9513:                         srchby => 'lastname',
1.555     raeburn  9514:                       );
                   9515:     my $srchterm;
1.625     raeburn  9516:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9517:         if ($srch->{'srchby'} ne '') {
                   9518:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9519:         }
                   9520:         if ($srch->{'srchin'} ne '') {
                   9521:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9522:         }
                   9523:         if ($srch->{'srchtype'} ne '') {
                   9524:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9525:         }
                   9526:         if ($srch->{'srchdomain'} ne '') {
                   9527:             $currdom = $srch->{'srchdomain'};
                   9528:         }
                   9529:         $srchterm = $srch->{'srchterm'};
                   9530:     }
1.1075.2.98  raeburn  9531:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  9532:                     'usr'       => 'Search criteria',
1.563     raeburn  9533:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9534:                     'uname'     => 'username',
                   9535:                     'lastname'  => 'last name',
1.555     raeburn  9536:                     'lastfirst' => 'last name, first name',
1.558     albertel 9537:                     'crs'       => 'in this course',
1.576     raeburn  9538:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9539:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9540:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9541:                     'exact'     => 'is',
                   9542:                     'contains'  => 'contains',
1.569     raeburn  9543:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  9544:                                        );
                   9545:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  9546:                     'youm'      => "You must include some text to search for.",
                   9547:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9548:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9549:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9550:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9551:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9552:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9553:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9554:                                        );
1.1075.2.98  raeburn  9555:     &html_escape(\%html_lt);
                   9556:     &js_escape(\%js_lt);
1.563     raeburn  9557:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   9558:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9559: 
                   9560:     my @srchins = ('crs','dom','alc','instd');
                   9561: 
                   9562:     foreach my $option (@srchins) {
                   9563:         # FIXME 'alc' option unavailable until 
                   9564:         #       loncreateuser::print_user_query_page()
                   9565:         #       has been completed.
                   9566:         next if ($option eq 'alc');
1.880     raeburn  9567:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9568:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  9569:         if ($curr_selected{'srchin'} eq $option) {
                   9570:             $srchinsel .= ' 
1.1075.2.98  raeburn  9571:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  9572:         } else {
                   9573:             $srchinsel .= '
1.1075.2.98  raeburn  9574:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  9575:         }
1.555     raeburn  9576:     }
1.563     raeburn  9577:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9578: 
                   9579:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9580:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9581:         if ($curr_selected{'srchby'} eq $option) {
                   9582:             $srchbysel .= '
1.1075.2.98  raeburn  9583:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9584:         } else {
                   9585:             $srchbysel .= '
1.1075.2.98  raeburn  9586:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9587:          }
                   9588:     }
                   9589:     $srchbysel .= "\n  </select>\n";
                   9590: 
                   9591:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9592:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9593:         if ($curr_selected{'srchtype'} eq $option) {
                   9594:             $srchtypesel .= '
1.1075.2.98  raeburn  9595:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9596:         } else {
                   9597:             $srchtypesel .= '
1.1075.2.98  raeburn  9598:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9599:         }
                   9600:     }
                   9601:     $srchtypesel .= "\n  </select>\n";
                   9602: 
1.558     albertel 9603:     my ($newuserscript,$new_user_create);
1.994     raeburn  9604:     my $context_dom = $env{'request.role.domain'};
                   9605:     if ($context eq 'requestcrs') {
                   9606:         if ($env{'form.coursedom'} ne '') { 
                   9607:             $context_dom = $env{'form.coursedom'};
                   9608:         }
                   9609:     }
1.556     raeburn  9610:     if ($forcenewuser) {
1.576     raeburn  9611:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9612:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9613:                 if ($cancreate) {
                   9614:                     $new_user_create = '<p> <input type="submit" name="forcenew" value="'.&HTML::Entities::encode(&mt('Make new user "[_1]"',$srchterm),'<>&"').'" onclick="javascript:setSearch(\'1\','.$caller.');" /> </p>';
                   9615:                 } else {
1.799     bisitz   9616:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9617:                     my %usertypetext = (
                   9618:                         official   => 'institutional',
                   9619:                         unofficial => 'non-institutional',
                   9620:                     );
1.799     bisitz   9621:                     $new_user_create = '<p class="LC_warning">'
                   9622:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9623:                                       .' '
                   9624:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9625:                                           ,'<a href="'.$helplink.'">','</a>')
                   9626:                                       .'</p><br />';
1.627     raeburn  9627:                 }
1.576     raeburn  9628:             }
                   9629:         }
                   9630: 
1.556     raeburn  9631:         $newuserscript = <<"ENDSCRIPT";
                   9632: 
1.570     raeburn  9633: function setSearch(createnew,callingForm) {
1.556     raeburn  9634:     if (createnew == 1) {
1.570     raeburn  9635:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9636:             if (callingForm.srchby.options[i].value == 'uname') {
                   9637:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9638:             }
                   9639:         }
1.570     raeburn  9640:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9641:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9642: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9643:             }
                   9644:         }
1.570     raeburn  9645:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9646:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9647:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9648:             }
                   9649:         }
1.570     raeburn  9650:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9651:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9652:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9653:             }
                   9654:         }
                   9655:     }
                   9656: }
                   9657: ENDSCRIPT
1.558     albertel 9658: 
1.556     raeburn  9659:     }
                   9660: 
1.555     raeburn  9661:     my $output = <<"END_BLOCK";
1.556     raeburn  9662: <script type="text/javascript">
1.824     bisitz   9663: // <![CDATA[
1.570     raeburn  9664: function validateEntry(callingForm) {
1.558     albertel 9665: 
1.556     raeburn  9666:     var checkok = 1;
1.558     albertel 9667:     var srchin;
1.570     raeburn  9668:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9669: 	if ( callingForm.srchin[i].checked ) {
                   9670: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9671: 	}
                   9672:     }
                   9673: 
1.570     raeburn  9674:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9675:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9676:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9677:     var srchterm =  callingForm.srchterm.value;
                   9678:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9679:     var msg = "";
                   9680: 
                   9681:     if (srchterm == "") {
                   9682:         checkok = 0;
1.1075.2.98  raeburn  9683:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  9684:     }
                   9685: 
1.569     raeburn  9686:     if (srchtype== 'begins') {
                   9687:         if (srchterm.length < 2) {
                   9688:             checkok = 0;
1.1075.2.98  raeburn  9689:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  9690:         }
                   9691:     }
                   9692: 
1.556     raeburn  9693:     if (srchtype== 'contains') {
                   9694:         if (srchterm.length < 3) {
                   9695:             checkok = 0;
1.1075.2.98  raeburn  9696:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  9697:         }
                   9698:     }
                   9699:     if (srchin == 'instd') {
                   9700:         if (srchdomain == '') {
                   9701:             checkok = 0;
1.1075.2.98  raeburn  9702:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  9703:         }
                   9704:     }
                   9705:     if (srchin == 'dom') {
                   9706:         if (srchdomain == '') {
                   9707:             checkok = 0;
1.1075.2.98  raeburn  9708:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  9709:         }
                   9710:     }
                   9711:     if (srchby == 'lastfirst') {
                   9712:         if (srchterm.indexOf(",") == -1) {
                   9713:             checkok = 0;
1.1075.2.98  raeburn  9714:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  9715:         }
                   9716:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9717:             checkok = 0;
1.1075.2.98  raeburn  9718:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  9719:         }
                   9720:     }
                   9721:     if (checkok == 0) {
1.1075.2.98  raeburn  9722:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  9723:         return;
                   9724:     }
                   9725:     if (checkok == 1) {
1.570     raeburn  9726:         callingForm.submit();
1.556     raeburn  9727:     }
                   9728: }
                   9729: 
                   9730: $newuserscript
                   9731: 
1.824     bisitz   9732: // ]]>
1.556     raeburn  9733: </script>
1.558     albertel 9734: 
                   9735: $new_user_create
                   9736: 
1.555     raeburn  9737: END_BLOCK
1.558     albertel 9738: 
1.876     raeburn  9739:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  9740:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  9741:                $domform.
                   9742:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  9743:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  9744:                $srchbysel.
                   9745:                $srchtypesel. 
                   9746:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9747:                $srchinsel.
                   9748:                &Apache::lonhtmlcommon::row_closure(1). 
                   9749:                &Apache::lonhtmlcommon::end_pick_box().
                   9750:                '<br />';
1.555     raeburn  9751:     return $output;
                   9752: }
                   9753: 
1.612     raeburn  9754: sub user_rule_check {
1.615     raeburn  9755:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  9756:     my ($response,%inst_response);
1.612     raeburn  9757:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  9758:         if (keys(%{$usershash}) > 1) {
                   9759:             my (%by_username,%by_id,%userdoms);
                   9760:             my $checkid;
1.612     raeburn  9761:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  9762:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   9763:                     $checkid = 1;
                   9764:                 }
                   9765:             }
                   9766:             foreach my $user (keys(%{$usershash})) {
                   9767:                 my ($uname,$udom) = split(/:/,$user);
                   9768:                 if ($checkid) {
                   9769:                     if (ref($usershash->{$user}) eq 'HASH') {
                   9770:                         if ($usershash->{$user}->{'id'} ne '') {
                   9771:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   9772:                             $userdoms{$udom} = 1;
                   9773:                             if (ref($inst_results) eq 'HASH') {
                   9774:                                 $inst_results->{$uname.':'.$udom} = {};
                   9775:                             }
                   9776:                         }
                   9777:                     }
                   9778:                 } else {
                   9779:                     $by_username{$udom}{$uname} = 1;
                   9780:                     $userdoms{$udom} = 1;
                   9781:                     if (ref($inst_results) eq 'HASH') {
                   9782:                         $inst_results->{$uname.':'.$udom} = {};
                   9783:                     }
                   9784:                 }
                   9785:             }
                   9786:             foreach my $udom (keys(%userdoms)) {
                   9787:                 if (!$got_rules->{$udom}) {
                   9788:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9789:                                                              ['usercreation'],$udom);
                   9790:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   9791:                         foreach my $item ('username','id') {
                   9792:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9793:                                 $$curr_rules{$udom}{$item} =
                   9794:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   9795:                             }
                   9796:                         }
                   9797:                     }
                   9798:                     $got_rules->{$udom} = 1;
                   9799:                 }
                   9800:             }
                   9801:             if ($checkid) {
                   9802:                 foreach my $udom (keys(%by_id)) {
                   9803:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   9804:                     if ($outcome eq 'ok') {
                   9805:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   9806:                             my $uname = $by_id{$udom}{$id};
                   9807:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9808:                         }
                   9809:                         if (ref($results) eq 'HASH') {
                   9810:                             foreach my $uname (keys(%{$results})) {
                   9811:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   9812:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   9813:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   9814:                                 }
                   9815:                             }
                   9816:                         }
                   9817:                     }
1.612     raeburn  9818:                 }
1.615     raeburn  9819:             } else {
1.1075.2.99  raeburn  9820:                 foreach my $udom (keys(%by_username)) {
                   9821:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   9822:                     if ($outcome eq 'ok') {
                   9823:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   9824:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9825:                         }
                   9826:                         if (ref($results) eq 'HASH') {
                   9827:                             foreach my $uname (keys(%{$results})) {
                   9828:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   9829:                             }
                   9830:                         }
                   9831:                     }
                   9832:                 }
1.612     raeburn  9833:             }
1.1075.2.99  raeburn  9834:         } elsif (keys(%{$usershash}) == 1) {
                   9835:             my $user = (keys(%{$usershash}))[0];
                   9836:             my ($uname,$udom) = split(/:/,$user);
                   9837:             if (($udom ne '') && ($uname ne '')) {
                   9838:                 if (ref($usershash->{$user}) eq 'HASH') {
                   9839:                     if (ref($checks) eq 'HASH') {
                   9840:                         if (defined($checks->{'username'})) {
                   9841:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   9842:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   9843:                         } elsif (defined($checks->{'id'})) {
                   9844:                             if ($usershash->{$user}->{'id'} ne '') {
                   9845:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   9846:                                     &Apache::lonnet::get_instuser($udom,undef,
                   9847:                                                                   $usershash->{$user}->{'id'});
                   9848:                             } else {
                   9849:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   9850:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   9851:                             }
                   9852:                         }
                   9853:                     } else {
                   9854:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   9855:                             &Apache::lonnet::get_instuser($udom,$uname);
                   9856:                        return;
                   9857:                     }
                   9858:                     if (!$got_rules->{$udom}) {
                   9859:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9860:                                                                  ['usercreation'],$udom);
                   9861:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   9862:                             foreach my $item ('username','id') {
                   9863:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9864:                                    $$curr_rules{$udom}{$item} =
                   9865:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   9866:                                 }
                   9867:                             }
1.585     raeburn  9868:                         }
1.1075.2.99  raeburn  9869:                         $got_rules->{$udom} = 1;
1.585     raeburn  9870:                     }
                   9871:                 }
1.1075.2.99  raeburn  9872:             } else {
                   9873:                 return;
                   9874:             }
                   9875:         } else {
                   9876:             return;
                   9877:         }
                   9878:         foreach my $user (keys(%{$usershash})) {
                   9879:             my ($uname,$udom) = split(/:/,$user);
                   9880:             next if (($udom eq '') || ($uname eq ''));
                   9881:             my $id;
                   9882:             if (ref($inst_results) eq 'HASH') {
                   9883:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   9884:                     $id = $inst_results->{$user}->{'id'};
                   9885:                 }
                   9886:             }
                   9887:             if ($id eq '') {
                   9888:                 if (ref($usershash->{$user})) {
                   9889:                     $id = $usershash->{$user}->{'id'};
                   9890:                 }
1.585     raeburn  9891:             }
1.612     raeburn  9892:             foreach my $item (keys(%{$checks})) {
                   9893:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   9894:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   9895:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  9896:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   9897:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  9898:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   9899:                                 if ($rule_check{$rule}) {
                   9900:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  9901:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  9902:                                         if (ref($inst_results) eq 'HASH') {
                   9903:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   9904:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   9905:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  9906:                                                 } elsif ($item eq 'id') {
                   9907:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   9908:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   9909:                                                     }
1.615     raeburn  9910:                                                 }
1.612     raeburn  9911:                                             }
                   9912:                                         }
1.615     raeburn  9913:                                     }
                   9914:                                     last;
1.585     raeburn  9915:                                 }
                   9916:                             }
                   9917:                         }
                   9918:                     }
                   9919:                 }
                   9920:             }
                   9921:         }
                   9922:     }
1.612     raeburn  9923:     return;
                   9924: }
                   9925: 
                   9926: sub user_rule_formats {
                   9927:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   9928:     my %text = ( 
                   9929:                  'username' => 'Usernames',
                   9930:                  'id'       => 'IDs',
                   9931:                );
                   9932:     my $output;
                   9933:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   9934:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   9935:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  9936:             $output = '<br />'.
                   9937:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   9938:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   9939:                       ' <ul>';
1.612     raeburn  9940:             foreach my $rule (@{$ruleorder}) {
                   9941:                 if (ref($curr_rules) eq 'ARRAY') {
                   9942:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   9943:                         if (ref($rules->{$rule}) eq 'HASH') {
                   9944:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   9945:                                         $rules->{$rule}{'desc'}.'</li>';
                   9946:                         }
                   9947:                     }
                   9948:                 }
                   9949:             }
                   9950:             $output .= '</ul>';
                   9951:         }
                   9952:     }
                   9953:     return $output;
                   9954: }
                   9955: 
                   9956: sub instrule_disallow_msg {
1.615     raeburn  9957:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  9958:     my $response;
                   9959:     my %text = (
                   9960:                   item   => 'username',
                   9961:                   items  => 'usernames',
                   9962:                   match  => 'matches',
                   9963:                   do     => 'does',
                   9964:                   action => 'a username',
                   9965:                   one    => 'one',
                   9966:                );
                   9967:     if ($count > 1) {
                   9968:         $text{'item'} = 'usernames';
                   9969:         $text{'match'} ='match';
                   9970:         $text{'do'} = 'do';
                   9971:         $text{'action'} = 'usernames',
                   9972:         $text{'one'} = 'ones';
                   9973:     }
                   9974:     if ($checkitem eq 'id') {
                   9975:         $text{'items'} = 'IDs';
                   9976:         $text{'item'} = 'ID';
                   9977:         $text{'action'} = 'an ID';
1.615     raeburn  9978:         if ($count > 1) {
                   9979:             $text{'item'} = 'IDs';
                   9980:             $text{'action'} = 'IDs';
                   9981:         }
1.612     raeburn  9982:     }
1.674     bisitz   9983:     $response = &mt("The $text{'item'} you chose $text{'match'} the format of $text{'items'} defined for [_1], but the $text{'item'} $text{'do'} not exist in the institutional directory.",'<span class="LC_cusr_emph">'.$domdesc.'</span>').'<br />';
1.615     raeburn  9984:     if ($mode eq 'upload') {
                   9985:         if ($checkitem eq 'username') {
                   9986:             $response .= &mt("You will need to modify your upload file so it will include $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   9987:         } elsif ($checkitem eq 'id') {
1.674     bisitz   9988:             $response .= &mt("Either upload a file which includes $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or when associating fields with data columns, omit an association for the Student/Employee ID field.");
1.615     raeburn  9989:         }
1.669     raeburn  9990:     } elsif ($mode eq 'selfcreate') {
                   9991:         if ($checkitem eq 'id') {
                   9992:             $response .= &mt("You must either choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or leave the ID field blank.");
                   9993:         }
1.615     raeburn  9994:     } else {
                   9995:         if ($checkitem eq 'username') {
                   9996:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   9997:         } elsif ($checkitem eq 'id') {
                   9998:             $response .= &mt("You must either choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or leave the ID field blank.");
                   9999:         }
1.612     raeburn  10000:     }
                   10001:     return $response;
1.585     raeburn  10002: }
                   10003: 
1.624     raeburn  10004: sub personal_data_fieldtitles {
                   10005:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10006:                         id => 'Student/Employee ID',
                   10007:                         permanentemail => 'E-mail address',
                   10008:                         lastname => 'Last Name',
                   10009:                         firstname => 'First Name',
                   10010:                         middlename => 'Middle Name',
                   10011:                         generation => 'Generation',
                   10012:                         gen => 'Generation',
1.765     raeburn  10013:                         inststatus => 'Affiliation',
1.624     raeburn  10014:                    );
                   10015:     return %fieldtitles;
                   10016: }
                   10017: 
1.642     raeburn  10018: sub sorted_inst_types {
                   10019:     my ($dom) = @_;
1.1075.2.70  raeburn  10020:     my ($usertypes,$order);
                   10021:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10022:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10023:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10024:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10025:     } else {
                   10026:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10027:     }
1.642     raeburn  10028:     my $othertitle = &mt('All users');
                   10029:     if ($env{'request.course.id'}) {
1.668     raeburn  10030:         $othertitle  = &mt('Any users');
1.642     raeburn  10031:     }
                   10032:     my @types;
                   10033:     if (ref($order) eq 'ARRAY') {
                   10034:         @types = @{$order};
                   10035:     }
                   10036:     if (@types == 0) {
                   10037:         if (ref($usertypes) eq 'HASH') {
                   10038:             @types = sort(keys(%{$usertypes}));
                   10039:         }
                   10040:     }
                   10041:     if (keys(%{$usertypes}) > 0) {
                   10042:         $othertitle = &mt('Other users');
                   10043:     }
                   10044:     return ($othertitle,$usertypes,\@types);
                   10045: }
                   10046: 
1.645     raeburn  10047: sub get_institutional_codes {
                   10048:     my ($settings,$allcourses,$LC_code) = @_;
                   10049: # Get complete list of course sections to update
                   10050:     my @currsections = ();
                   10051:     my @currxlists = ();
                   10052:     my $coursecode = $$settings{'internal.coursecode'};
                   10053: 
                   10054:     if ($$settings{'internal.sectionnums'} ne '') {
                   10055:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10056:     }
                   10057: 
                   10058:     if ($$settings{'internal.crosslistings'} ne '') {
                   10059:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10060:     }
                   10061: 
                   10062:     if (@currxlists > 0) {
                   10063:         foreach (@currxlists) {
                   10064:             if (m/^([^:]+):(\w*)$/) {
                   10065:                 unless (grep/^$1$/,@{$allcourses}) {
                   10066:                     push @{$allcourses},$1;
                   10067:                     $$LC_code{$1} = $2;
                   10068:                 }
                   10069:             }
                   10070:         }
                   10071:     }
                   10072:  
                   10073:     if (@currsections > 0) {
                   10074:         foreach (@currsections) {
                   10075:             if (m/^(\w+):(\w*)$/) {
                   10076:                 my $sec = $coursecode.$1;
                   10077:                 my $lc_sec = $2;
                   10078:                 unless (grep/^$sec$/,@{$allcourses}) {
                   10079:                     push @{$allcourses},$sec;
                   10080:                     $$LC_code{$sec} = $lc_sec;
                   10081:                 }
                   10082:             }
                   10083:         }
                   10084:     }
                   10085:     return;
                   10086: }
                   10087: 
1.971     raeburn  10088: sub get_standard_codeitems {
                   10089:     return ('Year','Semester','Department','Number','Section');
                   10090: }
                   10091: 
1.112     bowersj2 10092: =pod
                   10093: 
1.780     raeburn  10094: =head1 Slot Helpers
                   10095: 
                   10096: =over 4
                   10097: 
                   10098: =item * sorted_slots()
                   10099: 
1.1040    raeburn  10100: Sorts an array of slot names in order of an optional sort key,
                   10101: default sort is by slot start time (earliest first). 
1.780     raeburn  10102: 
                   10103: Inputs:
                   10104: 
                   10105: =over 4
                   10106: 
                   10107: slotsarr  - Reference to array of unsorted slot names.
                   10108: 
                   10109: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10110: 
1.1040    raeburn  10111: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10112: 
1.549     albertel 10113: =back
                   10114: 
1.780     raeburn  10115: Returns:
                   10116: 
                   10117: =over 4
                   10118: 
1.1040    raeburn  10119: sorted   - An array of slot names sorted by a specified sort key 
                   10120:            (default sort key is start time of the slot).
1.780     raeburn  10121: 
                   10122: =back
                   10123: 
                   10124: =cut
                   10125: 
                   10126: 
                   10127: sub sorted_slots {
1.1040    raeburn  10128:     my ($slotsarr,$slots,$sortkey) = @_;
                   10129:     if ($sortkey eq '') {
                   10130:         $sortkey = 'starttime';
                   10131:     }
1.780     raeburn  10132:     my @sorted;
                   10133:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10134:         @sorted =
                   10135:             sort {
                   10136:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10137:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10138:                      }
                   10139:                      if (ref($slots->{$a})) { return -1;}
                   10140:                      if (ref($slots->{$b})) { return 1;}
                   10141:                      return 0;
                   10142:                  } @{$slotsarr};
                   10143:     }
                   10144:     return @sorted;
                   10145: }
                   10146: 
1.1040    raeburn  10147: =pod
                   10148: 
                   10149: =item * get_future_slots()
                   10150: 
                   10151: Inputs:
                   10152: 
                   10153: =over 4
                   10154: 
                   10155: cnum - course number
                   10156: 
                   10157: cdom - course domain
                   10158: 
                   10159: now - current UNIX time
                   10160: 
                   10161: symb - optional symb
                   10162: 
                   10163: =back
                   10164: 
                   10165: Returns:
                   10166: 
                   10167: =over 4
                   10168: 
                   10169: sorted_reservable - ref to array of student_schedulable slots currently 
                   10170:                     reservable, ordered by end date of reservation period.
                   10171: 
                   10172: reservable_now - ref to hash of student_schedulable slots currently
                   10173:                  reservable.
                   10174: 
                   10175:     Keys in inner hash are:
                   10176:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  10177:     (b) endreserve: end date of reservation period.
                   10178:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10179:         selected.
1.1040    raeburn  10180: 
                   10181: sorted_future - ref to array of student_schedulable slots reservable in
                   10182:                 the future, ordered by start date of reservation period.
                   10183: 
                   10184: future_reservable - ref to hash of student_schedulable slots reservable
                   10185:                     in the future.
                   10186: 
                   10187:     Keys in inner hash are:
                   10188:     (a) symb: either blank or symb to which slot use is restricted.
                   10189:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  10190:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10191:         selected.
1.1040    raeburn  10192: 
                   10193: =back
                   10194: 
                   10195: =cut
                   10196: 
                   10197: sub get_future_slots {
                   10198:     my ($cnum,$cdom,$now,$symb) = @_;
                   10199:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10200:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10201:     foreach my $slot (keys(%slots)) {
                   10202:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10203:         if ($symb) {
                   10204:             next if (($slots{$slot}->{'symb'} ne '') && 
                   10205:                      ($slots{$slot}->{'symb'} ne $symb));
                   10206:         }
                   10207:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10208:             ($slots{$slot}->{'endtime'} > $now)) {
                   10209:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10210:                 my $userallowed = 0;
                   10211:                 if ($slots{$slot}->{'allowedsections'}) {
                   10212:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10213:                     if (!defined($env{'request.role.sec'})
                   10214:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10215:                         $userallowed=1;
                   10216:                     } else {
                   10217:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10218:                             $userallowed=1;
                   10219:                         }
                   10220:                     }
                   10221:                     unless ($userallowed) {
                   10222:                         if (defined($env{'request.course.groups'})) {
                   10223:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10224:                             foreach my $group (@groups) {
                   10225:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10226:                                     $userallowed=1;
                   10227:                                     last;
                   10228:                                 }
                   10229:                             }
                   10230:                         }
                   10231:                     }
                   10232:                 }
                   10233:                 if ($slots{$slot}->{'allowedusers'}) {
                   10234:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10235:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10236:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10237:                         $userallowed = 1;
                   10238:                     }
                   10239:                 }
                   10240:                 next unless($userallowed);
                   10241:             }
                   10242:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10243:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10244:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  10245:             my $uniqueperiod;
                   10246:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10247:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10248:             }
1.1040    raeburn  10249:             if (($startreserve < $now) &&
                   10250:                 (!$endreserve || $endreserve > $now)) {
                   10251:                 my $lastres = $endreserve;
                   10252:                 if (!$lastres) {
                   10253:                     $lastres = $slots{$slot}->{'starttime'};
                   10254:                 }
                   10255:                 $reservable_now{$slot} = {
                   10256:                                            symb       => $symb,
1.1075.2.104  raeburn  10257:                                            endreserve => $lastres,
                   10258:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  10259:                                          };
                   10260:             } elsif (($startreserve > $now) &&
                   10261:                      (!$endreserve || $endreserve > $startreserve)) {
                   10262:                 $future_reservable{$slot} = {
                   10263:                                               symb         => $symb,
1.1075.2.104  raeburn  10264:                                               startreserve => $startreserve,
                   10265:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10266:                                             };
                   10267:             }
                   10268:         }
                   10269:     }
                   10270:     my @unsorted_reservable = keys(%reservable_now);
                   10271:     if (@unsorted_reservable > 0) {
                   10272:         @sorted_reservable = 
                   10273:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10274:     }
                   10275:     my @unsorted_future = keys(%future_reservable);
                   10276:     if (@unsorted_future > 0) {
                   10277:         @sorted_future =
                   10278:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10279:     }
                   10280:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10281: }
1.780     raeburn  10282: 
                   10283: =pod
                   10284: 
1.1057    foxr     10285: =back
                   10286: 
1.549     albertel 10287: =head1 HTTP Helpers
                   10288: 
                   10289: =over 4
                   10290: 
1.648     raeburn  10291: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10292: 
1.258     albertel 10293: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10294: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10295: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10296: 
                   10297: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10298: $possible_names is an ref to an array of form element names.  As an example:
                   10299: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10300: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10301: 
                   10302: =cut
1.1       albertel 10303: 
1.6       albertel 10304: sub get_unprocessed_cgi {
1.25      albertel 10305:   my ($query,$possible_names)= @_;
1.26      matthew  10306:   # $Apache::lonxml::debug=1;
1.356     albertel 10307:   foreach my $pair (split(/&/,$query)) {
                   10308:     my ($name, $value) = split(/=/,$pair);
1.369     www      10309:     $name = &unescape($name);
1.25      albertel 10310:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10311:       $value =~ tr/+/ /;
                   10312:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10313:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10314:     }
1.16      harris41 10315:   }
1.6       albertel 10316: }
                   10317: 
1.112     bowersj2 10318: =pod
                   10319: 
1.648     raeburn  10320: =item * &cacheheader() 
1.112     bowersj2 10321: 
                   10322: returns cache-controlling header code
                   10323: 
                   10324: =cut
                   10325: 
1.7       albertel 10326: sub cacheheader {
1.258     albertel 10327:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10328:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10329:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10330:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10331:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10332:     return $output;
1.7       albertel 10333: }
                   10334: 
1.112     bowersj2 10335: =pod
                   10336: 
1.648     raeburn  10337: =item * &no_cache($r) 
1.112     bowersj2 10338: 
                   10339: specifies header code to not have cache
                   10340: 
                   10341: =cut
                   10342: 
1.9       albertel 10343: sub no_cache {
1.216     albertel 10344:     my ($r) = @_;
                   10345:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10346: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10347:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10348:     $r->no_cache(1);
                   10349:     $r->header_out("Expires" => $date);
                   10350:     $r->header_out("Pragma" => "no-cache");
1.123     www      10351: }
                   10352: 
                   10353: sub content_type {
1.181     albertel 10354:     my ($r,$type,$charset) = @_;
1.299     foxr     10355:     if ($r) {
                   10356: 	#  Note that printout.pl calls this with undef for $r.
                   10357: 	&no_cache($r);
                   10358:     }
1.258     albertel 10359:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10360:     unless ($charset) {
                   10361: 	$charset=&Apache::lonlocal::current_encoding;
                   10362:     }
                   10363:     if ($charset) { $type.='; charset='.$charset; }
                   10364:     if ($r) {
                   10365: 	$r->content_type($type);
                   10366:     } else {
                   10367: 	print("Content-type: $type\n\n");
                   10368:     }
1.9       albertel 10369: }
1.25      albertel 10370: 
1.112     bowersj2 10371: =pod
                   10372: 
1.648     raeburn  10373: =item * &add_to_env($name,$value) 
1.112     bowersj2 10374: 
1.258     albertel 10375: adds $name to the %env hash with value
1.112     bowersj2 10376: $value, if $name already exists, the entry is converted to an array
                   10377: reference and $value is added to the array.
                   10378: 
                   10379: =cut
                   10380: 
1.25      albertel 10381: sub add_to_env {
                   10382:   my ($name,$value)=@_;
1.258     albertel 10383:   if (defined($env{$name})) {
                   10384:     if (ref($env{$name})) {
1.25      albertel 10385:       #already have multiple values
1.258     albertel 10386:       push(@{ $env{$name} },$value);
1.25      albertel 10387:     } else {
                   10388:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10389:       my $first=$env{$name};
                   10390:       undef($env{$name});
                   10391:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10392:     }
                   10393:   } else {
1.258     albertel 10394:     $env{$name}=$value;
1.25      albertel 10395:   }
1.31      albertel 10396: }
1.149     albertel 10397: 
                   10398: =pod
                   10399: 
1.648     raeburn  10400: =item * &get_env_multiple($name) 
1.149     albertel 10401: 
1.258     albertel 10402: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10403: values may be defined and end up as an array ref.
                   10404: 
                   10405: returns an array of values
                   10406: 
                   10407: =cut
                   10408: 
                   10409: sub get_env_multiple {
                   10410:     my ($name) = @_;
                   10411:     my @values;
1.258     albertel 10412:     if (defined($env{$name})) {
1.149     albertel 10413:         # exists is it an array
1.258     albertel 10414:         if (ref($env{$name})) {
                   10415:             @values=@{ $env{$name} };
1.149     albertel 10416:         } else {
1.258     albertel 10417:             $values[0]=$env{$name};
1.149     albertel 10418:         }
                   10419:     }
                   10420:     return(@values);
                   10421: }
                   10422: 
1.660     raeburn  10423: sub ask_for_embedded_content {
                   10424:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10425:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  10426:         %currsubfile,%unused,$rem);
1.1071    raeburn  10427:     my $counter = 0;
                   10428:     my $numnew = 0;
1.987     raeburn  10429:     my $numremref = 0;
                   10430:     my $numinvalid = 0;
                   10431:     my $numpathchg = 0;
                   10432:     my $numexisting = 0;
1.1071    raeburn  10433:     my $numunused = 0;
                   10434:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  10435:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10436:     my $heading = &mt('Upload embedded files');
                   10437:     my $buttontext = &mt('Upload');
                   10438: 
1.1075.2.11  raeburn  10439:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  10440:         if ($actionurl eq '/adm/dependencies') {
                   10441:             $navmap = Apache::lonnavmaps::navmap->new();
                   10442:         }
                   10443:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10444:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  10445:     }
1.1075.2.35  raeburn  10446:     if (($actionurl eq '/adm/portfolio') ||
                   10447:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10448:         my $current_path='/';
                   10449:         if ($env{'form.currentpath'}) {
                   10450:             $current_path = $env{'form.currentpath'};
                   10451:         }
                   10452:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  10453:             $udom = $cdom;
                   10454:             $uname = $cnum;
1.984     raeburn  10455:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10456:         } else {
                   10457:             $udom = $env{'user.domain'};
                   10458:             $uname = $env{'user.name'};
                   10459:             $url = '/userfiles/portfolio';
                   10460:         }
1.987     raeburn  10461:         $toplevel = $url.'/';
1.984     raeburn  10462:         $url .= $current_path;
                   10463:         $getpropath = 1;
1.987     raeburn  10464:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10465:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10466:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10467:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10468:         $toplevel = $url;
1.984     raeburn  10469:         if ($rest ne '') {
1.987     raeburn  10470:             $url .= $rest;
                   10471:         }
                   10472:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10473:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10474:             $url = $args->{'docs_url'};
                   10475:             $toplevel = $url;
1.1075.2.11  raeburn  10476:             if ($args->{'context'} eq 'paste') {
                   10477:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10478:                 ($path) =
                   10479:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10480:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10481:                 $fileloc =~ s{^/}{};
                   10482:             }
1.1071    raeburn  10483:         }
                   10484:     } elsif ($actionurl eq '/adm/dependencies') {
                   10485:         if ($env{'request.course.id'} ne '') {
                   10486:             if (ref($args) eq 'HASH') {
                   10487:                 $url = $args->{'docs_url'};
                   10488:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  10489:                 $toplevel = $url;
                   10490:                 unless ($toplevel =~ m{^/}) {
                   10491:                     $toplevel = "/$url";
                   10492:                 }
1.1075.2.11  raeburn  10493:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  10494:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10495:                     $path = $1;
                   10496:                 } else {
                   10497:                     ($path) =
                   10498:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10499:                 }
1.1075.2.79  raeburn  10500:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10501:                     $fileloc = $toplevel;
                   10502:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10503:                     my ($udom,$uname,$fname) =
                   10504:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10505:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10506:                 } else {
                   10507:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10508:                 }
1.1071    raeburn  10509:                 $fileloc =~ s{^/}{};
                   10510:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10511:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10512:             }
1.987     raeburn  10513:         }
1.1075.2.35  raeburn  10514:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10515:         $udom = $cdom;
                   10516:         $uname = $cnum;
                   10517:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10518:         $toplevel = $url;
                   10519:         $path = $url;
                   10520:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10521:         $fileloc =~ s{^/}{};
                   10522:     }
                   10523:     foreach my $file (keys(%{$allfiles})) {
                   10524:         my $embed_file;
                   10525:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10526:             $embed_file = $1;
                   10527:         } else {
                   10528:             $embed_file = $file;
                   10529:         }
1.1075.2.55  raeburn  10530:         my ($absolutepath,$cleaned_file);
                   10531:         if ($embed_file =~ m{^\w+://}) {
                   10532:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  10533:             $newfiles{$cleaned_file} = 1;
                   10534:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10535:         } else {
1.1075.2.55  raeburn  10536:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10537:             if ($embed_file =~ m{^/}) {
                   10538:                 $absolutepath = $embed_file;
                   10539:             }
1.1075.2.47  raeburn  10540:             if ($cleaned_file =~ m{/}) {
                   10541:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10542:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10543:                 my $item = $fname;
                   10544:                 if ($path ne '') {
                   10545:                     $item = $path.'/'.$fname;
                   10546:                     $subdependencies{$path}{$fname} = 1;
                   10547:                 } else {
                   10548:                     $dependencies{$item} = 1;
                   10549:                 }
                   10550:                 if ($absolutepath) {
                   10551:                     $mapping{$item} = $absolutepath;
                   10552:                 } else {
                   10553:                     $mapping{$item} = $embed_file;
                   10554:                 }
                   10555:             } else {
                   10556:                 $dependencies{$embed_file} = 1;
                   10557:                 if ($absolutepath) {
1.1075.2.47  raeburn  10558:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10559:                 } else {
1.1075.2.47  raeburn  10560:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10561:                 }
                   10562:             }
1.984     raeburn  10563:         }
                   10564:     }
1.1071    raeburn  10565:     my $dirptr = 16384;
1.984     raeburn  10566:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10567:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  10568:         if (($actionurl eq '/adm/portfolio') ||
                   10569:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  10570:             my ($sublistref,$listerror) =
                   10571:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10572:             if (ref($sublistref) eq 'ARRAY') {
                   10573:                 foreach my $line (@{$sublistref}) {
                   10574:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10575:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10576:                 }
1.984     raeburn  10577:             }
1.987     raeburn  10578:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10579:             if (opendir(my $dir,$url.'/'.$path)) {
                   10580:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10581:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10582:             }
1.1075.2.11  raeburn  10583:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10584:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10585:                   ($args->{'context'} eq 'paste')) ||
                   10586:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10587:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  10588:                 my $dir;
                   10589:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10590:                     $dir = $fileloc;
                   10591:                 } else {
                   10592:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10593:                 }
1.1071    raeburn  10594:                 if ($dir ne '') {
                   10595:                     my ($sublistref,$listerror) =
                   10596:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10597:                     if (ref($sublistref) eq 'ARRAY') {
                   10598:                         foreach my $line (@{$sublistref}) {
                   10599:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10600:                                 undef,$mtime)=split(/\&/,$line,12);
                   10601:                             unless (($testdir&$dirptr) ||
                   10602:                                     ($file_name =~ /^\.\.?$/)) {
                   10603:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10604:                             }
                   10605:                         }
                   10606:                     }
                   10607:                 }
1.984     raeburn  10608:             }
                   10609:         }
                   10610:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10611:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10612:                 my $item = $path.'/'.$file;
                   10613:                 unless ($mapping{$item} eq $item) {
                   10614:                     $pathchanges{$item} = 1;
                   10615:                 }
                   10616:                 $existing{$item} = 1;
                   10617:                 $numexisting ++;
                   10618:             } else {
                   10619:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10620:             }
                   10621:         }
1.1071    raeburn  10622:         if ($actionurl eq '/adm/dependencies') {
                   10623:             foreach my $path (keys(%currsubfile)) {
                   10624:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10625:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10626:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  10627:                              next if (($rem ne '') &&
                   10628:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10629:                                        (ref($navmap) &&
                   10630:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10631:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10632:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10633:                              $unused{$path.'/'.$file} = 1; 
                   10634:                          }
                   10635:                     }
                   10636:                 }
                   10637:             }
                   10638:         }
1.984     raeburn  10639:     }
1.987     raeburn  10640:     my %currfile;
1.1075.2.35  raeburn  10641:     if (($actionurl eq '/adm/portfolio') ||
                   10642:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10643:         my ($dirlistref,$listerror) =
                   10644:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10645:         if (ref($dirlistref) eq 'ARRAY') {
                   10646:             foreach my $line (@{$dirlistref}) {
                   10647:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10648:                 $currfile{$file_name} = 1;
                   10649:             }
1.984     raeburn  10650:         }
1.987     raeburn  10651:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10652:         if (opendir(my $dir,$url)) {
1.987     raeburn  10653:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10654:             map {$currfile{$_} = 1;} @dir_list;
                   10655:         }
1.1075.2.11  raeburn  10656:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10657:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10658:               ($args->{'context'} eq 'paste')) ||
                   10659:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10660:         if ($env{'request.course.id'} ne '') {
                   10661:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10662:             if ($dir ne '') {
                   10663:                 my ($dirlistref,$listerror) =
                   10664:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10665:                 if (ref($dirlistref) eq 'ARRAY') {
                   10666:                     foreach my $line (@{$dirlistref}) {
                   10667:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10668:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10669:                         unless (($testdir&$dirptr) ||
                   10670:                                 ($file_name =~ /^\.\.?$/)) {
                   10671:                             $currfile{$file_name} = [$size,$mtime];
                   10672:                         }
                   10673:                     }
                   10674:                 }
                   10675:             }
                   10676:         }
1.984     raeburn  10677:     }
                   10678:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10679:         if (exists($currfile{$file})) {
1.987     raeburn  10680:             unless ($mapping{$file} eq $file) {
                   10681:                 $pathchanges{$file} = 1;
                   10682:             }
                   10683:             $existing{$file} = 1;
                   10684:             $numexisting ++;
                   10685:         } else {
1.984     raeburn  10686:             $newfiles{$file} = 1;
                   10687:         }
                   10688:     }
1.1071    raeburn  10689:     foreach my $file (keys(%currfile)) {
                   10690:         unless (($file eq $filename) ||
                   10691:                 ($file eq $filename.'.bak') ||
                   10692:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  10693:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  10694:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10695:                     next if (($rem ne '') &&
                   10696:                              (($env{"httpref.$rem".$file} ne '') ||
                   10697:                               (ref($navmap) &&
                   10698:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10699:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10700:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10701:                 }
1.1075.2.11  raeburn  10702:             }
1.1071    raeburn  10703:             $unused{$file} = 1;
                   10704:         }
                   10705:     }
1.1075.2.11  raeburn  10706:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10707:         ($args->{'context'} eq 'paste')) {
                   10708:         $counter = scalar(keys(%existing));
                   10709:         $numpathchg = scalar(keys(%pathchanges));
                   10710:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  10711:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   10712:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10713:         $counter = scalar(keys(%existing));
                   10714:         $numpathchg = scalar(keys(%pathchanges));
                   10715:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  10716:     }
1.984     raeburn  10717:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10718:         if ($actionurl eq '/adm/dependencies') {
                   10719:             next if ($embed_file =~ m{^\w+://});
                   10720:         }
1.660     raeburn  10721:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10722:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  10723:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  10724:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  10725:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   10726:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  10727:         }
1.1075.2.35  raeburn  10728:         $upload_output .= '</td>';
1.1071    raeburn  10729:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  10730:             $upload_output.='<td align="right">'.
                   10731:                             '<span class="LC_info LC_fontsize_medium">'.
                   10732:                             &mt("URL points to web address").'</span>';
1.987     raeburn  10733:             $numremref++;
1.660     raeburn  10734:         } elsif ($args->{'error_on_invalid_names'}
                   10735:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  10736:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   10737:                             &mt('Invalid characters').'</span>';
1.987     raeburn  10738:             $numinvalid++;
1.660     raeburn  10739:         } else {
1.1075.2.35  raeburn  10740:             $upload_output .= '<td>'.
                   10741:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  10742:                                                      $embed_file,\%mapping,
1.1071    raeburn  10743:                                                      $allfiles,$codebase,'upload');
                   10744:             $counter ++;
                   10745:             $numnew ++;
1.987     raeburn  10746:         }
                   10747:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   10748:     }
                   10749:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  10750:         if ($actionurl eq '/adm/dependencies') {
                   10751:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   10752:             $modify_output .= &start_data_table_row().
                   10753:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   10754:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   10755:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   10756:                               '<td>'.$size.'</td>'.
                   10757:                               '<td>'.$mtime.'</td>'.
                   10758:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   10759:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   10760:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   10761:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   10762:                               &embedded_file_element('upload_embedded',$counter,
                   10763:                                                      $embed_file,\%mapping,
                   10764:                                                      $allfiles,$codebase,'modify').
                   10765:                               '</div></td>'.
                   10766:                               &end_data_table_row()."\n";
                   10767:             $counter ++;
                   10768:         } else {
                   10769:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10770:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   10771:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   10772:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  10773:                               &Apache::loncommon::end_data_table_row()."\n";
                   10774:         }
                   10775:     }
                   10776:     my $delidx = $counter;
                   10777:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   10778:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   10779:         $delete_output .= &start_data_table_row().
                   10780:                           '<td><img src="'.&icon($oldfile).'" />'.
                   10781:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   10782:                           '<td>'.$size.'</td>'.
                   10783:                           '<td>'.$mtime.'</td>'.
                   10784:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   10785:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   10786:                           &embedded_file_element('upload_embedded',$delidx,
                   10787:                                                  $oldfile,\%mapping,$allfiles,
                   10788:                                                  $codebase,'delete').'</td>'.
                   10789:                           &end_data_table_row()."\n"; 
                   10790:         $numunused ++;
                   10791:         $delidx ++;
1.987     raeburn  10792:     }
                   10793:     if ($upload_output) {
                   10794:         $upload_output = &start_data_table().
                   10795:                          $upload_output.
                   10796:                          &end_data_table()."\n";
                   10797:     }
1.1071    raeburn  10798:     if ($modify_output) {
                   10799:         $modify_output = &start_data_table().
                   10800:                          &start_data_table_header_row().
                   10801:                          '<th>'.&mt('File').'</th>'.
                   10802:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10803:                          '<th>'.&mt('Modified').'</th>'.
                   10804:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   10805:                          &end_data_table_header_row().
                   10806:                          $modify_output.
                   10807:                          &end_data_table()."\n";
                   10808:     }
                   10809:     if ($delete_output) {
                   10810:         $delete_output = &start_data_table().
                   10811:                          &start_data_table_header_row().
                   10812:                          '<th>'.&mt('File').'</th>'.
                   10813:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10814:                          '<th>'.&mt('Modified').'</th>'.
                   10815:                          '<th>'.&mt('Delete?').'</th>'.
                   10816:                          &end_data_table_header_row().
                   10817:                          $delete_output.
                   10818:                          &end_data_table()."\n";
                   10819:     }
1.987     raeburn  10820:     my $applies = 0;
                   10821:     if ($numremref) {
                   10822:         $applies ++;
                   10823:     }
                   10824:     if ($numinvalid) {
                   10825:         $applies ++;
                   10826:     }
                   10827:     if ($numexisting) {
                   10828:         $applies ++;
                   10829:     }
1.1071    raeburn  10830:     if ($counter || $numunused) {
1.987     raeburn  10831:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   10832:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  10833:                   $state.'<h3>'.$heading.'</h3>'; 
                   10834:         if ($actionurl eq '/adm/dependencies') {
                   10835:             if ($numnew) {
                   10836:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   10837:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   10838:                            $upload_output.'<br />'."\n";
                   10839:             }
                   10840:             if ($numexisting) {
                   10841:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   10842:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   10843:                            $modify_output.'<br />'."\n";
                   10844:                            $buttontext = &mt('Save changes');
                   10845:             }
                   10846:             if ($numunused) {
                   10847:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   10848:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   10849:                            $delete_output.'<br />'."\n";
                   10850:                            $buttontext = &mt('Save changes');
                   10851:             }
                   10852:         } else {
                   10853:             $output .= $upload_output.'<br />'."\n";
                   10854:         }
                   10855:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   10856:                    $counter.'" />'."\n";
                   10857:         if ($actionurl eq '/adm/dependencies') { 
                   10858:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   10859:                        $numnew.'" />'."\n";
                   10860:         } elsif ($actionurl eq '') {
1.987     raeburn  10861:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   10862:         }
                   10863:     } elsif ($applies) {
                   10864:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   10865:         if ($applies > 1) {
                   10866:             $output .=  
1.1075.2.35  raeburn  10867:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  10868:             if ($numremref) {
                   10869:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   10870:             }
                   10871:             if ($numinvalid) {
                   10872:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   10873:             }
                   10874:             if ($numexisting) {
                   10875:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   10876:             }
                   10877:             $output .= '</ul><br />';
                   10878:         } elsif ($numremref) {
                   10879:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   10880:         } elsif ($numinvalid) {
                   10881:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   10882:         } elsif ($numexisting) {
                   10883:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   10884:         }
                   10885:         $output .= $upload_output.'<br />';
                   10886:     }
                   10887:     my ($pathchange_output,$chgcount);
1.1071    raeburn  10888:     $chgcount = $counter;
1.987     raeburn  10889:     if (keys(%pathchanges) > 0) {
                   10890:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  10891:             if ($counter) {
1.987     raeburn  10892:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   10893:                                                   $embed_file,\%mapping,
1.1071    raeburn  10894:                                                   $allfiles,$codebase,'change');
1.987     raeburn  10895:             } else {
                   10896:                 $pathchange_output .= 
                   10897:                     &start_data_table_row().
                   10898:                     '<td><input type ="checkbox" name="namechange" value="'.
                   10899:                     $chgcount.'" checked="checked" /></td>'.
                   10900:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   10901:                     '<td>'.$embed_file.
                   10902:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  10903:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  10904:                     '</td>'.&end_data_table_row();
1.660     raeburn  10905:             }
1.987     raeburn  10906:             $numpathchg ++;
                   10907:             $chgcount ++;
1.660     raeburn  10908:         }
                   10909:     }
1.1075.2.35  raeburn  10910:     if (($counter) || ($numunused)) {
1.987     raeburn  10911:         if ($numpathchg) {
                   10912:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   10913:                        $numpathchg.'" />'."\n";
                   10914:         }
                   10915:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   10916:             ($actionurl eq '/adm/imsimport')) {
                   10917:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   10918:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   10919:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  10920:         } elsif ($actionurl eq '/adm/dependencies') {
                   10921:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  10922:         }
1.1075.2.35  raeburn  10923:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  10924:     } elsif ($numpathchg) {
                   10925:         my %pathchange = ();
                   10926:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   10927:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10928:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  10929:         }
1.987     raeburn  10930:     }
1.1071    raeburn  10931:     return ($output,$counter,$numpathchg);
1.987     raeburn  10932: }
                   10933: 
1.1075.2.47  raeburn  10934: =pod
                   10935: 
                   10936: =item * clean_path($name)
                   10937: 
                   10938: Performs clean-up of directories, subdirectories and filename in an
                   10939: embedded object, referenced in an HTML file which is being uploaded
                   10940: to a course or portfolio, where
                   10941: "Upload embedded images/multimedia files if HTML file" checkbox was
                   10942: checked.
                   10943: 
                   10944: Clean-up is similar to replacements in lonnet::clean_filename()
                   10945: except each / between sub-directory and next level is preserved.
                   10946: 
                   10947: =cut
                   10948: 
                   10949: sub clean_path {
                   10950:     my ($embed_file) = @_;
                   10951:     $embed_file =~s{^/+}{};
                   10952:     my @contents;
                   10953:     if ($embed_file =~ m{/}) {
                   10954:         @contents = split(/\//,$embed_file);
                   10955:     } else {
                   10956:         @contents = ($embed_file);
                   10957:     }
                   10958:     my $lastidx = scalar(@contents)-1;
                   10959:     for (my $i=0; $i<=$lastidx; $i++) {
                   10960:         $contents[$i]=~s{\\}{/}g;
                   10961:         $contents[$i]=~s/\s+/\_/g;
                   10962:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   10963:         if ($i == $lastidx) {
                   10964:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   10965:         }
                   10966:     }
                   10967:     if ($lastidx > 0) {
                   10968:         return join('/',@contents);
                   10969:     } else {
                   10970:         return $contents[0];
                   10971:     }
                   10972: }
                   10973: 
1.987     raeburn  10974: sub embedded_file_element {
1.1071    raeburn  10975:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  10976:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   10977:                    (ref($codebase) eq 'HASH'));
                   10978:     my $output;
1.1071    raeburn  10979:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  10980:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   10981:     }
                   10982:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   10983:                &escape($embed_file).'" />';
                   10984:     unless (($context eq 'upload_embedded') && 
                   10985:             ($mapping->{$embed_file} eq $embed_file)) {
                   10986:         $output .='
                   10987:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   10988:     }
                   10989:     my $attrib;
                   10990:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   10991:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   10992:     }
                   10993:     $output .=
                   10994:         "\n\t\t".
                   10995:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   10996:         $attrib.'" />';
                   10997:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   10998:         $output .=
                   10999:             "\n\t\t".
                   11000:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11001:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11002:     }
1.987     raeburn  11003:     return $output;
1.660     raeburn  11004: }
                   11005: 
1.1071    raeburn  11006: sub get_dependency_details {
                   11007:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11008:     my ($size,$mtime,$showsize,$showmtime);
                   11009:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11010:         if ($embed_file =~ m{/}) {
                   11011:             my ($path,$fname) = split(/\//,$embed_file);
                   11012:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11013:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11014:             }
                   11015:         } else {
                   11016:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11017:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11018:             }
                   11019:         }
                   11020:         $showsize = $size/1024.0;
                   11021:         $showsize = sprintf("%.1f",$showsize);
                   11022:         if ($mtime > 0) {
                   11023:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11024:         }
                   11025:     }
                   11026:     return ($showsize,$showmtime);
                   11027: }
                   11028: 
                   11029: sub ask_embedded_js {
                   11030:     return <<"END";
                   11031: <script type="text/javascript"">
                   11032: // <![CDATA[
                   11033: function toggleBrowse(counter) {
                   11034:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11035:     var fileid = document.getElementById('embedded_item_'+counter);
                   11036:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11037:     if (chkboxid.checked == true) {
                   11038:         uploaddivid.style.display='block';
                   11039:     } else {
                   11040:         uploaddivid.style.display='none';
                   11041:         fileid.value = '';
                   11042:     }
                   11043: }
                   11044: // ]]>
                   11045: </script>
                   11046: 
                   11047: END
                   11048: }
                   11049: 
1.661     raeburn  11050: sub upload_embedded {
                   11051:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11052:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11053:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11054:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11055:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11056:         my $orig_uploaded_filename =
                   11057:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11058:         foreach my $type ('orig','ref','attrib','codebase') {
                   11059:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11060:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11061:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11062:             }
                   11063:         }
1.661     raeburn  11064:         my ($path,$fname) =
                   11065:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11066:         # no path, whole string is fname
                   11067:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11068:         $fname = &Apache::lonnet::clean_filename($fname);
                   11069:         # See if there is anything left
                   11070:         next if ($fname eq '');
                   11071: 
                   11072:         # Check if file already exists as a file or directory.
                   11073:         my ($state,$msg);
                   11074:         if ($context eq 'portfolio') {
                   11075:             my $port_path = $dirpath;
                   11076:             if ($group ne '') {
                   11077:                 $port_path = "groups/$group/$port_path";
                   11078:             }
1.987     raeburn  11079:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11080:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11081:                                               $dir_root,$port_path,$disk_quota,
                   11082:                                               $current_disk_usage,$uname,$udom);
                   11083:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11084:                 || $state eq 'file_locked') {
1.661     raeburn  11085:                 $output .= $msg;
                   11086:                 next;
                   11087:             }
                   11088:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11089:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11090:             if ($state eq 'exists') {
                   11091:                 $output .= $msg;
                   11092:                 next;
                   11093:             }
                   11094:         }
                   11095:         # Check if extension is valid
                   11096:         if (($fname =~ /\.(\w+)$/) &&
                   11097:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  11098:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11099:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11100:             next;
                   11101:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11102:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11103:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11104:             next;
                   11105:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  11106:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
1.661     raeburn  11107:             next;
                   11108:         }
                   11109:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  11110:         my $subdir = $path;
                   11111:         $subdir =~ s{/+$}{};
1.661     raeburn  11112:         if ($context eq 'portfolio') {
1.984     raeburn  11113:             my $result;
                   11114:             if ($state eq 'existingfile') {
                   11115:                 $result=
                   11116:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  11117:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11118:             } else {
1.984     raeburn  11119:                 $result=
                   11120:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11121:                                                     $dirpath.
1.1075.2.35  raeburn  11122:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11123:                 if ($result !~ m|^/uploaded/|) {
                   11124:                     $output .= '<span class="LC_error">'
                   11125:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11126:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11127:                                .'</span><br />';
                   11128:                     next;
                   11129:                 } else {
1.987     raeburn  11130:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11131:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11132:                 }
1.661     raeburn  11133:             }
1.1075.2.35  raeburn  11134:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   11135:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11136:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11137:             my $result =
1.1075.2.35  raeburn  11138:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11139:             if ($result !~ m|^/uploaded/|) {
                   11140:                 $output .= '<span class="LC_error">'
                   11141:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11142:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11143:                            .'</span><br />';
                   11144:                     next;
                   11145:             } else {
                   11146:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11147:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  11148:                 if ($context eq 'syllabus') {
                   11149:                     &Apache::lonnet::make_public_indefinitely($result);
                   11150:                 }
1.987     raeburn  11151:             }
1.661     raeburn  11152:         } else {
                   11153: # Save the file
                   11154:             my $target = $env{'form.embedded_item_'.$i};
                   11155:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11156:             my $dest = $fullpath.$fname;
                   11157:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11158:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11159:             my $count;
                   11160:             my $filepath = $dir_root;
1.1027    raeburn  11161:             foreach my $subdir (@parts) {
                   11162:                 $filepath .= "/$subdir";
                   11163:                 if (!-e $filepath) {
1.661     raeburn  11164:                     mkdir($filepath,0770);
                   11165:                 }
                   11166:             }
                   11167:             my $fh;
                   11168:             if (!open($fh,'>'.$dest)) {
                   11169:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11170:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11171:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11172:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11173:                            '</span><br />';
                   11174:             } else {
                   11175:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11176:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11177:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11178:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11179:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11180:                               '</span><br />';
                   11181:                 } else {
1.987     raeburn  11182:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11183:                                $url.'</span>').'<br />';
                   11184:                     unless ($context eq 'testbank') {
                   11185:                         $footer .= &mt('View embedded file: [_1]',
                   11186:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11187:                     }
                   11188:                 }
                   11189:                 close($fh);
                   11190:             }
                   11191:         }
                   11192:         if ($env{'form.embedded_ref_'.$i}) {
                   11193:             $pathchange{$i} = 1;
                   11194:         }
                   11195:     }
                   11196:     if ($output) {
                   11197:         $output = '<p>'.$output.'</p>';
                   11198:     }
                   11199:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11200:     $returnflag = 'ok';
1.1071    raeburn  11201:     my $numpathchgs = scalar(keys(%pathchange));
                   11202:     if ($numpathchgs > 0) {
1.987     raeburn  11203:         if ($context eq 'portfolio') {
                   11204:             $output .= '<p>'.&mt('or').'</p>';
                   11205:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11206:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11207:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11208:             $returnflag = 'modify_orightml';
                   11209:         }
                   11210:     }
1.1071    raeburn  11211:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11212: }
                   11213: 
                   11214: sub modify_html_form {
                   11215:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11216:     my $end = 0;
                   11217:     my $modifyform;
                   11218:     if ($context eq 'upload_embedded') {
                   11219:         return unless (ref($pathchange) eq 'HASH');
                   11220:         if ($env{'form.number_embedded_items'}) {
                   11221:             $end += $env{'form.number_embedded_items'};
                   11222:         }
                   11223:         if ($env{'form.number_pathchange_items'}) {
                   11224:             $end += $env{'form.number_pathchange_items'};
                   11225:         }
                   11226:         if ($end) {
                   11227:             for (my $i=0; $i<$end; $i++) {
                   11228:                 if ($i < $env{'form.number_embedded_items'}) {
                   11229:                     next unless($pathchange->{$i});
                   11230:                 }
                   11231:                 $modifyform .=
                   11232:                     &start_data_table_row().
                   11233:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11234:                     'checked="checked" /></td>'.
                   11235:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11236:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11237:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11238:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11239:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11240:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11241:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11242:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11243:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11244:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11245:                     &end_data_table_row();
1.1071    raeburn  11246:             }
1.987     raeburn  11247:         }
                   11248:     } else {
                   11249:         $modifyform = $pathchgtable;
                   11250:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11251:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11252:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11253:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11254:         }
                   11255:     }
                   11256:     if ($modifyform) {
1.1071    raeburn  11257:         if ($actionurl eq '/adm/dependencies') {
                   11258:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11259:         }
1.987     raeburn  11260:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11261:                '<p>'.&mt('Changes need to be made to the reference(s) used for one or more of the dependencies, if your HTML file is to work correctly:').'<ol>'."\n".
                   11262:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11263:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11264:                '</ol></p>'."\n".'<p>'.
                   11265:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11266:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11267:                &start_data_table()."\n".
                   11268:                &start_data_table_header_row().
                   11269:                '<th>'.&mt('Change?').'</th>'.
                   11270:                '<th>'.&mt('Current reference').'</th>'.
                   11271:                '<th>'.&mt('Required reference').'</th>'.
                   11272:                &end_data_table_header_row()."\n".
                   11273:                $modifyform.
                   11274:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11275:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11276:                '</form>'."\n";
                   11277:     }
                   11278:     return;
                   11279: }
                   11280: 
                   11281: sub modify_html_refs {
1.1075.2.35  raeburn  11282:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11283:     my $container;
                   11284:     if ($context eq 'portfolio') {
                   11285:         $container = $env{'form.container'};
                   11286:     } elsif ($context eq 'coursedoc') {
                   11287:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11288:     } elsif ($context eq 'manage_dependencies') {
                   11289:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11290:         $container = "/$container";
1.1075.2.35  raeburn  11291:     } elsif ($context eq 'syllabus') {
                   11292:         $container = $url;
1.987     raeburn  11293:     } else {
1.1027    raeburn  11294:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11295:     }
                   11296:     my (%allfiles,%codebase,$output,$content);
                   11297:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  11298:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  11299:         if (wantarray) {
                   11300:             return ('',0,0); 
                   11301:         } else {
                   11302:             return;
                   11303:         }
                   11304:     }
                   11305:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11306:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11307:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11308:             if (wantarray) {
                   11309:                 return ('',0,0);
                   11310:             } else {
                   11311:                 return;
                   11312:             }
                   11313:         } 
1.987     raeburn  11314:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11315:         if ($content eq '-1') {
                   11316:             if (wantarray) {
                   11317:                 return ('',0,0);
                   11318:             } else {
                   11319:                 return;
                   11320:             }
                   11321:         }
1.987     raeburn  11322:     } else {
1.1071    raeburn  11323:         unless ($container =~ /^\Q$dir_root\E/) {
                   11324:             if (wantarray) {
                   11325:                 return ('',0,0);
                   11326:             } else {
                   11327:                 return;
                   11328:             }
                   11329:         } 
1.987     raeburn  11330:         if (open(my $fh,"<$container")) {
                   11331:             $content = join('', <$fh>);
                   11332:             close($fh);
                   11333:         } else {
1.1071    raeburn  11334:             if (wantarray) {
                   11335:                 return ('',0,0);
                   11336:             } else {
                   11337:                 return;
                   11338:             }
1.987     raeburn  11339:         }
                   11340:     }
                   11341:     my ($count,$codebasecount) = (0,0);
                   11342:     my $mm = new File::MMagic;
                   11343:     my $mime_type = $mm->checktype_contents($content);
                   11344:     if ($mime_type eq 'text/html') {
                   11345:         my $parse_result = 
                   11346:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11347:                                                     \%codebase,\$content);
                   11348:         if ($parse_result eq 'ok') {
                   11349:             foreach my $i (@changes) {
                   11350:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11351:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11352:                 if ($allfiles{$ref}) {
                   11353:                     my $newname =  $orig;
                   11354:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11355:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11356:                     if ($attrib_regexp =~ /:/) {
                   11357:                         $attrib_regexp =~ s/\:/|/g;
                   11358:                     }
                   11359:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11360:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11361:                         $count += $numchg;
1.1075.2.35  raeburn  11362:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  11363:                         delete($allfiles{$ref});
1.987     raeburn  11364:                     }
                   11365:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11366:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11367:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11368:                         $codebasecount ++;
                   11369:                     }
                   11370:                 }
                   11371:             }
1.1075.2.35  raeburn  11372:             my $skiprewrites;
1.987     raeburn  11373:             if ($count || $codebasecount) {
                   11374:                 my $saveresult;
1.1071    raeburn  11375:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11376:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11377:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11378:                     if ($url eq $container) {
                   11379:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11380:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11381:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11382:                                             $fname.'</span>').'</p>';
1.987     raeburn  11383:                     } else {
                   11384:                          $output = '<p class="LC_error">'.
                   11385:                                    &mt('Error: update failed for: [_1].',
                   11386:                                    '<span class="LC_filename">'.
                   11387:                                    $container.'</span>').'</p>';
                   11388:                     }
1.1075.2.35  raeburn  11389:                     if ($context eq 'syllabus') {
                   11390:                         unless ($saveresult eq 'ok') {
                   11391:                             $skiprewrites = 1;
                   11392:                         }
                   11393:                     }
1.987     raeburn  11394:                 } else {
                   11395:                     if (open(my $fh,">$container")) {
                   11396:                         print $fh $content;
                   11397:                         close($fh);
                   11398:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11399:                                   $count,'<span class="LC_filename">'.
                   11400:                                   $container.'</span>').'</p>';
1.661     raeburn  11401:                     } else {
1.987     raeburn  11402:                          $output = '<p class="LC_error">'.
                   11403:                                    &mt('Error: could not update [_1].',
                   11404:                                    '<span class="LC_filename">'.
                   11405:                                    $container.'</span>').'</p>';
1.661     raeburn  11406:                     }
                   11407:                 }
                   11408:             }
1.1075.2.35  raeburn  11409:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11410:                 my ($actionurl,$state);
                   11411:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11412:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11413:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11414:                                               \%codebase,
                   11415:                                               {'context' => 'rewrites',
                   11416:                                                'ignore_remote_references' => 1,});
                   11417:                 if (ref($mapping) eq 'HASH') {
                   11418:                     my $rewrites = 0;
                   11419:                     foreach my $key (keys(%{$mapping})) {
                   11420:                         next if ($key =~ m{^https?://});
                   11421:                         my $ref = $mapping->{$key};
                   11422:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11423:                         my $attrib;
                   11424:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11425:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11426:                         }
                   11427:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11428:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11429:                             $rewrites += $numchg;
                   11430:                         }
                   11431:                     }
                   11432:                     if ($rewrites) {
                   11433:                         my $saveresult;
                   11434:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11435:                         if ($url eq $container) {
                   11436:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11437:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11438:                                             $count,'<span class="LC_filename">'.
                   11439:                                             $fname.'</span>').'</p>';
                   11440:                         } else {
                   11441:                             $output .= '<p class="LC_error">'.
                   11442:                                        &mt('Error: could not update links in [_1].',
                   11443:                                        '<span class="LC_filename">'.
                   11444:                                        $container.'</span>').'</p>';
                   11445: 
                   11446:                         }
                   11447:                     }
                   11448:                 }
                   11449:             }
1.987     raeburn  11450:         } else {
                   11451:             &logthis('Failed to parse '.$container.
                   11452:                      ' to modify references: '.$parse_result);
1.661     raeburn  11453:         }
                   11454:     }
1.1071    raeburn  11455:     if (wantarray) {
                   11456:         return ($output,$count,$codebasecount);
                   11457:     } else {
                   11458:         return $output;
                   11459:     }
1.661     raeburn  11460: }
                   11461: 
                   11462: sub check_for_existing {
                   11463:     my ($path,$fname,$element) = @_;
                   11464:     my ($state,$msg);
                   11465:     if (-d $path.'/'.$fname) {
                   11466:         $state = 'exists';
                   11467:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11468:     } elsif (-e $path.'/'.$fname) {
                   11469:         $state = 'exists';
                   11470:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11471:     }
                   11472:     if ($state eq 'exists') {
                   11473:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11474:     }
                   11475:     return ($state,$msg);
                   11476: }
                   11477: 
                   11478: sub check_for_upload {
                   11479:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11480:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11481:     my $filesize = length($env{'form.'.$element});
                   11482:     if (!$filesize) {
                   11483:         my $msg = '<span class="LC_error">'.
                   11484:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11485:                       '<span class="LC_filename">'.$fname.'</span>',
                   11486:                       $filesize).'<br />'.
1.1007    raeburn  11487:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11488:                   '</span>';
                   11489:         return ('zero_bytes',$msg);
                   11490:     }
                   11491:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11492:     my $getpropath = 1;
1.1021    raeburn  11493:     my ($dirlistref,$listerror) =
                   11494:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11495:     my $found_file = 0;
                   11496:     my $locked_file = 0;
1.991     raeburn  11497:     my @lockers;
                   11498:     my $navmap;
                   11499:     if ($env{'request.course.id'}) {
                   11500:         $navmap = Apache::lonnavmaps::navmap->new();
                   11501:     }
1.1021    raeburn  11502:     if (ref($dirlistref) eq 'ARRAY') {
                   11503:         foreach my $line (@{$dirlistref}) {
                   11504:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11505:             if ($file_name eq $fname){
                   11506:                 $file_name = $path.$file_name;
                   11507:                 if ($group ne '') {
                   11508:                     $file_name = $group.$file_name;
                   11509:                 }
                   11510:                 $found_file = 1;
                   11511:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11512:                     foreach my $lock (@lockers) {
                   11513:                         if (ref($lock) eq 'ARRAY') {
                   11514:                             my ($symb,$crsid) = @{$lock};
                   11515:                             if ($crsid eq $env{'request.course.id'}) {
                   11516:                                 if (ref($navmap)) {
                   11517:                                     my $res = $navmap->getBySymb($symb);
                   11518:                                     foreach my $part (@{$res->parts()}) { 
                   11519:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11520:                                         unless (($slot_status == $res->RESERVED) ||
                   11521:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11522:                                             $locked_file = 1;
                   11523:                                         }
1.991     raeburn  11524:                                     }
1.1021    raeburn  11525:                                 } else {
                   11526:                                     $locked_file = 1;
1.991     raeburn  11527:                                 }
                   11528:                             } else {
                   11529:                                 $locked_file = 1;
                   11530:                             }
                   11531:                         }
1.1021    raeburn  11532:                    }
                   11533:                 } else {
                   11534:                     my @info = split(/\&/,$rest);
                   11535:                     my $currsize = $info[6]/1000;
                   11536:                     if ($currsize < $filesize) {
                   11537:                         my $extra = $filesize - $currsize;
                   11538:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  11539:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11540:                                       &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded if existing (smaller) file with same name (size = [_3] kilobytes) is replaced.',
1.1075.2.69  raeburn  11541:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11542:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11543:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11544:                             return ('will_exceed_quota',$msg);
                   11545:                         }
1.984     raeburn  11546:                     }
                   11547:                 }
1.661     raeburn  11548:             }
                   11549:         }
                   11550:     }
                   11551:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  11552:         my $msg = '<p class="LC_warning">'.
                   11553:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   11554:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11555:         return ('will_exceed_quota',$msg);
                   11556:     } elsif ($found_file) {
                   11557:         if ($locked_file) {
1.1075.2.69  raeburn  11558:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11559:             $msg .= &mt('Unable to upload [_1]. A locked file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>','<span class="LC_filename">'.$port_path.$env{'form.currentpath'}.'</span>');
1.1075.2.69  raeburn  11560:             $msg .= '</p>';
1.661     raeburn  11561:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11562:             return ('file_locked',$msg);
                   11563:         } else {
1.1075.2.69  raeburn  11564:             my $msg = '<p class="LC_error">';
1.984     raeburn  11565:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.1075.2.69  raeburn  11566:             $msg .= '</p>';
1.984     raeburn  11567:             return ('existingfile',$msg);
1.661     raeburn  11568:         }
                   11569:     }
                   11570: }
                   11571: 
1.987     raeburn  11572: sub check_for_traversal {
                   11573:     my ($path,$url,$toplevel) = @_;
                   11574:     my @parts=split(/\//,$path);
                   11575:     my $cleanpath;
                   11576:     my $fullpath = $url;
                   11577:     for (my $i=0;$i<@parts;$i++) {
                   11578:         next if ($parts[$i] eq '.');
                   11579:         if ($parts[$i] eq '..') {
                   11580:             $fullpath =~ s{([^/]+/)$}{};
                   11581:         } else {
                   11582:             $fullpath .= $parts[$i].'/';
                   11583:         }
                   11584:     }
                   11585:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11586:         $cleanpath = $1;
                   11587:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11588:         my $curr_toprel = $1;
                   11589:         my @parts = split(/\//,$curr_toprel);
                   11590:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11591:         my @urlparts = split(/\//,$url_toprel);
                   11592:         my $doubledots;
                   11593:         my $startdiff = -1;
                   11594:         for (my $i=0; $i<@urlparts; $i++) {
                   11595:             if ($startdiff == -1) {
                   11596:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11597:                     $startdiff = $i;
                   11598:                     $doubledots .= '../';
                   11599:                 }
                   11600:             } else {
                   11601:                 $doubledots .= '../';
                   11602:             }
                   11603:         }
                   11604:         if ($startdiff > -1) {
                   11605:             $cleanpath = $doubledots;
                   11606:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11607:                 $cleanpath .= $parts[$i].'/';
                   11608:             }
                   11609:         }
                   11610:     }
                   11611:     $cleanpath =~ s{(/)$}{};
                   11612:     return $cleanpath;
                   11613: }
1.31      albertel 11614: 
1.1053    raeburn  11615: sub is_archive_file {
                   11616:     my ($mimetype) = @_;
                   11617:     if (($mimetype eq 'application/octet-stream') ||
                   11618:         ($mimetype eq 'application/x-stuffit') ||
                   11619:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11620:         return 1;
                   11621:     }
                   11622:     return;
                   11623: }
                   11624: 
                   11625: sub decompress_form {
1.1065    raeburn  11626:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11627:     my %lt = &Apache::lonlocal::texthash (
                   11628:         this => 'This file is an archive file.',
1.1067    raeburn  11629:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11630:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11631:         youm => 'You may wish to extract its contents.',
                   11632:         extr => 'Extract contents',
1.1067    raeburn  11633:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11634:         proa => 'Process automatically?',
1.1053    raeburn  11635:         yes  => 'Yes',
                   11636:         no   => 'No',
1.1067    raeburn  11637:         fold => 'Title for folder containing movie',
                   11638:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11639:     );
1.1065    raeburn  11640:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11641:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11642:     my $info = &list_archive_contents($fileloc,\@paths);
                   11643:     if (@paths) {
                   11644:         foreach my $path (@paths) {
                   11645:             $path =~ s{^/}{};
1.1067    raeburn  11646:             if ($path =~ m{^([^/]+)/$}) {
                   11647:                 $topdir = $1;
                   11648:             }
1.1065    raeburn  11649:             if ($path =~ m{^([^/]+)/}) {
                   11650:                 $toplevel{$1} = $path;
                   11651:             } else {
                   11652:                 $toplevel{$path} = $path;
                   11653:             }
                   11654:         }
                   11655:     }
1.1067    raeburn  11656:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  11657:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11658:                         "$topdir/media/",
                   11659:                         "$topdir/media/$topdir.mp4",
                   11660:                         "$topdir/media/FirstFrame.png",
                   11661:                         "$topdir/media/player.swf",
                   11662:                         "$topdir/media/swfobject.js",
                   11663:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  11664:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  11665:                          "$topdir/$topdir.mp4",
                   11666:                          "$topdir/$topdir\_config.xml",
                   11667:                          "$topdir/$topdir\_controller.swf",
                   11668:                          "$topdir/$topdir\_embed.css",
                   11669:                          "$topdir/$topdir\_First_Frame.png",
                   11670:                          "$topdir/$topdir\_player.html",
                   11671:                          "$topdir/$topdir\_Thumbnails.png",
                   11672:                          "$topdir/playerProductInstall.swf",
                   11673:                          "$topdir/scripts/",
                   11674:                          "$topdir/scripts/config_xml.js",
                   11675:                          "$topdir/scripts/handlebars.js",
                   11676:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11677:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11678:                          "$topdir/scripts/modernizr.js",
                   11679:                          "$topdir/scripts/player-min.js",
                   11680:                          "$topdir/scripts/swfobject.js",
                   11681:                          "$topdir/skins/",
                   11682:                          "$topdir/skins/configuration_express.xml",
                   11683:                          "$topdir/skins/express_show/",
                   11684:                          "$topdir/skins/express_show/player-min.css",
                   11685:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  11686:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   11687:                          "$topdir/$topdir.mp4",
                   11688:                          "$topdir/$topdir\_config.xml",
                   11689:                          "$topdir/$topdir\_controller.swf",
                   11690:                          "$topdir/$topdir\_embed.css",
                   11691:                          "$topdir/$topdir\_First_Frame.png",
                   11692:                          "$topdir/$topdir\_player.html",
                   11693:                          "$topdir/$topdir\_Thumbnails.png",
                   11694:                          "$topdir/playerProductInstall.swf",
                   11695:                          "$topdir/scripts/",
                   11696:                          "$topdir/scripts/config_xml.js",
                   11697:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   11698:                          "$topdir/skins/",
                   11699:                          "$topdir/skins/configuration_express.xml",
                   11700:                          "$topdir/skins/express_show/",
                   11701:                          "$topdir/skins/express_show/spritesheet.min.css",
                   11702:                          "$topdir/skins/express_show/spritesheet.png",
                   11703:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  11704:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11705:         if (@diffs == 0) {
1.1075.2.59  raeburn  11706:             $is_camtasia = 6;
                   11707:         } else {
1.1075.2.81  raeburn  11708:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  11709:             if (@diffs == 0) {
                   11710:                 $is_camtasia = 8;
1.1075.2.81  raeburn  11711:             } else {
                   11712:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   11713:                 if (@diffs == 0) {
                   11714:                     $is_camtasia = 8;
                   11715:                 }
1.1075.2.59  raeburn  11716:             }
1.1067    raeburn  11717:         }
                   11718:     }
                   11719:     my $output;
                   11720:     if ($is_camtasia) {
                   11721:         $output = <<"ENDCAM";
                   11722: <script type="text/javascript" language="Javascript">
                   11723: // <![CDATA[
                   11724: 
                   11725: function camtasiaToggle() {
                   11726:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   11727:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  11728:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  11729:                 document.getElementById('camtasia_titles').style.display='block';
                   11730:             } else {
                   11731:                 document.getElementById('camtasia_titles').style.display='none';
                   11732:             }
                   11733:         }
                   11734:     }
                   11735:     return;
                   11736: }
                   11737: 
                   11738: // ]]>
                   11739: </script>
                   11740: <p>$lt{'camt'}</p>
                   11741: ENDCAM
1.1065    raeburn  11742:     } else {
1.1067    raeburn  11743:         $output = '<p>'.$lt{'this'};
                   11744:         if ($info eq '') {
                   11745:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   11746:         } else {
                   11747:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   11748:                        '<div><pre>'.$info.'</pre></div>';
                   11749:         }
1.1065    raeburn  11750:     }
1.1067    raeburn  11751:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  11752:     my $duplicates;
                   11753:     my $num = 0;
                   11754:     if (ref($dirlist) eq 'ARRAY') {
                   11755:         foreach my $item (@{$dirlist}) {
                   11756:             if (ref($item) eq 'ARRAY') {
                   11757:                 if (exists($toplevel{$item->[0]})) {
                   11758:                     $duplicates .= 
                   11759:                         &start_data_table_row().
                   11760:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11761:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   11762:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11763:                         'value="1" />'.&mt('Yes').'</label>'.
                   11764:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   11765:                         '<td>'.$item->[0].'</td>';
                   11766:                     if ($item->[2]) {
                   11767:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   11768:                     } else {
                   11769:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   11770:                     }
                   11771:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   11772:                                    '<td>'.
                   11773:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   11774:                                    '</td>'.
                   11775:                                    &end_data_table_row();
                   11776:                     $num ++;
                   11777:                 }
                   11778:             }
                   11779:         }
                   11780:     }
                   11781:     my $itemcount;
                   11782:     if (@paths > 0) {
                   11783:         $itemcount = scalar(@paths);
                   11784:     } else {
                   11785:         $itemcount = 1;
                   11786:     }
1.1067    raeburn  11787:     if ($is_camtasia) {
                   11788:         $output .= $lt{'auto'}.'<br />'.
                   11789:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  11790:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  11791:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   11792:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   11793:                    $lt{'no'}.'</label></span><br />'.
                   11794:                    '<div id="camtasia_titles" style="display:block">'.
                   11795:                    &Apache::lonhtmlcommon::start_pick_box().
                   11796:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   11797:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   11798:                    &Apache::lonhtmlcommon::row_closure().
                   11799:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   11800:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   11801:                    &Apache::lonhtmlcommon::row_closure(1).
                   11802:                    &Apache::lonhtmlcommon::end_pick_box().
                   11803:                    '</div>';
                   11804:     }
1.1065    raeburn  11805:     $output .= 
                   11806:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  11807:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   11808:         "\n";
1.1065    raeburn  11809:     if ($duplicates ne '') {
                   11810:         $output .= '<p><span class="LC_warning">'.
                   11811:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   11812:                    &start_data_table().
                   11813:                    &start_data_table_header_row().
                   11814:                    '<th>'.&mt('Overwrite?').'</th>'.
                   11815:                    '<th>'.&mt('Name').'</th>'.
                   11816:                    '<th>'.&mt('Type').'</th>'.
                   11817:                    '<th>'.&mt('Size').'</th>'.
                   11818:                    '<th>'.&mt('Last modified').'</th>'.
                   11819:                    &end_data_table_header_row().
                   11820:                    $duplicates.
                   11821:                    &end_data_table().
                   11822:                    '</p>';
                   11823:     }
1.1067    raeburn  11824:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  11825:     if (ref($hiddenelements) eq 'HASH') {
                   11826:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   11827:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   11828:         }
                   11829:     }
                   11830:     $output .= <<"END";
1.1067    raeburn  11831: <br />
1.1053    raeburn  11832: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   11833: </form>
                   11834: $noextract
                   11835: END
                   11836:     return $output;
                   11837: }
                   11838: 
1.1065    raeburn  11839: sub decompression_utility {
                   11840:     my ($program) = @_;
                   11841:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   11842:     my $location;
                   11843:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   11844:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   11845:                          '/usr/sbin/') {
                   11846:             if (-x $dir.$program) {
                   11847:                 $location = $dir.$program;
                   11848:                 last;
                   11849:             }
                   11850:         }
                   11851:     }
                   11852:     return $location;
                   11853: }
                   11854: 
                   11855: sub list_archive_contents {
                   11856:     my ($file,$pathsref) = @_;
                   11857:     my (@cmd,$output);
                   11858:     my $needsregexp;
                   11859:     if ($file =~ /\.zip$/) {
                   11860:         @cmd = (&decompression_utility('unzip'),"-l");
                   11861:         $needsregexp = 1;
                   11862:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   11863:              ($file =~ /\.tgz$/)) {
                   11864:         @cmd = (&decompression_utility('tar'),"-ztf");
                   11865:     } elsif ($file =~ /\.tar\.bz2$/) {
                   11866:         @cmd = (&decompression_utility('tar'),"-jtf");
                   11867:     } elsif ($file =~ m|\.tar$|) {
                   11868:         @cmd = (&decompression_utility('tar'),"-tf");
                   11869:     }
                   11870:     if (@cmd) {
                   11871:         undef($!);
                   11872:         undef($@);
                   11873:         if (open(my $fh,"-|", @cmd, $file)) {
                   11874:             while (my $line = <$fh>) {
                   11875:                 $output .= $line;
                   11876:                 chomp($line);
                   11877:                 my $item;
                   11878:                 if ($needsregexp) {
                   11879:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   11880:                 } else {
                   11881:                     $item = $line;
                   11882:                 }
                   11883:                 if ($item ne '') {
                   11884:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   11885:                         push(@{$pathsref},$item);
                   11886:                     } 
                   11887:                 }
                   11888:             }
                   11889:             close($fh);
                   11890:         }
                   11891:     }
                   11892:     return $output;
                   11893: }
                   11894: 
1.1053    raeburn  11895: sub decompress_uploaded_file {
                   11896:     my ($file,$dir) = @_;
                   11897:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   11898:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   11899:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   11900:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   11901:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   11902:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   11903:     my $decompressed = $env{'cgi.decompressed'};
                   11904:     &Apache::lonnet::delenv('cgi.file');
                   11905:     &Apache::lonnet::delenv('cgi.dir');
                   11906:     &Apache::lonnet::delenv('cgi.decompressed');
                   11907:     return ($decompressed,$result);
                   11908: }
                   11909: 
1.1055    raeburn  11910: sub process_decompression {
                   11911:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   11912:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  11913:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  11914:         $error = &mt('Filename not a supported archive file type.').
                   11915:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  11916:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   11917:     } else {
                   11918:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11919:         if ($docuhome eq 'no_host') {
                   11920:             $error = &mt('Could not determine home server for course.');
                   11921:         } else {
                   11922:             my @ids=&Apache::lonnet::current_machine_ids();
                   11923:             my $currdir = "$dir_root/$destination";
                   11924:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11925:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   11926:                        "$dir_root/$destination";
                   11927:             } else {
                   11928:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   11929:                        "$dir_root/$docudom/$docuname/$destination";
                   11930:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   11931:                     $error = &mt('Archive file not found.');
                   11932:                 }
                   11933:             }
1.1065    raeburn  11934:             my (@to_overwrite,@to_skip);
                   11935:             if ($env{'form.archive_overwrite_total'} > 0) {
                   11936:                 my $total = $env{'form.archive_overwrite_total'};
                   11937:                 for (my $i=0; $i<$total; $i++) {
                   11938:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   11939:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   11940:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   11941:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   11942:                     }
                   11943:                 }
                   11944:             }
                   11945:             my $numskip = scalar(@to_skip);
                   11946:             if (($numskip > 0) && 
                   11947:                 ($numskip == $env{'form.archive_itemcount'})) {
                   11948:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   11949:             } elsif ($dir eq '') {
1.1055    raeburn  11950:                 $error = &mt('Directory containing archive file unavailable.');
                   11951:             } elsif (!$error) {
1.1065    raeburn  11952:                 my ($decompressed,$display);
                   11953:                 if ($numskip > 0) {
                   11954:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   11955:                     mkdir("$dir/$tempdir",0755);
                   11956:                     system("mv $dir/$file $dir/$tempdir/$file");
                   11957:                     ($decompressed,$display) = 
                   11958:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   11959:                     foreach my $item (@to_skip) {
                   11960:                         if (($item ne '') && ($item !~ /\.\./)) {
                   11961:                             if (-f "$dir/$tempdir/$item") { 
                   11962:                                 unlink("$dir/$tempdir/$item");
                   11963:                             } elsif (-d "$dir/$tempdir/$item") {
                   11964:                                 system("rm -rf $dir/$tempdir/$item");
                   11965:                             }
                   11966:                         }
                   11967:                     }
                   11968:                     system("mv $dir/$tempdir/* $dir");
                   11969:                     rmdir("$dir/$tempdir");   
                   11970:                 } else {
                   11971:                     ($decompressed,$display) = 
                   11972:                         &decompress_uploaded_file($file,$dir);
                   11973:                 }
1.1055    raeburn  11974:                 if ($decompressed eq 'ok') {
1.1065    raeburn  11975:                     $output = '<p class="LC_info">'.
                   11976:                               &mt('Files extracted successfully from archive.').
                   11977:                               '</p>'."\n";
1.1055    raeburn  11978:                     my ($warning,$result,@contents);
                   11979:                     my ($newdirlistref,$newlisterror) =
                   11980:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   11981:                                                  $docuname,1);
                   11982:                     my (%is_dir,%changes,@newitems);
                   11983:                     my $dirptr = 16384;
1.1065    raeburn  11984:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  11985:                         foreach my $dir_line (@{$newdirlistref}) {
                   11986:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  11987:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   11988:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  11989:                                 push(@newitems,$item);
                   11990:                                 if ($dirptr&$testdir) {
                   11991:                                     $is_dir{$item} = 1;
                   11992:                                 }
                   11993:                                 $changes{$item} = 1;
                   11994:                             }
                   11995:                         }
                   11996:                     }
                   11997:                     if (keys(%changes) > 0) {
                   11998:                         foreach my $item (sort(@newitems)) {
                   11999:                             if ($changes{$item}) {
                   12000:                                 push(@contents,$item);
                   12001:                             }
                   12002:                         }
                   12003:                     }
                   12004:                     if (@contents > 0) {
1.1067    raeburn  12005:                         my $wantform;
                   12006:                         unless ($env{'form.autoextract_camtasia'}) {
                   12007:                             $wantform = 1;
                   12008:                         }
1.1056    raeburn  12009:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12010:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12011:                                                                 $currdir,\%is_dir,
                   12012:                                                                 \%children,\%parent,
1.1056    raeburn  12013:                                                                 \@contents,\%dirorder,
                   12014:                                                                 \%titles,$wantform);
1.1055    raeburn  12015:                         if ($datatable ne '') {
                   12016:                             $output .= &archive_options_form('decompressed',$datatable,
                   12017:                                                              $count,$hiddenelem);
1.1065    raeburn  12018:                             my $startcount = 6;
1.1055    raeburn  12019:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12020:                                                            \%titles,\%children);
1.1055    raeburn  12021:                         }
1.1067    raeburn  12022:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  12023:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12024:                             my %displayed;
                   12025:                             my $total = 1;
                   12026:                             $env{'form.archive_directory'} = [];
                   12027:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12028:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12029:                                 $path =~ s{/$}{};
                   12030:                                 my $item;
                   12031:                                 if ($path ne '') {
                   12032:                                     $item = "$path/$titles{$i}";
                   12033:                                 } else {
                   12034:                                     $item = $titles{$i};
                   12035:                                 }
                   12036:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12037:                                 if ($item eq $contents[0]) {
                   12038:                                     push(@{$env{'form.archive_directory'}},$i);
                   12039:                                     $env{'form.archive_'.$i} = 'display';
                   12040:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12041:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  12042:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12043:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  12044:                                     $env{'form.archive_'.$i} = 'display';
                   12045:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12046:                                     $displayed{'web'} = $i;
                   12047:                                 } else {
1.1075.2.59  raeburn  12048:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12049:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12050:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12051:                                         push(@{$env{'form.archive_directory'}},$i);
                   12052:                                     }
                   12053:                                     $env{'form.archive_'.$i} = 'dependency';
                   12054:                                 }
                   12055:                                 $total ++;
                   12056:                             }
                   12057:                             for (my $i=1; $i<$total; $i++) {
                   12058:                                 next if ($i == $displayed{'web'});
                   12059:                                 next if ($i == $displayed{'folder'});
                   12060:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12061:                             }
                   12062:                             $env{'form.phase'} = 'decompress_cleanup';
                   12063:                             $env{'form.archivedelete'} = 1;
                   12064:                             $env{'form.archive_count'} = $total-1;
                   12065:                             $output .=
                   12066:                                 &process_extracted_files('coursedocs',$docudom,
                   12067:                                                          $docuname,$destination,
                   12068:                                                          $dir_root,$hiddenelem);
                   12069:                         }
1.1055    raeburn  12070:                     } else {
                   12071:                         $warning = &mt('No new items extracted from archive file.');
                   12072:                     }
                   12073:                 } else {
                   12074:                     $output = $display;
                   12075:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12076:                 }
                   12077:             }
                   12078:         }
                   12079:     }
                   12080:     if ($error) {
                   12081:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12082:                    $error.'</p>'."\n";
                   12083:     }
                   12084:     if ($warning) {
                   12085:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12086:     }
                   12087:     return $output;
                   12088: }
                   12089: 
                   12090: sub get_extracted {
1.1056    raeburn  12091:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12092:         $titles,$wantform) = @_;
1.1055    raeburn  12093:     my $count = 0;
                   12094:     my $depth = 0;
                   12095:     my $datatable;
1.1056    raeburn  12096:     my @hierarchy;
1.1055    raeburn  12097:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12098:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12099:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12100:     foreach my $item (@{$contents}) {
                   12101:         $count ++;
1.1056    raeburn  12102:         @{$dirorder->{$count}} = @hierarchy;
                   12103:         $titles->{$count} = $item;
1.1055    raeburn  12104:         &archive_hierarchy($depth,$count,$parent,$children);
                   12105:         if ($wantform) {
                   12106:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12107:                                        $currdir,$depth,$count);
                   12108:         }
                   12109:         if ($is_dir->{$item}) {
                   12110:             $depth ++;
1.1056    raeburn  12111:             push(@hierarchy,$count);
                   12112:             $parent->{$depth} = $count;
1.1055    raeburn  12113:             $datatable .=
                   12114:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12115:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12116:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12117:             $depth --;
1.1056    raeburn  12118:             pop(@hierarchy);
1.1055    raeburn  12119:         }
                   12120:     }
                   12121:     return ($count,$datatable);
                   12122: }
                   12123: 
                   12124: sub recurse_extracted_archive {
1.1056    raeburn  12125:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12126:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12127:     my $result='';
1.1056    raeburn  12128:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12129:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12130:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12131:         return $result;
                   12132:     }
                   12133:     my $dirptr = 16384;
                   12134:     my ($newdirlistref,$newlisterror) =
                   12135:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12136:     if (ref($newdirlistref) eq 'ARRAY') {
                   12137:         foreach my $dir_line (@{$newdirlistref}) {
                   12138:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12139:             unless ($item =~ /^\.+$/) {
                   12140:                 $$count ++;
1.1056    raeburn  12141:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12142:                 $titles->{$$count} = $item;
1.1055    raeburn  12143:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12144: 
1.1055    raeburn  12145:                 my $is_dir;
                   12146:                 if ($dirptr&$testdir) {
                   12147:                     $is_dir = 1;
                   12148:                 }
                   12149:                 if ($wantform) {
                   12150:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12151:                 }
                   12152:                 if ($is_dir) {
                   12153:                     $$depth ++;
1.1056    raeburn  12154:                     push(@{$hierarchy},$$count);
                   12155:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12156:                     $result .=
                   12157:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12158:                                                    $docuname,$depth,$count,
1.1056    raeburn  12159:                                                    $hierarchy,$dirorder,$children,
                   12160:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12161:                     $$depth --;
1.1056    raeburn  12162:                     pop(@{$hierarchy});
1.1055    raeburn  12163:                 }
                   12164:             }
                   12165:         }
                   12166:     }
                   12167:     return $result;
                   12168: }
                   12169: 
                   12170: sub archive_hierarchy {
                   12171:     my ($depth,$count,$parent,$children) =@_;
                   12172:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12173:         if (exists($parent->{$depth})) {
                   12174:              $children->{$parent->{$depth}} .= $count.':';
                   12175:         }
                   12176:     }
                   12177:     return;
                   12178: }
                   12179: 
                   12180: sub archive_row {
                   12181:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12182:     my ($name) = ($item =~ m{([^/]+)$});
                   12183:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12184:                                        'display'    => 'Add as file',
1.1055    raeburn  12185:                                        'dependency' => 'Include as dependency',
                   12186:                                        'discard'    => 'Discard',
                   12187:                                       );
                   12188:     if ($is_dir) {
1.1059    raeburn  12189:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12190:     }
1.1056    raeburn  12191:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12192:     my $offset = 0;
1.1055    raeburn  12193:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12194:         $offset ++;
1.1065    raeburn  12195:         if ($action ne 'display') {
                   12196:             $offset ++;
                   12197:         }  
1.1055    raeburn  12198:         $output .= '<td><span class="LC_nobreak">'.
                   12199:                    '<label><input type="radio" name="archive_'.$count.
                   12200:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12201:         my $text = $choices{$action};
                   12202:         if ($is_dir) {
                   12203:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12204:             if ($action eq 'display') {
1.1059    raeburn  12205:                 $text = &mt('Add as folder');
1.1055    raeburn  12206:             }
1.1056    raeburn  12207:         } else {
                   12208:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12209: 
                   12210:         }
                   12211:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12212:         if ($action eq 'dependency') {
                   12213:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12214:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12215:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12216:                        '<option value=""></option>'."\n".
                   12217:                        '</select>'."\n".
                   12218:                        '</div>';
1.1059    raeburn  12219:         } elsif ($action eq 'display') {
                   12220:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12221:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12222:                        '</div>';
1.1055    raeburn  12223:         }
1.1056    raeburn  12224:         $output .= '</td>';
1.1055    raeburn  12225:     }
                   12226:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12227:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12228:     for (my $i=0; $i<$depth; $i++) {
                   12229:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12230:     }
                   12231:     if ($is_dir) {
                   12232:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12233:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12234:     } else {
                   12235:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12236:     }
                   12237:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12238:                &end_data_table_row();
                   12239:     return $output;
                   12240: }
                   12241: 
                   12242: sub archive_options_form {
1.1065    raeburn  12243:     my ($form,$display,$count,$hiddenelem) = @_;
                   12244:     my %lt = &Apache::lonlocal::texthash(
                   12245:                perm => 'Permanently remove archive file?',
                   12246:                hows => 'How should each extracted item be incorporated in the course?',
                   12247:                cont => 'Content actions for all',
                   12248:                addf => 'Add as folder/file',
                   12249:                incd => 'Include as dependency for a displayed file',
                   12250:                disc => 'Discard',
                   12251:                no   => 'No',
                   12252:                yes  => 'Yes',
                   12253:                save => 'Save',
                   12254:     );
                   12255:     my $output = <<"END";
                   12256: <form name="$form" method="post" action="">
                   12257: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12258: <label>
                   12259:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12260: </label>
                   12261: &nbsp;
                   12262: <label>
                   12263:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12264: </span>
                   12265: </p>
                   12266: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12267: <br />$lt{'hows'}
                   12268: <div class="LC_columnSection">
                   12269:   <fieldset>
                   12270:     <legend>$lt{'cont'}</legend>
                   12271:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12272:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12273:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12274:   </fieldset>
                   12275: </div>
                   12276: END
                   12277:     return $output.
1.1055    raeburn  12278:            &start_data_table()."\n".
1.1065    raeburn  12279:            $display."\n".
1.1055    raeburn  12280:            &end_data_table()."\n".
                   12281:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12282:            $hiddenelem.
1.1065    raeburn  12283:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12284:            '</form>';
                   12285: }
                   12286: 
                   12287: sub archive_javascript {
1.1056    raeburn  12288:     my ($startcount,$numitems,$titles,$children) = @_;
                   12289:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12290:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12291:     my $scripttag = <<START;
                   12292: <script type="text/javascript">
                   12293: // <![CDATA[
                   12294: 
                   12295: function checkAll(form,prefix) {
                   12296:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12297:     for (var i=0; i < form.elements.length; i++) {
                   12298:         var id = form.elements[i].id;
                   12299:         if ((id != '') && (id != undefined)) {
                   12300:             if (idstr.test(id)) {
                   12301:                 if (form.elements[i].type == 'radio') {
                   12302:                     form.elements[i].checked = true;
1.1056    raeburn  12303:                     var nostart = i-$startcount;
1.1059    raeburn  12304:                     var offset = nostart%7;
                   12305:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12306:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12307:                 }
                   12308:             }
                   12309:         }
                   12310:     }
                   12311: }
                   12312: 
                   12313: function propagateCheck(form,count) {
                   12314:     if (count > 0) {
1.1059    raeburn  12315:         var startelement = $startcount + ((count-1) * 7);
                   12316:         for (var j=1; j<6; j++) {
                   12317:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12318:                 var item = startelement + j; 
                   12319:                 if (form.elements[item].type == 'radio') {
                   12320:                     if (form.elements[item].checked) {
                   12321:                         containerCheck(form,count,j);
                   12322:                         break;
                   12323:                     }
1.1055    raeburn  12324:                 }
                   12325:             }
                   12326:         }
                   12327:     }
                   12328: }
                   12329: 
                   12330: numitems = $numitems
1.1056    raeburn  12331: var titles = new Array(numitems);
                   12332: var parents = new Array(numitems);
1.1055    raeburn  12333: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12334:     parents[i] = new Array;
1.1055    raeburn  12335: }
1.1059    raeburn  12336: var maintitle = '$maintitle';
1.1055    raeburn  12337: 
                   12338: START
                   12339: 
1.1056    raeburn  12340:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12341:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12342:         for (my $i=0; $i<@contents; $i ++) {
                   12343:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12344:         }
                   12345:     }
                   12346: 
1.1056    raeburn  12347:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12348:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12349:     }
                   12350: 
1.1055    raeburn  12351:     $scripttag .= <<END;
                   12352: 
                   12353: function containerCheck(form,count,offset) {
                   12354:     if (count > 0) {
1.1056    raeburn  12355:         dependencyCheck(form,count,offset);
1.1059    raeburn  12356:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12357:         form.elements[item].checked = true;
                   12358:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12359:             if (parents[count].length > 0) {
                   12360:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12361:                     containerCheck(form,parents[count][j],offset);
                   12362:                 }
                   12363:             }
                   12364:         }
                   12365:     }
                   12366: }
                   12367: 
                   12368: function dependencyCheck(form,count,offset) {
                   12369:     if (count > 0) {
1.1059    raeburn  12370:         var chosen = (offset+$startcount)+7*(count-1);
                   12371:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12372:         var currtype = form.elements[depitem].type;
                   12373:         if (form.elements[chosen].value == 'dependency') {
                   12374:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12375:             form.elements[depitem].options.length = 0;
                   12376:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  12377:             for (var i=1; i<=numitems; i++) {
                   12378:                 if (i == count) {
                   12379:                     continue;
                   12380:                 }
1.1059    raeburn  12381:                 var startelement = $startcount + (i-1) * 7;
                   12382:                 for (var j=1; j<6; j++) {
                   12383:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12384:                         var item = startelement + j;
                   12385:                         if (form.elements[item].type == 'radio') {
                   12386:                             if (form.elements[item].checked) {
                   12387:                                 if (form.elements[item].value == 'display') {
                   12388:                                     var n = form.elements[depitem].options.length;
                   12389:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12390:                                 }
                   12391:                             }
                   12392:                         }
                   12393:                     }
                   12394:                 }
                   12395:             }
                   12396:         } else {
                   12397:             document.getElementById('arc_depon_'+count).style.display='none';
                   12398:             form.elements[depitem].options.length = 0;
                   12399:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12400:         }
1.1059    raeburn  12401:         titleCheck(form,count,offset);
1.1056    raeburn  12402:     }
                   12403: }
                   12404: 
                   12405: function propagateSelect(form,count,offset) {
                   12406:     if (count > 0) {
1.1065    raeburn  12407:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12408:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12409:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12410:             if (parents[count].length > 0) {
                   12411:                 for (var j=0; j<parents[count].length; j++) {
                   12412:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12413:                 }
                   12414:             }
                   12415:         }
                   12416:     }
                   12417: }
1.1056    raeburn  12418: 
                   12419: function containerSelect(form,count,offset,picked) {
                   12420:     if (count > 0) {
1.1065    raeburn  12421:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12422:         if (form.elements[item].type == 'radio') {
                   12423:             if (form.elements[item].value == 'dependency') {
                   12424:                 if (form.elements[item+1].type == 'select-one') {
                   12425:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12426:                         if (form.elements[item+1].options[i].value == picked) {
                   12427:                             form.elements[item+1].selectedIndex = i;
                   12428:                             break;
                   12429:                         }
                   12430:                     }
                   12431:                 }
                   12432:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12433:                     if (parents[count].length > 0) {
                   12434:                         for (var j=0; j<parents[count].length; j++) {
                   12435:                             containerSelect(form,parents[count][j],offset,picked);
                   12436:                         }
                   12437:                     }
                   12438:                 }
                   12439:             }
                   12440:         }
                   12441:     }
                   12442: }
                   12443: 
1.1059    raeburn  12444: function titleCheck(form,count,offset) {
                   12445:     if (count > 0) {
                   12446:         var chosen = (offset+$startcount)+7*(count-1);
                   12447:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12448:         var currtype = form.elements[depitem].type;
                   12449:         if (form.elements[chosen].value == 'display') {
                   12450:             document.getElementById('arc_title_'+count).style.display='block';
                   12451:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12452:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12453:             }
                   12454:         } else {
                   12455:             document.getElementById('arc_title_'+count).style.display='none';
                   12456:             if (currtype == 'text') { 
                   12457:                 document.getElementById('archive_title_'+count).value='';
                   12458:             }
                   12459:         }
                   12460:     }
                   12461:     return;
                   12462: }
                   12463: 
1.1055    raeburn  12464: // ]]>
                   12465: </script>
                   12466: END
                   12467:     return $scripttag;
                   12468: }
                   12469: 
                   12470: sub process_extracted_files {
1.1067    raeburn  12471:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12472:     my $numitems = $env{'form.archive_count'};
                   12473:     return unless ($numitems);
                   12474:     my @ids=&Apache::lonnet::current_machine_ids();
                   12475:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12476:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12477:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12478:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12479:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12480:         $pathtocheck = "$dir_root/$destination";
                   12481:         $dir = $dir_root;
                   12482:         $ishome = 1;
                   12483:     } else {
                   12484:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12485:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   12486:         $dir = "$dir_root/$docudom/$docuname";    
                   12487:     }
                   12488:     my $currdir = "$dir_root/$destination";
                   12489:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12490:     if ($env{'form.folderpath'}) {
                   12491:         my @items = split('&',$env{'form.folderpath'});
                   12492:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  12493:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12494:             $containers{'0'}='page';
                   12495:         } else {
                   12496:             $containers{'0'}='sequence';
                   12497:         }
1.1055    raeburn  12498:     }
                   12499:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12500:     if ($numitems) {
                   12501:         for (my $i=1; $i<=$numitems; $i++) {
                   12502:             my $path = $env{'form.archive_content_'.$i};
                   12503:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12504:                 my $item = $1;
                   12505:                 $toplevelitems{$item} = $i;
                   12506:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12507:                     $is_dir{$item} = 1;
                   12508:                 }
                   12509:             }
                   12510:         }
                   12511:     }
1.1067    raeburn  12512:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12513:     if (keys(%toplevelitems) > 0) {
                   12514:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12515:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12516:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12517:     }
1.1066    raeburn  12518:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12519:     if ($numitems) {
                   12520:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  12521:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12522:             my $path = $env{'form.archive_content_'.$i};
                   12523:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12524:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12525:                     if ($prefix ne '' && $path ne '') {
                   12526:                         if (-e $prefix.$path) {
1.1066    raeburn  12527:                             if ((@archdirs > 0) && 
                   12528:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12529:                                 $todeletedir{$prefix.$path} = 1;
                   12530:                             } else {
                   12531:                                 $todelete{$prefix.$path} = 1;
                   12532:                             }
1.1055    raeburn  12533:                         }
                   12534:                     }
                   12535:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12536:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12537:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12538:                     $docstitle = $env{'form.archive_title_'.$i};
                   12539:                     if ($docstitle eq '') {
                   12540:                         $docstitle = $title;
                   12541:                     }
1.1055    raeburn  12542:                     $outer = 0;
1.1056    raeburn  12543:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12544:                         if (@{$dirorder{$i}} > 0) {
                   12545:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12546:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12547:                                     $outer = $item;
                   12548:                                     last;
                   12549:                                 }
                   12550:                             }
                   12551:                         }
                   12552:                     }
                   12553:                     my ($errtext,$fatal) = 
                   12554:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12555:                                                '/'.$folders{$outer}.'.'.
                   12556:                                                $containers{$outer});
                   12557:                     next if ($fatal);
                   12558:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12559:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12560:                             $mapinner{$i} = time;
1.1055    raeburn  12561:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12562:                             $containers{$i} = 'sequence';
                   12563:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12564:                                       $folders{$i}.'.'.$containers{$i};
                   12565:                             my $newidx = &LONCAPA::map::getresidx();
                   12566:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12567:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12568:                             push(@LONCAPA::map::order,$newidx);
                   12569:                             my ($outtext,$errtext) =
                   12570:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12571:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12572:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12573:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12574:                             unless ($errtext) {
                   12575:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   12576:                             }
1.1055    raeburn  12577:                         }
                   12578:                     } else {
                   12579:                         if ($context eq 'coursedocs') {
                   12580:                             my $newidx=&LONCAPA::map::getresidx();
                   12581:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12582:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12583:                                       $title;
                   12584:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12585:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   12586:                             }
                   12587:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12588:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12589:                             }
                   12590:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12591:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  12592:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  12593:                                 unless ($ishome) {
                   12594:                                     my $fetch = "$newdest{$i}/$title";
                   12595:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   12596:                                     $prompttofetch{$fetch} = 1;
                   12597:                                 }
1.1055    raeburn  12598:                             }
                   12599:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12600:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12601:                             push(@LONCAPA::map::order, $newidx);
                   12602:                             my ($outtext,$errtext)=
                   12603:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12604:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12605:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  12606:                             unless ($errtext) {
                   12607:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12608:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   12609:                                 }
                   12610:                             }
1.1055    raeburn  12611:                         }
                   12612:                     }
1.1075.2.11  raeburn  12613:                 }
                   12614:             } else {
                   12615:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
                   12616:             }
                   12617:         }
                   12618:         for (my $i=1; $i<=$numitems; $i++) {
                   12619:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12620:             my $path = $env{'form.archive_content_'.$i};
                   12621:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12622:                 my ($title) = ($path =~ m{/([^/]+)$});
                   12623:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   12624:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   12625:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12626:                         my ($itemidx,$fullpath,$relpath);
                   12627:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   12628:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  12629:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  12630:                                 if ($dirorder{$i}->[$j] eq $container) {
                   12631:                                     $itemidx = $j;
1.1056    raeburn  12632:                                 }
                   12633:                             }
1.1075.2.11  raeburn  12634:                         }
                   12635:                         if ($itemidx eq '') {
                   12636:                             $itemidx =  0;
                   12637:                         }
                   12638:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   12639:                             if ($mapinner{$referrer{$i}}) {
                   12640:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   12641:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12642:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12643:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12644:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12645:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12646:                                             if (!-e $fullpath) {
                   12647:                                                 mkdir($fullpath,0755);
1.1056    raeburn  12648:                                             }
                   12649:                                         }
1.1075.2.11  raeburn  12650:                                     } else {
                   12651:                                         last;
1.1056    raeburn  12652:                                     }
1.1075.2.11  raeburn  12653:                                 }
                   12654:                             }
                   12655:                         } elsif ($newdest{$referrer{$i}}) {
                   12656:                             $fullpath = $newdest{$referrer{$i}};
                   12657:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12658:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   12659:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   12660:                                     last;
                   12661:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12662:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12663:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12664:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12665:                                         if (!-e $fullpath) {
                   12666:                                             mkdir($fullpath,0755);
1.1056    raeburn  12667:                                         }
                   12668:                                     }
1.1075.2.11  raeburn  12669:                                 } else {
                   12670:                                     last;
1.1056    raeburn  12671:                                 }
1.1075.2.11  raeburn  12672:                             }
                   12673:                         }
                   12674:                         if ($fullpath ne '') {
                   12675:                             if (-e "$prefix$path") {
                   12676:                                 system("mv $prefix$path $fullpath/$title");
                   12677:                             }
                   12678:                             if (-e "$fullpath/$title") {
                   12679:                                 my $showpath;
                   12680:                                 if ($relpath ne '') {
                   12681:                                     $showpath = "$relpath/$title";
                   12682:                                 } else {
                   12683:                                     $showpath = "/$title";
1.1056    raeburn  12684:                                 }
1.1075.2.11  raeburn  12685:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   12686:                             }
                   12687:                             unless ($ishome) {
                   12688:                                 my $fetch = "$fullpath/$title";
                   12689:                                 $fetch =~ s/^\Q$prefix$dir\E//;
                   12690:                                 $prompttofetch{$fetch} = 1;
1.1055    raeburn  12691:                             }
                   12692:                         }
                   12693:                     }
1.1075.2.11  raeburn  12694:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   12695:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   12696:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  12697:                 }
                   12698:             } else {
1.1075.2.11  raeburn  12699:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
1.1055    raeburn  12700:             }
                   12701:         }
                   12702:         if (keys(%todelete)) {
                   12703:             foreach my $key (keys(%todelete)) {
                   12704:                 unlink($key);
1.1066    raeburn  12705:             }
                   12706:         }
                   12707:         if (keys(%todeletedir)) {
                   12708:             foreach my $key (keys(%todeletedir)) {
                   12709:                 rmdir($key);
                   12710:             }
                   12711:         }
                   12712:         foreach my $dir (sort(keys(%is_dir))) {
                   12713:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   12714:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  12715:             }
                   12716:         }
1.1067    raeburn  12717:         if ($result ne '') {
                   12718:             $output .= '<ul>'."\n".
                   12719:                        $result."\n".
                   12720:                        '</ul>';
                   12721:         }
                   12722:         unless ($ishome) {
                   12723:             my $replicationfail;
                   12724:             foreach my $item (keys(%prompttofetch)) {
                   12725:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   12726:                 unless ($fetchresult eq 'ok') {
                   12727:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   12728:                 }
                   12729:             }
                   12730:             if ($replicationfail) {
                   12731:                 $output .= '<p class="LC_error">'.
                   12732:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   12733:                            $replicationfail.
                   12734:                            '</ul></p>';
                   12735:             }
                   12736:         }
1.1055    raeburn  12737:     } else {
                   12738:         $warning = &mt('No items found in archive.');
                   12739:     }
                   12740:     if ($error) {
                   12741:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12742:                    $error.'</p>'."\n";
                   12743:     }
                   12744:     if ($warning) {
                   12745:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12746:     }
                   12747:     return $output;
                   12748: }
                   12749: 
1.1066    raeburn  12750: sub cleanup_empty_dirs {
                   12751:     my ($path) = @_;
                   12752:     if (($path ne '') && (-d $path)) {
                   12753:         if (opendir(my $dirh,$path)) {
                   12754:             my @dircontents = grep(!/^\./,readdir($dirh));
                   12755:             my $numitems = 0;
                   12756:             foreach my $item (@dircontents) {
                   12757:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  12758:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  12759:                     if (-e "$path/$item") {
                   12760:                         $numitems ++;
                   12761:                     }
                   12762:                 } else {
                   12763:                     $numitems ++;
                   12764:                 }
                   12765:             }
                   12766:             if ($numitems == 0) {
                   12767:                 rmdir($path);
                   12768:             }
                   12769:             closedir($dirh);
                   12770:         }
                   12771:     }
                   12772:     return;
                   12773: }
                   12774: 
1.41      ng       12775: =pod
1.45      matthew  12776: 
1.1075.2.56  raeburn  12777: =item * &get_folder_hierarchy()
1.1068    raeburn  12778: 
                   12779: Provides hierarchy of names of folders/sub-folders containing the current
                   12780: item,
                   12781: 
                   12782: Inputs: 3
                   12783:      - $navmap - navmaps object
                   12784: 
                   12785:      - $map - url for map (either the trigger itself, or map containing
                   12786:                            the resource, which is the trigger).
                   12787: 
                   12788:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   12789: 
                   12790: Outputs: 1 @pathitems - array of folder/subfolder names.
                   12791: 
                   12792: =cut
                   12793: 
                   12794: sub get_folder_hierarchy {
                   12795:     my ($navmap,$map,$showitem) = @_;
                   12796:     my @pathitems;
                   12797:     if (ref($navmap)) {
                   12798:         my $mapres = $navmap->getResourceByUrl($map);
                   12799:         if (ref($mapres)) {
                   12800:             my $pcslist = $mapres->map_hierarchy();
                   12801:             if ($pcslist ne '') {
                   12802:                 my @pcs = split(/,/,$pcslist);
                   12803:                 foreach my $pc (@pcs) {
                   12804:                     if ($pc == 1) {
1.1075.2.38  raeburn  12805:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  12806:                     } else {
                   12807:                         my $res = $navmap->getByMapPc($pc);
                   12808:                         if (ref($res)) {
                   12809:                             my $title = $res->compTitle();
                   12810:                             $title =~ s/\W+/_/g;
                   12811:                             if ($title ne '') {
                   12812:                                 push(@pathitems,$title);
                   12813:                             }
                   12814:                         }
                   12815:                     }
                   12816:                 }
                   12817:             }
1.1071    raeburn  12818:             if ($showitem) {
                   12819:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  12820:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  12821:                 } else {
                   12822:                     my $maptitle = $mapres->compTitle();
                   12823:                     $maptitle =~ s/\W+/_/g;
                   12824:                     if ($maptitle ne '') {
                   12825:                         push(@pathitems,$maptitle);
                   12826:                     }
1.1068    raeburn  12827:                 }
                   12828:             }
                   12829:         }
                   12830:     }
                   12831:     return @pathitems;
                   12832: }
                   12833: 
                   12834: =pod
                   12835: 
1.1015    raeburn  12836: =item * &get_turnedin_filepath()
                   12837: 
                   12838: Determines path in a user's portfolio file for storage of files uploaded
                   12839: to a specific essayresponse or dropbox item.
                   12840: 
                   12841: Inputs: 3 required + 1 optional.
                   12842: $symb is symb for resource, $uname and $udom are for current user (required).
                   12843: $caller is optional (can be "submission", if routine is called when storing
                   12844: an upoaded file when "Submit Answer" button was pressed).
                   12845: 
                   12846: Returns array containing $path and $multiresp. 
                   12847: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   12848: than one file upload item.  Callers of routine should append partid as a 
                   12849: subdirectory to $path in cases where $multiresp is 1.
                   12850: 
                   12851: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   12852: 
                   12853: =cut
                   12854: 
                   12855: sub get_turnedin_filepath {
                   12856:     my ($symb,$uname,$udom,$caller) = @_;
                   12857:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   12858:     my $turnindir;
                   12859:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   12860:     $turnindir = $userhash{'turnindir'};
                   12861:     my ($path,$multiresp);
                   12862:     if ($turnindir eq '') {
                   12863:         if ($caller eq 'submission') {
                   12864:             $turnindir = &mt('turned in');
                   12865:             $turnindir =~ s/\W+/_/g;
                   12866:             my %newhash = (
                   12867:                             'turnindir' => $turnindir,
                   12868:                           );
                   12869:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   12870:         }
                   12871:     }
                   12872:     if ($turnindir ne '') {
                   12873:         $path = '/'.$turnindir.'/';
                   12874:         my ($multipart,$turnin,@pathitems);
                   12875:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12876:         if (defined($navmap)) {
                   12877:             my $mapres = $navmap->getResourceByUrl($map);
                   12878:             if (ref($mapres)) {
                   12879:                 my $pcslist = $mapres->map_hierarchy();
                   12880:                 if ($pcslist ne '') {
                   12881:                     foreach my $pc (split(/,/,$pcslist)) {
                   12882:                         my $res = $navmap->getByMapPc($pc);
                   12883:                         if (ref($res)) {
                   12884:                             my $title = $res->compTitle();
                   12885:                             $title =~ s/\W+/_/g;
                   12886:                             if ($title ne '') {
1.1075.2.48  raeburn  12887:                                 if (($pc > 1) && (length($title) > 12)) {
                   12888:                                     $title = substr($title,0,12);
                   12889:                                 }
1.1015    raeburn  12890:                                 push(@pathitems,$title);
                   12891:                             }
                   12892:                         }
                   12893:                     }
                   12894:                 }
                   12895:                 my $maptitle = $mapres->compTitle();
                   12896:                 $maptitle =~ s/\W+/_/g;
                   12897:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  12898:                     if (length($maptitle) > 12) {
                   12899:                         $maptitle = substr($maptitle,0,12);
                   12900:                     }
1.1015    raeburn  12901:                     push(@pathitems,$maptitle);
                   12902:                 }
                   12903:                 unless ($env{'request.state'} eq 'construct') {
                   12904:                     my $res = $navmap->getBySymb($symb);
                   12905:                     if (ref($res)) {
                   12906:                         my $partlist = $res->parts();
                   12907:                         my $totaluploads = 0;
                   12908:                         if (ref($partlist) eq 'ARRAY') {
                   12909:                             foreach my $part (@{$partlist}) {
                   12910:                                 my @types = $res->responseType($part);
                   12911:                                 my @ids = $res->responseIds($part);
                   12912:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   12913:                                     if ($types[$i] eq 'essay') {
                   12914:                                         my $partid = $part.'_'.$ids[$i];
                   12915:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   12916:                                             $totaluploads ++;
                   12917:                                         }
                   12918:                                     }
                   12919:                                 }
                   12920:                             }
                   12921:                             if ($totaluploads > 1) {
                   12922:                                 $multiresp = 1;
                   12923:                             }
                   12924:                         }
                   12925:                     }
                   12926:                 }
                   12927:             } else {
                   12928:                 return;
                   12929:             }
                   12930:         } else {
                   12931:             return;
                   12932:         }
                   12933:         my $restitle=&Apache::lonnet::gettitle($symb);
                   12934:         $restitle =~ s/\W+/_/g;
                   12935:         if ($restitle eq '') {
                   12936:             $restitle = ($resurl =~ m{/[^/]+$});
                   12937:             if ($restitle eq '') {
                   12938:                 $restitle = time;
                   12939:             }
                   12940:         }
1.1075.2.48  raeburn  12941:         if (length($restitle) > 12) {
                   12942:             $restitle = substr($restitle,0,12);
                   12943:         }
1.1015    raeburn  12944:         push(@pathitems,$restitle);
                   12945:         $path .= join('/',@pathitems);
                   12946:     }
                   12947:     return ($path,$multiresp);
                   12948: }
                   12949: 
                   12950: =pod
                   12951: 
1.464     albertel 12952: =back
1.41      ng       12953: 
1.112     bowersj2 12954: =head1 CSV Upload/Handling functions
1.38      albertel 12955: 
1.41      ng       12956: =over 4
                   12957: 
1.648     raeburn  12958: =item * &upfile_store($r)
1.41      ng       12959: 
                   12960: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 12961: needs $env{'form.upfile'}
1.41      ng       12962: returns $datatoken to be put into hidden field
                   12963: 
                   12964: =cut
1.31      albertel 12965: 
                   12966: sub upfile_store {
                   12967:     my $r=shift;
1.258     albertel 12968:     $env{'form.upfile'}=~s/\r/\n/gs;
                   12969:     $env{'form.upfile'}=~s/\f/\n/gs;
                   12970:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   12971:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 12972: 
1.258     albertel 12973:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   12974: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 12975:     {
1.158     raeburn  12976:         my $datafile = $r->dir_config('lonDaemons').
                   12977:                            '/tmp/'.$datatoken.'.tmp';
                   12978:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 12979:             print $fh $env{'form.upfile'};
1.158     raeburn  12980:             close($fh);
                   12981:         }
1.31      albertel 12982:     }
                   12983:     return $datatoken;
                   12984: }
                   12985: 
1.56      matthew  12986: =pod
                   12987: 
1.648     raeburn  12988: =item * &load_tmp_file($r)
1.41      ng       12989: 
                   12990: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 12991: needs $env{'form.datatoken'},
                   12992: sets $env{'form.upfile'} to the contents of the file
1.41      ng       12993: 
                   12994: =cut
1.31      albertel 12995: 
                   12996: sub load_tmp_file {
                   12997:     my $r=shift;
                   12998:     my @studentdata=();
                   12999:     {
1.158     raeburn  13000:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 13001:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  13002:         if ( open(my $fh,"<$studentfile") ) {
                   13003:             @studentdata=<$fh>;
                   13004:             close($fh);
                   13005:         }
1.31      albertel 13006:     }
1.258     albertel 13007:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13008: }
                   13009: 
1.56      matthew  13010: =pod
                   13011: 
1.648     raeburn  13012: =item * &upfile_record_sep()
1.41      ng       13013: 
                   13014: Separate uploaded file into records
                   13015: returns array of records,
1.258     albertel 13016: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13017: 
                   13018: =cut
1.31      albertel 13019: 
                   13020: sub upfile_record_sep {
1.258     albertel 13021:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13022:     } else {
1.248     albertel 13023: 	my @records;
1.258     albertel 13024: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13025: 	    if ($line=~/^\s*$/) { next; }
                   13026: 	    push(@records,$line);
                   13027: 	}
                   13028: 	return @records;
1.31      albertel 13029:     }
                   13030: }
                   13031: 
1.56      matthew  13032: =pod
                   13033: 
1.648     raeburn  13034: =item * &record_sep($record)
1.41      ng       13035: 
1.258     albertel 13036: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13037: 
                   13038: =cut
                   13039: 
1.263     www      13040: sub takeleft {
                   13041:     my $index=shift;
                   13042:     return substr('0000'.$index,-4,4);
                   13043: }
                   13044: 
1.31      albertel 13045: sub record_sep {
                   13046:     my $record=shift;
                   13047:     my %components=();
1.258     albertel 13048:     if ($env{'form.upfiletype'} eq 'xml') {
                   13049:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13050:         my $i=0;
1.356     albertel 13051:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13052:             $field=~s/^(\"|\')//;
                   13053:             $field=~s/(\"|\')$//;
1.263     www      13054:             $components{&takeleft($i)}=$field;
1.31      albertel 13055:             $i++;
                   13056:         }
1.258     albertel 13057:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13058:         my $i=0;
1.356     albertel 13059:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13060:             $field=~s/^(\"|\')//;
                   13061:             $field=~s/(\"|\')$//;
1.263     www      13062:             $components{&takeleft($i)}=$field;
1.31      albertel 13063:             $i++;
                   13064:         }
                   13065:     } else {
1.561     www      13066:         my $separator=',';
1.480     banghart 13067:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13068:             $separator=';';
1.480     banghart 13069:         }
1.31      albertel 13070:         my $i=0;
1.561     www      13071: # the character we are looking for to indicate the end of a quote or a record 
                   13072:         my $looking_for=$separator;
                   13073: # do not add the characters to the fields
                   13074:         my $ignore=0;
                   13075: # we just encountered a separator (or the beginning of the record)
                   13076:         my $just_found_separator=1;
                   13077: # store the field we are working on here
                   13078:         my $field='';
                   13079: # work our way through all characters in record
                   13080:         foreach my $character ($record=~/(.)/g) {
                   13081:             if ($character eq $looking_for) {
                   13082:                if ($character ne $separator) {
                   13083: # Found the end of a quote, again looking for separator
                   13084:                   $looking_for=$separator;
                   13085:                   $ignore=1;
                   13086:                } else {
                   13087: # Found a separator, store away what we got
                   13088:                   $components{&takeleft($i)}=$field;
                   13089: 	          $i++;
                   13090:                   $just_found_separator=1;
                   13091:                   $ignore=0;
                   13092:                   $field='';
                   13093:                }
                   13094:                next;
                   13095:             }
                   13096: # single or double quotation marks after a separator indicate beginning of a quote
                   13097: # we are now looking for the end of the quote and need to ignore separators
                   13098:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13099:                $looking_for=$character;
                   13100:                next;
                   13101:             }
                   13102: # ignore would be true after we reached the end of a quote
                   13103:             if ($ignore) { next; }
                   13104:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13105:             $field.=$character;
                   13106:             $just_found_separator=0; 
1.31      albertel 13107:         }
1.561     www      13108: # catch the very last entry, since we never encountered the separator
                   13109:         $components{&takeleft($i)}=$field;
1.31      albertel 13110:     }
                   13111:     return %components;
                   13112: }
                   13113: 
1.144     matthew  13114: ######################################################
                   13115: ######################################################
                   13116: 
1.56      matthew  13117: =pod
                   13118: 
1.648     raeburn  13119: =item * &upfile_select_html()
1.41      ng       13120: 
1.144     matthew  13121: Return HTML code to select a file from the users machine and specify 
                   13122: the file type.
1.41      ng       13123: 
                   13124: =cut
                   13125: 
1.144     matthew  13126: ######################################################
                   13127: ######################################################
1.31      albertel 13128: sub upfile_select_html {
1.144     matthew  13129:     my %Types = (
                   13130:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13131:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13132:                  space => &mt('Space separated'),
                   13133:                  tab   => &mt('Tabulator separated'),
                   13134: #                 xml   => &mt('HTML/XML'),
                   13135:                  );
                   13136:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13137:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13138:     foreach my $type (sort(keys(%Types))) {
                   13139:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13140:     }
                   13141:     $Str .= "</select>\n";
                   13142:     return $Str;
1.31      albertel 13143: }
                   13144: 
1.301     albertel 13145: sub get_samples {
                   13146:     my ($records,$toget) = @_;
                   13147:     my @samples=({});
                   13148:     my $got=0;
                   13149:     foreach my $rec (@$records) {
                   13150: 	my %temp = &record_sep($rec);
                   13151: 	if (! grep(/\S/, values(%temp))) { next; }
                   13152: 	if (%temp) {
                   13153: 	    $samples[$got]=\%temp;
                   13154: 	    $got++;
                   13155: 	    if ($got == $toget) { last; }
                   13156: 	}
                   13157:     }
                   13158:     return \@samples;
                   13159: }
                   13160: 
1.144     matthew  13161: ######################################################
                   13162: ######################################################
                   13163: 
1.56      matthew  13164: =pod
                   13165: 
1.648     raeburn  13166: =item * &csv_print_samples($r,$records)
1.41      ng       13167: 
                   13168: Prints a table of sample values from each column uploaded $r is an
                   13169: Apache Request ref, $records is an arrayref from
                   13170: &Apache::loncommon::upfile_record_sep
                   13171: 
                   13172: =cut
                   13173: 
1.144     matthew  13174: ######################################################
                   13175: ######################################################
1.31      albertel 13176: sub csv_print_samples {
                   13177:     my ($r,$records) = @_;
1.662     bisitz   13178:     my $samples = &get_samples($records,5);
1.301     albertel 13179: 
1.594     raeburn  13180:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13181:               &start_data_table_header_row());
1.356     albertel 13182:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13183:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13184:     $r->print(&end_data_table_header_row());
1.301     albertel 13185:     foreach my $hash (@$samples) {
1.594     raeburn  13186: 	$r->print(&start_data_table_row());
1.356     albertel 13187: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13188: 	    $r->print('<td>');
1.356     albertel 13189: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13190: 	    $r->print('</td>');
                   13191: 	}
1.594     raeburn  13192: 	$r->print(&end_data_table_row());
1.31      albertel 13193:     }
1.594     raeburn  13194:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13195: }
                   13196: 
1.144     matthew  13197: ######################################################
                   13198: ######################################################
                   13199: 
1.56      matthew  13200: =pod
                   13201: 
1.648     raeburn  13202: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13203: 
                   13204: Prints a table to create associations between values and table columns.
1.144     matthew  13205: 
1.41      ng       13206: $r is an Apache Request ref,
                   13207: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13208: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13209: 
                   13210: =cut
                   13211: 
1.144     matthew  13212: ######################################################
                   13213: ######################################################
1.31      albertel 13214: sub csv_print_select_table {
                   13215:     my ($r,$records,$d) = @_;
1.301     albertel 13216:     my $i=0;
                   13217:     my $samples = &get_samples($records,1);
1.144     matthew  13218:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13219: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13220:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13221:               '<th>'.&mt('Column').'</th>'.
                   13222:               &end_data_table_header_row()."\n");
1.356     albertel 13223:     foreach my $array_ref (@$d) {
                   13224: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13225: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13226: 
1.875     bisitz   13227: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13228: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13229: 	$r->print('<option value="none"></option>');
1.356     albertel 13230: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13231: 	    $r->print('<option value="'.$sample.'"'.
                   13232:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13233:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13234: 	}
1.594     raeburn  13235: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13236: 	$i++;
                   13237:     }
1.594     raeburn  13238:     $r->print(&end_data_table());
1.31      albertel 13239:     $i--;
                   13240:     return $i;
                   13241: }
1.56      matthew  13242: 
1.144     matthew  13243: ######################################################
                   13244: ######################################################
                   13245: 
1.56      matthew  13246: =pod
1.31      albertel 13247: 
1.648     raeburn  13248: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13249: 
                   13250: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13251: 
                   13252: $r is an Apache Request ref,
                   13253: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13254: $d is an array of 2 element arrays (internal name, displayed name)
                   13255: 
                   13256: =cut
                   13257: 
1.144     matthew  13258: ######################################################
                   13259: ######################################################
1.31      albertel 13260: sub csv_samples_select_table {
                   13261:     my ($r,$records,$d) = @_;
                   13262:     my $i=0;
1.144     matthew  13263:     #
1.662     bisitz   13264:     my $max_samples = 5;
                   13265:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13266:     $r->print(&start_data_table().
                   13267:               &start_data_table_header_row().'<th>'.
                   13268:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13269:               &end_data_table_header_row());
1.301     albertel 13270: 
                   13271:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13272: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13273: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13274: 	foreach my $option (@$d) {
                   13275: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13276: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13277:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13278:                       $display.'</option>');
1.31      albertel 13279: 	}
                   13280: 	$r->print('</select></td><td>');
1.662     bisitz   13281: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13282: 	    if (defined($samples->[$line]{$key})) { 
                   13283: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13284: 	    }
                   13285: 	}
1.594     raeburn  13286: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13287: 	$i++;
                   13288:     }
1.594     raeburn  13289:     $r->print(&end_data_table());
1.31      albertel 13290:     $i--;
                   13291:     return($i);
1.115     matthew  13292: }
                   13293: 
1.144     matthew  13294: ######################################################
                   13295: ######################################################
                   13296: 
1.115     matthew  13297: =pod
                   13298: 
1.648     raeburn  13299: =item * &clean_excel_name($name)
1.115     matthew  13300: 
                   13301: Returns a replacement for $name which does not contain any illegal characters.
                   13302: 
                   13303: =cut
                   13304: 
1.144     matthew  13305: ######################################################
                   13306: ######################################################
1.115     matthew  13307: sub clean_excel_name {
                   13308:     my ($name) = @_;
                   13309:     $name =~ s/[:\*\?\/\\]//g;
                   13310:     if (length($name) > 31) {
                   13311:         $name = substr($name,0,31);
                   13312:     }
                   13313:     return $name;
1.25      albertel 13314: }
1.84      albertel 13315: 
1.85      albertel 13316: =pod
                   13317: 
1.648     raeburn  13318: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13319: 
                   13320: Returns either 1 or undef
                   13321: 
                   13322: 1 if the part is to be hidden, undef if it is to be shown
                   13323: 
                   13324: Arguments are:
                   13325: 
                   13326: $id the id of the part to be checked
                   13327: $symb, optional the symb of the resource to check
                   13328: $udom, optional the domain of the user to check for
                   13329: $uname, optional the username of the user to check for
                   13330: 
                   13331: =cut
1.84      albertel 13332: 
                   13333: sub check_if_partid_hidden {
                   13334:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13335:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13336: 					 $symb,$udom,$uname);
1.141     albertel 13337:     my $truth=1;
                   13338:     #if the string starts with !, then the list is the list to show not hide
                   13339:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13340:     my @hiddenlist=split(/,/,$hiddenparts);
                   13341:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13342: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13343:     }
1.141     albertel 13344:     return !$truth;
1.84      albertel 13345: }
1.127     matthew  13346: 
1.138     matthew  13347: 
                   13348: ############################################################
                   13349: ############################################################
                   13350: 
                   13351: =pod
                   13352: 
1.157     matthew  13353: =back 
                   13354: 
1.138     matthew  13355: =head1 cgi-bin script and graphing routines
                   13356: 
1.157     matthew  13357: =over 4
                   13358: 
1.648     raeburn  13359: =item * &get_cgi_id()
1.138     matthew  13360: 
                   13361: Inputs: none
                   13362: 
                   13363: Returns an id which can be used to pass environment variables
                   13364: to various cgi-bin scripts.  These environment variables will
                   13365: be removed from the users environment after a given time by
                   13366: the routine &Apache::lonnet::transfer_profile_to_env.
                   13367: 
                   13368: =cut
                   13369: 
                   13370: ############################################################
                   13371: ############################################################
1.152     albertel 13372: my $uniq=0;
1.136     matthew  13373: sub get_cgi_id {
1.154     albertel 13374:     $uniq=($uniq+1)%100000;
1.280     albertel 13375:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13376: }
                   13377: 
1.127     matthew  13378: ############################################################
                   13379: ############################################################
                   13380: 
                   13381: =pod
                   13382: 
1.648     raeburn  13383: =item * &DrawBarGraph()
1.127     matthew  13384: 
1.138     matthew  13385: Facilitates the plotting of data in a (stacked) bar graph.
                   13386: Puts plot definition data into the users environment in order for 
                   13387: graph.png to plot it.  Returns an <img> tag for the plot.
                   13388: The bars on the plot are labeled '1','2',...,'n'.
                   13389: 
                   13390: Inputs:
                   13391: 
                   13392: =over 4
                   13393: 
                   13394: =item $Title: string, the title of the plot
                   13395: 
                   13396: =item $xlabel: string, text describing the X-axis of the plot
                   13397: 
                   13398: =item $ylabel: string, text describing the Y-axis of the plot
                   13399: 
                   13400: =item $Max: scalar, the maximum Y value to use in the plot
                   13401: If $Max is < any data point, the graph will not be rendered.
                   13402: 
1.140     matthew  13403: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13404: they are plotted.  If undefined, default values will be used.
                   13405: 
1.178     matthew  13406: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13407: 
1.138     matthew  13408: =item @Values: An array of array references.  Each array reference holds data
                   13409: to be plotted in a stacked bar chart.
                   13410: 
1.239     matthew  13411: =item If the final element of @Values is a hash reference the key/value
                   13412: pairs will be added to the graph definition.
                   13413: 
1.138     matthew  13414: =back
                   13415: 
                   13416: Returns:
                   13417: 
                   13418: An <img> tag which references graph.png and the appropriate identifying
                   13419: information for the plot.
                   13420: 
1.127     matthew  13421: =cut
                   13422: 
                   13423: ############################################################
                   13424: ############################################################
1.134     matthew  13425: sub DrawBarGraph {
1.178     matthew  13426:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13427:     #
                   13428:     if (! defined($colors)) {
                   13429:         $colors = ['#33ff00', 
                   13430:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13431:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13432:                   ]; 
                   13433:     }
1.228     matthew  13434:     my $extra_settings = {};
                   13435:     if (ref($Values[-1]) eq 'HASH') {
                   13436:         $extra_settings = pop(@Values);
                   13437:     }
1.127     matthew  13438:     #
1.136     matthew  13439:     my $identifier = &get_cgi_id();
                   13440:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13441:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13442:         return '';
                   13443:     }
1.225     matthew  13444:     #
                   13445:     my @Labels;
                   13446:     if (defined($labels)) {
                   13447:         @Labels = @$labels;
                   13448:     } else {
                   13449:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   13450:             push (@Labels,$i+1);
                   13451:         }
                   13452:     }
                   13453:     #
1.129     matthew  13454:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13455:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13456:     my %ValuesHash;
                   13457:     my $NumSets=1;
                   13458:     foreach my $array (@Values) {
                   13459:         next if (! ref($array));
1.136     matthew  13460:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13461:             join(',',@$array);
1.129     matthew  13462:     }
1.127     matthew  13463:     #
1.136     matthew  13464:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13465:     if ($NumBars < 3) {
                   13466:         $width = 120+$NumBars*32;
1.220     matthew  13467:         $xskip = 1;
1.225     matthew  13468:         $bar_width = 30;
                   13469:     } elsif ($NumBars < 5) {
                   13470:         $width = 120+$NumBars*20;
                   13471:         $xskip = 1;
                   13472:         $bar_width = 20;
1.220     matthew  13473:     } elsif ($NumBars < 10) {
1.136     matthew  13474:         $width = 120+$NumBars*15;
                   13475:         $xskip = 1;
                   13476:         $bar_width = 15;
                   13477:     } elsif ($NumBars <= 25) {
                   13478:         $width = 120+$NumBars*11;
                   13479:         $xskip = 5;
                   13480:         $bar_width = 8;
                   13481:     } elsif ($NumBars <= 50) {
                   13482:         $width = 120+$NumBars*8;
                   13483:         $xskip = 5;
                   13484:         $bar_width = 4;
                   13485:     } else {
                   13486:         $width = 120+$NumBars*8;
                   13487:         $xskip = 5;
                   13488:         $bar_width = 4;
                   13489:     }
                   13490:     #
1.137     matthew  13491:     $Max = 1 if ($Max < 1);
                   13492:     if ( int($Max) < $Max ) {
                   13493:         $Max++;
                   13494:         $Max = int($Max);
                   13495:     }
1.127     matthew  13496:     $Title  = '' if (! defined($Title));
                   13497:     $xlabel = '' if (! defined($xlabel));
                   13498:     $ylabel = '' if (! defined($ylabel));
1.369     www      13499:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13500:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13501:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13502:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13503:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13504:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13505:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13506:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13507:     $ValuesHash{$id.'.height'}   = $height;
                   13508:     $ValuesHash{$id.'.width'}    = $width;
                   13509:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13510:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13511:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13512:     #
1.228     matthew  13513:     # Deal with other parameters
                   13514:     while (my ($key,$value) = each(%$extra_settings)) {
                   13515:         $ValuesHash{$id.'.'.$key} = $value;
                   13516:     }
                   13517:     #
1.646     raeburn  13518:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13519:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13520: }
                   13521: 
                   13522: ############################################################
                   13523: ############################################################
                   13524: 
                   13525: =pod
                   13526: 
1.648     raeburn  13527: =item * &DrawXYGraph()
1.137     matthew  13528: 
1.138     matthew  13529: Facilitates the plotting of data in an XY graph.
                   13530: Puts plot definition data into the users environment in order for 
                   13531: graph.png to plot it.  Returns an <img> tag for the plot.
                   13532: 
                   13533: Inputs:
                   13534: 
                   13535: =over 4
                   13536: 
                   13537: =item $Title: string, the title of the plot
                   13538: 
                   13539: =item $xlabel: string, text describing the X-axis of the plot
                   13540: 
                   13541: =item $ylabel: string, text describing the Y-axis of the plot
                   13542: 
                   13543: =item $Max: scalar, the maximum Y value to use in the plot
                   13544: If $Max is < any data point, the graph will not be rendered.
                   13545: 
                   13546: =item $colors: Array ref containing the hex color codes for the data to be 
                   13547: plotted in.  If undefined, default values will be used.
                   13548: 
                   13549: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13550: 
                   13551: =item $Ydata: Array ref containing Array refs.  
1.185     www      13552: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13553: 
                   13554: =item %Values: hash indicating or overriding any default values which are 
                   13555: passed to graph.png.  
                   13556: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13557: 
                   13558: =back
                   13559: 
                   13560: Returns:
                   13561: 
                   13562: An <img> tag which references graph.png and the appropriate identifying
                   13563: information for the plot.
                   13564: 
1.137     matthew  13565: =cut
                   13566: 
                   13567: ############################################################
                   13568: ############################################################
                   13569: sub DrawXYGraph {
                   13570:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13571:     #
                   13572:     # Create the identifier for the graph
                   13573:     my $identifier = &get_cgi_id();
                   13574:     my $id = 'cgi.'.$identifier;
                   13575:     #
                   13576:     $Title  = '' if (! defined($Title));
                   13577:     $xlabel = '' if (! defined($xlabel));
                   13578:     $ylabel = '' if (! defined($ylabel));
                   13579:     my %ValuesHash = 
                   13580:         (
1.369     www      13581:          $id.'.title'  => &escape($Title),
                   13582:          $id.'.xlabel' => &escape($xlabel),
                   13583:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13584:          $id.'.y_max_value'=> $Max,
                   13585:          $id.'.labels'     => join(',',@$Xlabels),
                   13586:          $id.'.PlotType'   => 'XY',
                   13587:          );
                   13588:     #
                   13589:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13590:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13591:     }
                   13592:     #
                   13593:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13594:         return '';
                   13595:     }
                   13596:     my $NumSets=1;
1.138     matthew  13597:     foreach my $array (@{$Ydata}){
1.137     matthew  13598:         next if (! ref($array));
                   13599:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13600:     }
1.138     matthew  13601:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  13602:     #
                   13603:     # Deal with other parameters
                   13604:     while (my ($key,$value) = each(%Values)) {
                   13605:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  13606:     }
                   13607:     #
1.646     raeburn  13608:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  13609:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13610: }
                   13611: 
                   13612: ############################################################
                   13613: ############################################################
                   13614: 
                   13615: =pod
                   13616: 
1.648     raeburn  13617: =item * &DrawXYYGraph()
1.138     matthew  13618: 
                   13619: Facilitates the plotting of data in an XY graph with two Y axes.
                   13620: Puts plot definition data into the users environment in order for 
                   13621: graph.png to plot it.  Returns an <img> tag for the plot.
                   13622: 
                   13623: Inputs:
                   13624: 
                   13625: =over 4
                   13626: 
                   13627: =item $Title: string, the title of the plot
                   13628: 
                   13629: =item $xlabel: string, text describing the X-axis of the plot
                   13630: 
                   13631: =item $ylabel: string, text describing the Y-axis of the plot
                   13632: 
                   13633: =item $colors: Array ref containing the hex color codes for the data to be 
                   13634: plotted in.  If undefined, default values will be used.
                   13635: 
                   13636: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13637: 
                   13638: =item $Ydata1: The first data set
                   13639: 
                   13640: =item $Min1: The minimum value of the left Y-axis
                   13641: 
                   13642: =item $Max1: The maximum value of the left Y-axis
                   13643: 
                   13644: =item $Ydata2: The second data set
                   13645: 
                   13646: =item $Min2: The minimum value of the right Y-axis
                   13647: 
                   13648: =item $Max2: The maximum value of the left Y-axis
                   13649: 
                   13650: =item %Values: hash indicating or overriding any default values which are 
                   13651: passed to graph.png.  
                   13652: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13653: 
                   13654: =back
                   13655: 
                   13656: Returns:
                   13657: 
                   13658: An <img> tag which references graph.png and the appropriate identifying
                   13659: information for the plot.
1.136     matthew  13660: 
                   13661: =cut
                   13662: 
                   13663: ############################################################
                   13664: ############################################################
1.137     matthew  13665: sub DrawXYYGraph {
                   13666:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   13667:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  13668:     #
                   13669:     # Create the identifier for the graph
                   13670:     my $identifier = &get_cgi_id();
                   13671:     my $id = 'cgi.'.$identifier;
                   13672:     #
                   13673:     $Title  = '' if (! defined($Title));
                   13674:     $xlabel = '' if (! defined($xlabel));
                   13675:     $ylabel = '' if (! defined($ylabel));
                   13676:     my %ValuesHash = 
                   13677:         (
1.369     www      13678:          $id.'.title'  => &escape($Title),
                   13679:          $id.'.xlabel' => &escape($xlabel),
                   13680:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  13681:          $id.'.labels' => join(',',@$Xlabels),
                   13682:          $id.'.PlotType' => 'XY',
                   13683:          $id.'.NumSets' => 2,
1.137     matthew  13684:          $id.'.two_axes' => 1,
                   13685:          $id.'.y1_max_value' => $Max1,
                   13686:          $id.'.y1_min_value' => $Min1,
                   13687:          $id.'.y2_max_value' => $Max2,
                   13688:          $id.'.y2_min_value' => $Min2,
1.136     matthew  13689:          );
                   13690:     #
1.137     matthew  13691:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13692:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13693:     }
                   13694:     #
                   13695:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   13696:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  13697:         return '';
                   13698:     }
                   13699:     my $NumSets=1;
1.137     matthew  13700:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  13701:         next if (! ref($array));
                   13702:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  13703:     }
                   13704:     #
                   13705:     # Deal with other parameters
                   13706:     while (my ($key,$value) = each(%Values)) {
                   13707:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  13708:     }
                   13709:     #
1.646     raeburn  13710:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 13711:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  13712: }
                   13713: 
                   13714: ############################################################
                   13715: ############################################################
                   13716: 
                   13717: =pod
                   13718: 
1.157     matthew  13719: =back 
                   13720: 
1.139     matthew  13721: =head1 Statistics helper routines?  
                   13722: 
                   13723: Bad place for them but what the hell.
                   13724: 
1.157     matthew  13725: =over 4
                   13726: 
1.648     raeburn  13727: =item * &chartlink()
1.139     matthew  13728: 
                   13729: Returns a link to the chart for a specific student.  
                   13730: 
                   13731: Inputs:
                   13732: 
                   13733: =over 4
                   13734: 
                   13735: =item $linktext: The text of the link
                   13736: 
                   13737: =item $sname: The students username
                   13738: 
                   13739: =item $sdomain: The students domain
                   13740: 
                   13741: =back
                   13742: 
1.157     matthew  13743: =back
                   13744: 
1.139     matthew  13745: =cut
                   13746: 
                   13747: ############################################################
                   13748: ############################################################
                   13749: sub chartlink {
                   13750:     my ($linktext, $sname, $sdomain) = @_;
                   13751:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      13752:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 13753:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  13754:        '">'.$linktext.'</a>';
1.153     matthew  13755: }
                   13756: 
                   13757: #######################################################
                   13758: #######################################################
                   13759: 
                   13760: =pod
                   13761: 
                   13762: =head1 Course Environment Routines
1.157     matthew  13763: 
                   13764: =over 4
1.153     matthew  13765: 
1.648     raeburn  13766: =item * &restore_course_settings()
1.153     matthew  13767: 
1.648     raeburn  13768: =item * &store_course_settings()
1.153     matthew  13769: 
                   13770: Restores/Store indicated form parameters from the course environment.
                   13771: Will not overwrite existing values of the form parameters.
                   13772: 
                   13773: Inputs: 
                   13774: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   13775: 
                   13776: a hash ref describing the data to be stored.  For example:
                   13777:    
                   13778: %Save_Parameters = ('Status' => 'scalar',
                   13779:     'chartoutputmode' => 'scalar',
                   13780:     'chartoutputdata' => 'scalar',
                   13781:     'Section' => 'array',
1.373     raeburn  13782:     'Group' => 'array',
1.153     matthew  13783:     'StudentData' => 'array',
                   13784:     'Maps' => 'array');
                   13785: 
                   13786: Returns: both routines return nothing
                   13787: 
1.631     raeburn  13788: =back
                   13789: 
1.153     matthew  13790: =cut
                   13791: 
                   13792: #######################################################
                   13793: #######################################################
                   13794: sub store_course_settings {
1.496     albertel 13795:     return &store_settings($env{'request.course.id'},@_);
                   13796: }
                   13797: 
                   13798: sub store_settings {
1.153     matthew  13799:     # save to the environment
                   13800:     # appenv the same items, just to be safe
1.300     albertel 13801:     my $udom  = $env{'user.domain'};
                   13802:     my $uname = $env{'user.name'};
1.496     albertel 13803:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13804:     my %SaveHash;
                   13805:     my %AppHash;
                   13806:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 13807:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 13808:         my $envname = 'environment.'.$basename;
1.258     albertel 13809:         if (exists($env{'form.'.$setting})) {
1.153     matthew  13810:             # Save this value away
                   13811:             if ($type eq 'scalar' &&
1.258     albertel 13812:                 (! exists($env{$envname}) || 
                   13813:                  $env{$envname} ne $env{'form.'.$setting})) {
                   13814:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   13815:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  13816:             } elsif ($type eq 'array') {
                   13817:                 my $stored_form;
1.258     albertel 13818:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  13819:                     $stored_form = join(',',
                   13820:                                         map {
1.369     www      13821:                                             &escape($_);
1.258     albertel 13822:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  13823:                 } else {
                   13824:                     $stored_form = 
1.369     www      13825:                         &escape($env{'form.'.$setting});
1.153     matthew  13826:                 }
                   13827:                 # Determine if the array contents are the same.
1.258     albertel 13828:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  13829:                     $SaveHash{$basename} = $stored_form;
                   13830:                     $AppHash{$envname}   = $stored_form;
                   13831:                 }
                   13832:             }
                   13833:         }
                   13834:     }
                   13835:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 13836:                                           $udom,$uname);
1.153     matthew  13837:     if ($put_result !~ /^(ok|delayed)/) {
                   13838:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   13839:                                  'got error:'.$put_result);
                   13840:     }
                   13841:     # Make sure these settings stick around in this session, too
1.646     raeburn  13842:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  13843:     return;
                   13844: }
                   13845: 
                   13846: sub restore_course_settings {
1.499     albertel 13847:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 13848: }
                   13849: 
                   13850: sub restore_settings {
                   13851:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13852:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 13853:         next if (exists($env{'form.'.$setting}));
1.496     albertel 13854:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  13855:             '.'.$setting;
1.258     albertel 13856:         if (exists($env{$envname})) {
1.153     matthew  13857:             if ($type eq 'scalar') {
1.258     albertel 13858:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  13859:             } elsif ($type eq 'array') {
1.258     albertel 13860:                 $env{'form.'.$setting} = [ 
1.153     matthew  13861:                                            map { 
1.369     www      13862:                                                &unescape($_); 
1.258     albertel 13863:                                            } split(',',$env{$envname})
1.153     matthew  13864:                                            ];
                   13865:             }
                   13866:         }
                   13867:     }
1.127     matthew  13868: }
                   13869: 
1.618     raeburn  13870: #######################################################
                   13871: #######################################################
                   13872: 
                   13873: =pod
                   13874: 
                   13875: =head1 Domain E-mail Routines  
                   13876: 
                   13877: =over 4
                   13878: 
1.648     raeburn  13879: =item * &build_recipient_list()
1.618     raeburn  13880: 
1.1075.2.44  raeburn  13881: Build recipient lists for following types of e-mail:
1.766     raeburn  13882: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  13883: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   13884: module change checking, student/employee ID conflict checks, as
                   13885: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   13886: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  13887: 
                   13888: Inputs:
1.1075.2.44  raeburn  13889: defmail (scalar - email address of default recipient),
                   13890: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   13891: requestsmail, updatesmail, or idconflictsmail).
                   13892: 
1.619     raeburn  13893: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  13894: 
                   13895: origmail (scalar - email address of recipient from loncapa.conf,
                   13896: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  13897: 
1.655     raeburn  13898: Returns: comma separated list of addresses to which to send e-mail.
                   13899: 
                   13900: =back
1.618     raeburn  13901: 
                   13902: =cut
                   13903: 
                   13904: ############################################################
                   13905: ############################################################
                   13906: sub build_recipient_list {
1.619     raeburn  13907:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  13908:     my @recipients;
                   13909:     my $otheremails;
                   13910:     my %domconfig =
                   13911:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   13912:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  13913:         if (exists($domconfig{'contacts'}{$mailing})) {
                   13914:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   13915:                 my @contacts = ('adminemail','supportemail');
                   13916:                 foreach my $item (@contacts) {
                   13917:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   13918:                         my $addr = $domconfig{'contacts'}{$item}; 
                   13919:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13920:                             push(@recipients,$addr);
                   13921:                         }
1.619     raeburn  13922:                     }
1.766     raeburn  13923:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  13924:                 }
                   13925:             }
1.766     raeburn  13926:         } elsif ($origmail ne '') {
                   13927:             push(@recipients,$origmail);
1.618     raeburn  13928:         }
1.619     raeburn  13929:     } elsif ($origmail ne '') {
                   13930:         push(@recipients,$origmail);
1.618     raeburn  13931:     }
1.688     raeburn  13932:     if (defined($defmail)) {
                   13933:         if ($defmail ne '') {
                   13934:             push(@recipients,$defmail);
                   13935:         }
1.618     raeburn  13936:     }
                   13937:     if ($otheremails) {
1.619     raeburn  13938:         my @others;
                   13939:         if ($otheremails =~ /,/) {
                   13940:             @others = split(/,/,$otheremails);
1.618     raeburn  13941:         } else {
1.619     raeburn  13942:             push(@others,$otheremails);
                   13943:         }
                   13944:         foreach my $addr (@others) {
                   13945:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13946:                 push(@recipients,$addr);
                   13947:             }
1.618     raeburn  13948:         }
                   13949:     }
1.619     raeburn  13950:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  13951:     return $recipientlist;
                   13952: }
                   13953: 
1.127     matthew  13954: ############################################################
                   13955: ############################################################
1.154     albertel 13956: 
1.655     raeburn  13957: =pod
                   13958: 
                   13959: =head1 Course Catalog Routines
                   13960: 
                   13961: =over 4
                   13962: 
                   13963: =item * &gather_categories()
                   13964: 
                   13965: Converts category definitions - keys of categories hash stored in  
                   13966: coursecategories in configuration.db on the primary library server in a 
                   13967: domain - to an array.  Also generates javascript and idx hash used to 
                   13968: generate Domain Coordinator interface for editing Course Categories.
                   13969: 
                   13970: Inputs:
1.663     raeburn  13971: 
1.655     raeburn  13972: categories (reference to hash of category definitions).
1.663     raeburn  13973: 
1.655     raeburn  13974: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13975:       categories and subcategories).
1.663     raeburn  13976: 
1.655     raeburn  13977: idx (reference to hash of counters used in Domain Coordinator interface for 
                   13978:       editing Course Categories).
1.663     raeburn  13979: 
1.655     raeburn  13980: jsarray (reference to array of categories used to create Javascript arrays for
                   13981:          Domain Coordinator interface for editing Course Categories).
                   13982: 
                   13983: Returns: nothing
                   13984: 
                   13985: Side effects: populates cats, idx and jsarray. 
                   13986: 
                   13987: =cut
                   13988: 
                   13989: sub gather_categories {
                   13990:     my ($categories,$cats,$idx,$jsarray) = @_;
                   13991:     my %counters;
                   13992:     my $num = 0;
                   13993:     foreach my $item (keys(%{$categories})) {
                   13994:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   13995:         if ($container eq '' && $depth == 0) {
                   13996:             $cats->[$depth][$categories->{$item}] = $cat;
                   13997:         } else {
                   13998:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   13999:         }
                   14000:         my ($escitem,$tail) = split(/:/,$item,2);
                   14001:         if ($counters{$tail} eq '') {
                   14002:             $counters{$tail} = $num;
                   14003:             $num ++;
                   14004:         }
                   14005:         if (ref($idx) eq 'HASH') {
                   14006:             $idx->{$item} = $counters{$tail};
                   14007:         }
                   14008:         if (ref($jsarray) eq 'ARRAY') {
                   14009:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14010:         }
                   14011:     }
                   14012:     return;
                   14013: }
                   14014: 
                   14015: =pod
                   14016: 
                   14017: =item * &extract_categories()
                   14018: 
                   14019: Used to generate breadcrumb trails for course categories.
                   14020: 
                   14021: Inputs:
1.663     raeburn  14022: 
1.655     raeburn  14023: categories (reference to hash of category definitions).
1.663     raeburn  14024: 
1.655     raeburn  14025: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14026:       categories and subcategories).
1.663     raeburn  14027: 
1.655     raeburn  14028: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14029: 
1.655     raeburn  14030: allitems (reference to hash - key is category key 
                   14031:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14032: 
1.655     raeburn  14033: idx (reference to hash of counters used in Domain Coordinator interface for
                   14034:       editing Course Categories).
1.663     raeburn  14035: 
1.655     raeburn  14036: jsarray (reference to array of categories used to create Javascript arrays for
                   14037:          Domain Coordinator interface for editing Course Categories).
                   14038: 
1.665     raeburn  14039: subcats (reference to hash of arrays containing all subcategories within each 
                   14040:          category, -recursive)
                   14041: 
1.655     raeburn  14042: Returns: nothing
                   14043: 
                   14044: Side effects: populates trails and allitems hash references.
                   14045: 
                   14046: =cut
                   14047: 
                   14048: sub extract_categories {
1.665     raeburn  14049:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  14050:     if (ref($categories) eq 'HASH') {
                   14051:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14052:         if (ref($cats->[0]) eq 'ARRAY') {
                   14053:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14054:                 my $name = $cats->[0][$i];
                   14055:                 my $item = &escape($name).'::0';
                   14056:                 my $trailstr;
                   14057:                 if ($name eq 'instcode') {
                   14058:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14059:                 } elsif ($name eq 'communities') {
                   14060:                     $trailstr = &mt('Communities');
1.655     raeburn  14061:                 } else {
                   14062:                     $trailstr = $name;
                   14063:                 }
                   14064:                 if ($allitems->{$item} eq '') {
                   14065:                     push(@{$trails},$trailstr);
                   14066:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14067:                 }
                   14068:                 my @parents = ($name);
                   14069:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14070:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14071:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14072:                         if (ref($subcats) eq 'HASH') {
                   14073:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14074:                         }
                   14075:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   14076:                     }
                   14077:                 } else {
                   14078:                     if (ref($subcats) eq 'HASH') {
                   14079:                         $subcats->{$item} = [];
1.655     raeburn  14080:                     }
                   14081:                 }
                   14082:             }
                   14083:         }
                   14084:     }
                   14085:     return;
                   14086: }
                   14087: 
                   14088: =pod
                   14089: 
1.1075.2.56  raeburn  14090: =item * &recurse_categories()
1.655     raeburn  14091: 
                   14092: Recursively used to generate breadcrumb trails for course categories.
                   14093: 
                   14094: Inputs:
1.663     raeburn  14095: 
1.655     raeburn  14096: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14097:       categories and subcategories).
1.663     raeburn  14098: 
1.655     raeburn  14099: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14100: 
                   14101: category (current course category, for which breadcrumb trail is being generated).
                   14102: 
                   14103: trails (reference to array of breadcrumb trails for each category).
                   14104: 
1.655     raeburn  14105: allitems (reference to hash - key is category key
                   14106:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14107: 
1.655     raeburn  14108: parents (array containing containers directories for current category, 
                   14109:          back to top level). 
                   14110: 
                   14111: Returns: nothing
                   14112: 
                   14113: Side effects: populates trails and allitems hash references
                   14114: 
                   14115: =cut
                   14116: 
                   14117: sub recurse_categories {
1.665     raeburn  14118:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  14119:     my $shallower = $depth - 1;
                   14120:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14121:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14122:             my $name = $cats->[$depth]{$category}[$k];
                   14123:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14124:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14125:             if ($allitems->{$item} eq '') {
                   14126:                 push(@{$trails},$trailstr);
                   14127:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14128:             }
                   14129:             my $deeper = $depth+1;
                   14130:             push(@{$parents},$category);
1.665     raeburn  14131:             if (ref($subcats) eq 'HASH') {
                   14132:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14133:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14134:                     my $higher;
                   14135:                     if ($j > 0) {
                   14136:                         $higher = &escape($parents->[$j]).':'.
                   14137:                                   &escape($parents->[$j-1]).':'.$j;
                   14138:                     } else {
                   14139:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14140:                     }
                   14141:                     push(@{$subcats->{$higher}},$subcat);
                   14142:                 }
                   14143:             }
                   14144:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   14145:                                 $subcats);
1.655     raeburn  14146:             pop(@{$parents});
                   14147:         }
                   14148:     } else {
                   14149:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14150:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14151:         if ($allitems->{$item} eq '') {
                   14152:             push(@{$trails},$trailstr);
                   14153:             $allitems->{$item} = scalar(@{$trails})-1;
                   14154:         }
                   14155:     }
                   14156:     return;
                   14157: }
                   14158: 
1.663     raeburn  14159: =pod
                   14160: 
1.1075.2.56  raeburn  14161: =item * &assign_categories_table()
1.663     raeburn  14162: 
                   14163: Create a datatable for display of hierarchical categories in a domain,
                   14164: with checkboxes to allow a course to be categorized. 
                   14165: 
                   14166: Inputs:
                   14167: 
                   14168: cathash - reference to hash of categories defined for the domain (from
                   14169:           configuration.db)
                   14170: 
                   14171: currcat - scalar with an & separated list of categories assigned to a course. 
                   14172: 
1.919     raeburn  14173: type    - scalar contains course type (Course or Community).
                   14174: 
1.663     raeburn  14175: Returns: $output (markup to be displayed) 
                   14176: 
                   14177: =cut
                   14178: 
                   14179: sub assign_categories_table {
1.919     raeburn  14180:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  14181:     my $output;
                   14182:     if (ref($cathash) eq 'HASH') {
                   14183:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   14184:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   14185:         $maxdepth = scalar(@cats);
                   14186:         if (@cats > 0) {
                   14187:             my $itemcount = 0;
                   14188:             if (ref($cats[0]) eq 'ARRAY') {
                   14189:                 my @currcategories;
                   14190:                 if ($currcat ne '') {
                   14191:                     @currcategories = split('&',$currcat);
                   14192:                 }
1.919     raeburn  14193:                 my $table;
1.663     raeburn  14194:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14195:                     my $parent = $cats[0][$i];
1.919     raeburn  14196:                     next if ($parent eq 'instcode');
                   14197:                     if ($type eq 'Community') {
                   14198:                         next unless ($parent eq 'communities');
                   14199:                     } else {
                   14200:                         next if ($parent eq 'communities');
                   14201:                     }
1.663     raeburn  14202:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14203:                     my $item = &escape($parent).'::0';
                   14204:                     my $checked = '';
                   14205:                     if (@currcategories > 0) {
                   14206:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14207:                             $checked = ' checked="checked"';
1.663     raeburn  14208:                         }
                   14209:                     }
1.919     raeburn  14210:                     my $parent_title = $parent;
                   14211:                     if ($parent eq 'communities') {
                   14212:                         $parent_title = &mt('Communities');
                   14213:                     }
                   14214:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14215:                               '<input type="checkbox" name="usecategory" value="'.
                   14216:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   14217:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14218:                     my $depth = 1;
                   14219:                     push(@path,$parent);
1.919     raeburn  14220:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  14221:                     pop(@path);
1.919     raeburn  14222:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14223:                     $itemcount ++;
                   14224:                 }
1.919     raeburn  14225:                 if ($itemcount) {
                   14226:                     $output = &Apache::loncommon::start_data_table().
                   14227:                               $table.
                   14228:                               &Apache::loncommon::end_data_table();
                   14229:                 }
1.663     raeburn  14230:             }
                   14231:         }
                   14232:     }
                   14233:     return $output;
                   14234: }
                   14235: 
                   14236: =pod
                   14237: 
1.1075.2.56  raeburn  14238: =item * &assign_category_rows()
1.663     raeburn  14239: 
                   14240: Create a datatable row for display of nested categories in a domain,
                   14241: with checkboxes to allow a course to be categorized,called recursively.
                   14242: 
                   14243: Inputs:
                   14244: 
                   14245: itemcount - track row number for alternating colors
                   14246: 
                   14247: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14248:       categories and subcategories.
                   14249: 
                   14250: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14251: 
                   14252: parent - parent of current category item
                   14253: 
                   14254: path - Array containing all categories back up through the hierarchy from the
                   14255:        current category to the top level.
                   14256: 
                   14257: currcategories - reference to array of current categories assigned to the course
                   14258: 
                   14259: Returns: $output (markup to be displayed).
                   14260: 
                   14261: =cut
                   14262: 
                   14263: sub assign_category_rows {
                   14264:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   14265:     my ($text,$name,$item,$chgstr);
                   14266:     if (ref($cats) eq 'ARRAY') {
                   14267:         my $maxdepth = scalar(@{$cats});
                   14268:         if (ref($cats->[$depth]) eq 'HASH') {
                   14269:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14270:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14271:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  14272:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14273:                 for (my $j=0; $j<$numchildren; $j++) {
                   14274:                     $name = $cats->[$depth]{$parent}[$j];
                   14275:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14276:                     my $deeper = $depth+1;
                   14277:                     my $checked = '';
                   14278:                     if (ref($currcategories) eq 'ARRAY') {
                   14279:                         if (@{$currcategories} > 0) {
                   14280:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14281:                                 $checked = ' checked="checked"';
1.663     raeburn  14282:                             }
                   14283:                         }
                   14284:                     }
1.664     raeburn  14285:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14286:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  14287:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   14288:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14289:                              '</td><td>';
1.663     raeburn  14290:                     if (ref($path) eq 'ARRAY') {
                   14291:                         push(@{$path},$name);
                   14292:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   14293:                         pop(@{$path});
                   14294:                     }
                   14295:                     $text .= '</td></tr>';
                   14296:                 }
                   14297:                 $text .= '</table></td>';
                   14298:             }
                   14299:         }
                   14300:     }
                   14301:     return $text;
                   14302: }
                   14303: 
1.1075.2.69  raeburn  14304: =pod
                   14305: 
                   14306: =back
                   14307: 
                   14308: =cut
                   14309: 
1.655     raeburn  14310: ############################################################
                   14311: ############################################################
                   14312: 
                   14313: 
1.443     albertel 14314: sub commit_customrole {
1.664     raeburn  14315:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14316:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14317:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14318:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14319:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14320:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14321:                  '</b><br />';
                   14322:     return $output;
                   14323: }
                   14324: 
                   14325: sub commit_standardrole {
1.1075.2.31  raeburn  14326:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14327:     my ($output,$logmsg,$linefeed);
                   14328:     if ($context eq 'auto') {
                   14329:         $linefeed = "\n";
                   14330:     } else {
                   14331:         $linefeed = "<br />\n";
                   14332:     }  
1.443     albertel 14333:     if ($three eq 'st') {
1.541     raeburn  14334:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  14335:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14336:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14337:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14338:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14339:         } else {
1.541     raeburn  14340:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14341:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14342:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14343:             if ($context eq 'auto') {
                   14344:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14345:             } else {
                   14346:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14347:                &mt('Add to classlist').': <b>ok</b>';
                   14348:             }
                   14349:             $output .= $linefeed;
1.443     albertel 14350:         }
                   14351:     } else {
                   14352:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14353:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14354:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14355:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14356:         if ($context eq 'auto') {
                   14357:             $output .= $result.$linefeed;
                   14358:         } else {
                   14359:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14360:         }
1.443     albertel 14361:     }
                   14362:     return $output;
                   14363: }
                   14364: 
                   14365: sub commit_studentrole {
1.1075.2.31  raeburn  14366:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14367:         $credits) = @_;
1.626     raeburn  14368:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  14369:     if ($context eq 'auto') {
                   14370:         $linefeed = "\n";
                   14371:     } else {
                   14372:         $linefeed = '<br />'."\n";
                   14373:     }
1.443     albertel 14374:     if (defined($one) && defined($two)) {
                   14375:         my $cid=$one.'_'.$two;
                   14376:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   14377:         my $secchange = 0;
                   14378:         my $expire_role_result;
                   14379:         my $modify_section_result;
1.628     raeburn  14380:         if ($oldsec ne '-1') { 
                   14381:             if ($oldsec ne $sec) {
1.443     albertel 14382:                 $secchange = 1;
1.628     raeburn  14383:                 my $now = time;
1.443     albertel 14384:                 my $uurl='/'.$cid;
                   14385:                 $uurl=~s/\_/\//g;
                   14386:                 if ($oldsec) {
                   14387:                     $uurl.='/'.$oldsec;
                   14388:                 }
1.626     raeburn  14389:                 $oldsecurl = $uurl;
1.628     raeburn  14390:                 $expire_role_result = 
1.652     raeburn  14391:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  14392:                 if ($env{'request.course.sec'} ne '') { 
                   14393:                     if ($expire_role_result eq 'refused') {
                   14394:                         my @roles = ('st');
                   14395:                         my @statuses = ('previous');
                   14396:                         my @roledoms = ($one);
                   14397:                         my $withsec = 1;
                   14398:                         my %roleshash = 
                   14399:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   14400:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   14401:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   14402:                             my ($oldstart,$oldend) = 
                   14403:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   14404:                             if ($oldend > 0 && $oldend <= $now) {
                   14405:                                 $expire_role_result = 'ok';
                   14406:                             }
                   14407:                         }
                   14408:                     }
                   14409:                 }
1.443     albertel 14410:                 $result = $expire_role_result;
                   14411:             }
                   14412:         }
                   14413:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  14414:             $modify_section_result = 
                   14415:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   14416:                                                            undef,undef,undef,$sec,
                   14417:                                                            $end,$start,'','',$cid,
                   14418:                                                            '',$context,$credits);
1.443     albertel 14419:             if ($modify_section_result =~ /^ok/) {
                   14420:                 if ($secchange == 1) {
1.628     raeburn  14421:                     if ($sec eq '') {
                   14422:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   14423:                     } else {
                   14424:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   14425:                     }
1.443     albertel 14426:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  14427:                     if ($sec eq '') {
                   14428:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   14429:                     } else {
                   14430:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14431:                     }
1.443     albertel 14432:                 } else {
1.628     raeburn  14433:                     if ($sec eq '') {
                   14434:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   14435:                     } else {
                   14436:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14437:                     }
1.443     albertel 14438:                 }
                   14439:             } else {
1.628     raeburn  14440:                 if ($secchange) {       
                   14441:                     $$logmsg .= &mt('Error when attempting section change for [_1] from old section "[_2]" to new section: "[_3]" in course [_4] -error:',$uname,$oldsec,$sec,$cid).' '.$modify_section_result.$linefeed;
                   14442:                 } else {
                   14443:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   14444:                 }
1.443     albertel 14445:             }
                   14446:             $result = $modify_section_result;
                   14447:         } elsif ($secchange == 1) {
1.628     raeburn  14448:             if ($oldsec eq '') {
1.1075.2.20  raeburn  14449:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
1.628     raeburn  14450:             } else {
                   14451:                 $$logmsg .= &mt('Error when attempting to expire existing role for [_1] in section [_2] in course [_3] -error: ',$uname,$oldsec,$cid).' '.$expire_role_result.$linefeed;
                   14452:             }
1.626     raeburn  14453:             if ($expire_role_result eq 'refused') {
                   14454:                 my $newsecurl = '/'.$cid;
                   14455:                 $newsecurl =~ s/\_/\//g;
                   14456:                 if ($sec ne '') {
                   14457:                     $newsecurl.='/'.$sec;
                   14458:                 }
                   14459:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   14460:                     if ($sec eq '') {
                   14461:                         $$logmsg .= &mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments unaffiliated with any section.',$sec).$linefeed;
                   14462:                     } else {
                   14463:                         $$logmsg .= &mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments in other sections.',$sec).$linefeed;
                   14464:                     }
                   14465:                 }
                   14466:             }
1.443     albertel 14467:         }
                   14468:     } else {
1.626     raeburn  14469:         $$logmsg .= &mt('Incomplete course id defined.').$linefeed.&mt('Addition of user [_1] from domain [_2] to course [_3], section [_4] not completed.',$uname,$udom,$one.'_'.$two,$sec).$linefeed;
1.443     albertel 14470:         $result = "error: incomplete course id\n";
                   14471:     }
                   14472:     return $result;
                   14473: }
                   14474: 
1.1075.2.25  raeburn  14475: sub show_role_extent {
                   14476:     my ($scope,$context,$role) = @_;
                   14477:     $scope =~ s{^/}{};
                   14478:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   14479:     push(@courseroles,'co');
                   14480:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   14481:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   14482:         $scope =~ s{/}{_};
                   14483:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   14484:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   14485:         my ($audom,$auname) = split(/\//,$scope);
                   14486:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   14487:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   14488:     } else {
                   14489:         $scope =~ s{/$}{};
                   14490:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   14491:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   14492:     }
                   14493: }
                   14494: 
1.443     albertel 14495: ############################################################
                   14496: ############################################################
                   14497: 
1.566     albertel 14498: sub check_clone {
1.578     raeburn  14499:     my ($args,$linefeed) = @_;
1.566     albertel 14500:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   14501:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   14502:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   14503:     my $clonemsg;
                   14504:     my $can_clone = 0;
1.944     raeburn  14505:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  14506:     if ($lctype ne 'community') {
                   14507:         $lctype = 'course';
                   14508:     }
1.566     albertel 14509:     if ($clonehome eq 'no_host') {
1.944     raeburn  14510:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14511:             $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
                   14512:         } else {
                   14513:             $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
                   14514:         }     
1.566     albertel 14515:     } else {
                   14516: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  14517:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14518:             if ($clonedesc{'type'} ne 'Community') {
                   14519:                  $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
                   14520:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14521:             }
                   14522:         }
1.882     raeburn  14523: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   14524:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 14525: 	    $can_clone = 1;
                   14526: 	} else {
1.1075.2.95  raeburn  14527: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 14528: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  14529:             if ($clonehash{'cloners'} eq '') {
                   14530:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   14531:                 if ($domdefs{'canclone'}) {
                   14532:                     unless ($domdefs{'canclone'} eq 'none') {
                   14533:                         if ($domdefs{'canclone'} eq 'domain') {
                   14534:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   14535:                                 $can_clone = 1;
                   14536:                             }
                   14537:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   14538:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   14539:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   14540:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   14541:                                 $can_clone = 1;
                   14542:                             }
                   14543:                         }
                   14544:                     }
1.908     raeburn  14545:                 }
1.1075.2.95  raeburn  14546:             } else {
                   14547: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   14548:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  14549:                     $can_clone = 1;
1.1075.2.95  raeburn  14550:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  14551:                     $can_clone = 1;
1.1075.2.96  raeburn  14552:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   14553:                     $can_clone = 1;
1.1075.2.95  raeburn  14554:                 }
                   14555:                 unless ($can_clone) {
1.1075.2.96  raeburn  14556:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   14557:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  14558:                         my (%gotdomdefaults,%gotcodedefaults);
                   14559:                         foreach my $cloner (@cloners) {
                   14560:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   14561:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   14562:                                 my (%codedefaults,@code_order);
                   14563:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   14564:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   14565:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   14566:                                     }
                   14567:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   14568:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   14569:                                     }
                   14570:                                 } else {
                   14571:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   14572:                                                                             \%codedefaults,
                   14573:                                                                             \@code_order);
                   14574:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   14575:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   14576:                                 }
                   14577:                                 if (@code_order > 0) {
                   14578:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   14579:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   14580:                                                                                 $args->{'crscode'})) {
                   14581:                                         $can_clone = 1;
                   14582:                                         last;
                   14583:                                     }
                   14584:                                 }
                   14585:                             }
                   14586:                         }
                   14587:                     }
1.1075.2.96  raeburn  14588:                 }
                   14589:             }
                   14590:             unless ($can_clone) {
                   14591:                 my $ccrole = 'cc';
                   14592:                 if ($args->{'crstype'} eq 'Community') {
                   14593:                     $ccrole = 'co';
                   14594:                 }
                   14595:                 my %roleshash =
                   14596:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   14597:                                                   $args->{'ccdomain'},
                   14598:                                                   'userroles',['active'],[$ccrole],
                   14599:                                                   [$args->{'clonedomain'}]);
                   14600:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   14601:                     $can_clone = 1;
                   14602:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   14603:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   14604:                     $can_clone = 1;
1.1075.2.95  raeburn  14605:                 }
                   14606:             }
                   14607:             unless ($can_clone) {
                   14608:                 if ($args->{'crstype'} eq 'Community') {
                   14609:                     $clonemsg = &mt('No new community created.').$linefeed.&mt('The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
                   14610:                 } else {
                   14611:                     $clonemsg = &mt('No new course created.').$linefeed.&mt('The new course could not be cloned from the existing course because the new course owner ([_1]) does not have cloning rights in the existing course ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
1.578     raeburn  14612: 	        }
1.566     albertel 14613: 	    }
1.578     raeburn  14614:         }
1.566     albertel 14615:     }
                   14616:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14617: }
                   14618: 
1.444     albertel 14619: sub construct_course {
1.1075.2.59  raeburn  14620:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
1.444     albertel 14621:     my $outcome;
1.541     raeburn  14622:     my $linefeed =  '<br />'."\n";
                   14623:     if ($context eq 'auto') {
                   14624:         $linefeed = "\n";
                   14625:     }
1.566     albertel 14626: 
                   14627: #
                   14628: # Are we cloning?
                   14629: #
                   14630:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14631:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  14632: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 14633: 	if ($context ne 'auto') {
1.578     raeburn  14634:             if ($clonemsg ne '') {
                   14635: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   14636:             }
1.566     albertel 14637: 	}
                   14638: 	$outcome .= $clonemsg.$linefeed;
                   14639: 
                   14640:         if (!$can_clone) {
                   14641: 	    return (0,$outcome);
                   14642: 	}
                   14643:     }
                   14644: 
1.444     albertel 14645: #
                   14646: # Open course
                   14647: #
                   14648:     my $crstype = lc($args->{'crstype'});
                   14649:     my %cenv=();
                   14650:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   14651:                                              $args->{'cdescr'},
                   14652:                                              $args->{'curl'},
                   14653:                                              $args->{'course_home'},
                   14654:                                              $args->{'nonstandard'},
                   14655:                                              $args->{'crscode'},
                   14656:                                              $args->{'ccuname'}.':'.
                   14657:                                              $args->{'ccdomain'},
1.882     raeburn  14658:                                              $args->{'crstype'},
1.885     raeburn  14659:                                              $cnum,$context,$category);
1.444     albertel 14660: 
                   14661:     # Note: The testing routines depend on this being output; see 
                   14662:     # Utils::Course. This needs to at least be output as a comment
                   14663:     # if anyone ever decides to not show this, and Utils::Course::new
                   14664:     # will need to be suitably modified.
1.541     raeburn  14665:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  14666:     if ($$courseid =~ /^error:/) {
                   14667:         return (0,$outcome);
                   14668:     }
                   14669: 
1.444     albertel 14670: #
                   14671: # Check if created correctly
                   14672: #
1.479     albertel 14673:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 14674:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  14675:     if ($crsuhome eq 'no_host') {
                   14676:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   14677:         return (0,$outcome);
                   14678:     }
1.541     raeburn  14679:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 14680: 
1.444     albertel 14681: #
1.566     albertel 14682: # Do the cloning
                   14683: #   
                   14684:     if ($can_clone && $cloneid) {
                   14685: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   14686: 	if ($context ne 'auto') {
                   14687: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   14688: 	}
                   14689: 	$outcome .= $clonemsg.$linefeed;
                   14690: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 14691: # Copy all files
1.637     www      14692: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 14693: # Restore URL
1.566     albertel 14694: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 14695: # Restore title
1.566     albertel 14696: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  14697: # Restore creation date, creator and creation context.
                   14698:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   14699:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   14700:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 14701: # Mark as cloned
1.566     albertel 14702: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      14703: # Need to clone grading mode
                   14704:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   14705:         $cenv{'grading'}=$newenv{'grading'};
                   14706: # Do not clone these environment entries
                   14707:         &Apache::lonnet::del('environment',
                   14708:                   ['default_enrollment_start_date',
                   14709:                    'default_enrollment_end_date',
                   14710:                    'question.email',
                   14711:                    'policy.email',
                   14712:                    'comment.email',
                   14713:                    'pch.users.denied',
1.725     raeburn  14714:                    'plc.users.denied',
                   14715:                    'hidefromcat',
1.1075.2.36  raeburn  14716:                    'checkforpriv',
1.1075.2.59  raeburn  14717:                    'categories',
                   14718:                    'internal.uniquecode'],
1.638     www      14719:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  14720:         if ($args->{'textbook'}) {
                   14721:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   14722:         }
1.444     albertel 14723:     }
1.566     albertel 14724: 
1.444     albertel 14725: #
                   14726: # Set environment (will override cloned, if existing)
                   14727: #
                   14728:     my @sections = ();
                   14729:     my @xlists = ();
                   14730:     if ($args->{'crstype'}) {
                   14731:         $cenv{'type'}=$args->{'crstype'};
                   14732:     }
                   14733:     if ($args->{'crsid'}) {
                   14734:         $cenv{'courseid'}=$args->{'crsid'};
                   14735:     }
                   14736:     if ($args->{'crscode'}) {
                   14737:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   14738:     }
                   14739:     if ($args->{'crsquota'} ne '') {
                   14740:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   14741:     } else {
                   14742:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   14743:     }
                   14744:     if ($args->{'ccuname'}) {
                   14745:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   14746:                                         ':'.$args->{'ccdomain'};
                   14747:     } else {
                   14748:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   14749:     }
1.1075.2.31  raeburn  14750:     if ($args->{'defaultcredits'}) {
                   14751:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   14752:     }
1.444     albertel 14753:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   14754:     if ($args->{'crssections'}) {
                   14755:         $cenv{'internal.sectionnums'} = '';
                   14756:         if ($args->{'crssections'} =~ m/,/) {
                   14757:             @sections = split/,/,$args->{'crssections'};
                   14758:         } else {
                   14759:             $sections[0] = $args->{'crssections'};
                   14760:         }
                   14761:         if (@sections > 0) {
                   14762:             foreach my $item (@sections) {
                   14763:                 my ($sec,$gp) = split/:/,$item;
                   14764:                 my $class = $args->{'crscode'}.$sec;
                   14765:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   14766:                 $cenv{'internal.sectionnums'} .= $item.',';
                   14767:                 unless ($addcheck eq 'ok') {
                   14768:                     push @badclasses, $class;
                   14769:                 }
                   14770:             }
                   14771:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   14772:         }
                   14773:     }
                   14774: # do not hide course coordinator from staff listing, 
                   14775: # even if privileged
                   14776:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  14777: # add course coordinator's domain to domains to check for privileged users
                   14778: # if different to course domain
                   14779:     if ($$crsudom ne $args->{'ccdomain'}) {
                   14780:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   14781:     }
1.444     albertel 14782: # add crosslistings
                   14783:     if ($args->{'crsxlist'}) {
                   14784:         $cenv{'internal.crosslistings'}='';
                   14785:         if ($args->{'crsxlist'} =~ m/,/) {
                   14786:             @xlists = split/,/,$args->{'crsxlist'};
                   14787:         } else {
                   14788:             $xlists[0] = $args->{'crsxlist'};
                   14789:         }
                   14790:         if (@xlists > 0) {
                   14791:             foreach my $item (@xlists) {
                   14792:                 my ($xl,$gp) = split/:/,$item;
                   14793:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   14794:                 $cenv{'internal.crosslistings'} .= $item.',';
                   14795:                 unless ($addcheck eq 'ok') {
                   14796:                     push @badclasses, $xl;
                   14797:                 }
                   14798:             }
                   14799:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   14800:         }
                   14801:     }
                   14802:     if ($args->{'autoadds'}) {
                   14803:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   14804:     }
                   14805:     if ($args->{'autodrops'}) {
                   14806:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   14807:     }
                   14808: # check for notification of enrollment changes
                   14809:     my @notified = ();
                   14810:     if ($args->{'notify_owner'}) {
                   14811:         if ($args->{'ccuname'} ne '') {
                   14812:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   14813:         }
                   14814:     }
                   14815:     if ($args->{'notify_dc'}) {
                   14816:         if ($uname ne '') { 
1.630     raeburn  14817:             push(@notified,$uname.':'.$udom);
1.444     albertel 14818:         }
                   14819:     }
                   14820:     if (@notified > 0) {
                   14821:         my $notifylist;
                   14822:         if (@notified > 1) {
                   14823:             $notifylist = join(',',@notified);
                   14824:         } else {
                   14825:             $notifylist = $notified[0];
                   14826:         }
                   14827:         $cenv{'internal.notifylist'} = $notifylist;
                   14828:     }
                   14829:     if (@badclasses > 0) {
                   14830:         my %lt=&Apache::lonlocal::texthash(
                   14831:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.  However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
                   14832:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   14833:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   14834:         );
1.541     raeburn  14835:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   14836:                            ' ('.$lt{'adby'}.')';
                   14837:         if ($context eq 'auto') {
                   14838:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 14839:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  14840:             foreach my $item (@badclasses) {
                   14841:                 if ($context eq 'auto') {
                   14842:                     $outcome .= " - $item\n";
                   14843:                 } else {
                   14844:                     $outcome .= "<li>$item</li>\n";
                   14845:                 }
                   14846:             }
                   14847:             if ($context eq 'auto') {
                   14848:                 $outcome .= $linefeed;
                   14849:             } else {
1.566     albertel 14850:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  14851:             }
                   14852:         } 
1.444     albertel 14853:     }
                   14854:     if ($args->{'no_end_date'}) {
                   14855:         $args->{'endaccess'} = 0;
                   14856:     }
                   14857:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   14858:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   14859:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   14860:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   14861:     if ($args->{'showphotos'}) {
                   14862:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   14863:     }
                   14864:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   14865:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   14866:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   14867:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  14868:             my $krb_msg = &mt('As you did not include the default Kerberos domain to be used for authentication in this class, the institutional data used by the automated enrollment process must include the Kerberos domain for each new student'); 
                   14869:             if ($context eq 'auto') {
                   14870:                 $outcome .= $krb_msg;
                   14871:             } else {
1.566     albertel 14872:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  14873:             }
                   14874:             $outcome .= $linefeed;
1.444     albertel 14875:         }
                   14876:     }
                   14877:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   14878:        if ($args->{'setpolicy'}) {
                   14879:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14880:        }
                   14881:        if ($args->{'setcontent'}) {
                   14882:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14883:        }
1.1075.2.110  raeburn  14884:        if ($args->{'setcomment'}) {
                   14885:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14886:        }
1.444     albertel 14887:     }
                   14888:     if ($args->{'reshome'}) {
                   14889: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   14890: 	$cenv{'reshome'}=~s/\/+$/\//;
                   14891:     }
                   14892: #
                   14893: # course has keyed access
                   14894: #
                   14895:     if ($args->{'setkeys'}) {
                   14896:        $cenv{'keyaccess'}='yes';
                   14897:     }
                   14898: # if specified, key authority is not course, but user
                   14899: # only active if keyaccess is yes
                   14900:     if ($args->{'keyauth'}) {
1.487     albertel 14901: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   14902: 	$user = &LONCAPA::clean_username($user);
                   14903: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     14904: 	if ($user ne '' && $domain ne '') {
1.487     albertel 14905: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 14906: 	}
                   14907:     }
                   14908: 
1.1075.2.59  raeburn  14909: #
                   14910: #  generate and store uniquecode (available to course requester), if course should have one.
                   14911: #
                   14912:     if ($args->{'uniquecode'}) {
                   14913:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   14914:         if ($code) {
                   14915:             $cenv{'internal.uniquecode'} = $code;
                   14916:             my %crsinfo =
                   14917:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   14918:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   14919:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   14920:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   14921:             }
                   14922:             if (ref($coderef)) {
                   14923:                 $$coderef = $code;
                   14924:             }
                   14925:         }
                   14926:     }
                   14927: 
1.444     albertel 14928:     if ($args->{'disresdis'}) {
                   14929:         $cenv{'pch.roles.denied'}='st';
                   14930:     }
                   14931:     if ($args->{'disablechat'}) {
                   14932:         $cenv{'plc.roles.denied'}='st';
                   14933:     }
                   14934: 
                   14935:     # Record we've not yet viewed the Course Initialization Helper for this 
                   14936:     # course
                   14937:     $cenv{'course.helper.not.run'} = 1;
                   14938:     #
                   14939:     # Use new Randomseed
                   14940:     #
                   14941:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   14942:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   14943:     #
                   14944:     # The encryption code and receipt prefix for this course
                   14945:     #
                   14946:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   14947:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   14948:     #
                   14949:     # By default, use standard grading
                   14950:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   14951: 
1.541     raeburn  14952:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   14953:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14954: #
                   14955: # Open all assignments
                   14956: #
                   14957:     if ($args->{'openall'}) {
                   14958:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   14959:        my %storecontent = ($storeunder         => time,
                   14960:                            $storeunder.'.type' => 'date_start');
                   14961:        
                   14962:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  14963:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14964:    }
                   14965: #
                   14966: # Set first page
                   14967: #
                   14968:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   14969: 	    || ($cloneid)) {
1.445     albertel 14970: 	use LONCAPA::map;
1.444     albertel 14971: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 14972: 
                   14973: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   14974:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   14975: 
1.444     albertel 14976:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   14977:         my $title; my $url;
                   14978:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   14979: 	    $title=&mt('Syllabus');
1.444     albertel 14980:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   14981:         } else {
1.963     raeburn  14982:             $title=&mt('Table of Contents');
1.444     albertel 14983:             $url='/adm/navmaps';
                   14984:         }
1.445     albertel 14985: 
                   14986:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   14987: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   14988: 
                   14989: 	if ($errtext) { $fatal=2; }
1.541     raeburn  14990:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 14991:     }
1.566     albertel 14992: 
                   14993:     return (1,$outcome);
1.444     albertel 14994: }
                   14995: 
1.1075.2.59  raeburn  14996: sub make_unique_code {
                   14997:     my ($cdom,$cnum) = @_;
                   14998:     # get lock on uniquecodes db
                   14999:     my $lockhash = {
                   15000:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15001:                                                   ':'.$env{'user.domain'},
                   15002:                    };
                   15003:     my $tries = 0;
                   15004:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15005:     my ($code,$error);
                   15006: 
                   15007:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15008:         $tries ++;
                   15009:         sleep 1;
                   15010:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15011:     }
                   15012:     if ($gotlock eq 'ok') {
                   15013:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15014:         my $gotcode;
                   15015:         my $attempts = 0;
                   15016:         while ((!$gotcode) && ($attempts < 100)) {
                   15017:             $code = &generate_code();
                   15018:             if (!exists($currcodes{$code})) {
                   15019:                 $gotcode = 1;
                   15020:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15021:                     $error = 'nostore';
                   15022:                 }
                   15023:             }
                   15024:             $attempts ++;
                   15025:         }
                   15026:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15027:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15028:     } else {
                   15029:         $error = 'nolock';
                   15030:     }
                   15031:     return ($code,$error);
                   15032: }
                   15033: 
                   15034: sub generate_code {
                   15035:     my $code;
                   15036:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15037:     for (my $i=0; $i<6; $i++) {
                   15038:         my $lettnum = int (rand 2);
                   15039:         my $item = '';
                   15040:         if ($lettnum) {
                   15041:             $item = $letts[int( rand(18) )];
                   15042:         } else {
                   15043:             $item = 1+int( rand(8) );
                   15044:         }
                   15045:         $code .= $item;
                   15046:     }
                   15047:     return $code;
                   15048: }
                   15049: 
1.444     albertel 15050: ############################################################
                   15051: ############################################################
                   15052: 
1.953     droeschl 15053: #SD
                   15054: # only Community and Course, or anything else?
1.378     raeburn  15055: sub course_type {
                   15056:     my ($cid) = @_;
                   15057:     if (!defined($cid)) {
                   15058:         $cid = $env{'request.course.id'};
                   15059:     }
1.404     albertel 15060:     if (defined($env{'course.'.$cid.'.type'})) {
                   15061:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15062:     } else {
                   15063:         return 'Course';
1.377     raeburn  15064:     }
                   15065: }
1.156     albertel 15066: 
1.406     raeburn  15067: sub group_term {
                   15068:     my $crstype = &course_type();
                   15069:     my %names = (
                   15070:                   'Course' => 'group',
1.865     raeburn  15071:                   'Community' => 'group',
1.406     raeburn  15072:                 );
                   15073:     return $names{$crstype};
                   15074: }
                   15075: 
1.902     raeburn  15076: sub course_types {
1.1075.2.59  raeburn  15077:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  15078:     my %typename = (
                   15079:                          official   => 'Official course',
                   15080:                          unofficial => 'Unofficial course',
                   15081:                          community  => 'Community',
1.1075.2.59  raeburn  15082:                          textbook   => 'Textbook course',
1.902     raeburn  15083:                    );
                   15084:     return (\@types,\%typename);
                   15085: }
                   15086: 
1.156     albertel 15087: sub icon {
                   15088:     my ($file)=@_;
1.505     albertel 15089:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15090:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15091:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15092:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15093: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15094: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15095: 	            $curfext.".gif") {
                   15096: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15097: 		$curfext.".gif";
                   15098: 	}
                   15099:     }
1.249     albertel 15100:     return &lonhttpdurl($iconname);
1.154     albertel 15101: } 
1.84      albertel 15102: 
1.575     albertel 15103: sub lonhttpdurl {
1.692     www      15104: #
                   15105: # Had been used for "small fry" static images on separate port 8080.
                   15106: # Modify here if lightweight http functionality desired again.
                   15107: # Currently eliminated due to increasing firewall issues.
                   15108: #
1.575     albertel 15109:     my ($url)=@_;
1.692     www      15110:     return $url;
1.215     albertel 15111: }
                   15112: 
1.213     albertel 15113: sub connection_aborted {
                   15114:     my ($r)=@_;
                   15115:     $r->print(" ");$r->rflush();
                   15116:     my $c = $r->connection;
                   15117:     return $c->aborted();
                   15118: }
                   15119: 
1.221     foxr     15120: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15121: #    strings as 'strings'.
                   15122: sub escape_single {
1.221     foxr     15123:     my ($input) = @_;
1.223     albertel 15124:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15125:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15126:     return $input;
                   15127: }
1.223     albertel 15128: 
1.222     foxr     15129: #  Same as escape_single, but escape's "'s  This 
                   15130: #  can be used for  "strings"
                   15131: sub escape_double {
                   15132:     my ($input) = @_;
                   15133:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15134:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15135:     return $input;
                   15136: }
1.223     albertel 15137:  
1.222     foxr     15138: #   Escapes the last element of a full URL.
                   15139: sub escape_url {
                   15140:     my ($url)   = @_;
1.238     raeburn  15141:     my @urlslices = split(/\//, $url,-1);
1.369     www      15142:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  15143:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15144: }
1.462     albertel 15145: 
1.820     raeburn  15146: sub compare_arrays {
                   15147:     my ($arrayref1,$arrayref2) = @_;
                   15148:     my (@difference,%count);
                   15149:     @difference = ();
                   15150:     %count = ();
                   15151:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   15152:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   15153:         foreach my $element (keys(%count)) {
                   15154:             if ($count{$element} == 1) {
                   15155:                 push(@difference,$element);
                   15156:             }
                   15157:         }
                   15158:     }
                   15159:     return @difference;
                   15160: }
                   15161: 
1.817     bisitz   15162: # -------------------------------------------------------- Initialize user login
1.462     albertel 15163: sub init_user_environment {
1.463     albertel 15164:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 15165:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   15166: 
                   15167:     my $public=($username eq 'public' && $domain eq 'public');
                   15168: 
                   15169: # See if old ID present, if so, remove
                   15170: 
1.1062    raeburn  15171:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 15172:     my $now=time;
                   15173: 
                   15174:     if ($public) {
                   15175: 	my $max_public=100;
                   15176: 	my $oldest;
                   15177: 	my $oldest_time=0;
                   15178: 	for(my $next=1;$next<=$max_public;$next++) {
                   15179: 	    if (-e $lonids."/publicuser_$next.id") {
                   15180: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   15181: 		if ($mtime<$oldest_time || !$oldest_time) {
                   15182: 		    $oldest_time=$mtime;
                   15183: 		    $oldest=$next;
                   15184: 		}
                   15185: 	    } else {
                   15186: 		$cookie="publicuser_$next";
                   15187: 		last;
                   15188: 	    }
                   15189: 	}
                   15190: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   15191:     } else {
1.463     albertel 15192: 	# if this isn't a robot, kill any existing non-robot sessions
                   15193: 	if (!$args->{'robot'}) {
                   15194: 	    opendir(DIR,$lonids);
                   15195: 	    while ($filename=readdir(DIR)) {
                   15196: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   15197: 		    unlink($lonids.'/'.$filename);
                   15198: 		}
1.462     albertel 15199: 	    }
1.463     albertel 15200: 	    closedir(DIR);
1.1075.2.84  raeburn  15201: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   15202:             my $namespace = 'nohist_courseeditor';
                   15203:             my $lockingkey = 'paste'."\0".'locked_num';
                   15204:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15205:                                                 $domain,$username);
                   15206:             if (exists($lockhash{$lockingkey})) {
                   15207:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15208:                 unless ($delresult eq 'ok') {
                   15209:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15210:                 }
                   15211:             }
1.462     albertel 15212: 	}
                   15213: # Give them a new cookie
1.463     albertel 15214: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15215: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15216: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15217:     
                   15218: # Initialize roles
                   15219: 
1.1062    raeburn  15220: 	($userroles,$firstaccenv,$timerintenv) = 
                   15221:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15222:     }
                   15223: # ------------------------------------ Check browser type and MathML capability
                   15224: 
1.1075.2.77  raeburn  15225:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15226:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15227: 
                   15228: # ------------------------------------------------------------- Get environment
                   15229: 
                   15230:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15231:     my ($tmp) = keys(%userenv);
                   15232:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15233:     } else {
                   15234: 	undef(%userenv);
                   15235:     }
                   15236:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15237: 	$form->{'interface'}=$userenv{'interface'};
                   15238:     }
                   15239:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15240: 
                   15241: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15242:     foreach my $option ('interface','localpath','localres') {
                   15243:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15244:     }
                   15245: # --------------------------------------------------------- Write first profile
                   15246: 
                   15247:     {
                   15248: 	my %initial_env = 
                   15249: 	    ("user.name"          => $username,
                   15250: 	     "user.domain"        => $domain,
                   15251: 	     "user.home"          => $authhost,
                   15252: 	     "browser.type"       => $clientbrowser,
                   15253: 	     "browser.version"    => $clientversion,
                   15254: 	     "browser.mathml"     => $clientmathml,
                   15255: 	     "browser.unicode"    => $clientunicode,
                   15256: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  15257:              "browser.mobile"     => $clientmobile,
                   15258:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  15259:              "browser.osversion"  => $clientosversion,
1.462     albertel 15260: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15261: 	     "request.course.fn"  => '',
                   15262: 	     "request.course.uri" => '',
                   15263: 	     "request.course.sec" => '',
                   15264: 	     "request.role"       => 'cm',
                   15265: 	     "request.role.adv"   => $env{'user.adv'},
                   15266: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   15267: 
                   15268:         if ($form->{'localpath'}) {
                   15269: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15270: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15271:         }
                   15272: 	
                   15273: 	if ($form->{'interface'}) {
                   15274: 	    $form->{'interface'}=~s/\W//gs;
                   15275: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15276: 	    $env{'browser.interface'}=$form->{'interface'};
                   15277: 	}
                   15278: 
1.1075.2.54  raeburn  15279:         if ($form->{'iptoken'}) {
                   15280:             my $lonhost = $r->dir_config('lonHostID');
                   15281:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15282:             $env{'user.noloadbalance'} = $lonhost;
                   15283:         }
                   15284: 
1.981     raeburn  15285:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  15286:         my %domdef;
                   15287:         unless ($domain eq 'public') {
                   15288:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   15289:         }
1.980     raeburn  15290: 
1.1075.2.7  raeburn  15291:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  15292:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  15293:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   15294:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  15295:         }
                   15296: 
1.1075.2.59  raeburn  15297:         foreach my $crstype ('official','unofficial','community','textbook') {
1.765     raeburn  15298:             $userenv{'canrequest.'.$crstype} =
                   15299:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  15300:                                                   'reload','requestcourses',
                   15301:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  15302:         }
                   15303: 
1.1075.2.14  raeburn  15304:         $userenv{'canrequest.author'} =
                   15305:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   15306:                                         'reload','requestauthor',
                   15307:                                         \%userenv,\%domdef,\%is_adv);
                   15308:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   15309:                                              $domain,$username);
                   15310:         my $reqstatus = $reqauthor{'author_status'};
                   15311:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   15312:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   15313:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   15314:                                                   $reqauthor{'author'}{'timestamp'};
                   15315:             }
                   15316:         }
                   15317: 
1.462     albertel 15318: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  15319: 
1.462     albertel 15320: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   15321: 		 &GDBM_WRCREAT(),0640)) {
                   15322: 	    &_add_to_env(\%disk_env,\%initial_env);
                   15323: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   15324: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  15325:             if (ref($firstaccenv) eq 'HASH') {
                   15326:                 &_add_to_env(\%disk_env,$firstaccenv);
                   15327:             }
                   15328:             if (ref($timerintenv) eq 'HASH') {
                   15329:                 &_add_to_env(\%disk_env,$timerintenv);
                   15330:             }
1.463     albertel 15331: 	    if (ref($args->{'extra_env'})) {
                   15332: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   15333: 	    }
1.462     albertel 15334: 	    untie(%disk_env);
                   15335: 	} else {
1.705     tempelho 15336: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   15337: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 15338: 	    return 'error: '.$!;
                   15339: 	}
                   15340:     }
                   15341:     $env{'request.role'}='cm';
                   15342:     $env{'request.role.adv'}=$env{'user.adv'};
                   15343:     $env{'browser.type'}=$clientbrowser;
                   15344: 
                   15345:     return $cookie;
                   15346: 
                   15347: }
                   15348: 
                   15349: sub _add_to_env {
                   15350:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  15351:     if (ref($env_data) eq 'HASH') {
                   15352:         while (my ($key,$value) = each(%$env_data)) {
                   15353: 	    $idf->{$prefix.$key} = $value;
                   15354: 	    $env{$prefix.$key}   = $value;
                   15355:         }
1.462     albertel 15356:     }
                   15357: }
                   15358: 
1.685     tempelho 15359: # --- Get the symbolic name of a problem and the url
                   15360: sub get_symb {
                   15361:     my ($request,$silent) = @_;
1.726     raeburn  15362:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 15363:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   15364:     if ($symb eq '') {
                   15365:         if (!$silent) {
1.1071    raeburn  15366:             if (ref($request)) { 
                   15367:                 $request->print("Unable to handle ambiguous references:$url:.");
                   15368:             }
1.685     tempelho 15369:             return ();
                   15370:         }
                   15371:     }
                   15372:     &Apache::lonenc::check_decrypt(\$symb);
                   15373:     return ($symb);
                   15374: }
                   15375: 
                   15376: # --------------------------------------------------------------Get annotation
                   15377: 
                   15378: sub get_annotation {
                   15379:     my ($symb,$enc) = @_;
                   15380: 
                   15381:     my $key = $symb;
                   15382:     if (!$enc) {
                   15383:         $key =
                   15384:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   15385:     }
                   15386:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   15387:     return $annotation{$key};
                   15388: }
                   15389: 
                   15390: sub clean_symb {
1.731     raeburn  15391:     my ($symb,$delete_enc) = @_;
1.685     tempelho 15392: 
                   15393:     &Apache::lonenc::check_decrypt(\$symb);
                   15394:     my $enc = $env{'request.enc'};
1.731     raeburn  15395:     if ($delete_enc) {
1.730     raeburn  15396:         delete($env{'request.enc'});
                   15397:     }
1.685     tempelho 15398: 
                   15399:     return ($symb,$enc);
                   15400: }
1.462     albertel 15401: 
1.1075.2.69  raeburn  15402: ############################################################
                   15403: ############################################################
                   15404: 
                   15405: =pod
                   15406: 
                   15407: =head1 Routines for building display used to search for courses
                   15408: 
                   15409: 
                   15410: =over 4
                   15411: 
                   15412: =item * &build_filters()
                   15413: 
                   15414: Create markup for a table used to set filters to use when selecting
                   15415: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   15416: and quotacheck.pl
                   15417: 
                   15418: 
                   15419: Inputs:
                   15420: 
                   15421: filterlist - anonymous array of fields to include as potential filters
                   15422: 
                   15423: crstype - course type
                   15424: 
                   15425: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   15426:               to pop-open a course selector (will contain "extra element").
                   15427: 
                   15428: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   15429: 
                   15430: filter - anonymous hash of criteria and their values
                   15431: 
                   15432: action - form action
                   15433: 
                   15434: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   15435: 
                   15436: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   15437: 
                   15438: cloneruname - username of owner of new course who wants to clone
                   15439: 
                   15440: clonerudom - domain of owner of new course who wants to clone
                   15441: 
                   15442: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   15443: 
                   15444: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   15445: 
                   15446: codedom - domain
                   15447: 
                   15448: formname - value of form element named "form".
                   15449: 
                   15450: fixeddom - domain, if fixed.
                   15451: 
                   15452: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   15453: 
                   15454: cnameelement - name of form element in form on opener page which will receive title of selected course
                   15455: 
                   15456: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   15457: 
                   15458: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   15459: 
                   15460: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   15461: 
                   15462: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   15463: 
                   15464: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   15465: 
                   15466: 
                   15467: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   15468: 
                   15469: 
                   15470: Side Effects: None
                   15471: 
                   15472: =cut
                   15473: 
                   15474: # ---------------------------------------------- search for courses based on last activity etc.
                   15475: 
                   15476: sub build_filters {
                   15477:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   15478:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   15479:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   15480:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   15481:         $clonetext,$clonewarning) = @_;
                   15482:     my ($list,$jscript);
                   15483:     my $onchange = 'javascript:updateFilters(this)';
                   15484:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   15485:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   15486:         $typeselectform,$instcodetitle);
                   15487:     if ($formname eq '') {
                   15488:         $formname = $caller;
                   15489:     }
                   15490:     foreach my $item (@{$filterlist}) {
                   15491:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   15492:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   15493:             if ($item eq 'domainfilter') {
                   15494:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   15495:             } elsif ($item eq 'coursefilter') {
                   15496:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   15497:             } elsif ($item eq 'ownerfilter') {
                   15498:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15499:             } elsif ($item eq 'ownerdomfilter') {
                   15500:                 $filter->{'ownerdomfilter'} =
                   15501:                     &LONCAPA::clean_domain($filter->{$item});
                   15502:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   15503:                                                        'ownerdomfilter',1);
                   15504:             } elsif ($item eq 'personfilter') {
                   15505:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15506:             } elsif ($item eq 'persondomfilter') {
                   15507:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   15508:                                                         'persondomfilter',1);
                   15509:             } else {
                   15510:                 $filter->{$item} =~ s/\W//g;
                   15511:             }
                   15512:             if (!$filter->{$item}) {
                   15513:                 $filter->{$item} = '';
                   15514:             }
                   15515:         }
                   15516:         if ($item eq 'domainfilter') {
                   15517:             my $allow_blank = 1;
                   15518:             if ($formname eq 'portform') {
                   15519:                 $allow_blank=0;
                   15520:             } elsif ($formname eq 'studentform') {
                   15521:                 $allow_blank=0;
                   15522:             }
                   15523:             if ($fixeddom) {
                   15524:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   15525:                                     ' value="'.$codedom.'" />'.
                   15526:                                     &Apache::lonnet::domain($codedom,'description');
                   15527:             } else {
                   15528:                 $domainselectform = &select_dom_form($filter->{$item},
                   15529:                                                      'domainfilter',
                   15530:                                                       $allow_blank,'',$onchange);
                   15531:             }
                   15532:         } else {
                   15533:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   15534:         }
                   15535:     }
                   15536: 
                   15537:     # last course activity filter and selection
                   15538:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   15539: 
                   15540:     # course created filter and selection
                   15541:     if (exists($filter->{'createdfilter'})) {
                   15542:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   15543:     }
                   15544: 
                   15545:     my %lt = &Apache::lonlocal::texthash(
                   15546:                 'cac' => "$crstype Activity",
                   15547:                 'ccr' => "$crstype Created",
                   15548:                 'cde' => "$crstype Title",
                   15549:                 'cdo' => "$crstype Domain",
                   15550:                 'ins' => 'Institutional Code',
                   15551:                 'inc' => 'Institutional Categorization',
                   15552:                 'cow' => "$crstype Owner/Co-owner",
                   15553:                 'cop' => "$crstype Personnel Includes",
                   15554:                 'cog' => 'Type',
                   15555:              );
                   15556: 
                   15557:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15558:         my $typeval = 'Course';
                   15559:         if ($crstype eq 'Community') {
                   15560:             $typeval = 'Community';
                   15561:         }
                   15562:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   15563:     } else {
                   15564:         $typeselectform =  '<select name="type" size="1"';
                   15565:         if ($onchange) {
                   15566:             $typeselectform .= ' onchange="'.$onchange.'"';
                   15567:         }
                   15568:         $typeselectform .= '>'."\n";
                   15569:         foreach my $posstype ('Course','Community') {
                   15570:             $typeselectform.='<option value="'.$posstype.'"'.
                   15571:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   15572:         }
                   15573:         $typeselectform.="</select>";
                   15574:     }
                   15575: 
                   15576:     my ($cloneableonlyform,$cloneabletitle);
                   15577:     if (exists($filter->{'cloneableonly'})) {
                   15578:         my $cloneableon = '';
                   15579:         my $cloneableoff = ' checked="checked"';
                   15580:         if ($filter->{'cloneableonly'}) {
                   15581:             $cloneableon = $cloneableoff;
                   15582:             $cloneableoff = '';
                   15583:         }
                   15584:         $cloneableonlyform = '<span class="LC_nobreak"><label><input type="radio" name="cloneableonly" value="1" '.$cloneableon.'/>&nbsp;'.&mt('Required').'</label>'.('&nbsp;'x3).'<label><input type="radio" name="cloneableonly" value="" '.$cloneableoff.' />&nbsp;'.&mt('No restriction').'</label></span>';
                   15585:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  15586:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  15587:         } else {
                   15588:             $cloneabletitle = &mt('Cloneable by you');
                   15589:         }
                   15590:     }
                   15591:     my $officialjs;
                   15592:     if ($crstype eq 'Course') {
                   15593:         if (exists($filter->{'instcodefilter'})) {
                   15594: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   15595: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   15596:             if ($codedom) {
                   15597:                 $officialjs = 1;
                   15598:                 ($instcodeform,$jscript,$$numtitlesref) =
                   15599:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   15600:                                                                   $officialjs,$codetitlesref);
                   15601:                 if ($jscript) {
                   15602:                     $jscript = '<script type="text/javascript">'."\n".
                   15603:                                '// <![CDATA['."\n".
                   15604:                                $jscript."\n".
                   15605:                                '// ]]>'."\n".
                   15606:                                '</script>'."\n";
                   15607:                 }
                   15608:             }
                   15609:             if ($instcodeform eq '') {
                   15610:                 $instcodeform =
                   15611:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   15612:                     $list->{'instcodefilter'}.'" />';
                   15613:                 $instcodetitle = $lt{'ins'};
                   15614:             } else {
                   15615:                 $instcodetitle = $lt{'inc'};
                   15616:             }
                   15617:             if ($fixeddom) {
                   15618:                 $instcodetitle .= '<br />('.$codedom.')';
                   15619:             }
                   15620:         }
                   15621:     }
                   15622:     my $output = qq|
                   15623: <form method="post" name="filterpicker" action="$action">
                   15624: <input type="hidden" name="form" value="$formname" />
                   15625: |;
                   15626:     if ($formname eq 'modifycourse') {
                   15627:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   15628:                    '<input type="hidden" name="prevphase" value="'.
                   15629:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  15630:     } elsif ($formname eq 'quotacheck') {
                   15631:         $output .= qq|
                   15632: <input type="hidden" name="sortby" value="" />
                   15633: <input type="hidden" name="sortorder" value="" />
                   15634: |;
                   15635:     } else {
1.1075.2.69  raeburn  15636:         my $name_input;
                   15637:         if ($cnameelement ne '') {
                   15638:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   15639:                           $cnameelement.'" />';
                   15640:         }
                   15641:         $output .= qq|
                   15642: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   15643: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   15644: $name_input
                   15645: $roleelement
                   15646: $multelement
                   15647: $typeelement
                   15648: |;
                   15649:         if ($formname eq 'portform') {
                   15650:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   15651:         }
                   15652:     }
                   15653:     if ($fixeddom) {
                   15654:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   15655:     }
                   15656:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   15657:     if ($sincefilterform) {
                   15658:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   15659:                   .$sincefilterform
                   15660:                   .&Apache::lonhtmlcommon::row_closure();
                   15661:     }
                   15662:     if ($createdfilterform) {
                   15663:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   15664:                   .$createdfilterform
                   15665:                   .&Apache::lonhtmlcommon::row_closure();
                   15666:     }
                   15667:     if ($domainselectform) {
                   15668:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   15669:                   .$domainselectform
                   15670:                   .&Apache::lonhtmlcommon::row_closure();
                   15671:     }
                   15672:     if ($typeselectform) {
                   15673:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15674:             $output .= $typeselectform;
                   15675:         } else {
                   15676:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   15677:                       .$typeselectform
                   15678:                       .&Apache::lonhtmlcommon::row_closure();
                   15679:         }
                   15680:     }
                   15681:     if ($instcodeform) {
                   15682:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   15683:                   .$instcodeform
                   15684:                   .&Apache::lonhtmlcommon::row_closure();
                   15685:     }
                   15686:     if (exists($filter->{'ownerfilter'})) {
                   15687:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   15688:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15689:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   15690:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15691:                    $ownerdomselectform.'</td></tr></table>'.
                   15692:                    &Apache::lonhtmlcommon::row_closure();
                   15693:     }
                   15694:     if (exists($filter->{'personfilter'})) {
                   15695:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   15696:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15697:                    '<input type="text" name="personfilter" size="20" value="'.
                   15698:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15699:                    $persondomselectform.'</td></tr></table>'.
                   15700:                    &Apache::lonhtmlcommon::row_closure();
                   15701:     }
                   15702:     if (exists($filter->{'coursefilter'})) {
                   15703:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   15704:                   .'<input type="text" name="coursefilter" size="25" value="'
                   15705:                   .$list->{'coursefilter'}.'" />'
                   15706:                   .&Apache::lonhtmlcommon::row_closure();
                   15707:     }
                   15708:     if ($cloneableonlyform) {
                   15709:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   15710:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   15711:     }
                   15712:     if (exists($filter->{'descriptfilter'})) {
                   15713:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   15714:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   15715:                   .$list->{'descriptfilter'}.'" />'
                   15716:                   .&Apache::lonhtmlcommon::row_closure(1);
                   15717:     }
                   15718:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   15719:                '<input type="hidden" name="updater" value="" />'."\n".
                   15720:                '<input type="submit" name="gosearch" value="'.
                   15721:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   15722:     return $jscript.$clonewarning.$output;
                   15723: }
                   15724: 
                   15725: =pod
                   15726: 
                   15727: =item * &timebased_select_form()
                   15728: 
                   15729: Create markup for a dropdown list used to select a time-based
                   15730: filter e.g., Course Activity, Course Created, when searching for courses
                   15731: or communities
                   15732: 
                   15733: Inputs:
                   15734: 
                   15735: item - name of form element (sincefilter or createdfilter)
                   15736: 
                   15737: filter - anonymous hash of criteria and their values
                   15738: 
                   15739: Returns: HTML for a select box contained a blank, then six time selections,
                   15740:          with value set in incoming form variables currently selected.
                   15741: 
                   15742: Side Effects: None
                   15743: 
                   15744: =cut
                   15745: 
                   15746: sub timebased_select_form {
                   15747:     my ($item,$filter) = @_;
                   15748:     if (ref($filter) eq 'HASH') {
                   15749:         $filter->{$item} =~ s/[^\d-]//g;
                   15750:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   15751:         return &select_form(
                   15752:                             $filter->{$item},
                   15753:                             $item,
                   15754:                             {      '-1' => '',
                   15755:                                 '86400' => &mt('today'),
                   15756:                                '604800' => &mt('last week'),
                   15757:                               '2592000' => &mt('last month'),
                   15758:                               '7776000' => &mt('last three months'),
                   15759:                              '15552000' => &mt('last six months'),
                   15760:                              '31104000' => &mt('last year'),
                   15761:                     'select_form_order' =>
                   15762:                            ['-1','86400','604800','2592000','7776000',
                   15763:                             '15552000','31104000']});
                   15764:     }
                   15765: }
                   15766: 
                   15767: =pod
                   15768: 
                   15769: =item * &js_changer()
                   15770: 
                   15771: Create script tag containing Javascript used to submit course search form
                   15772: when course type or domain is changed, and also to hide 'Searching ...' on
                   15773: page load completion for page showing search result.
                   15774: 
                   15775: Inputs: None
                   15776: 
                   15777: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   15778: 
                   15779: Side Effects: None
                   15780: 
                   15781: =cut
                   15782: 
                   15783: sub js_changer {
                   15784:     return <<ENDJS;
                   15785: <script type="text/javascript">
                   15786: // <![CDATA[
                   15787: function updateFilters(caller) {
                   15788:     if (typeof(caller) != "undefined") {
                   15789:         document.filterpicker.updater.value = caller.name;
                   15790:     }
                   15791:     document.filterpicker.submit();
                   15792: }
                   15793: 
                   15794: function hideSearching() {
                   15795:     if (document.getElementById('searching')) {
                   15796:         document.getElementById('searching').style.display = 'none';
                   15797:     }
                   15798:     return;
                   15799: }
                   15800: 
                   15801: // ]]>
                   15802: </script>
                   15803: 
                   15804: ENDJS
                   15805: }
                   15806: 
                   15807: =pod
                   15808: 
                   15809: =item * &search_courses()
                   15810: 
                   15811: Process selected filters form course search form and pass to lonnet::courseiddump
                   15812: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   15813: 
                   15814: Inputs:
                   15815: 
                   15816: dom - domain being searched
                   15817: 
                   15818: type - course type ('Course' or 'Community' or '.' if any).
                   15819: 
                   15820: filter - anonymous hash of criteria and their values
                   15821: 
                   15822: numtitles - for institutional codes - number of categories
                   15823: 
                   15824: cloneruname - optional username of new course owner
                   15825: 
                   15826: clonerudom - optional domain of new course owner
                   15827: 
1.1075.2.95  raeburn  15828: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  15829:             (used when DC is using course creation form)
                   15830: 
                   15831: codetitles - reference to array of titles of components in institutional codes (official courses).
                   15832: 
1.1075.2.95  raeburn  15833: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   15834:            (and so can clone automatically)
                   15835: 
                   15836: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   15837: 
                   15838: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   15839:               courses to clone
1.1075.2.69  raeburn  15840: 
                   15841: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   15842: 
                   15843: 
                   15844: Side Effects: None
                   15845: 
                   15846: =cut
                   15847: 
                   15848: 
                   15849: sub search_courses {
1.1075.2.95  raeburn  15850:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   15851:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  15852:     my (%courses,%showcourses,$cloner);
                   15853:     if (($filter->{'ownerfilter'} ne '') ||
                   15854:         ($filter->{'ownerdomfilter'} ne '')) {
                   15855:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   15856:                                        $filter->{'ownerdomfilter'};
                   15857:     }
                   15858:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   15859:         if (!$filter->{$item}) {
                   15860:             $filter->{$item}='.';
                   15861:         }
                   15862:     }
                   15863:     my $now = time;
                   15864:     my $timefilter =
                   15865:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   15866:     my ($createdbefore,$createdafter);
                   15867:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   15868:         $createdbefore = $now;
                   15869:         $createdafter = $now-$filter->{'createdfilter'};
                   15870:     }
                   15871:     my ($instcodefilter,$regexpok);
                   15872:     if ($numtitles) {
                   15873:         if ($env{'form.official'} eq 'on') {
                   15874:             $instcodefilter =
                   15875:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   15876:             $regexpok = 1;
                   15877:         } elsif ($env{'form.official'} eq 'off') {
                   15878:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   15879:             unless ($instcodefilter eq '') {
                   15880:                 $regexpok = -1;
                   15881:             }
                   15882:         }
                   15883:     } else {
                   15884:         $instcodefilter = $filter->{'instcodefilter'};
                   15885:     }
                   15886:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   15887:     if ($type eq '') { $type = '.'; }
                   15888: 
                   15889:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   15890:         $cloner = $cloneruname.':'.$clonerudom;
                   15891:     }
                   15892:     %courses = &Apache::lonnet::courseiddump($dom,
                   15893:                                              $filter->{'descriptfilter'},
                   15894:                                              $timefilter,
                   15895:                                              $instcodefilter,
                   15896:                                              $filter->{'combownerfilter'},
                   15897:                                              $filter->{'coursefilter'},
                   15898:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  15899:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  15900:                                              $filter->{'cloneableonly'},
                   15901:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  15902:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  15903:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   15904:         my $ccrole;
                   15905:         if ($type eq 'Community') {
                   15906:             $ccrole = 'co';
                   15907:         } else {
                   15908:             $ccrole = 'cc';
                   15909:         }
                   15910:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   15911:                                                      $filter->{'persondomfilter'},
                   15912:                                                      'userroles',undef,
                   15913:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   15914:                                                      $dom);
                   15915:         foreach my $role (keys(%rolehash)) {
                   15916:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   15917:             my $cid = $cdom.'_'.$cnum;
                   15918:             if (exists($courses{$cid})) {
                   15919:                 if (ref($courses{$cid}) eq 'HASH') {
                   15920:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   15921:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
                   15922:                             push (@{$courses{$cid}{roles}},$courserole);
                   15923:                         }
                   15924:                     } else {
                   15925:                         $courses{$cid}{roles} = [$courserole];
                   15926:                     }
                   15927:                     $showcourses{$cid} = $courses{$cid};
                   15928:                 }
                   15929:             }
                   15930:         }
                   15931:         %courses = %showcourses;
                   15932:     }
                   15933:     return %courses;
                   15934: }
                   15935: 
                   15936: =pod
                   15937: 
                   15938: =back
                   15939: 
1.1075.2.88  raeburn  15940: =head1 Routines for version requirements for current course.
                   15941: 
                   15942: =over 4
                   15943: 
                   15944: =item * &check_release_required()
                   15945: 
                   15946: Compares required LON-CAPA version with version on server, and
                   15947: if required version is newer looks for a server with the required version.
                   15948: 
                   15949: Looks first at servers in user's owen domain; if none suitable, looks at
                   15950: servers in course's domain are permitted to host sessions for user's domain.
                   15951: 
                   15952: Inputs:
                   15953: 
                   15954: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   15955: 
                   15956: $courseid - Course ID of current course
                   15957: 
                   15958: $rolecode - User's current role in course (for switchserver query string).
                   15959: 
                   15960: $required - LON-CAPA version needed by course (format: Major.Minor).
                   15961: 
                   15962: 
                   15963: Returns:
                   15964: 
                   15965: $switchserver - query string tp append to /adm/switchserver call (if
                   15966:                 current server's LON-CAPA version is too old.
                   15967: 
                   15968: $warning - Message is displayed if no suitable server could be found.
                   15969: 
                   15970: =cut
                   15971: 
                   15972: sub check_release_required {
                   15973:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   15974:     my ($switchserver,$warning);
                   15975:     if ($required ne '') {
                   15976:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   15977:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   15978:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   15979:             my $otherserver;
                   15980:             if (($major eq '' && $minor eq '') ||
                   15981:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   15982:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   15983:                 my $switchlcrev =
                   15984:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   15985:                                                            $userdomserver);
                   15986:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   15987:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   15988:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   15989:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   15990:                     if ($cdom ne $env{'user.domain'}) {
                   15991:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   15992:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   15993:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   15994:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   15995:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   15996:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   15997:                         my $canhost =
                   15998:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   15999:                                                               $coursedomserver,
                   16000:                                                               $remoterev,
                   16001:                                                               $udomdefaults{'remotesessions'},
                   16002:                                                               $defdomdefaults{'hostedsessions'});
                   16003: 
                   16004:                         if ($canhost) {
                   16005:                             $otherserver = $coursedomserver;
                   16006:                         } else {
                   16007:                             $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'. &mt("No suitable server could be found amongst servers in either your own domain or in the course's domain.");
                   16008:                         }
                   16009:                     } else {
                   16010:                         $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'.&mt("No suitable server could be found amongst servers in your own domain (which is also the course's domain).");
                   16011:                     }
                   16012:                 } else {
                   16013:                     $otherserver = $userdomserver;
                   16014:                 }
                   16015:             }
                   16016:             if ($otherserver ne '') {
                   16017:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16018:             }
                   16019:         }
                   16020:     }
                   16021:     return ($switchserver,$warning);
                   16022: }
                   16023: 
                   16024: =pod
                   16025: 
                   16026: =item * &check_release_result()
                   16027: 
                   16028: Inputs:
                   16029: 
                   16030: $switchwarning - Warning message if no suitable server found to host session.
                   16031: 
                   16032: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16033:                 and current role.
                   16034: 
                   16035: Returns: HTML to display with information about requirement to switch server.
                   16036:          Either displaying warning with link to Roles/Courses screen or
                   16037:          display link to switchserver.
                   16038: 
1.1075.2.69  raeburn  16039: =cut
                   16040: 
1.1075.2.88  raeburn  16041: sub check_release_result {
                   16042:     my ($switchwarning,$switchserver) = @_;
                   16043:     my $output = &start_page('Selected course unavailable on this server').
                   16044:                  '<p class="LC_warning">';
                   16045:     if ($switchwarning) {
                   16046:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16047:         if (&show_course()) {
                   16048:             $output .= &mt('Display courses');
                   16049:         } else {
                   16050:             $output .= &mt('Display roles');
                   16051:         }
                   16052:         $output .= '</a>';
                   16053:     } elsif ($switchserver) {
                   16054:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16055:                    '<br />'.
                   16056:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16057:                    &mt('Switch Server').
                   16058:                    '</a>';
                   16059:     }
                   16060:     $output .= '</p>'.&end_page();
                   16061:     return $output;
                   16062: }
                   16063: 
                   16064: =pod
                   16065: 
                   16066: =item * &needs_coursereinit()
                   16067: 
                   16068: Determine if course contents stored for user's session needs to be
                   16069: refreshed, because content has changed since "Big Hash" last tied.
                   16070: 
                   16071: Check for change is made if time last checked is more than 10 minutes ago
                   16072: (by default).
                   16073: 
                   16074: Inputs:
                   16075: 
                   16076: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16077: 
                   16078: $interval (optional) - Time which may elapse (in s) between last check for content
                   16079:                        change in current course. (default: 600 s).
                   16080: 
                   16081: Returns: an array; first element is:
                   16082: 
                   16083: =over 4
                   16084: 
                   16085: 'switch' - if content updates mean user's session
                   16086:            needs to be switched to a server running a newer LON-CAPA version
                   16087: 
                   16088: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16089:            on current server hosting user's session
                   16090: 
                   16091: ''       - if no action required.
                   16092: 
                   16093: =back
                   16094: 
                   16095: If first item element is 'switch':
                   16096: 
                   16097: second item is $switchwarning - Warning message if no suitable server found to host session.
                   16098: 
                   16099: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16100:                               and current role.
                   16101: 
                   16102: otherwise: no other elements returned.
                   16103: 
                   16104: =back
                   16105: 
                   16106: =cut
                   16107: 
                   16108: sub needs_coursereinit {
                   16109:     my ($loncaparev,$interval) = @_;
                   16110:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16111:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16112:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16113:     my $now = time;
                   16114:     if ($interval eq '') {
                   16115:         $interval = 600;
                   16116:     }
                   16117:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16118:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16119:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   16120:         if ($lastchange > $env{'request.course.tied'}) {
                   16121:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16122:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16123:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16124:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16125:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16126:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16127:                     my ($switchserver,$switchwarning) =
                   16128:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   16129:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   16130:                     if ($switchwarning ne '' || $switchserver ne '') {
                   16131:                         return ('switch',$switchwarning,$switchserver);
                   16132:                     }
                   16133:                 }
                   16134:             }
                   16135:             return ('update');
                   16136:         }
                   16137:     }
                   16138:     return ();
                   16139: }
1.1075.2.69  raeburn  16140: 
1.1075.2.11  raeburn  16141: sub update_content_constraints {
                   16142:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16143:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16144:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   16145:     my %checkresponsetypes;
                   16146:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   16147:         my ($item,$name,$value) = split(/:/,$key);
                   16148:         if ($item eq 'resourcetag') {
                   16149:             if ($name eq 'responsetype') {
                   16150:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   16151:             }
                   16152:         }
                   16153:     }
                   16154:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16155:     if (defined($navmap)) {
                   16156:         my %allresponses;
                   16157:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   16158:             my %responses = $res->responseTypes();
                   16159:             foreach my $key (keys(%responses)) {
                   16160:                 next unless(exists($checkresponsetypes{$key}));
                   16161:                 $allresponses{$key} += $responses{$key};
                   16162:             }
                   16163:         }
                   16164:         foreach my $key (keys(%allresponses)) {
                   16165:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   16166:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   16167:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   16168:             }
                   16169:         }
                   16170:         undef($navmap);
                   16171:     }
                   16172:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   16173:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   16174:     }
                   16175:     return;
                   16176: }
                   16177: 
1.1075.2.27  raeburn  16178: sub allmaps_incourse {
                   16179:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16180:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   16181:         $cid = $env{'request.course.id'};
                   16182:         $cdom = $env{'course.'.$cid.'.domain'};
                   16183:         $cnum = $env{'course.'.$cid.'.num'};
                   16184:         $chome = $env{'course.'.$cid.'.home'};
                   16185:     }
                   16186:     my %allmaps = ();
                   16187:     my $lastchange =
                   16188:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16189:     if ($lastchange > $env{'request.course.tied'}) {
                   16190:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   16191:         unless ($ferr) {
                   16192:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   16193:         }
                   16194:     }
                   16195:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16196:     if (defined($navmap)) {
                   16197:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   16198:             $allmaps{$res->src()} = 1;
                   16199:         }
                   16200:     }
                   16201:     return \%allmaps;
                   16202: }
                   16203: 
1.1075.2.11  raeburn  16204: sub parse_supplemental_title {
                   16205:     my ($title) = @_;
                   16206: 
                   16207:     my ($foldertitle,$renametitle);
                   16208:     if ($title =~ /&amp;&amp;&amp;/) {
                   16209:         $title = &HTML::Entites::decode($title);
                   16210:     }
                   16211:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   16212:         $renametitle=$4;
                   16213:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16214:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16215:         my $name =  &plainname($uname,$udom);
                   16216:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16217:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16218:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16219:             $name.': <br />'.$foldertitle;
                   16220:     }
                   16221:     if (wantarray) {
                   16222:         return ($title,$foldertitle,$renametitle);
                   16223:     }
                   16224:     return $title;
                   16225: }
                   16226: 
1.1075.2.43  raeburn  16227: sub recurse_supplemental {
                   16228:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16229:     if ($suppmap) {
                   16230:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16231:         if ($fatal) {
                   16232:             $errors ++;
                   16233:         } else {
                   16234:             if ($#LONCAPA::map::resources > 0) {
                   16235:                 foreach my $res (@LONCAPA::map::resources) {
                   16236:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16237:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  16238:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16239:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  16240:                         } else {
                   16241:                             $numfiles ++;
                   16242:                         }
                   16243:                     }
                   16244:                 }
                   16245:             }
                   16246:         }
                   16247:     }
                   16248:     return ($numfiles,$errors);
                   16249: }
                   16250: 
1.1075.2.18  raeburn  16251: sub symb_to_docspath {
                   16252:     my ($symb) = @_;
                   16253:     return unless ($symb);
                   16254:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16255:     if ($resurl=~/\.(sequence|page)$/) {
                   16256:         $mapurl=$resurl;
                   16257:     } elsif ($resurl eq 'adm/navmaps') {
                   16258:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16259:     }
                   16260:     my $mapresobj;
                   16261:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16262:     if (ref($navmap)) {
                   16263:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   16264:     }
                   16265:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16266:     my $type=$2;
                   16267:     my $path;
                   16268:     if (ref($mapresobj)) {
                   16269:         my $pcslist = $mapresobj->map_hierarchy();
                   16270:         if ($pcslist ne '') {
                   16271:             foreach my $pc (split(/,/,$pcslist)) {
                   16272:                 next if ($pc <= 1);
                   16273:                 my $res = $navmap->getByMapPc($pc);
                   16274:                 if (ref($res)) {
                   16275:                     my $thisurl = $res->src();
                   16276:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16277:                     my $thistitle = $res->title();
                   16278:                     $path .= '&'.
                   16279:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  16280:                              &escape($thistitle).
1.1075.2.18  raeburn  16281:                              ':'.$res->randompick().
                   16282:                              ':'.$res->randomout().
                   16283:                              ':'.$res->encrypted().
                   16284:                              ':'.$res->randomorder().
                   16285:                              ':'.$res->is_page();
                   16286:                 }
                   16287:             }
                   16288:         }
                   16289:         $path =~ s/^\&//;
                   16290:         my $maptitle = $mapresobj->title();
                   16291:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16292:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16293:         }
                   16294:         $path .= (($path ne '')? '&' : '').
                   16295:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16296:                  &escape($maptitle).
1.1075.2.18  raeburn  16297:                  ':'.$mapresobj->randompick().
                   16298:                  ':'.$mapresobj->randomout().
                   16299:                  ':'.$mapresobj->encrypted().
                   16300:                  ':'.$mapresobj->randomorder().
                   16301:                  ':'.$mapresobj->is_page();
                   16302:     } else {
                   16303:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   16304:         my $ispage = (($type eq 'page')? 1 : '');
                   16305:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16306:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16307:         }
                   16308:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16309:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  16310:     }
                   16311:     unless ($mapurl eq 'default') {
                   16312:         $path = 'default&'.
1.1075.2.46  raeburn  16313:                 &escape('Main Content').
1.1075.2.18  raeburn  16314:                 ':::::&'.$path;
                   16315:     }
                   16316:     return $path;
                   16317: }
                   16318: 
1.1075.2.14  raeburn  16319: sub captcha_display {
                   16320:     my ($context,$lonhost) = @_;
                   16321:     my ($output,$error);
1.1075.2.107  raeburn  16322:     my ($captcha,$pubkey,$privkey,$version) =
                   16323:         &get_captcha_config($context,$lonhost);
1.1075.2.14  raeburn  16324:     if ($captcha eq 'original') {
                   16325:         $output = &create_captcha();
                   16326:         unless ($output) {
                   16327:             $error = 'captcha';
                   16328:         }
                   16329:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  16330:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  16331:         unless ($output) {
                   16332:             $error = 'recaptcha';
                   16333:         }
                   16334:     }
1.1075.2.107  raeburn  16335:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  16336: }
                   16337: 
                   16338: sub captcha_response {
                   16339:     my ($context,$lonhost) = @_;
                   16340:     my ($captcha_chk,$captcha_error);
1.1075.2.109  raeburn  16341:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
1.1075.2.14  raeburn  16342:     if ($captcha eq 'original') {
                   16343:         ($captcha_chk,$captcha_error) = &check_captcha();
                   16344:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  16345:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  16346:     } else {
                   16347:         $captcha_chk = 1;
                   16348:     }
                   16349:     return ($captcha_chk,$captcha_error);
                   16350: }
                   16351: 
                   16352: sub get_captcha_config {
                   16353:     my ($context,$lonhost) = @_;
1.1075.2.107  raeburn  16354:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  16355:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   16356:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   16357:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16358:     if ($context eq 'usercreation') {
                   16359:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   16360:         if (ref($domconfig{$context}) eq 'HASH') {
                   16361:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   16362:             if (ref($hashtocheck) eq 'HASH') {
                   16363:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   16364:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   16365:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   16366:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   16367:                     }
                   16368:                     if ($privkey && $pubkey) {
                   16369:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  16370:                         $version = $hashtocheck->{'recaptchaversion'};
                   16371:                         if ($version ne '2') {
                   16372:                             $version = 1;
                   16373:                         }
1.1075.2.14  raeburn  16374:                     } else {
                   16375:                         $captcha = 'original';
                   16376:                     }
                   16377:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   16378:                     $captcha = 'original';
                   16379:                 }
                   16380:             }
                   16381:         } else {
                   16382:             $captcha = 'captcha';
                   16383:         }
                   16384:     } elsif ($context eq 'login') {
                   16385:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   16386:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   16387:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   16388:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   16389:             if ($privkey && $pubkey) {
                   16390:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  16391:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   16392:                 if ($version ne '2') {
                   16393:                     $version = 1;
                   16394:                 }
1.1075.2.14  raeburn  16395:             } else {
                   16396:                 $captcha = 'original';
                   16397:             }
                   16398:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   16399:             $captcha = 'original';
                   16400:         }
                   16401:     }
1.1075.2.107  raeburn  16402:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  16403: }
                   16404: 
                   16405: sub create_captcha {
                   16406:     my %captcha_params = &captcha_settings();
                   16407:     my ($output,$maxtries,$tries) = ('',10,0);
                   16408:     while ($tries < $maxtries) {
                   16409:         $tries ++;
                   16410:         my $captcha = Authen::Captcha->new (
                   16411:                                            output_folder => $captcha_params{'output_dir'},
                   16412:                                            data_folder   => $captcha_params{'db_dir'},
                   16413:                                           );
                   16414:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   16415: 
                   16416:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   16417:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   16418:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.66  raeburn  16419:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   16420:                       '<br />'.
                   16421:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  16422:             last;
                   16423:         }
                   16424:     }
                   16425:     return $output;
                   16426: }
                   16427: 
                   16428: sub captcha_settings {
                   16429:     my %captcha_params = (
                   16430:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   16431:                            www_output_dir => "/captchaspool",
                   16432:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   16433:                            numchars       => '5',
                   16434:                          );
                   16435:     return %captcha_params;
                   16436: }
                   16437: 
                   16438: sub check_captcha {
                   16439:     my ($captcha_chk,$captcha_error);
                   16440:     my $code = $env{'form.code'};
                   16441:     my $md5sum = $env{'form.crypt'};
                   16442:     my %captcha_params = &captcha_settings();
                   16443:     my $captcha = Authen::Captcha->new(
                   16444:                       output_folder => $captcha_params{'output_dir'},
                   16445:                       data_folder   => $captcha_params{'db_dir'},
                   16446:                   );
1.1075.2.26  raeburn  16447:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  16448:     my %captcha_hash = (
                   16449:                         0       => 'Code not checked (file error)',
                   16450:                        -1      => 'Failed: code expired',
                   16451:                        -2      => 'Failed: invalid code (not in database)',
                   16452:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   16453:     );
                   16454:     if ($captcha_chk != 1) {
                   16455:         $captcha_error = $captcha_hash{$captcha_chk}
                   16456:     }
                   16457:     return ($captcha_chk,$captcha_error);
                   16458: }
                   16459: 
                   16460: sub create_recaptcha {
1.1075.2.107  raeburn  16461:     my ($pubkey,$version) = @_;
                   16462:     if ($version >= 2) {
                   16463:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   16464:     } else {
                   16465:         my $use_ssl;
                   16466:         if ($ENV{'SERVER_PORT'} == 443) {
                   16467:             $use_ssl = 1;
                   16468:         }
                   16469:         my $captcha = Captcha::reCAPTCHA->new;
                   16470:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   16471:                $captcha->get_html($pubkey,undef,$use_ssl).
                   16472:                &mt('If the text is hard to read, [_1] will replace them.',
                   16473:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   16474:                '<br /><br />';
                   16475:      }
1.1075.2.14  raeburn  16476: }
                   16477: 
                   16478: sub check_recaptcha {
1.1075.2.107  raeburn  16479:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  16480:     my $captcha_chk;
1.1075.2.107  raeburn  16481:     if ($version >= 2) {
                   16482:         my $ua = LWP::UserAgent->new;
                   16483:         $ua->timeout(10);
                   16484:         my %info = (
                   16485:                      secret   => $privkey,
                   16486:                      response => $env{'form.g-recaptcha-response'},
                   16487:                      remoteip => $ENV{'REMOTE_ADDR'},
                   16488:                    );
                   16489:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   16490:         if ($response->is_success)  {
                   16491:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   16492:             if (ref($data) eq 'HASH') {
                   16493:                 if ($data->{'success'}) {
                   16494:                     $captcha_chk = 1;
                   16495:                 }
                   16496:             }
                   16497:         }
                   16498:     } else {
                   16499:         my $captcha = Captcha::reCAPTCHA->new;
                   16500:         my $captcha_result =
                   16501:             $captcha->check_answer(
                   16502:                                     $privkey,
                   16503:                                     $ENV{'REMOTE_ADDR'},
                   16504:                                     $env{'form.recaptcha_challenge_field'},
                   16505:                                     $env{'form.recaptcha_response_field'},
                   16506:                                   );
                   16507:         if ($captcha_result->{is_valid}) {
                   16508:             $captcha_chk = 1;
                   16509:         }
1.1075.2.14  raeburn  16510:     }
                   16511:     return $captcha_chk;
                   16512: }
                   16513: 
1.1075.2.64  raeburn  16514: sub emailusername_info {
1.1075.2.103  raeburn  16515:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  16516:     my %titles = &Apache::lonlocal::texthash (
                   16517:                      lastname      => 'Last Name',
                   16518:                      firstname     => 'First Name',
                   16519:                      institution   => 'School/college/university',
                   16520:                      location      => "School's city, state/province, country",
                   16521:                      web           => "School's web address",
                   16522:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  16523:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  16524:                  );
                   16525:     return (\@fields,\%titles);
                   16526: }
                   16527: 
1.1075.2.56  raeburn  16528: sub cleanup_html {
                   16529:     my ($incoming) = @_;
                   16530:     my $outgoing;
                   16531:     if ($incoming ne '') {
                   16532:         $outgoing = $incoming;
                   16533:         $outgoing =~ s/;/&#059;/g;
                   16534:         $outgoing =~ s/\#/&#035;/g;
                   16535:         $outgoing =~ s/\&/&#038;/g;
                   16536:         $outgoing =~ s/</&#060;/g;
                   16537:         $outgoing =~ s/>/&#062;/g;
                   16538:         $outgoing =~ s/\(/&#040/g;
                   16539:         $outgoing =~ s/\)/&#041;/g;
                   16540:         $outgoing =~ s/"/&#034;/g;
                   16541:         $outgoing =~ s/'/&#039;/g;
                   16542:         $outgoing =~ s/\$/&#036;/g;
                   16543:         $outgoing =~ s{/}{&#047;}g;
                   16544:         $outgoing =~ s/=/&#061;/g;
                   16545:         $outgoing =~ s/\\/&#092;/g
                   16546:     }
                   16547:     return $outgoing;
                   16548: }
                   16549: 
1.1075.2.74  raeburn  16550: # Checks for critical messages and returns a redirect url if one exists.
                   16551: # $interval indicates how often to check for messages.
                   16552: sub critical_redirect {
                   16553:     my ($interval) = @_;
                   16554:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   16555:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   16556:                                         $env{'user.name'});
                   16557:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   16558:         my $redirecturl;
                   16559:         if ($what[0]) {
                   16560:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   16561:                 $redirecturl='/adm/email?critical=display';
                   16562:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   16563:                 return (1, $url);
                   16564:             }
                   16565:         }
                   16566:     }
                   16567:     return ();
                   16568: }
                   16569: 
1.1075.2.64  raeburn  16570: # Use:
                   16571: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   16572: #
                   16573: ##################################################
                   16574: #          password associated functions         #
                   16575: ##################################################
                   16576: sub des_keys {
                   16577:     # Make a new key for DES encryption.
                   16578:     # Each key has two parts which are returned separately.
                   16579:     # Please note:  Each key must be passed through the &hex function
                   16580:     # before it is output to the web browser.  The hex versions cannot
                   16581:     # be used to decrypt.
                   16582:     my @hexstr=('0','1','2','3','4','5','6','7',
                   16583:                 '8','9','a','b','c','d','e','f');
                   16584:     my $lkey='';
                   16585:     for (0..7) {
                   16586:         $lkey.=$hexstr[rand(15)];
                   16587:     }
                   16588:     my $ukey='';
                   16589:     for (0..7) {
                   16590:         $ukey.=$hexstr[rand(15)];
                   16591:     }
                   16592:     return ($lkey,$ukey);
                   16593: }
                   16594: 
                   16595: sub des_decrypt {
                   16596:     my ($key,$cyphertext) = @_;
                   16597:     my $keybin=pack("H16",$key);
                   16598:     my $cypher;
                   16599:     if ($Crypt::DES::VERSION>=2.03) {
                   16600:         $cypher=new Crypt::DES $keybin;
                   16601:     } else {
                   16602:         $cypher=new DES $keybin;
                   16603:     }
1.1075.2.106  raeburn  16604:     my $plaintext='';
                   16605:     my $cypherlength = length($cyphertext);
                   16606:     my $numchunks = int($cypherlength/32);
                   16607:     for (my $j=0; $j<$numchunks; $j++) {
                   16608:         my $start = $j*32;
                   16609:         my $cypherblock = substr($cyphertext,$start,32);
                   16610:         my $chunk =
                   16611:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   16612:         $chunk .=
                   16613:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   16614:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   16615:         $plaintext .= $chunk;
                   16616:     }
1.1075.2.64  raeburn  16617:     return $plaintext;
                   16618: }
                   16619: 
1.112     bowersj2 16620: 1;
                   16621: __END__;
1.41      ng       16622: 

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