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

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.127.  .1(raebu    4:20): # $Id: loncommon.pm,v 1.1075.2.127 2017/04/02 03:09:27 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.1075.2.119  raeburn   265:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   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.1075.2.115  raeburn   939:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    940:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   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 {
1.1075.2.115  raeburn   961:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    962:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   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 {
1.1075.2.115  raeburn  1014:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  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.1075.2.115  raeburn  1026:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
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) {
1.1075.2.119  raeburn  1141:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  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.1075.2.115  raeburn  2242: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
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
1.1075.2.115  raeburn  2247: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2248: An optional arg -- $readonly -- if true will cause the select form
                   2249: to be disabled, e.g., for the case where an instructor has a section-
                   2250: specific role, and is viewing/modifying parameters.  
1.970     raeburn  2251: 
1.88      www      2252: See lonrights.pm for an example invocation and use.
                   2253: 
                   2254: =cut
                   2255: 
                   2256: #-------------------------------------------
                   2257: sub select_form {
1.1075.2.115  raeburn  2258:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2259:     return unless (ref($hashref) eq 'HASH');
                   2260:     if ($onchange) {
                   2261:         $onchange = ' onchange="'.$onchange.'"';
                   2262:     }
                   2263:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.128     albertel 2264:     my @keys;
1.970     raeburn  2265:     if (exists($hashref->{'select_form_order'})) {
                   2266: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2267:     } else {
1.970     raeburn  2268: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2269:     }
1.356     albertel 2270:     foreach my $key (@keys) {
                   2271:         $selectform.=
                   2272: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2273:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2274:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2275:     }
                   2276:     $selectform.="</select>";
                   2277:     return $selectform;
                   2278: }
                   2279: 
1.475     www      2280: # For display filters
                   2281: 
                   2282: sub display_filter {
1.1074    raeburn  2283:     my ($context) = @_;
1.475     www      2284:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2285:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2286:     my $phraseinput = 'hidden';
                   2287:     my $includeinput = 'hidden';
                   2288:     my ($checked,$includetypestext);
                   2289:     if ($env{'form.displayfilter'} eq 'containing') {
                   2290:         $phraseinput = 'text'; 
                   2291:         if ($context eq 'parmslog') {
                   2292:             $includeinput = 'checkbox';
                   2293:             if ($env{'form.includetypes'}) {
                   2294:                 $checked = ' checked="checked"';
                   2295:             }
                   2296:             $includetypestext = &mt('Include parameter types');
                   2297:         }
                   2298:     } else {
                   2299:         $includetypestext = '&nbsp;';
                   2300:     }
                   2301:     my ($additional,$secondid,$thirdid);
                   2302:     if ($context eq 'parmslog') {
                   2303:         $additional = 
                   2304:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2305:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2306:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2307:             '</label>';
                   2308:         $secondid = 'includetypes';
                   2309:         $thirdid = 'includetypestext';
                   2310:     }
                   2311:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2312:                                                     '$secondid','$thirdid')";
                   2313:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2314: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2315: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2316: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2317:            &mt('Filter: [_1]',
1.477     www      2318: 	   &select_form($env{'form.displayfilter'},
                   2319: 			'displayfilter',
1.970     raeburn  2320: 			{'currentfolder' => 'Current folder/page',
1.477     www      2321: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2322: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2323: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2324:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2325:                          '" />'.$additional;
                   2326: }
                   2327: 
                   2328: sub display_filter_js {
                   2329:     my $includetext = &mt('Include parameter types');
                   2330:     return <<"ENDJS";
                   2331:   
                   2332: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2333:     var firstType = 'hidden';
                   2334:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2335:         firstType = 'text';
                   2336:     }
                   2337:     firstObject = document.getElementById(firstid);
                   2338:     if (typeof(firstObject) == 'object') {
                   2339:         if (firstObject.type != firstType) {
                   2340:             changeInputType(firstObject,firstType);
                   2341:         }
                   2342:     }
                   2343:     if (context == 'parmslog') {
                   2344:         var secondType = 'hidden';
                   2345:         if (firstType == 'text') {
                   2346:             secondType = 'checkbox';
                   2347:         }
                   2348:         secondObject = document.getElementById(secondid);  
                   2349:         if (typeof(secondObject) == 'object') {
                   2350:             if (secondObject.type != secondType) {
                   2351:                 changeInputType(secondObject,secondType);
                   2352:             }
                   2353:         }
                   2354:         var textItem = document.getElementById(thirdid);
                   2355:         var currtext = textItem.innerHTML;
                   2356:         var newtext;
                   2357:         if (firstType == 'text') {
                   2358:             newtext = '$includetext';
                   2359:         } else {
                   2360:             newtext = '&nbsp;';
                   2361:         }
                   2362:         if (currtext != newtext) {
                   2363:             textItem.innerHTML = newtext;
                   2364:         }
                   2365:     }
                   2366:     return;
                   2367: }
                   2368: 
                   2369: function changeInputType(oldObject,newType) {
                   2370:     var newObject = document.createElement('input');
                   2371:     newObject.type = newType;
                   2372:     if (oldObject.size) {
                   2373:         newObject.size = oldObject.size;
                   2374:     }
                   2375:     if (oldObject.value) {
                   2376:         newObject.value = oldObject.value;
                   2377:     }
                   2378:     if (oldObject.name) {
                   2379:         newObject.name = oldObject.name;
                   2380:     }
                   2381:     if (oldObject.id) {
                   2382:         newObject.id = oldObject.id;
                   2383:     }
                   2384:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2385:     return;
                   2386: }
                   2387: 
                   2388: ENDJS
1.475     www      2389: }
                   2390: 
1.167     www      2391: sub gradeleveldescription {
                   2392:     my $gradelevel=shift;
                   2393:     my %gradelevels=(0 => 'Not specified',
                   2394: 		     1 => 'Grade 1',
                   2395: 		     2 => 'Grade 2',
                   2396: 		     3 => 'Grade 3',
                   2397: 		     4 => 'Grade 4',
                   2398: 		     5 => 'Grade 5',
                   2399: 		     6 => 'Grade 6',
                   2400: 		     7 => 'Grade 7',
                   2401: 		     8 => 'Grade 8',
                   2402: 		     9 => 'Grade 9',
                   2403: 		     10 => 'Grade 10',
                   2404: 		     11 => 'Grade 11',
                   2405: 		     12 => 'Grade 12',
                   2406: 		     13 => 'Grade 13',
                   2407: 		     14 => '100 Level',
                   2408: 		     15 => '200 Level',
                   2409: 		     16 => '300 Level',
                   2410: 		     17 => '400 Level',
                   2411: 		     18 => 'Graduate Level');
                   2412:     return &mt($gradelevels{$gradelevel});
                   2413: }
                   2414: 
1.163     www      2415: sub select_level_form {
                   2416:     my ($deflevel,$name)=@_;
                   2417:     unless ($deflevel) { $deflevel=0; }
1.167     www      2418:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2419:     for (my $i=0; $i<=18; $i++) {
                   2420:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2421:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2422:                 ">".&gradeleveldescription($i)."</option>\n";
                   2423:     }
                   2424:     $selectform.="</select>";
                   2425:     return $selectform;
1.163     www      2426: }
1.167     www      2427: 
1.35      matthew  2428: #-------------------------------------------
                   2429: 
1.45      matthew  2430: =pod
                   2431: 
1.1075.2.115  raeburn  2432: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2433: 
                   2434: Returns a string containing a <select name='$name' size='1'> form to 
                   2435: allow a user to select the domain to preform an operation in.  
                   2436: See loncreateuser.pm for an example invocation and use.
                   2437: 
1.90      www      2438: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2439: selected");
                   2440: 
1.743     raeburn  2441: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2442: 
1.910     raeburn  2443: 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.
                   2444: 
1.1075.2.36  raeburn  2445: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2446: 
1.1075.2.115  raeburn  2447: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
                   2448: 
                   2449: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
1.563     raeburn  2450: 
1.35      matthew  2451: =cut
                   2452: 
                   2453: #-------------------------------------------
1.34      matthew  2454: sub select_dom_form {
1.1075.2.115  raeburn  2455:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2456:     if ($onchange) {
1.874     raeburn  2457:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2458:     }
1.1075.2.115  raeburn  2459:     if ($disabled) {
                   2460:         $disabled = ' disabled="disabled"';
                   2461:     }
1.1075.2.36  raeburn  2462:     my (@domains,%exclude);
1.910     raeburn  2463:     if (ref($incdoms) eq 'ARRAY') {
                   2464:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2465:     } else {
                   2466:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2467:     }
1.90      www      2468:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2469:     if (ref($excdoms) eq 'ARRAY') {
                   2470:         map { $exclude{$_} = 1; } @{$excdoms};
                   2471:     }
1.1075.2.115  raeburn  2472:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2473:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2474:         next if ($exclude{$dom});
1.356     albertel 2475:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2476:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2477:         if ($showdomdesc) {
                   2478:             if ($dom ne '') {
                   2479:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2480:                 if ($domdesc ne '') {
                   2481:                     $selectdomain .= ' ('.$domdesc.')';
                   2482:                 }
                   2483:             } 
                   2484:         }
                   2485:         $selectdomain .= "</option>\n";
1.34      matthew  2486:     }
                   2487:     $selectdomain.="</select>";
                   2488:     return $selectdomain;
                   2489: }
                   2490: 
1.35      matthew  2491: #-------------------------------------------
                   2492: 
1.45      matthew  2493: =pod
                   2494: 
1.648     raeburn  2495: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2496: 
1.586     raeburn  2497: input: 4 arguments (two required, two optional) - 
                   2498:     $domain - domain of new user
                   2499:     $name - name of form element
                   2500:     $default - Value of 'default' causes a default item to be first 
                   2501:                             option, and selected by default. 
                   2502:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2503:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2504: output: returns 2 items: 
1.586     raeburn  2505: (a) form element which contains either:
                   2506:    (i) <select name="$name">
                   2507:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2508:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2509:        </select>
                   2510:        form item if there are multiple library servers in $domain, or
                   2511:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2512:        if there is only one library server in $domain.
                   2513: 
                   2514: (b) number of library servers found.
                   2515: 
                   2516: See loncreateuser.pm for example of use.
1.35      matthew  2517: 
                   2518: =cut
                   2519: 
                   2520: #-------------------------------------------
1.586     raeburn  2521: sub home_server_form_item {
                   2522:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2523:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2524:     my $result;
                   2525:     my $numlib = keys(%servers);
                   2526:     if ($numlib > 1) {
                   2527:         $result .= '<select name="'.$name.'" />'."\n";
                   2528:         if ($default) {
1.804     bisitz   2529:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2530:                        '</option>'."\n";
                   2531:         }
                   2532:         foreach my $hostid (sort(keys(%servers))) {
                   2533:             $result.= '<option value="'.$hostid.'">'.
                   2534: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2535:         }
                   2536:         $result .= '</select>'."\n";
                   2537:     } elsif ($numlib == 1) {
                   2538:         my $hostid;
                   2539:         foreach my $item (keys(%servers)) {
                   2540:             $hostid = $item;
                   2541:         }
                   2542:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2543:                    $hostid.'" />';
                   2544:                    if (!$hide) {
                   2545:                        $result .= $hostid.' '.$servers{$hostid};
                   2546:                    }
                   2547:                    $result .= "\n";
                   2548:     } elsif ($default) {
                   2549:         $result .= '<input type="hidden" name="'.$name.
                   2550:                    '" value="default" />';
                   2551:                    if (!$hide) {
                   2552:                        $result .= &mt('default');
                   2553:                    }
                   2554:                    $result .= "\n";
1.33      matthew  2555:     }
1.586     raeburn  2556:     return ($result,$numlib);
1.33      matthew  2557: }
1.112     bowersj2 2558: 
                   2559: =pod
                   2560: 
1.534     albertel 2561: =back 
                   2562: 
1.112     bowersj2 2563: =cut
1.87      matthew  2564: 
                   2565: ###############################################################
1.112     bowersj2 2566: ##                  Decoding User Agent                      ##
1.87      matthew  2567: ###############################################################
                   2568: 
                   2569: =pod
                   2570: 
1.112     bowersj2 2571: =head1 Decoding the User Agent
                   2572: 
                   2573: =over 4
                   2574: 
                   2575: =item * &decode_user_agent()
1.87      matthew  2576: 
                   2577: Inputs: $r
                   2578: 
                   2579: Outputs:
                   2580: 
                   2581: =over 4
                   2582: 
1.112     bowersj2 2583: =item * $httpbrowser
1.87      matthew  2584: 
1.112     bowersj2 2585: =item * $clientbrowser
1.87      matthew  2586: 
1.112     bowersj2 2587: =item * $clientversion
1.87      matthew  2588: 
1.112     bowersj2 2589: =item * $clientmathml
1.87      matthew  2590: 
1.112     bowersj2 2591: =item * $clientunicode
1.87      matthew  2592: 
1.112     bowersj2 2593: =item * $clientos
1.87      matthew  2594: 
1.1075.2.42  raeburn  2595: =item * $clientmobile
                   2596: 
                   2597: =item * $clientinfo
                   2598: 
1.1075.2.77  raeburn  2599: =item * $clientosversion
                   2600: 
1.87      matthew  2601: =back
                   2602: 
1.157     matthew  2603: =back 
                   2604: 
1.87      matthew  2605: =cut
                   2606: 
                   2607: ###############################################################
                   2608: ###############################################################
                   2609: sub decode_user_agent {
1.247     albertel 2610:     my ($r)=@_;
1.87      matthew  2611:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2612:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2613:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2614:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2615:     my $clientbrowser='unknown';
                   2616:     my $clientversion='0';
                   2617:     my $clientmathml='';
                   2618:     my $clientunicode='0';
1.1075.2.42  raeburn  2619:     my $clientmobile=0;
1.1075.2.77  raeburn  2620:     my $clientosversion='';
1.87      matthew  2621:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1075.2.76  raeburn  2622:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2623: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2624: 	    $clientbrowser=$bname;
                   2625:             $httpbrowser=~/$vreg/i;
                   2626: 	    $clientversion=$1;
                   2627:             $clientmathml=($clientversion>=$minv);
                   2628:             $clientunicode=($clientversion>=$univ);
                   2629: 	}
                   2630:     }
                   2631:     my $clientos='unknown';
1.1075.2.42  raeburn  2632:     my $clientinfo;
1.87      matthew  2633:     if (($httpbrowser=~/linux/i) ||
                   2634:         ($httpbrowser=~/unix/i) ||
                   2635:         ($httpbrowser=~/ux/i) ||
                   2636:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2637:     if (($httpbrowser=~/vax/i) ||
                   2638:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2639:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2640:     if (($httpbrowser=~/mac/i) ||
                   2641:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1075.2.77  raeburn  2642:     if ($httpbrowser=~/win/i) {
                   2643:         $clientos='win';
                   2644:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2645:             $clientosversion = $1;
                   2646:         }
                   2647:     }
1.87      matthew  2648:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2649:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2650:         $clientmobile=lc($1);
                   2651:     }
                   2652:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2653:         $clientinfo = 'firefox-'.$1;
                   2654:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2655:         $clientinfo = 'chromeframe-'.$1;
                   2656:     }
1.87      matthew  2657:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.77  raeburn  2658:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2659:             $clientosversion);
1.87      matthew  2660: }
                   2661: 
1.32      matthew  2662: ###############################################################
                   2663: ##    Authentication changing form generation subroutines    ##
                   2664: ###############################################################
                   2665: ##
                   2666: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2667: ## hash, and have reasonable default values.
                   2668: ##
                   2669: ##    formname = the name given in the <form> tag.
1.35      matthew  2670: #-------------------------------------------
                   2671: 
1.45      matthew  2672: =pod
                   2673: 
1.112     bowersj2 2674: =head1 Authentication Routines
                   2675: 
                   2676: =over 4
                   2677: 
1.648     raeburn  2678: =item * &authform_xxxxxx()
1.35      matthew  2679: 
                   2680: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2681: handle some of the conveniences required for authentication forms.  
                   2682: This is not an optimal method, but it works.  
                   2683: 
                   2684: =over 4
                   2685: 
1.112     bowersj2 2686: =item * authform_header
1.35      matthew  2687: 
1.112     bowersj2 2688: =item * authform_authorwarning
1.35      matthew  2689: 
1.112     bowersj2 2690: =item * authform_nochange
1.35      matthew  2691: 
1.112     bowersj2 2692: =item * authform_kerberos
1.35      matthew  2693: 
1.112     bowersj2 2694: =item * authform_internal
1.35      matthew  2695: 
1.112     bowersj2 2696: =item * authform_filesystem
1.35      matthew  2697: 
                   2698: =back
                   2699: 
1.648     raeburn  2700: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2701: 
1.35      matthew  2702: =cut
                   2703: 
                   2704: #-------------------------------------------
1.32      matthew  2705: sub authform_header{  
                   2706:     my %in = (
                   2707:         formname => 'cu',
1.80      albertel 2708:         kerb_def_dom => '',
1.32      matthew  2709:         @_,
                   2710:     );
                   2711:     $in{'formname'} = 'document.' . $in{'formname'};
                   2712:     my $result='';
1.80      albertel 2713: 
                   2714: #---------------------------------------------- Code for upper case translation
                   2715:     my $Javascript_toUpperCase;
                   2716:     unless ($in{kerb_def_dom}) {
                   2717:         $Javascript_toUpperCase =<<"END";
                   2718:         switch (choice) {
                   2719:            case 'krb': currentform.elements[choicearg].value =
                   2720:                currentform.elements[choicearg].value.toUpperCase();
                   2721:                break;
                   2722:            default:
                   2723:         }
                   2724: END
                   2725:     } else {
                   2726:         $Javascript_toUpperCase = "";
                   2727:     }
                   2728: 
1.165     raeburn  2729:     my $radioval = "'nochange'";
1.591     raeburn  2730:     if (defined($in{'curr_authtype'})) {
                   2731:         if ($in{'curr_authtype'} ne '') {
                   2732:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2733:         }
1.174     matthew  2734:     }
1.165     raeburn  2735:     my $argfield = 'null';
1.591     raeburn  2736:     if (defined($in{'mode'})) {
1.165     raeburn  2737:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2738:             if (defined($in{'curr_autharg'})) {
                   2739:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2740:                     $argfield = "'$in{'curr_autharg'}'";
                   2741:                 }
                   2742:             }
                   2743:         }
                   2744:     }
                   2745: 
1.32      matthew  2746:     $result.=<<"END";
                   2747: var current = new Object();
1.165     raeburn  2748: current.radiovalue = $radioval;
                   2749: current.argfield = $argfield;
1.32      matthew  2750: 
                   2751: function changed_radio(choice,currentform) {
                   2752:     var choicearg = choice + 'arg';
                   2753:     // If a radio button in changed, we need to change the argfield
                   2754:     if (current.radiovalue != choice) {
                   2755:         current.radiovalue = choice;
                   2756:         if (current.argfield != null) {
                   2757:             currentform.elements[current.argfield].value = '';
                   2758:         }
                   2759:         if (choice == 'nochange') {
                   2760:             current.argfield = null;
                   2761:         } else {
                   2762:             current.argfield = choicearg;
                   2763:             switch(choice) {
                   2764:                 case 'krb': 
                   2765:                     currentform.elements[current.argfield].value = 
                   2766:                         "$in{'kerb_def_dom'}";
                   2767:                 break;
                   2768:               default:
                   2769:                 break;
                   2770:             }
                   2771:         }
                   2772:     }
                   2773:     return;
                   2774: }
1.22      www      2775: 
1.32      matthew  2776: function changed_text(choice,currentform) {
                   2777:     var choicearg = choice + 'arg';
                   2778:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2779:         $Javascript_toUpperCase
1.32      matthew  2780:         // clear old field
                   2781:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2782:             currentform.elements[current.argfield].value = '';
                   2783:         }
                   2784:         current.argfield = choicearg;
                   2785:     }
                   2786:     set_auth_radio_buttons(choice,currentform);
                   2787:     return;
1.20      www      2788: }
1.32      matthew  2789: 
                   2790: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2791:     var numauthchoices = currentform.login.length;
                   2792:     if (typeof numauthchoices  == "undefined") {
                   2793:         return;
                   2794:     } 
1.32      matthew  2795:     var i=0;
1.986     raeburn  2796:     while (i < numauthchoices) {
1.32      matthew  2797:         if (currentform.login[i].value == newvalue) { break; }
                   2798:         i++;
                   2799:     }
1.986     raeburn  2800:     if (i == numauthchoices) {
1.32      matthew  2801:         return;
                   2802:     }
                   2803:     current.radiovalue = newvalue;
                   2804:     currentform.login[i].checked = true;
                   2805:     return;
                   2806: }
                   2807: END
                   2808:     return $result;
                   2809: }
                   2810: 
1.1075.2.20  raeburn  2811: sub authform_authorwarning {
1.32      matthew  2812:     my $result='';
1.144     matthew  2813:     $result='<i>'.
                   2814:         &mt('As a general rule, only authors or co-authors should be '.
                   2815:             'filesystem authenticated '.
                   2816:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2817:     return $result;
                   2818: }
                   2819: 
1.1075.2.20  raeburn  2820: sub authform_nochange {
1.32      matthew  2821:     my %in = (
                   2822:               formname => 'document.cu',
                   2823:               kerb_def_dom => 'MSU.EDU',
                   2824:               @_,
                   2825:           );
1.1075.2.20  raeburn  2826:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2827:     my $result;
1.1075.2.20  raeburn  2828:     if (!$authnum) {
                   2829:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2830:     } else {
                   2831:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2832:                   '<input type="radio" name="login" value="nochange" '.
                   2833:                   'checked="checked" onclick="'.
1.281     albertel 2834:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2835: 	    '</label>';
1.586     raeburn  2836:     }
1.32      matthew  2837:     return $result;
                   2838: }
                   2839: 
1.591     raeburn  2840: sub authform_kerberos {
1.32      matthew  2841:     my %in = (
                   2842:               formname => 'document.cu',
                   2843:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2844:               kerb_def_auth => 'krb4',
1.32      matthew  2845:               @_,
                   2846:               );
1.586     raeburn  2847:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1075.2.117  raeburn  2848:         $autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2849:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2850:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2851:        $check5 = ' checked="checked"';
1.80      albertel 2852:     } else {
1.772     bisitz   2853:        $check4 = ' checked="checked"';
1.80      albertel 2854:     }
1.1075.2.117  raeburn  2855:     if ($in{'readonly'}) {
                   2856:         $disabled = ' disabled="disabled"';
                   2857:     }
1.165     raeburn  2858:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2859:     if (defined($in{'curr_authtype'})) {
                   2860:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2861:             $krbcheck = ' checked="checked"';
1.623     raeburn  2862:             if (defined($in{'mode'})) {
                   2863:                 if ($in{'mode'} eq 'modifyuser') {
                   2864:                     $krbcheck = '';
                   2865:                 }
                   2866:             }
1.591     raeburn  2867:             if (defined($in{'curr_kerb_ver'})) {
                   2868:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2869:                     $check5 = ' checked="checked"';
1.591     raeburn  2870:                     $check4 = '';
                   2871:                 } else {
1.772     bisitz   2872:                     $check4 = ' checked="checked"';
1.591     raeburn  2873:                     $check5 = '';
                   2874:                 }
1.586     raeburn  2875:             }
1.591     raeburn  2876:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2877:                 $krbarg = $in{'curr_autharg'};
                   2878:             }
1.586     raeburn  2879:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2880:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2881:                     $result = 
                   2882:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2883:         $in{'curr_autharg'},$krbver);
                   2884:                 } else {
                   2885:                     $result =
                   2886:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2887:                 }
                   2888:                 return $result; 
                   2889:             }
                   2890:         }
                   2891:     } else {
                   2892:         if ($authnum == 1) {
1.784     bisitz   2893:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2894:         }
                   2895:     }
1.586     raeburn  2896:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2897:         return;
1.587     raeburn  2898:     } elsif ($authtype eq '') {
1.591     raeburn  2899:         if (defined($in{'mode'})) {
1.587     raeburn  2900:             if ($in{'mode'} eq 'modifycourse') {
                   2901:                 if ($authnum == 1) {
1.1075.2.117  raeburn  2902:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  2903:                 }
                   2904:             }
                   2905:         }
1.586     raeburn  2906:     }
                   2907:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2908:     if ($authtype eq '') {
                   2909:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2910:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1075.2.117  raeburn  2911:                     $krbcheck.$disabled.' />';
1.586     raeburn  2912:     }
                   2913:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2914:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2915:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2916:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2917:          $in{'curr_authtype'} eq 'krb4')) {
                   2918:         $result .= &mt
1.144     matthew  2919:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2920:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2921:          '<label>'.$authtype,
1.281     albertel 2922:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2923:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2924:              'onchange="'.$jscall.'"'.$disabled.' />',
                   2925:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   2926:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 2927: 	 '</label>');
1.586     raeburn  2928:     } elsif ($can_assign{'krb4'}) {
                   2929:         $result .= &mt
                   2930:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2931:          '[_3] Version 4 [_4]',
                   2932:          '<label>'.$authtype,
                   2933:          '</label><input type="text" size="10" name="krbarg" '.
                   2934:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2935:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2936:          '<label><input type="hidden" name="krbver" value="4" />',
                   2937:          '</label>');
                   2938:     } elsif ($can_assign{'krb5'}) {
                   2939:         $result .= &mt
                   2940:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2941:          '[_3] Version 5 [_4]',
                   2942:          '<label>'.$authtype,
                   2943:          '</label><input type="text" size="10" name="krbarg" '.
                   2944:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2945:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2946:          '<label><input type="hidden" name="krbver" value="5" />',
                   2947:          '</label>');
                   2948:     }
1.32      matthew  2949:     return $result;
                   2950: }
                   2951: 
1.1075.2.20  raeburn  2952: sub authform_internal {
1.586     raeburn  2953:     my %in = (
1.32      matthew  2954:                 formname => 'document.cu',
                   2955:                 kerb_def_dom => 'MSU.EDU',
                   2956:                 @_,
                   2957:                 );
1.1075.2.117  raeburn  2958:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2959:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  2960:     if ($in{'readonly'}) {
                   2961:         $disabled = ' disabled="disabled"';
                   2962:     }
1.591     raeburn  2963:     if (defined($in{'curr_authtype'})) {
                   2964:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2965:             if ($can_assign{'int'}) {
1.772     bisitz   2966:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2967:                 if (defined($in{'mode'})) {
                   2968:                     if ($in{'mode'} eq 'modifyuser') {
                   2969:                         $intcheck = '';
                   2970:                     }
                   2971:                 }
1.591     raeburn  2972:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2973:                     $intarg = $in{'curr_autharg'};
                   2974:                 }
                   2975:             } else {
                   2976:                 $result = &mt('Currently internally authenticated.');
                   2977:                 return $result;
1.165     raeburn  2978:             }
                   2979:         }
1.586     raeburn  2980:     } else {
                   2981:         if ($authnum == 1) {
1.784     bisitz   2982:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2983:         }
                   2984:     }
                   2985:     if (!$can_assign{'int'}) {
                   2986:         return;
1.587     raeburn  2987:     } elsif ($authtype eq '') {
1.591     raeburn  2988:         if (defined($in{'mode'})) {
1.587     raeburn  2989:             if ($in{'mode'} eq 'modifycourse') {
                   2990:                 if ($authnum == 1) {
1.1075.2.117  raeburn  2991:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  2992:                 }
                   2993:             }
                   2994:         }
1.165     raeburn  2995:     }
1.586     raeburn  2996:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2997:     if ($authtype eq '') {
                   2998:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1075.2.117  raeburn  2999:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3000:     }
1.605     bisitz   3001:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1075.2.117  raeburn  3002:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3003:     $result = &mt
1.144     matthew  3004:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3005:          '<label>'.$authtype,'</label>'.$autharg);
1.1075.2.118  raeburn  3006:     $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
1.32      matthew  3007:     return $result;
                   3008: }
                   3009: 
1.1075.2.20  raeburn  3010: sub authform_local {
1.32      matthew  3011:     my %in = (
                   3012:               formname => 'document.cu',
                   3013:               kerb_def_dom => 'MSU.EDU',
                   3014:               @_,
                   3015:               );
1.1075.2.117  raeburn  3016:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3017:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3018:     if ($in{'readonly'}) {
                   3019:         $disabled = ' disabled="disabled"';
                   3020:     }
1.591     raeburn  3021:     if (defined($in{'curr_authtype'})) {
                   3022:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3023:             if ($can_assign{'loc'}) {
1.772     bisitz   3024:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3025:                 if (defined($in{'mode'})) {
                   3026:                     if ($in{'mode'} eq 'modifyuser') {
                   3027:                         $loccheck = '';
                   3028:                     }
                   3029:                 }
1.591     raeburn  3030:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3031:                     $locarg = $in{'curr_autharg'};
                   3032:                 }
                   3033:             } else {
                   3034:                 $result = &mt('Currently using local (institutional) authentication.');
                   3035:                 return $result;
1.165     raeburn  3036:             }
                   3037:         }
1.586     raeburn  3038:     } else {
                   3039:         if ($authnum == 1) {
1.784     bisitz   3040:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3041:         }
                   3042:     }
                   3043:     if (!$can_assign{'loc'}) {
                   3044:         return;
1.587     raeburn  3045:     } elsif ($authtype eq '') {
1.591     raeburn  3046:         if (defined($in{'mode'})) {
1.587     raeburn  3047:             if ($in{'mode'} eq 'modifycourse') {
                   3048:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3049:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3050:                 }
                   3051:             }
                   3052:         }
1.165     raeburn  3053:     }
1.586     raeburn  3054:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3055:     if ($authtype eq '') {
                   3056:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3057:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3058:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3059:     }
                   3060:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1075.2.117  raeburn  3061:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3062:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3063:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3064:     return $result;
                   3065: }
                   3066: 
1.1075.2.20  raeburn  3067: sub authform_filesystem {
1.32      matthew  3068:     my %in = (
                   3069:               formname => 'document.cu',
                   3070:               kerb_def_dom => 'MSU.EDU',
                   3071:               @_,
                   3072:               );
1.1075.2.117  raeburn  3073:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3074:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3075:     if ($in{'readonly'}) {
                   3076:         $disabled = ' disabled="disabled"';
                   3077:     }
1.591     raeburn  3078:     if (defined($in{'curr_authtype'})) {
                   3079:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3080:             if ($can_assign{'fsys'}) {
1.772     bisitz   3081:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3082:                 if (defined($in{'mode'})) {
                   3083:                     if ($in{'mode'} eq 'modifyuser') {
                   3084:                         $fsyscheck = '';
                   3085:                     }
                   3086:                 }
1.586     raeburn  3087:             } else {
                   3088:                 $result = &mt('Currently Filesystem Authenticated.');
                   3089:                 return $result;
                   3090:             }           
                   3091:         }
                   3092:     } else {
                   3093:         if ($authnum == 1) {
1.784     bisitz   3094:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3095:         }
                   3096:     }
                   3097:     if (!$can_assign{'fsys'}) {
                   3098:         return;
1.587     raeburn  3099:     } elsif ($authtype eq '') {
1.591     raeburn  3100:         if (defined($in{'mode'})) {
1.587     raeburn  3101:             if ($in{'mode'} eq 'modifycourse') {
                   3102:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3103:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3104:                 }
                   3105:             }
                   3106:         }
1.586     raeburn  3107:     }
                   3108:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3109:     if ($authtype eq '') {
                   3110:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3111:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3112:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3113:     }
                   3114:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
1.1075.2.117  raeburn  3115:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3116:     $result = &mt
1.144     matthew  3117:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3118:          '<label><input type="radio" name="login" value="fsys" '.
1.1075.2.117  raeburn  3119:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
1.605     bisitz   3120:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.1075.2.117  raeburn  3121:                   'onchange="'.$jscall.'"'.$disabled.' />');
1.32      matthew  3122:     return $result;
                   3123: }
                   3124: 
1.586     raeburn  3125: sub get_assignable_auth {
                   3126:     my ($dom) = @_;
                   3127:     if ($dom eq '') {
                   3128:         $dom = $env{'request.role.domain'};
                   3129:     }
                   3130:     my %can_assign = (
                   3131:                           krb4 => 1,
                   3132:                           krb5 => 1,
                   3133:                           int  => 1,
                   3134:                           loc  => 1,
                   3135:                      );
                   3136:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3137:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3138:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3139:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3140:             my $context;
                   3141:             if ($env{'request.role'} =~ /^au/) {
                   3142:                 $context = 'author';
1.1075.2.117  raeburn  3143:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3144:                 $context = 'domain';
                   3145:             } elsif ($env{'request.course.id'}) {
                   3146:                 $context = 'course';
                   3147:             }
                   3148:             if ($context) {
                   3149:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3150:                    %can_assign = %{$authhash->{$context}}; 
                   3151:                 }
                   3152:             }
                   3153:         }
                   3154:     }
                   3155:     my $authnum = 0;
                   3156:     foreach my $key (keys(%can_assign)) {
                   3157:         if ($can_assign{$key}) {
                   3158:             $authnum ++;
                   3159:         }
                   3160:     }
                   3161:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3162:         $authnum --;
                   3163:     }
                   3164:     return ($authnum,%can_assign);
                   3165: }
                   3166: 
1.80      albertel 3167: ###############################################################
                   3168: ##    Get Kerberos Defaults for Domain                 ##
                   3169: ###############################################################
                   3170: ##
                   3171: ## Returns default kerberos version and an associated argument
                   3172: ## as listed in file domain.tab. If not listed, provides
                   3173: ## appropriate default domain and kerberos version.
                   3174: ##
                   3175: #-------------------------------------------
                   3176: 
                   3177: =pod
                   3178: 
1.648     raeburn  3179: =item * &get_kerberos_defaults()
1.80      albertel 3180: 
                   3181: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3182: version and domain. If not found, it defaults to version 4 and the 
                   3183: domain of the server.
1.80      albertel 3184: 
1.648     raeburn  3185: =over 4
                   3186: 
1.80      albertel 3187: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3188: 
1.648     raeburn  3189: =back
                   3190: 
                   3191: =back
                   3192: 
1.80      albertel 3193: =cut
                   3194: 
                   3195: #-------------------------------------------
                   3196: sub get_kerberos_defaults {
                   3197:     my $domain=shift;
1.641     raeburn  3198:     my ($krbdef,$krbdefdom);
                   3199:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3200:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3201:         $krbdef = $domdefaults{'auth_def'};
                   3202:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3203:     } else {
1.80      albertel 3204:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3205:         my $krbdefdom=$1;
                   3206:         $krbdefdom=~tr/a-z/A-Z/;
                   3207:         $krbdef = "krb4";
                   3208:     }
                   3209:     return ($krbdef,$krbdefdom);
                   3210: }
1.112     bowersj2 3211: 
1.32      matthew  3212: 
1.46      matthew  3213: ###############################################################
                   3214: ##                Thesaurus Functions                        ##
                   3215: ###############################################################
1.20      www      3216: 
1.46      matthew  3217: =pod
1.20      www      3218: 
1.112     bowersj2 3219: =head1 Thesaurus Functions
                   3220: 
                   3221: =over 4
                   3222: 
1.648     raeburn  3223: =item * &initialize_keywords()
1.46      matthew  3224: 
                   3225: Initializes the package variable %Keywords if it is empty.  Uses the
                   3226: package variable $thesaurus_db_file.
                   3227: 
                   3228: =cut
                   3229: 
                   3230: ###################################################
                   3231: 
                   3232: sub initialize_keywords {
                   3233:     return 1 if (scalar keys(%Keywords));
                   3234:     # If we are here, %Keywords is empty, so fill it up
                   3235:     #   Make sure the file we need exists...
                   3236:     if (! -e $thesaurus_db_file) {
                   3237:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3238:                                  " failed because it does not exist");
                   3239:         return 0;
                   3240:     }
                   3241:     #   Set up the hash as a database
                   3242:     my %thesaurus_db;
                   3243:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3244:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3245:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3246:                                  $thesaurus_db_file);
                   3247:         return 0;
                   3248:     } 
                   3249:     #  Get the average number of appearances of a word.
                   3250:     my $avecount = $thesaurus_db{'average.count'};
                   3251:     #  Put keywords (those that appear > average) into %Keywords
                   3252:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3253:         my ($count,undef) = split /:/,$data;
                   3254:         $Keywords{$word}++ if ($count > $avecount);
                   3255:     }
                   3256:     untie %thesaurus_db;
                   3257:     # Remove special values from %Keywords.
1.356     albertel 3258:     foreach my $value ('total.count','average.count') {
                   3259:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3260:   }
1.46      matthew  3261:     return 1;
                   3262: }
                   3263: 
                   3264: ###################################################
                   3265: 
                   3266: =pod
                   3267: 
1.648     raeburn  3268: =item * &keyword($word)
1.46      matthew  3269: 
                   3270: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3271: than the average number of times in the thesaurus database.  Calls 
                   3272: &initialize_keywords
                   3273: 
                   3274: =cut
                   3275: 
                   3276: ###################################################
1.20      www      3277: 
                   3278: sub keyword {
1.46      matthew  3279:     return if (!&initialize_keywords());
                   3280:     my $word=lc(shift());
                   3281:     $word=~s/\W//g;
                   3282:     return exists($Keywords{$word});
1.20      www      3283: }
1.46      matthew  3284: 
                   3285: ###############################################################
                   3286: 
                   3287: =pod 
1.20      www      3288: 
1.648     raeburn  3289: =item * &get_related_words()
1.46      matthew  3290: 
1.160     matthew  3291: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3292: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3293: will be returned.  The order of the words returned is determined by the
                   3294: database which holds them.
                   3295: 
                   3296: Uses global $thesaurus_db_file.
                   3297: 
1.1057    foxr     3298: 
1.46      matthew  3299: =cut
                   3300: 
                   3301: ###############################################################
                   3302: sub get_related_words {
                   3303:     my $keyword = shift;
                   3304:     my %thesaurus_db;
                   3305:     if (! -e $thesaurus_db_file) {
                   3306:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3307:                                  "failed because the file does not exist");
                   3308:         return ();
                   3309:     }
                   3310:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3311:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3312:         return ();
                   3313:     } 
                   3314:     my @Words=();
1.429     www      3315:     my $count=0;
1.46      matthew  3316:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3317: 	# The first element is the number of times
                   3318: 	# the word appears.  We do not need it now.
1.429     www      3319: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3320: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3321: 	my $threshold=$mostfrequentcount/10;
                   3322:         foreach my $possibleword (@RelatedWords) {
                   3323:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3324:             if ($wordcount>$threshold) {
                   3325: 		push(@Words,$word);
                   3326:                 $count++;
                   3327:                 if ($count>10) { last; }
                   3328: 	    }
1.20      www      3329:         }
                   3330:     }
1.46      matthew  3331:     untie %thesaurus_db;
                   3332:     return @Words;
1.14      harris41 3333: }
1.46      matthew  3334: 
1.112     bowersj2 3335: =pod
                   3336: 
                   3337: =back
                   3338: 
                   3339: =cut
1.61      www      3340: 
                   3341: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3342: =pod
                   3343: 
1.112     bowersj2 3344: =head1 User Name Functions
                   3345: 
                   3346: =over 4
                   3347: 
1.648     raeburn  3348: =item * &plainname($uname,$udom,$first)
1.81      albertel 3349: 
1.112     bowersj2 3350: Takes a users logon name and returns it as a string in
1.226     albertel 3351: "first middle last generation" form 
                   3352: if $first is set to 'lastname' then it returns it as
                   3353: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3354: 
                   3355: =cut
1.61      www      3356: 
1.295     www      3357: 
1.81      albertel 3358: ###############################################################
1.61      www      3359: sub plainname {
1.226     albertel 3360:     my ($uname,$udom,$first)=@_;
1.537     albertel 3361:     return if (!defined($uname) || !defined($udom));
1.295     www      3362:     my %names=&getnames($uname,$udom);
1.226     albertel 3363:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3364: 					  $names{'middlename'},
                   3365: 					  $names{'lastname'},
                   3366: 					  $names{'generation'},$first);
                   3367:     $name=~s/^\s+//;
1.62      www      3368:     $name=~s/\s+$//;
                   3369:     $name=~s/\s+/ /g;
1.353     albertel 3370:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3371:     return $name;
1.61      www      3372: }
1.66      www      3373: 
                   3374: # -------------------------------------------------------------------- Nickname
1.81      albertel 3375: =pod
                   3376: 
1.648     raeburn  3377: =item * &nickname($uname,$udom)
1.81      albertel 3378: 
                   3379: Gets a users name and returns it as a string as
                   3380: 
                   3381: "&quot;nickname&quot;"
1.66      www      3382: 
1.81      albertel 3383: if the user has a nickname or
                   3384: 
                   3385: "first middle last generation"
                   3386: 
                   3387: if the user does not
                   3388: 
                   3389: =cut
1.66      www      3390: 
                   3391: sub nickname {
                   3392:     my ($uname,$udom)=@_;
1.537     albertel 3393:     return if (!defined($uname) || !defined($udom));
1.295     www      3394:     my %names=&getnames($uname,$udom);
1.68      albertel 3395:     my $name=$names{'nickname'};
1.66      www      3396:     if ($name) {
                   3397:        $name='&quot;'.$name.'&quot;'; 
                   3398:     } else {
                   3399:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3400: 	     $names{'lastname'}.' '.$names{'generation'};
                   3401:        $name=~s/\s+$//;
                   3402:        $name=~s/\s+/ /g;
                   3403:     }
                   3404:     return $name;
                   3405: }
                   3406: 
1.295     www      3407: sub getnames {
                   3408:     my ($uname,$udom)=@_;
1.537     albertel 3409:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3410:     if ($udom eq 'public' && $uname eq 'public') {
                   3411: 	return ('lastname' => &mt('Public'));
                   3412:     }
1.295     www      3413:     my $id=$uname.':'.$udom;
                   3414:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3415:     if ($cached) {
                   3416: 	return %{$names};
                   3417:     } else {
                   3418: 	my %loadnames=&Apache::lonnet::get('environment',
                   3419:                     ['firstname','middlename','lastname','generation','nickname'],
                   3420: 					 $udom,$uname);
                   3421: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3422: 	return %loadnames;
                   3423:     }
                   3424: }
1.61      www      3425: 
1.542     raeburn  3426: # -------------------------------------------------------------------- getemails
1.648     raeburn  3427: 
1.542     raeburn  3428: =pod
                   3429: 
1.648     raeburn  3430: =item * &getemails($uname,$udom)
1.542     raeburn  3431: 
                   3432: Gets a user's email information and returns it as a hash with keys:
                   3433: notification, critnotification, permanentemail
                   3434: 
                   3435: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3436: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3437:  
1.648     raeburn  3438: 
1.542     raeburn  3439: =cut
                   3440: 
1.648     raeburn  3441: 
1.466     albertel 3442: sub getemails {
                   3443:     my ($uname,$udom)=@_;
                   3444:     if ($udom eq 'public' && $uname eq 'public') {
                   3445: 	return;
                   3446:     }
1.467     www      3447:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3448:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3449:     my $id=$uname.':'.$udom;
                   3450:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3451:     if ($cached) {
                   3452: 	return %{$names};
                   3453:     } else {
                   3454: 	my %loadnames=&Apache::lonnet::get('environment',
                   3455:                     			   ['notification','critnotification',
                   3456: 					    'permanentemail'],
                   3457: 					   $udom,$uname);
                   3458: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3459: 	return %loadnames;
                   3460:     }
                   3461: }
                   3462: 
1.551     albertel 3463: sub flush_email_cache {
                   3464:     my ($uname,$udom)=@_;
                   3465:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3466:     if (!$uname) { $uname=$env{'user.name'};   }
                   3467:     return if ($udom eq 'public' && $uname eq 'public');
                   3468:     my $id=$uname.':'.$udom;
                   3469:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3470: }
                   3471: 
1.728     raeburn  3472: # -------------------------------------------------------------------- getlangs
                   3473: 
                   3474: =pod
                   3475: 
                   3476: =item * &getlangs($uname,$udom)
                   3477: 
                   3478: Gets a user's language preference and returns it as a hash with key:
                   3479: language.
                   3480: 
                   3481: =cut
                   3482: 
                   3483: 
                   3484: sub getlangs {
                   3485:     my ($uname,$udom) = @_;
                   3486:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3487:     if (!$uname) { $uname=$env{'user.name'};   }
                   3488:     my $id=$uname.':'.$udom;
                   3489:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3490:     if ($cached) {
                   3491:         return %{$langs};
                   3492:     } else {
                   3493:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3494:                                            $udom,$uname);
                   3495:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3496:         return %loadlangs;
                   3497:     }
                   3498: }
                   3499: 
                   3500: sub flush_langs_cache {
                   3501:     my ($uname,$udom)=@_;
                   3502:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3503:     if (!$uname) { $uname=$env{'user.name'};   }
                   3504:     return if ($udom eq 'public' && $uname eq 'public');
                   3505:     my $id=$uname.':'.$udom;
                   3506:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3507: }
                   3508: 
1.61      www      3509: # ------------------------------------------------------------------ Screenname
1.81      albertel 3510: 
                   3511: =pod
                   3512: 
1.648     raeburn  3513: =item * &screenname($uname,$udom)
1.81      albertel 3514: 
                   3515: Gets a users screenname and returns it as a string
                   3516: 
                   3517: =cut
1.61      www      3518: 
                   3519: sub screenname {
                   3520:     my ($uname,$udom)=@_;
1.258     albertel 3521:     if ($uname eq $env{'user.name'} &&
                   3522: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3523:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3524:     return $names{'screenname'};
1.62      www      3525: }
                   3526: 
1.212     albertel 3527: 
1.802     bisitz   3528: # ------------------------------------------------------------- Confirm Wrapper
                   3529: =pod
                   3530: 
1.1075.2.42  raeburn  3531: =item * &confirmwrapper($message)
1.802     bisitz   3532: 
                   3533: Wrap messages about completion of operation in box
                   3534: 
                   3535: =cut
                   3536: 
                   3537: sub confirmwrapper {
                   3538:     my ($message)=@_;
                   3539:     if ($message) {
                   3540:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3541:                .$message."\n"
                   3542:                .'</div>'."\n";
                   3543:     } else {
                   3544:         return $message;
                   3545:     }
                   3546: }
                   3547: 
1.62      www      3548: # ------------------------------------------------------------- Message Wrapper
                   3549: 
                   3550: sub messagewrapper {
1.369     www      3551:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3552:     return 
1.441     albertel 3553:         '<a href="/adm/email?compose=individual&amp;'.
                   3554:         'recname='.$username.'&amp;recdom='.$domain.
                   3555: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3556:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3557: }
1.802     bisitz   3558: 
1.74      www      3559: # --------------------------------------------------------------- Notes Wrapper
                   3560: 
                   3561: sub noteswrapper {
                   3562:     my ($link,$un,$do)=@_;
                   3563:     return 
1.896     amueller 3564: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3565: }
1.802     bisitz   3566: 
1.62      www      3567: # ------------------------------------------------------------- Aboutme Wrapper
                   3568: 
                   3569: sub aboutmewrapper {
1.1070    raeburn  3570:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3571:     if (!defined($username)  && !defined($domain)) {
                   3572:         return;
                   3573:     }
1.1075.2.15  raeburn  3574:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3575: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3576: }
                   3577: 
                   3578: # ------------------------------------------------------------ Syllabus Wrapper
                   3579: 
                   3580: sub syllabuswrapper {
1.707     bisitz   3581:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3582:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3583: }
1.14      harris41 3584: 
1.802     bisitz   3585: # -----------------------------------------------------------------------------
                   3586: 
1.208     matthew  3587: sub track_student_link {
1.887     raeburn  3588:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3589:     my $link ="/adm/trackstudent?";
1.208     matthew  3590:     my $title = 'View recent activity';
                   3591:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3592:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3593:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3594:         $title .= ' of this student';
1.268     albertel 3595:     } 
1.208     matthew  3596:     if (defined($target) && $target !~ /^\s*$/) {
                   3597:         $target = qq{target="$target"};
                   3598:     } else {
                   3599:         $target = '';
                   3600:     }
1.268     albertel 3601:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3602:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3603:     $title = &mt($title);
                   3604:     $linktext = &mt($linktext);
1.448     albertel 3605:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3606: 	&help_open_topic('View_recent_activity');
1.208     matthew  3607: }
                   3608: 
1.781     raeburn  3609: sub slot_reservations_link {
                   3610:     my ($linktext,$sname,$sdom,$target) = @_;
                   3611:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3612:     my $title = 'View slot reservation history';
                   3613:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3614:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3615:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3616:         $title .= ' of this student';
                   3617:     }
                   3618:     if (defined($target) && $target !~ /^\s*$/) {
                   3619:         $target = qq{target="$target"};
                   3620:     } else {
                   3621:         $target = '';
                   3622:     }
                   3623:     $title = &mt($title);
                   3624:     $linktext = &mt($linktext);
                   3625:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3626: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3627: 
                   3628: }
                   3629: 
1.508     www      3630: # ===================================================== Display a student photo
                   3631: 
                   3632: 
1.509     albertel 3633: sub student_image_tag {
1.508     www      3634:     my ($domain,$user)=@_;
                   3635:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3636:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3637: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3638:     } else {
                   3639: 	return '';
                   3640:     }
                   3641: }
                   3642: 
1.112     bowersj2 3643: =pod
                   3644: 
                   3645: =back
                   3646: 
                   3647: =head1 Access .tab File Data
                   3648: 
                   3649: =over 4
                   3650: 
1.648     raeburn  3651: =item * &languageids() 
1.112     bowersj2 3652: 
                   3653: returns list of all language ids
                   3654: 
                   3655: =cut
                   3656: 
1.14      harris41 3657: sub languageids {
1.16      harris41 3658:     return sort(keys(%language));
1.14      harris41 3659: }
                   3660: 
1.112     bowersj2 3661: =pod
                   3662: 
1.648     raeburn  3663: =item * &languagedescription() 
1.112     bowersj2 3664: 
                   3665: returns description of a specified language id
                   3666: 
                   3667: =cut
                   3668: 
1.14      harris41 3669: sub languagedescription {
1.125     www      3670:     my $code=shift;
                   3671:     return  ($supported_language{$code}?'* ':'').
                   3672:             $language{$code}.
1.126     www      3673: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3674: }
                   3675: 
1.1048    foxr     3676: =pod
                   3677: 
                   3678: =item * &plainlanguagedescription
                   3679: 
                   3680: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3681: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3682: 
                   3683: =cut
                   3684: 
1.145     www      3685: sub plainlanguagedescription {
                   3686:     my $code=shift;
                   3687:     return $language{$code};
                   3688: }
                   3689: 
1.1048    foxr     3690: =pod
                   3691: 
                   3692: =item * &supportedlanguagecode
                   3693: 
                   3694: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3695: code.
                   3696: 
                   3697: =cut
                   3698: 
1.145     www      3699: sub supportedlanguagecode {
                   3700:     my $code=shift;
                   3701:     return $supported_language{$code};
1.97      www      3702: }
                   3703: 
1.112     bowersj2 3704: =pod
                   3705: 
1.1048    foxr     3706: =item * &latexlanguage()
                   3707: 
                   3708: Given a language key code returns the correspondnig language to use
                   3709: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3710: is no supported hyphenation for the language code.
                   3711: 
                   3712: =cut
                   3713: 
                   3714: sub latexlanguage {
                   3715:     my $code = shift;
                   3716:     return $latex_language{$code};
                   3717: }
                   3718: 
                   3719: =pod
                   3720: 
                   3721: =item * &latexhyphenation()
                   3722: 
                   3723: Same as above but what's supplied is the language as it might be stored
                   3724: in the metadata.
                   3725: 
                   3726: =cut
                   3727: 
                   3728: sub latexhyphenation {
                   3729:     my $key = shift;
                   3730:     return $latex_language_bykey{$key};
                   3731: }
                   3732: 
                   3733: =pod
                   3734: 
1.648     raeburn  3735: =item * &copyrightids() 
1.112     bowersj2 3736: 
                   3737: returns list of all copyrights
                   3738: 
                   3739: =cut
                   3740: 
                   3741: sub copyrightids {
                   3742:     return sort(keys(%cprtag));
                   3743: }
                   3744: 
                   3745: =pod
                   3746: 
1.648     raeburn  3747: =item * &copyrightdescription() 
1.112     bowersj2 3748: 
                   3749: returns description of a specified copyright id
                   3750: 
                   3751: =cut
                   3752: 
                   3753: sub copyrightdescription {
1.166     www      3754:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3755: }
1.197     matthew  3756: 
                   3757: =pod
                   3758: 
1.648     raeburn  3759: =item * &source_copyrightids() 
1.192     taceyjo1 3760: 
                   3761: returns list of all source copyrights
                   3762: 
                   3763: =cut
                   3764: 
                   3765: sub source_copyrightids {
                   3766:     return sort(keys(%scprtag));
                   3767: }
                   3768: 
                   3769: =pod
                   3770: 
1.648     raeburn  3771: =item * &source_copyrightdescription() 
1.192     taceyjo1 3772: 
                   3773: returns description of a specified source copyright id
                   3774: 
                   3775: =cut
                   3776: 
                   3777: sub source_copyrightdescription {
                   3778:     return &mt($scprtag{shift(@_)});
                   3779: }
1.112     bowersj2 3780: 
                   3781: =pod
                   3782: 
1.648     raeburn  3783: =item * &filecategories() 
1.112     bowersj2 3784: 
                   3785: returns list of all file categories
                   3786: 
                   3787: =cut
                   3788: 
                   3789: sub filecategories {
                   3790:     return sort(keys(%category_extensions));
                   3791: }
                   3792: 
                   3793: =pod
                   3794: 
1.648     raeburn  3795: =item * &filecategorytypes() 
1.112     bowersj2 3796: 
                   3797: returns list of file types belonging to a given file
                   3798: category
                   3799: 
                   3800: =cut
                   3801: 
                   3802: sub filecategorytypes {
1.356     albertel 3803:     my ($cat) = @_;
                   3804:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3805: }
                   3806: 
                   3807: =pod
                   3808: 
1.648     raeburn  3809: =item * &fileembstyle() 
1.112     bowersj2 3810: 
                   3811: returns embedding style for a specified file type
                   3812: 
                   3813: =cut
                   3814: 
                   3815: sub fileembstyle {
                   3816:     return $fe{lc(shift(@_))};
1.169     www      3817: }
                   3818: 
1.351     www      3819: sub filemimetype {
                   3820:     return $fm{lc(shift(@_))};
                   3821: }
                   3822: 
1.169     www      3823: 
                   3824: sub filecategoryselect {
                   3825:     my ($name,$value)=@_;
1.189     matthew  3826:     return &select_form($value,$name,
1.970     raeburn  3827:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3828: }
                   3829: 
                   3830: =pod
                   3831: 
1.648     raeburn  3832: =item * &filedescription() 
1.112     bowersj2 3833: 
                   3834: returns description for a specified file type
                   3835: 
                   3836: =cut
                   3837: 
                   3838: sub filedescription {
1.188     matthew  3839:     my $file_description = $fd{lc(shift())};
                   3840:     $file_description =~ s:([\[\]]):~$1:g;
                   3841:     return &mt($file_description);
1.112     bowersj2 3842: }
                   3843: 
                   3844: =pod
                   3845: 
1.648     raeburn  3846: =item * &filedescriptionex() 
1.112     bowersj2 3847: 
                   3848: returns description for a specified file type with
                   3849: extra formatting
                   3850: 
                   3851: =cut
                   3852: 
                   3853: sub filedescriptionex {
                   3854:     my $ex=shift;
1.188     matthew  3855:     my $file_description = $fd{lc($ex)};
                   3856:     $file_description =~ s:([\[\]]):~$1:g;
                   3857:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3858: }
                   3859: 
                   3860: # End of .tab access
                   3861: =pod
                   3862: 
                   3863: =back
                   3864: 
                   3865: =cut
                   3866: 
                   3867: # ------------------------------------------------------------------ File Types
                   3868: sub fileextensions {
                   3869:     return sort(keys(%fe));
                   3870: }
                   3871: 
1.97      www      3872: # ----------------------------------------------------------- Display Languages
                   3873: # returns a hash with all desired display languages
                   3874: #
                   3875: 
                   3876: sub display_languages {
                   3877:     my %languages=();
1.695     raeburn  3878:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3879: 	$languages{$lang}=1;
1.97      www      3880:     }
                   3881:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3882:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3883: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3884: 	    $languages{$lang}=1;
1.97      www      3885:         }
                   3886:     }
                   3887:     return %languages;
1.14      harris41 3888: }
                   3889: 
1.582     albertel 3890: sub languages {
                   3891:     my ($possible_langs) = @_;
1.695     raeburn  3892:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3893:     if (!ref($possible_langs)) {
                   3894: 	if( wantarray ) {
                   3895: 	    return @preferred_langs;
                   3896: 	} else {
                   3897: 	    return $preferred_langs[0];
                   3898: 	}
                   3899:     }
                   3900:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3901:     my @preferred_possibilities;
                   3902:     foreach my $preferred_lang (@preferred_langs) {
                   3903: 	if (exists($possibilities{$preferred_lang})) {
                   3904: 	    push(@preferred_possibilities, $preferred_lang);
                   3905: 	}
                   3906:     }
                   3907:     if( wantarray ) {
                   3908: 	return @preferred_possibilities;
                   3909:     }
                   3910:     return $preferred_possibilities[0];
                   3911: }
                   3912: 
1.742     raeburn  3913: sub user_lang {
                   3914:     my ($touname,$toudom,$fromcid) = @_;
                   3915:     my @userlangs;
                   3916:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3917:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3918:                     $env{'course.'.$fromcid.'.languages'}));
                   3919:     } else {
                   3920:         my %langhash = &getlangs($touname,$toudom);
                   3921:         if ($langhash{'languages'} ne '') {
                   3922:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3923:         } else {
                   3924:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3925:             if ($domdefs{'lang_def'} ne '') {
                   3926:                 @userlangs = ($domdefs{'lang_def'});
                   3927:             }
                   3928:         }
                   3929:     }
                   3930:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3931:     my $user_lh = Apache::localize->get_handle(@languages);
                   3932:     return $user_lh;
                   3933: }
                   3934: 
                   3935: 
1.112     bowersj2 3936: ###############################################################
                   3937: ##               Student Answer Attempts                     ##
                   3938: ###############################################################
                   3939: 
                   3940: =pod
                   3941: 
                   3942: =head1 Alternate Problem Views
                   3943: 
                   3944: =over 4
                   3945: 
1.648     raeburn  3946: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  3947:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 3948: 
                   3949: Return string with previous attempt on problem. Arguments:
                   3950: 
                   3951: =over 4
                   3952: 
                   3953: =item * $symb: Problem, including path
                   3954: 
                   3955: =item * $username: username of the desired student
                   3956: 
                   3957: =item * $domain: domain of the desired student
1.14      harris41 3958: 
1.112     bowersj2 3959: =item * $course: Course ID
1.14      harris41 3960: 
1.112     bowersj2 3961: =item * $getattempt: Leave blank for all attempts, otherwise put
                   3962:     something
1.14      harris41 3963: 
1.112     bowersj2 3964: =item * $regexp: if string matches this regexp, the string will be
                   3965:     sent to $gradesub
1.14      harris41 3966: 
1.112     bowersj2 3967: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 3968: 
1.1075.2.86  raeburn  3969: =item * $usec: section of the desired student
                   3970: 
                   3971: =item * $identifier: counter for student (multiple students one problem) or
                   3972:     problem (one student; whole sequence).
                   3973: 
1.112     bowersj2 3974: =back
1.14      harris41 3975: 
1.112     bowersj2 3976: The output string is a table containing all desired attempts, if any.
1.16      harris41 3977: 
1.112     bowersj2 3978: =cut
1.1       albertel 3979: 
                   3980: sub get_previous_attempt {
1.1075.2.86  raeburn  3981:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 3982:   my $prevattempts='';
1.43      ng       3983:   no strict 'refs';
1.1       albertel 3984:   if ($symb) {
1.3       albertel 3985:     my (%returnhash)=
                   3986:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 3987:     if ($returnhash{'version'}) {
                   3988:       my %lasthash=();
                   3989:       my $version;
                   3990:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  3991:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   3992:             if ($key =~ /\.rawrndseed$/) {
                   3993:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   3994:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   3995:             } else {
                   3996:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   3997:             }
1.19      harris41 3998:         }
1.1       albertel 3999:       }
1.596     albertel 4000:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4001:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  4002:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4003:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4004:       foreach my $key (sort(keys(%lasthash))) {
                   4005: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4006: 	if ($#parts > 0) {
1.31      albertel 4007: 	  my $data=$parts[-1];
1.989     raeburn  4008:           next if ($data eq 'foilorder');
1.31      albertel 4009: 	  pop(@parts);
1.1010    www      4010:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4011:           if ($data eq 'type') {
                   4012:               unless ($showsurv) {
                   4013:                   my $id = join(',',@parts);
                   4014:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4015:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4016:                       $lasthidden{$ign.'.'.$id} = 1;
                   4017:                   }
1.945     raeburn  4018:               }
1.1075.2.86  raeburn  4019:               if ($identifier ne '') {
                   4020:                   my $id = join(',',@parts);
                   4021:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4022:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4023:                       $hidestatus{$ign.'.'.$id} = 1;
                   4024:                   }
                   4025:               }
                   4026:           } elsif ($data eq 'regrader') {
                   4027:               if (($identifier ne '') && (@parts)) {
                   4028:                   my $id = join(',',@parts);
                   4029:                   $regraded{$ign.'.'.$id} = 1;
                   4030:               }
1.1010    www      4031:           } 
1.31      albertel 4032: 	} else {
1.41      ng       4033: 	  if ($#parts == 0) {
                   4034: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4035: 	  } else {
                   4036: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4037: 	  }
1.31      albertel 4038: 	}
1.16      harris41 4039:       }
1.596     albertel 4040:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4041:       if ($getattempt eq '') {
1.1075.2.86  raeburn  4042:         my (%solved,%resets,%probstatus);
                   4043:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4044:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4045:                 foreach my $id (keys(%regraded)) {
                   4046:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4047:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4048:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4049:                         push(@{$resets{$id}},$version);
                   4050:                     }
                   4051:                 }
                   4052:             }
                   4053:         }
1.40      ng       4054: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  4055:             my (@hidden,@unsolved);
1.945     raeburn  4056:             if (%typeparts) {
                   4057:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  4058:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   4059:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4060:                         push(@hidden,$id);
1.1075.2.86  raeburn  4061:                     } elsif ($identifier ne '') {
                   4062:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4063:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4064:                                 ($hidestatus{$id})) {
                   4065:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   4066:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4067:                                 push(@{$solved{$id}},$version);
                   4068:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4069:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4070:                                 my $skip;
                   4071:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4072:                                     foreach my $reset (@{$resets{$id}}) {
                   4073:                                         if ($reset > $solved{$id}[-1]) {
                   4074:                                             $skip=1;
                   4075:                                             last;
                   4076:                                         }
                   4077:                                     }
                   4078:                                 }
                   4079:                                 unless ($skip) {
                   4080:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4081:                                     push(@unsolved,$partslist);
                   4082:                                 }
                   4083:                             }
                   4084:                         }
1.945     raeburn  4085:                     }
                   4086:                 }
                   4087:             }
                   4088:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  4089:                            '<td>'.&mt('Transaction [_1]',$version);
                   4090:             if (@unsolved) {
                   4091:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4092:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4093:                                  &mt('Hide').'</label></span>';
                   4094:             }
                   4095:             $prevattempts .= '</td>';
1.945     raeburn  4096:             if (@hidden) {
                   4097:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4098:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4099:                     my $hide;
                   4100:                     foreach my $id (@hidden) {
                   4101:                         if ($key =~ /^\Q$id\E/) {
                   4102:                             $hide = 1;
                   4103:                             last;
                   4104:                         }
                   4105:                     }
                   4106:                     if ($hide) {
                   4107:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4108:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4109:                             my $value = &format_previous_attempt_value($key,
                   4110:                                              $returnhash{$version.':'.$key});
                   4111:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4112:                         } else {
                   4113:                             $prevattempts.='<td>&nbsp;</td>';
                   4114:                         }
                   4115:                     } else {
                   4116:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  4117:                             my $value = $returnhash{$version.':'.$key};
                   4118:                             if ($key =~ /\.rndseed$/) {
                   4119:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4120:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4121:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4122:                                 }
                   4123:                             }
                   4124:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4125:                                            '&nbsp;</td>';
1.945     raeburn  4126:                         } else {
                   4127:                             $prevattempts.='<td>&nbsp;</td>';
                   4128:                         }
                   4129:                     }
                   4130:                 }
                   4131:             } else {
                   4132: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4133:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  4134:                     my $value = $returnhash{$version.':'.$key};
                   4135:                     if ($key =~ /\.rndseed$/) {
                   4136:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4137:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4138:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4139:                         }
                   4140:                     }
                   4141:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4142:                                    '&nbsp;</td>';
1.945     raeburn  4143: 	        }
                   4144:             }
                   4145: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4146: 	 }
1.1       albertel 4147:       }
1.945     raeburn  4148:       my @currhidden = keys(%lasthidden);
1.596     albertel 4149:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4150:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4151:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4152:           if (%typeparts) {
                   4153:               my $hidden;
                   4154:               foreach my $id (@currhidden) {
                   4155:                   if ($key =~ /^\Q$id\E/) {
                   4156:                       $hidden = 1;
                   4157:                       last;
                   4158:                   }
                   4159:               }
                   4160:               if ($hidden) {
                   4161:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4162:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4163:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4164:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4165:                           $value = &$gradesub($value);
                   4166:                       }
                   4167:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4168:                   } else {
                   4169:                       $prevattempts.='<td>&nbsp;</td>';
                   4170:                   }
                   4171:               } else {
                   4172:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4173:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4174:                       $value = &$gradesub($value);
                   4175:                   }
                   4176:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4177:               }
                   4178:           } else {
                   4179: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4180: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4181:                   $value = &$gradesub($value);
                   4182:               }
                   4183: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4184:           }
1.16      harris41 4185:       }
1.596     albertel 4186:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4187:     } else {
1.596     albertel 4188:       $prevattempts=
                   4189: 	  &start_data_table().&start_data_table_row().
                   4190: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4191: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4192:     }
                   4193:   } else {
1.596     albertel 4194:     $prevattempts=
                   4195: 	  &start_data_table().&start_data_table_row().
                   4196: 	  '<td>'.&mt('No data.').'</td>'.
                   4197: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4198:   }
1.10      albertel 4199: }
                   4200: 
1.581     albertel 4201: sub format_previous_attempt_value {
                   4202:     my ($key,$value) = @_;
1.1011    www      4203:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 4204: 	$value = &Apache::lonlocal::locallocaltime($value);
                   4205:     } elsif (ref($value) eq 'ARRAY') {
                   4206: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  4207:     } elsif ($key =~ /answerstring$/) {
                   4208:         my %answers = &Apache::lonnet::str2hash($value);
                   4209:         my @anskeys = sort(keys(%answers));
                   4210:         if (@anskeys == 1) {
                   4211:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4212:             if ($answer =~ m{\0}) {
                   4213:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4214:             }
                   4215:             my $tag_internal_answer_name = 'INTERNAL';
                   4216:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4217:                 $value = $answer; 
                   4218:             } else {
                   4219:                 $value = $anskeys[0].'='.$answer;
                   4220:             }
                   4221:         } else {
                   4222:             foreach my $ans (@anskeys) {
                   4223:                 my $answer = $answers{$ans};
1.1001    raeburn  4224:                 if ($answer =~ m{\0}) {
                   4225:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4226:                 }
                   4227:                 $value .=  $ans.'='.$answer.'<br />';;
                   4228:             } 
                   4229:         }
1.581     albertel 4230:     } else {
                   4231: 	$value = &unescape($value);
                   4232:     }
                   4233:     return $value;
                   4234: }
                   4235: 
                   4236: 
1.107     albertel 4237: sub relative_to_absolute {
                   4238:     my ($url,$output)=@_;
                   4239:     my $parser=HTML::TokeParser->new(\$output);
                   4240:     my $token;
                   4241:     my $thisdir=$url;
                   4242:     my @rlinks=();
                   4243:     while ($token=$parser->get_token) {
                   4244: 	if ($token->[0] eq 'S') {
                   4245: 	    if ($token->[1] eq 'a') {
                   4246: 		if ($token->[2]->{'href'}) {
                   4247: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4248: 		}
                   4249: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4250: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4251: 	    } elsif ($token->[1] eq 'base') {
                   4252: 		$thisdir=$token->[2]->{'href'};
                   4253: 	    }
                   4254: 	}
                   4255:     }
                   4256:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4257:     foreach my $link (@rlinks) {
1.726     raeburn  4258: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4259: 		($link=~/^\//) ||
                   4260: 		($link=~/^javascript:/i) ||
                   4261: 		($link=~/^mailto:/i) ||
                   4262: 		($link=~/^\#/)) {
                   4263: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4264: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4265: 	}
                   4266:     }
                   4267: # -------------------------------------------------- Deal with Applet codebases
                   4268:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4269:     return $output;
                   4270: }
                   4271: 
1.112     bowersj2 4272: =pod
                   4273: 
1.648     raeburn  4274: =item * &get_student_view()
1.112     bowersj2 4275: 
                   4276: show a snapshot of what student was looking at
                   4277: 
                   4278: =cut
                   4279: 
1.10      albertel 4280: sub get_student_view {
1.186     albertel 4281:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4282:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4283:   my (%form);
1.10      albertel 4284:   my @elements=('symb','courseid','domain','username');
                   4285:   foreach my $element (@elements) {
1.186     albertel 4286:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4287:   }
1.186     albertel 4288:   if (defined($moreenv)) {
                   4289:       %form=(%form,%{$moreenv});
                   4290:   }
1.236     albertel 4291:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4292:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4293:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4294:   $userview=~s/\<body[^\>]*\>//gi;
                   4295:   $userview=~s/\<\/body\>//gi;
                   4296:   $userview=~s/\<html\>//gi;
                   4297:   $userview=~s/\<\/html\>//gi;
                   4298:   $userview=~s/\<head\>//gi;
                   4299:   $userview=~s/\<\/head\>//gi;
                   4300:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4301:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4302:   if (wantarray) {
                   4303:      return ($userview,$response);
                   4304:   } else {
                   4305:      return $userview;
                   4306:   }
                   4307: }
                   4308: 
                   4309: sub get_student_view_with_retries {
                   4310:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4311: 
                   4312:     my $ok = 0;                 # True if we got a good response.
                   4313:     my $content;
                   4314:     my $response;
                   4315: 
                   4316:     # Try to get the student_view done. within the retries count:
                   4317:     
                   4318:     do {
                   4319:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4320:          $ok      = $response->is_success;
                   4321:          if (!$ok) {
                   4322:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4323:          }
                   4324:          $retries--;
                   4325:     } while (!$ok && ($retries > 0));
                   4326:     
                   4327:     if (!$ok) {
                   4328:        $content = '';          # On error return an empty content.
                   4329:     }
1.651     www      4330:     if (wantarray) {
                   4331:        return ($content, $response);
                   4332:     } else {
                   4333:        return $content;
                   4334:     }
1.11      albertel 4335: }
                   4336: 
1.112     bowersj2 4337: =pod
                   4338: 
1.648     raeburn  4339: =item * &get_student_answers() 
1.112     bowersj2 4340: 
                   4341: show a snapshot of how student was answering problem
                   4342: 
                   4343: =cut
                   4344: 
1.11      albertel 4345: sub get_student_answers {
1.100     sakharuk 4346:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4347:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4348:   my (%moreenv);
1.11      albertel 4349:   my @elements=('symb','courseid','domain','username');
                   4350:   foreach my $element (@elements) {
1.186     albertel 4351:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4352:   }
1.186     albertel 4353:   $moreenv{'grade_target'}='answer';
                   4354:   %moreenv=(%form,%moreenv);
1.497     raeburn  4355:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4356:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4357:   return $userview;
1.1       albertel 4358: }
1.116     albertel 4359: 
                   4360: =pod
                   4361: 
                   4362: =item * &submlink()
                   4363: 
1.242     albertel 4364: Inputs: $text $uname $udom $symb $target
1.116     albertel 4365: 
                   4366: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4367: 
                   4368: =cut
                   4369: 
                   4370: ###############################################
                   4371: sub submlink {
1.242     albertel 4372:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4373:     if (!($uname && $udom)) {
                   4374: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4375: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4376: 	if (!$symb) { $symb=$cursymb; }
                   4377:     }
1.254     matthew  4378:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4379:     $symb=&escape($symb);
1.960     bisitz   4380:     if ($target) { $target=" target=\"$target\""; }
                   4381:     return
                   4382:         '<a href="/adm/grades?command=submission'.
                   4383:         '&amp;symb='.$symb.
                   4384:         '&amp;student='.$uname.
                   4385:         '&amp;userdom='.$udom.'"'.
                   4386:         $target.'>'.$text.'</a>';
1.242     albertel 4387: }
                   4388: ##############################################
                   4389: 
                   4390: =pod
                   4391: 
                   4392: =item * &pgrdlink()
                   4393: 
                   4394: Inputs: $text $uname $udom $symb $target
                   4395: 
                   4396: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4397: 
                   4398: =cut
                   4399: 
                   4400: ###############################################
                   4401: sub pgrdlink {
                   4402:     my $link=&submlink(@_);
                   4403:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4404:     return $link;
                   4405: }
                   4406: ##############################################
                   4407: 
                   4408: =pod
                   4409: 
                   4410: =item * &pprmlink()
                   4411: 
                   4412: Inputs: $text $uname $udom $symb $target
                   4413: 
                   4414: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4415: student and a specific resource
1.242     albertel 4416: 
                   4417: =cut
                   4418: 
                   4419: ###############################################
                   4420: sub pprmlink {
                   4421:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4422:     if (!($uname && $udom)) {
                   4423: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4424: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4425: 	if (!$symb) { $symb=$cursymb; }
                   4426:     }
1.254     matthew  4427:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4428:     $symb=&escape($symb);
1.242     albertel 4429:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4430:     return '<a href="/adm/parmset?command=set&amp;'.
                   4431: 	'symb='.$symb.'&amp;uname='.$uname.
                   4432: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4433: }
                   4434: ##############################################
1.37      matthew  4435: 
1.112     bowersj2 4436: =pod
                   4437: 
                   4438: =back
                   4439: 
                   4440: =cut
                   4441: 
1.37      matthew  4442: ###############################################
1.51      www      4443: 
                   4444: 
                   4445: sub timehash {
1.687     raeburn  4446:     my ($thistime) = @_;
                   4447:     my $timezone = &Apache::lonlocal::gettimezone();
                   4448:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4449:                      ->set_time_zone($timezone);
                   4450:     my $wday = $dt->day_of_week();
                   4451:     if ($wday == 7) { $wday = 0; }
                   4452:     return ( 'second' => $dt->second(),
                   4453:              'minute' => $dt->minute(),
                   4454:              'hour'   => $dt->hour(),
                   4455:              'day'     => $dt->day_of_month(),
                   4456:              'month'   => $dt->month(),
                   4457:              'year'    => $dt->year(),
                   4458:              'weekday' => $wday,
                   4459:              'dayyear' => $dt->day_of_year(),
                   4460:              'dlsav'   => $dt->is_dst() );
1.51      www      4461: }
                   4462: 
1.370     www      4463: sub utc_string {
                   4464:     my ($date)=@_;
1.371     www      4465:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4466: }
                   4467: 
1.51      www      4468: sub maketime {
                   4469:     my %th=@_;
1.687     raeburn  4470:     my ($epoch_time,$timezone,$dt);
                   4471:     $timezone = &Apache::lonlocal::gettimezone();
                   4472:     eval {
                   4473:         $dt = DateTime->new( year   => $th{'year'},
                   4474:                              month  => $th{'month'},
                   4475:                              day    => $th{'day'},
                   4476:                              hour   => $th{'hour'},
                   4477:                              minute => $th{'minute'},
                   4478:                              second => $th{'second'},
                   4479:                              time_zone => $timezone,
                   4480:                          );
                   4481:     };
                   4482:     if (!$@) {
                   4483:         $epoch_time = $dt->epoch;
                   4484:         if ($epoch_time) {
                   4485:             return $epoch_time;
                   4486:         }
                   4487:     }
1.51      www      4488:     return POSIX::mktime(
                   4489:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4490:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4491: }
                   4492: 
                   4493: #########################################
1.51      www      4494: 
                   4495: sub findallcourses {
1.482     raeburn  4496:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4497:     my %roles;
                   4498:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4499:     my %courses;
1.51      www      4500:     my $now=time;
1.482     raeburn  4501:     if (!defined($uname)) {
                   4502:         $uname = $env{'user.name'};
                   4503:     }
                   4504:     if (!defined($udom)) {
                   4505:         $udom = $env{'user.domain'};
                   4506:     }
                   4507:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4508:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4509:         if (!%roles) {
                   4510:             %roles = (
                   4511:                        cc => 1,
1.907     raeburn  4512:                        co => 1,
1.482     raeburn  4513:                        in => 1,
                   4514:                        ep => 1,
                   4515:                        ta => 1,
                   4516:                        cr => 1,
                   4517:                        st => 1,
                   4518:              );
                   4519:         }
                   4520:         foreach my $entry (keys(%roleshash)) {
                   4521:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4522:             if ($trole =~ /^cr/) { 
                   4523:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4524:             } else {
                   4525:                 next if (!exists($roles{$trole}));
                   4526:             }
                   4527:             if ($tend) {
                   4528:                 next if ($tend < $now);
                   4529:             }
                   4530:             if ($tstart) {
                   4531:                 next if ($tstart > $now);
                   4532:             }
1.1058    raeburn  4533:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4534:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4535:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4536:             if ($secpart eq '') {
                   4537:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4538:                 $sec = 'none';
1.1058    raeburn  4539:                 $value .= $cnum.'/';
1.482     raeburn  4540:             } else {
                   4541:                 $cnum = $cnumpart;
                   4542:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4543:                 $value .= $cnum.'/'.$sec;
                   4544:             }
                   4545:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4546:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4547:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4548:                 }
                   4549:             } else {
                   4550:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4551:             }
1.482     raeburn  4552:         }
                   4553:     } else {
                   4554:         foreach my $key (keys(%env)) {
1.483     albertel 4555: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4556:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4557: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4558: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4559: 	        next if (%roles && !exists($roles{$role}));
                   4560: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4561:                 my $active=1;
                   4562:                 if ($starttime) {
                   4563: 		    if ($now<$starttime) { $active=0; }
                   4564:                 }
                   4565:                 if ($endtime) {
                   4566:                     if ($now>$endtime) { $active=0; }
                   4567:                 }
                   4568:                 if ($active) {
1.1058    raeburn  4569:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4570:                     if ($sec eq '') {
                   4571:                         $sec = 'none';
1.1058    raeburn  4572:                     } else {
                   4573:                         $value .= $sec;
                   4574:                     }
                   4575:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4576:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4577:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4578:                         }
                   4579:                     } else {
                   4580:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4581:                     }
1.474     raeburn  4582:                 }
                   4583:             }
1.51      www      4584:         }
                   4585:     }
1.474     raeburn  4586:     return %courses;
1.51      www      4587: }
1.37      matthew  4588: 
1.54      www      4589: ###############################################
1.474     raeburn  4590: 
                   4591: sub blockcheck {
1.1075.2.73  raeburn  4592:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4593: 
1.1075.2.73  raeburn  4594:     if (defined($udom) && defined($uname)) {
                   4595:         # If uname and udom are for a course, check for blocks in the course.
                   4596:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4597:             my ($startblock,$endblock,$triggerblock) =
                   4598:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4599:             return ($startblock,$endblock,$triggerblock);
                   4600:         }
                   4601:     } else {
1.490     raeburn  4602:         $udom = $env{'user.domain'};
                   4603:         $uname = $env{'user.name'};
                   4604:     }
                   4605: 
1.502     raeburn  4606:     my $startblock = 0;
                   4607:     my $endblock = 0;
1.1062    raeburn  4608:     my $triggerblock = '';
1.482     raeburn  4609:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4610: 
1.490     raeburn  4611:     # If uname is for a user, and activity is course-specific, i.e.,
                   4612:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4613: 
1.490     raeburn  4614:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.73  raeburn  4615:          $activity eq 'groups' || $activity eq 'printout') &&
                   4616:         ($env{'request.course.id'})) {
1.490     raeburn  4617:         foreach my $key (keys(%live_courses)) {
                   4618:             if ($key ne $env{'request.course.id'}) {
                   4619:                 delete($live_courses{$key});
                   4620:             }
                   4621:         }
                   4622:     }
                   4623: 
                   4624:     my $otheruser = 0;
                   4625:     my %own_courses;
                   4626:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4627:         # Resource belongs to user other than current user.
                   4628:         $otheruser = 1;
                   4629:         # Gather courses for current user
                   4630:         %own_courses = 
                   4631:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4632:     }
                   4633: 
                   4634:     # Gather active course roles - course coordinator, instructor, 
                   4635:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4636: 
                   4637:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4638:         my ($cdom,$cnum);
                   4639:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4640:             $cdom = $env{'course.'.$course.'.domain'};
                   4641:             $cnum = $env{'course.'.$course.'.num'};
                   4642:         } else {
1.490     raeburn  4643:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4644:         }
                   4645:         my $no_ownblock = 0;
                   4646:         my $no_userblock = 0;
1.533     raeburn  4647:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4648:             # Check if current user has 'evb' priv for this
                   4649:             if (defined($own_courses{$course})) {
                   4650:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4651:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4652:                     if ($sec ne 'none') {
                   4653:                         $checkrole .= '/'.$sec;
                   4654:                     }
                   4655:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4656:                         $no_ownblock = 1;
                   4657:                         last;
                   4658:                     }
                   4659:                 }
                   4660:             }
                   4661:             # if they have 'evb' priv and are currently not playing student
                   4662:             next if (($no_ownblock) &&
                   4663:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4664:         }
1.474     raeburn  4665:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4666:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4667:             if ($sec ne 'none') {
1.482     raeburn  4668:                 $checkrole .= '/'.$sec;
1.474     raeburn  4669:             }
1.490     raeburn  4670:             if ($otheruser) {
                   4671:                 # Resource belongs to user other than current user.
                   4672:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4673:                 my (%allroles,%userroles);
                   4674:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4675:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4676:                         my ($trole,$tdom,$tnum,$tsec);
                   4677:                         if ($entry =~ /^cr/) {
                   4678:                             ($trole,$tdom,$tnum,$tsec) = 
                   4679:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4680:                         } else {
                   4681:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4682:                         }
                   4683:                         my ($spec,$area,$trest);
                   4684:                         $area = '/'.$tdom.'/'.$tnum;
                   4685:                         $trest = $tnum;
                   4686:                         if ($tsec ne '') {
                   4687:                             $area .= '/'.$tsec;
                   4688:                             $trest .= '/'.$tsec;
                   4689:                         }
                   4690:                         $spec = $trole.'.'.$area;
                   4691:                         if ($trole =~ /^cr/) {
                   4692:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4693:                                                               $tdom,$spec,$trest,$area);
                   4694:                         } else {
                   4695:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4696:                                                                 $tdom,$spec,$trest,$area);
                   4697:                         }
                   4698:                     }
1.1075.2.124  raeburn  4699:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  4700:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4701:                         if ($1) {
                   4702:                             $no_userblock = 1;
                   4703:                             last;
                   4704:                         }
1.486     raeburn  4705:                     }
                   4706:                 }
1.490     raeburn  4707:             } else {
                   4708:                 # Resource belongs to current user
                   4709:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4710:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4711:                     $no_ownblock = 1;
                   4712:                     last;
                   4713:                 }
1.474     raeburn  4714:             }
                   4715:         }
                   4716:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4717:         next if (($no_ownblock) &&
1.491     albertel 4718:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4719:         next if ($no_userblock);
1.474     raeburn  4720: 
1.866     kalberla 4721:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  4722:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4723:         
1.1062    raeburn  4724:         my ($start,$end,$trigger) = 
                   4725:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4726:         if (($start != 0) && 
                   4727:             (($startblock == 0) || ($startblock > $start))) {
                   4728:             $startblock = $start;
1.1062    raeburn  4729:             if ($trigger ne '') {
                   4730:                 $triggerblock = $trigger;
                   4731:             }
1.502     raeburn  4732:         }
                   4733:         if (($end != 0)  &&
                   4734:             (($endblock == 0) || ($endblock < $end))) {
                   4735:             $endblock = $end;
1.1062    raeburn  4736:             if ($trigger ne '') {
                   4737:                 $triggerblock = $trigger;
                   4738:             }
1.502     raeburn  4739:         }
1.490     raeburn  4740:     }
1.1062    raeburn  4741:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4742: }
                   4743: 
                   4744: sub get_blocks {
1.1062    raeburn  4745:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4746:     my $startblock = 0;
                   4747:     my $endblock = 0;
1.1062    raeburn  4748:     my $triggerblock = '';
1.490     raeburn  4749:     my $course = $cdom.'_'.$cnum;
                   4750:     $setters->{$course} = {};
                   4751:     $setters->{$course}{'staff'} = [];
                   4752:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4753:     $setters->{$course}{'triggers'} = [];
                   4754:     my (@blockers,%triggered);
                   4755:     my $now = time;
                   4756:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4757:     if ($activity eq 'docs') {
                   4758:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4759:         foreach my $block (@blockers) {
                   4760:             if ($block =~ /^firstaccess____(.+)$/) {
                   4761:                 my $item = $1;
                   4762:                 my $type = 'map';
                   4763:                 my $timersymb = $item;
                   4764:                 if ($item eq 'course') {
                   4765:                     $type = 'course';
                   4766:                 } elsif ($item =~ /___\d+___/) {
                   4767:                     $type = 'resource';
                   4768:                 } else {
                   4769:                     $timersymb = &Apache::lonnet::symbread($item);
                   4770:                 }
                   4771:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4772:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4773:                 $triggered{$block} = {
                   4774:                                        start => $start,
                   4775:                                        end   => $end,
                   4776:                                        type  => $type,
                   4777:                                      };
                   4778:             }
                   4779:         }
                   4780:     } else {
                   4781:         foreach my $block (keys(%commblocks)) {
                   4782:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4783:                 my ($start,$end) = ($1,$2);
                   4784:                 if ($start <= time && $end >= time) {
                   4785:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4786:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4787:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4788:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4789:                                     push(@blockers,$block);
                   4790:                                 }
                   4791:                             }
                   4792:                         }
                   4793:                     }
                   4794:                 }
                   4795:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4796:                 my $item = $1;
                   4797:                 my $timersymb = $item; 
                   4798:                 my $type = 'map';
                   4799:                 if ($item eq 'course') {
                   4800:                     $type = 'course';
                   4801:                 } elsif ($item =~ /___\d+___/) {
                   4802:                     $type = 'resource';
                   4803:                 } else {
                   4804:                     $timersymb = &Apache::lonnet::symbread($item);
                   4805:                 }
                   4806:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4807:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4808:                 if ($start && $end) {
                   4809:                     if (($start <= time) && ($end >= time)) {
                   4810:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4811:                             push(@blockers,$block);
                   4812:                             $triggered{$block} = {
                   4813:                                                    start => $start,
                   4814:                                                    end   => $end,
                   4815:                                                    type  => $type,
                   4816:                                                  };
                   4817:                         }
                   4818:                     }
1.490     raeburn  4819:                 }
1.1062    raeburn  4820:             }
                   4821:         }
                   4822:     }
                   4823:     foreach my $blocker (@blockers) {
                   4824:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4825:             &parse_block_record($commblocks{$blocker});
                   4826:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4827:         my ($start,$end,$triggertype);
                   4828:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4829:             ($start,$end) = ($1,$2);
                   4830:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4831:             $start = $triggered{$blocker}{'start'};
                   4832:             $end = $triggered{$blocker}{'end'};
                   4833:             $triggertype = $triggered{$blocker}{'type'};
                   4834:         }
                   4835:         if ($start) {
                   4836:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4837:             if ($triggertype) {
                   4838:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4839:             } else {
                   4840:                 push(@{$$setters{$course}{'triggers'}},0);
                   4841:             }
                   4842:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4843:                 $startblock = $start;
                   4844:                 if ($triggertype) {
                   4845:                     $triggerblock = $blocker;
1.474     raeburn  4846:                 }
                   4847:             }
1.1062    raeburn  4848:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4849:                $endblock = $end;
                   4850:                if ($triggertype) {
                   4851:                    $triggerblock = $blocker;
                   4852:                }
                   4853:             }
1.474     raeburn  4854:         }
                   4855:     }
1.1062    raeburn  4856:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4857: }
                   4858: 
                   4859: sub parse_block_record {
                   4860:     my ($record) = @_;
                   4861:     my ($setuname,$setudom,$title,$blocks);
                   4862:     if (ref($record) eq 'HASH') {
                   4863:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4864:         $title = &unescape($record->{'event'});
                   4865:         $blocks = $record->{'blocks'};
                   4866:     } else {
                   4867:         my @data = split(/:/,$record,3);
                   4868:         if (scalar(@data) eq 2) {
                   4869:             $title = $data[1];
                   4870:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4871:         } else {
                   4872:             ($setuname,$setudom,$title) = @data;
                   4873:         }
                   4874:         $blocks = { 'com' => 'on' };
                   4875:     }
                   4876:     return ($setuname,$setudom,$title,$blocks);
                   4877: }
                   4878: 
1.854     kalberla 4879: sub blocking_status {
1.1075.2.73  raeburn  4880:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  4881:     my %setters;
1.890     droeschl 4882: 
1.1061    raeburn  4883: # check for active blocking
1.1062    raeburn  4884:     my ($startblock,$endblock,$triggerblock) = 
1.1075.2.73  raeburn  4885:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  4886:     my $blocked = 0;
                   4887:     if ($startblock && $endblock) {
                   4888:         $blocked = 1;
                   4889:     }
1.890     droeschl 4890: 
1.1061    raeburn  4891: # caller just wants to know whether a block is active
                   4892:     if (!wantarray) { return $blocked; }
                   4893: 
                   4894: # build a link to a popup window containing the details
                   4895:     my $querystring  = "?activity=$activity";
                   4896: # $uname and $udom decide whose portfolio the user is trying to look at
1.1075.2.97  raeburn  4897:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   4898:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
                   4899:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  4900:     } elsif ($activity eq 'docs') {
                   4901:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4902:     }
1.1061    raeburn  4903: 
                   4904:     my $output .= <<'END_MYBLOCK';
                   4905: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4906:     var options = "width=" + w + ",height=" + h + ",";
                   4907:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4908:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   4909:     var newWin = window.open(url, wdwName, options);
                   4910:     newWin.focus();
                   4911: }
1.890     droeschl 4912: END_MYBLOCK
1.854     kalberla 4913: 
1.1061    raeburn  4914:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 4915:   
1.1061    raeburn  4916:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  4917:     my $text = &mt('Communication Blocked');
1.1075.2.93  raeburn  4918:     my $class = 'LC_comblock';
1.1062    raeburn  4919:     if ($activity eq 'docs') {
                   4920:         $text = &mt('Content Access Blocked');
1.1075.2.93  raeburn  4921:         $class = '';
1.1063    raeburn  4922:     } elsif ($activity eq 'printout') {
                   4923:         $text = &mt('Printing Blocked');
1.1075.2.97  raeburn  4924:     } elsif ($activity eq 'passwd') {
                   4925:         $text = &mt('Password Changing Blocked');
1.1062    raeburn  4926:     }
1.1061    raeburn  4927:     $output .= <<"END_BLOCK";
1.1075.2.93  raeburn  4928: <div class='$class'>
1.869     kalberla 4929:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 4930:   title='$text'>
                   4931:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 4932:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 4933:   title='$text'>$text</a>
1.867     kalberla 4934: </div>
                   4935: 
                   4936: END_BLOCK
1.474     raeburn  4937: 
1.1061    raeburn  4938:     return ($blocked, $output);
1.854     kalberla 4939: }
1.490     raeburn  4940: 
1.60      matthew  4941: ###############################################
                   4942: 
1.682     raeburn  4943: sub check_ip_acc {
1.1075.2.105  raeburn  4944:     my ($acc,$clientip)=@_;
1.682     raeburn  4945:     &Apache::lonxml::debug("acc is $acc");
                   4946:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4947:         return 1;
                   4948:     }
1.1075.2.127.  .1(raebu 4949:20):     my $ip;
1.682     raeburn  4950:     my $allowed=0;
1.1075.2.127.  .1(raebu 4951:20):     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   4952:20):         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   4953:20):         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   4954:20):     } else {
                   4955:20):         $ip = $ENV{'REMOTE_ADDR'} || $env{'request.host'} || $clientip;
                   4956:20):     }
1.682     raeburn  4957: 
                   4958:     my $name;
                   4959:     foreach my $pattern (split(',',$acc)) {
                   4960:         $pattern =~ s/^\s*//;
                   4961:         $pattern =~ s/\s*$//;
                   4962:         if ($pattern =~ /\*$/) {
                   4963:             #35.8.*
                   4964:             $pattern=~s/\*//;
                   4965:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4966:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   4967:             #35.8.3.[34-56]
                   4968:             my $low=$2;
                   4969:             my $high=$3;
                   4970:             $pattern=$1;
                   4971:             if ($ip =~ /^\Q$pattern\E/) {
                   4972:                 my $last=(split(/\./,$ip))[3];
                   4973:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   4974:             }
                   4975:         } elsif ($pattern =~ /^\*/) {
                   4976:             #*.msu.edu
                   4977:             $pattern=~s/\*//;
                   4978:             if (!defined($name)) {
                   4979:                 use Socket;
                   4980:                 my $netaddr=inet_aton($ip);
                   4981:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4982:             }
                   4983:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4984:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   4985:             #127.0.0.1
                   4986:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4987:         } else {
                   4988:             #some.name.com
                   4989:             if (!defined($name)) {
                   4990:                 use Socket;
                   4991:                 my $netaddr=inet_aton($ip);
                   4992:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4993:             }
                   4994:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4995:         }
                   4996:         if ($allowed) { last; }
                   4997:     }
                   4998:     return $allowed;
                   4999: }
                   5000: 
                   5001: ###############################################
                   5002: 
1.60      matthew  5003: =pod
                   5004: 
1.112     bowersj2 5005: =head1 Domain Template Functions
                   5006: 
                   5007: =over 4
                   5008: 
                   5009: =item * &determinedomain()
1.60      matthew  5010: 
                   5011: Inputs: $domain (usually will be undef)
                   5012: 
1.63      www      5013: Returns: Determines which domain should be used for designs
1.60      matthew  5014: 
                   5015: =cut
1.54      www      5016: 
1.60      matthew  5017: ###############################################
1.63      www      5018: sub determinedomain {
                   5019:     my $domain=shift;
1.531     albertel 5020:     if (! $domain) {
1.60      matthew  5021:         # Determine domain if we have not been given one
1.893     raeburn  5022:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5023:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5024:         if ($env{'request.role.domain'}) { 
                   5025:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5026:         }
                   5027:     }
1.63      www      5028:     return $domain;
                   5029: }
                   5030: ###############################################
1.517     raeburn  5031: 
1.518     albertel 5032: sub devalidate_domconfig_cache {
                   5033:     my ($udom)=@_;
                   5034:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5035: }
                   5036: 
                   5037: # ---------------------- Get domain configuration for a domain
                   5038: sub get_domainconf {
                   5039:     my ($udom) = @_;
                   5040:     my $cachetime=1800;
                   5041:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5042:     if (defined($cached)) { return %{$result}; }
                   5043: 
                   5044:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5045: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5046:     my (%designhash,%legacy);
1.518     albertel 5047:     if (keys(%domconfig) > 0) {
                   5048:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5049:             if (keys(%{$domconfig{'login'}})) {
                   5050:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5051:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  5052:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5053:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5054:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5055:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5056:                                         if ($key eq 'loginvia') {
                   5057:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5058:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5059:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5060:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5061:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5062:                                                 } else {
                   5063:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5064:                                                 }
1.948     raeburn  5065:                                             }
1.1075.2.87  raeburn  5066:                                         } elsif ($key eq 'headtag') {
                   5067:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5068:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5069:                                             }
1.946     raeburn  5070:                                         }
1.1075.2.87  raeburn  5071:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5072:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5073:                                         }
1.946     raeburn  5074:                                     }
                   5075:                                 }
                   5076:                             }
                   5077:                         } else {
                   5078:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5079:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5080:                                     $domconfig{'login'}{$key}{$img};
                   5081:                             }
1.699     raeburn  5082:                         }
                   5083:                     } else {
                   5084:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5085:                     }
1.632     raeburn  5086:                 }
                   5087:             } else {
                   5088:                 $legacy{'login'} = 1;
1.518     albertel 5089:             }
1.632     raeburn  5090:         } else {
                   5091:             $legacy{'login'} = 1;
1.518     albertel 5092:         }
                   5093:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5094:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5095:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5096:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5097:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5098:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5099:                         }
1.518     albertel 5100:                     }
                   5101:                 }
1.632     raeburn  5102:             } else {
                   5103:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5104:             }
1.632     raeburn  5105:         } else {
                   5106:             $legacy{'rolecolors'} = 1;
1.518     albertel 5107:         }
1.948     raeburn  5108:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5109:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5110:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5111:             }
                   5112:         }
1.632     raeburn  5113:         if (keys(%legacy) > 0) {
                   5114:             my %legacyhash = &get_legacy_domconf($udom);
                   5115:             foreach my $item (keys(%legacyhash)) {
                   5116:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5117:                     if ($legacy{'login'}) { 
                   5118:                         $designhash{$item} = $legacyhash{$item};
                   5119:                     }
                   5120:                 } else {
                   5121:                     if ($legacy{'rolecolors'}) {
                   5122:                         $designhash{$item} = $legacyhash{$item};
                   5123:                     }
1.518     albertel 5124:                 }
                   5125:             }
                   5126:         }
1.632     raeburn  5127:     } else {
                   5128:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5129:     }
                   5130:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5131: 				  $cachetime);
                   5132:     return %designhash;
                   5133: }
                   5134: 
1.632     raeburn  5135: sub get_legacy_domconf {
                   5136:     my ($udom) = @_;
                   5137:     my %legacyhash;
                   5138:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5139:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5140:     if (-e $designfile) {
                   5141:         if ( open (my $fh,"<$designfile") ) {
                   5142:             while (my $line = <$fh>) {
                   5143:                 next if ($line =~ /^\#/);
                   5144:                 chomp($line);
                   5145:                 my ($key,$val)=(split(/\=/,$line));
                   5146:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5147:             }
                   5148:             close($fh);
                   5149:         }
                   5150:     }
1.1026    raeburn  5151:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5152:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5153:     }
                   5154:     return %legacyhash;
                   5155: }
                   5156: 
1.63      www      5157: =pod
                   5158: 
1.112     bowersj2 5159: =item * &domainlogo()
1.63      www      5160: 
                   5161: Inputs: $domain (usually will be undef)
                   5162: 
                   5163: Returns: A link to a domain logo, if the domain logo exists.
                   5164: If the domain logo does not exist, a description of the domain.
                   5165: 
                   5166: =cut
1.112     bowersj2 5167: 
1.63      www      5168: ###############################################
                   5169: sub domainlogo {
1.517     raeburn  5170:     my $domain = &determinedomain(shift);
1.518     albertel 5171:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5172:     # See if there is a logo
                   5173:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5174:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5175:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5176: 	    if ($imgsrc =~ m{^/res/}) {
                   5177: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5178: 		&Apache::lonnet::repcopy($local_name);
                   5179: 	    }
                   5180: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5181:         } 
                   5182:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5183:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5184:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5185:     } else {
1.60      matthew  5186:         return '';
1.59      www      5187:     }
                   5188: }
1.63      www      5189: ##############################################
                   5190: 
                   5191: =pod
                   5192: 
1.112     bowersj2 5193: =item * &designparm()
1.63      www      5194: 
                   5195: Inputs: $which parameter; $domain (usually will be undef)
                   5196: 
                   5197: Returns: value of designparamter $which
                   5198: 
                   5199: =cut
1.112     bowersj2 5200: 
1.397     albertel 5201: 
1.400     albertel 5202: ##############################################
1.397     albertel 5203: sub designparm {
                   5204:     my ($which,$domain)=@_;
                   5205:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5206:         return $env{'environment.color.'.$which};
1.96      www      5207:     }
1.63      www      5208:     $domain=&determinedomain($domain);
1.1016    raeburn  5209:     my %domdesign;
                   5210:     unless ($domain eq 'public') {
                   5211:         %domdesign = &get_domainconf($domain);
                   5212:     }
1.520     raeburn  5213:     my $output;
1.517     raeburn  5214:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5215:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5216:     } else {
1.520     raeburn  5217:         $output = $defaultdesign{$which};
                   5218:     }
                   5219:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5220:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5221:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5222:             if ($output =~ m{^/res/}) {
                   5223:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5224:                 &Apache::lonnet::repcopy($local_name);
                   5225:             }
1.520     raeburn  5226:             $output = &lonhttpdurl($output);
                   5227:         }
1.63      www      5228:     }
1.520     raeburn  5229:     return $output;
1.63      www      5230: }
1.59      www      5231: 
1.822     bisitz   5232: ##############################################
                   5233: =pod
                   5234: 
1.832     bisitz   5235: =item * &authorspace()
                   5236: 
1.1028    raeburn  5237: Inputs: $url (usually will be undef).
1.832     bisitz   5238: 
1.1075.2.40  raeburn  5239: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5240:          directory being viewed (or for which action is being taken). 
                   5241:          If $url is provided, and begins /priv/<domain>/<uname>
                   5242:          the path will be that portion of the $context argument.
                   5243:          Otherwise the path will be for the author space of the current
                   5244:          user when the current role is author, or for that of the 
                   5245:          co-author/assistant co-author space when the current role 
                   5246:          is co-author or assistant co-author.
1.832     bisitz   5247: 
                   5248: =cut
                   5249: 
                   5250: sub authorspace {
1.1028    raeburn  5251:     my ($url) = @_;
                   5252:     if ($url ne '') {
                   5253:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5254:            return $1;
                   5255:         }
                   5256:     }
1.832     bisitz   5257:     my $caname = '';
1.1024    www      5258:     my $cadom = '';
1.1028    raeburn  5259:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5260:         ($cadom,$caname) =
1.832     bisitz   5261:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5262:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5263:         $caname = $env{'user.name'};
1.1024    www      5264:         $cadom = $env{'user.domain'};
1.832     bisitz   5265:     }
1.1028    raeburn  5266:     if (($caname ne '') && ($cadom ne '')) {
                   5267:         return "/priv/$cadom/$caname/";
                   5268:     }
                   5269:     return;
1.832     bisitz   5270: }
                   5271: 
                   5272: ##############################################
                   5273: =pod
                   5274: 
1.822     bisitz   5275: =item * &head_subbox()
                   5276: 
                   5277: Inputs: $content (contains HTML code with page functions, etc.)
                   5278: 
                   5279: Returns: HTML div with $content
                   5280:          To be included in page header
                   5281: 
                   5282: =cut
                   5283: 
                   5284: sub head_subbox {
                   5285:     my ($content)=@_;
                   5286:     my $output =
1.993     raeburn  5287:         '<div class="LC_head_subbox">'
1.822     bisitz   5288:        .$content
                   5289:        .'</div>'
                   5290: }
                   5291: 
                   5292: ##############################################
                   5293: =pod
                   5294: 
                   5295: =item * &CSTR_pageheader()
                   5296: 
1.1026    raeburn  5297: Input: (optional) filename from which breadcrumb trail is built.
                   5298:        In most cases no input as needed, as $env{'request.filename'}
                   5299:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5300: 
                   5301: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5302:          To be included on Authoring Space pages
1.822     bisitz   5303: 
                   5304: =cut
                   5305: 
                   5306: sub CSTR_pageheader {
1.1026    raeburn  5307:     my ($trailfile) = @_;
                   5308:     if ($trailfile eq '') {
                   5309:         $trailfile = $env{'request.filename'};
                   5310:     }
                   5311: 
                   5312: # this is for resources; directories have customtitle, and crumbs
                   5313: # and select recent are created in lonpubdir.pm
                   5314: 
                   5315:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5316:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5317:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5318:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5319:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5320: 
                   5321:     my $parentpath = '';
                   5322:     my $lastitem = '';
                   5323:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5324:         $parentpath = $1;
                   5325:         $lastitem = $2;
                   5326:     } else {
                   5327:         $lastitem = $thisdisfn;
                   5328:     }
1.921     bisitz   5329: 
                   5330:     my $output =
1.822     bisitz   5331:          '<div>'
                   5332:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  5333:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5334:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5335:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5336:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5337: 
                   5338:     if ($lastitem) {
                   5339:         $output .=
                   5340:              '<span class="LC_filename">'
                   5341:             .$lastitem
                   5342:             .'</span>';
                   5343:     }
                   5344:     $output .=
                   5345:          '<br />'
1.822     bisitz   5346:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5347:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5348:         .'</form>'
                   5349:         .&Apache::lonmenu::constspaceform()
                   5350:         .'</div>';
1.921     bisitz   5351: 
                   5352:     return $output;
1.822     bisitz   5353: }
                   5354: 
1.60      matthew  5355: ###############################################
                   5356: ###############################################
                   5357: 
                   5358: =pod
                   5359: 
1.112     bowersj2 5360: =back
                   5361: 
1.549     albertel 5362: =head1 HTML Helpers
1.112     bowersj2 5363: 
                   5364: =over 4
                   5365: 
                   5366: =item * &bodytag()
1.60      matthew  5367: 
                   5368: Returns a uniform header for LON-CAPA web pages.
                   5369: 
                   5370: Inputs: 
                   5371: 
1.112     bowersj2 5372: =over 4
                   5373: 
                   5374: =item * $title, A title to be displayed on the page.
                   5375: 
                   5376: =item * $function, the current role (can be undef).
                   5377: 
                   5378: =item * $addentries, extra parameters for the <body> tag.
                   5379: 
                   5380: =item * $bodyonly, if defined, only return the <body> tag.
                   5381: 
                   5382: =item * $domain, if defined, force a given domain.
                   5383: 
                   5384: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5385:             text interface only)
1.60      matthew  5386: 
1.814     bisitz   5387: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5388:                      navigational links
1.317     albertel 5389: 
1.338     albertel 5390: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5391: 
1.1075.2.12  raeburn  5392: =item * $no_inline_link, if true and in remote mode, don't show the
                   5393:          'Switch To Inline Menu' link
                   5394: 
1.460     albertel 5395: =item * $args, optional argument valid values are
                   5396:             no_auto_mt_title -> prevents &mt()ing the title arg
                   5397: 
1.1075.2.15  raeburn  5398: =item * $advtoolsref, optional argument, ref to an array containing
                   5399:             inlineremote items to be added in "Functions" menu below
                   5400:             breadcrumbs.
                   5401: 
1.112     bowersj2 5402: =back
                   5403: 
1.60      matthew  5404: Returns: A uniform header for LON-CAPA web pages.  
                   5405: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5406: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5407: other decorations will be returned.
                   5408: 
                   5409: =cut
                   5410: 
1.54      www      5411: sub bodytag {
1.831     bisitz   5412:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.15  raeburn  5413:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
1.339     albertel 5414: 
1.954     raeburn  5415:     my $public;
                   5416:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5417:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5418:         $public = 1;
                   5419:     }
1.460     albertel 5420:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5421:     my $httphost = $args->{'use_absolute'};
1.339     albertel 5422: 
1.183     matthew  5423:     $function = &get_users_function() if (!$function);
1.339     albertel 5424:     my $img =    &designparm($function.'.img',$domain);
                   5425:     my $font =   &designparm($function.'.font',$domain);
                   5426:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5427: 
1.803     bisitz   5428:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5429: 		   'bgcolor' => $pgbg,
1.339     albertel 5430: 		   'text'    => $font,
                   5431:                    'alink'   => &designparm($function.'.alink',$domain),
                   5432: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5433: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5434:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5435: 
1.63      www      5436:  # role and realm
1.1075.2.68  raeburn  5437:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5438:     if ($realm) {
                   5439:         $realm = '/'.$realm;
                   5440:     }
1.378     raeburn  5441:     if ($role  eq 'ca') {
1.479     albertel 5442:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5443:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5444:     } 
1.55      www      5445: # realm
1.258     albertel 5446:     if ($env{'request.course.id'}) {
1.378     raeburn  5447:         if ($env{'request.role'} !~ /^cr/) {
                   5448:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1075.2.115  raeburn  5449:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1075.2.121  raeburn  5450:             if ($env{'request.role.desc'}) {
                   5451:                 $role = $env{'request.role.desc'};
                   5452:             } else {
                   5453:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   5454:             }
1.1075.2.115  raeburn  5455:         } else {
                   5456:             $role = (split(/\//,$role,4))[-1];
1.378     raeburn  5457:         }
1.898     raeburn  5458:         if ($env{'request.course.sec'}) {
                   5459:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5460:         }   
1.359     albertel 5461: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5462:     } else {
                   5463:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5464:     }
1.433     albertel 5465: 
1.359     albertel 5466:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5467: 
1.438     albertel 5468:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5469: 
1.101     www      5470: # construct main body tag
1.359     albertel 5471:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  5472: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5473: 
1.1075.2.38  raeburn  5474:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5475: 
                   5476:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5477:         return $bodytag;
1.1075.2.38  raeburn  5478:     }
1.359     albertel 5479: 
1.954     raeburn  5480:     if ($public) {
1.433     albertel 5481: 	undef($role);
                   5482:     }
1.359     albertel 5483:     
1.762     bisitz   5484:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5485:     #
                   5486:     # Extra info if you are the DC
                   5487:     my $dc_info = '';
                   5488:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5489:                         $env{'course.'.$env{'request.course.id'}.
                   5490:                                  '.domain'}.'/'})) {
                   5491:         my $cid = $env{'request.course.id'};
1.917     raeburn  5492:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5493:         $dc_info =~ s/\s+$//;
1.359     albertel 5494:     }
                   5495: 
1.1075.2.108  raeburn  5496:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 5497: 
1.1075.2.13  raeburn  5498:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5499: 
1.1075.2.38  raeburn  5500: 
                   5501: 
1.1075.2.21  raeburn  5502:     my $funclist;
                   5503:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  5504:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  5505:                     Apache::lonmenu::serverform();
                   5506:         my $forbodytag;
                   5507:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5508:                                             $forcereg,$args->{'group'},
                   5509:                                             $args->{'bread_crumbs'},
                   5510:                                             $advtoolsref,'',\$forbodytag);
                   5511:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5512:             $funclist = $forbodytag;
                   5513:         }
                   5514:     } else {
1.903     droeschl 5515: 
                   5516:         #    if ($env{'request.state'} eq 'construct') {
                   5517:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5518:         #    }
                   5519: 
1.1075.2.38  raeburn  5520:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5521:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5522: 
1.1075.2.38  raeburn  5523:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.1075.2.2  raeburn  5524: 
1.916     droeschl 5525:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.1075.2.22  raeburn  5526:             if ($dc_info) {
                   5527:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
1.1075.2.1  raeburn  5528:             }
1.1075.2.38  raeburn  5529:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.1075.2.22  raeburn  5530:                            <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5531:             return $bodytag;
                   5532:         }
1.894     droeschl 5533: 
1.927     raeburn  5534:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1075.2.38  raeburn  5535:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5536:         }
1.916     droeschl 5537: 
1.1075.2.38  raeburn  5538:         $bodytag .= $right;
1.852     droeschl 5539: 
1.917     raeburn  5540:         if ($dc_info) {
                   5541:             $dc_info = &dc_courseid_toggle($dc_info);
                   5542:         }
                   5543:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5544: 
1.1075.2.61  raeburn  5545:         #if directed to not display the secondary menu, don't.
                   5546:         if ($args->{'no_secondary_menu'}) {
                   5547:             return $bodytag;
                   5548:         }
1.903     droeschl 5549:         #don't show menus for public users
1.954     raeburn  5550:         if (!$public){
1.1075.2.52  raeburn  5551:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5552:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5553:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5554:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5555:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5556:                                 $args->{'bread_crumbs'});
1.1075.2.116  raeburn  5557:             } elsif ($forcereg) {
1.1075.2.22  raeburn  5558:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1075.2.116  raeburn  5559:                                                             $args->{'group'},
                   5560:                                                             $args->{'hide_buttons'});
1.1075.2.15  raeburn  5561:             } else {
1.1075.2.21  raeburn  5562:                 my $forbodytag;
                   5563:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5564:                                                     $forcereg,$args->{'group'},
                   5565:                                                     $args->{'bread_crumbs'},
                   5566:                                                     $advtoolsref,'',\$forbodytag);
                   5567:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5568:                     $bodytag .= $forbodytag;
                   5569:                 }
1.920     raeburn  5570:             }
1.903     droeschl 5571:         }else{
                   5572:             # this is to seperate menu from content when there's no secondary
                   5573:             # menu. Especially needed for public accessible ressources.
                   5574:             $bodytag .= '<hr style="clear:both" />';
                   5575:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5576:         }
1.903     droeschl 5577: 
1.235     raeburn  5578:         return $bodytag;
1.1075.2.12  raeburn  5579:     }
                   5580: 
                   5581: #
                   5582: # Top frame rendering, Remote is up
                   5583: #
                   5584: 
                   5585:     my $imgsrc = $img;
                   5586:     if ($img =~ /^\/adm/) {
                   5587:         $imgsrc = &lonhttpdurl($img);
                   5588:     }
                   5589:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5590: 
1.1075.2.60  raeburn  5591:     my $help=($no_inline_link?''
                   5592:               :&Apache::loncommon::top_nav_help('Help'));
                   5593: 
1.1075.2.12  raeburn  5594:     # Explicit link to get inline menu
                   5595:     my $menu= ($no_inline_link?''
                   5596:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5597: 
                   5598:     if ($dc_info) {
                   5599:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5600:     }
                   5601: 
1.1075.2.38  raeburn  5602:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   5603:     unless ($public) {
                   5604:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5605:                                 undef,'LC_menubuttons_link');
                   5606:     }
                   5607: 
1.1075.2.12  raeburn  5608:     unless ($env{'form.inhibitmenu'}) {
                   5609:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  5610:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  5611:                        <li>$help</li>
1.1075.2.12  raeburn  5612:                        <li>$menu</li>
                   5613:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5614:     }
1.1075.2.13  raeburn  5615:     if ($env{'request.state'} eq 'construct') {
                   5616:         if (!$public){
                   5617:             if ($env{'request.state'} eq 'construct') {
                   5618:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5619:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  5620:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5621:                             &Apache::lonmenu::innerregister($forcereg,
                   5622:                                                             $args->{'bread_crumbs'});
                   5623:             }
                   5624:         }
                   5625:     }
1.1075.2.21  raeburn  5626:     return $bodytag."\n".$funclist;
1.182     matthew  5627: }
                   5628: 
1.917     raeburn  5629: sub dc_courseid_toggle {
                   5630:     my ($dc_info) = @_;
1.980     raeburn  5631:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5632:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5633:            &mt('(More ...)').'</a></span>'.
                   5634:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5635: }
                   5636: 
1.330     albertel 5637: sub make_attr_string {
                   5638:     my ($register,$attr_ref) = @_;
                   5639: 
                   5640:     if ($attr_ref && !ref($attr_ref)) {
                   5641: 	die("addentries Must be a hash ref ".
                   5642: 	    join(':',caller(1))." ".
                   5643: 	    join(':',caller(0))." ");
                   5644:     }
                   5645: 
                   5646:     if ($register) {
1.339     albertel 5647: 	my ($on_load,$on_unload);
                   5648: 	foreach my $key (keys(%{$attr_ref})) {
                   5649: 	    if      (lc($key) eq 'onload') {
                   5650: 		$on_load.=$attr_ref->{$key}.';';
                   5651: 		delete($attr_ref->{$key});
                   5652: 
                   5653: 	    } elsif (lc($key) eq 'onunload') {
                   5654: 		$on_unload.=$attr_ref->{$key}.';';
                   5655: 		delete($attr_ref->{$key});
                   5656: 	    }
                   5657: 	}
1.1075.2.12  raeburn  5658:         if ($env{'environment.remote'} eq 'on') {
                   5659:             $attr_ref->{'onload'}  =
                   5660:                 &Apache::lonmenu::loadevents().  $on_load;
                   5661:             $attr_ref->{'onunload'}=
                   5662:                 &Apache::lonmenu::unloadevents().$on_unload;
                   5663:         } else {  
                   5664: 	    $attr_ref->{'onload'}  = $on_load;
                   5665: 	    $attr_ref->{'onunload'}= $on_unload;
                   5666:         }
1.330     albertel 5667:     }
1.339     albertel 5668: 
1.330     albertel 5669:     my $attr_string;
1.1075.2.56  raeburn  5670:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5671: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5672:     }
                   5673:     return $attr_string;
                   5674: }
                   5675: 
                   5676: 
1.182     matthew  5677: ###############################################
1.251     albertel 5678: ###############################################
                   5679: 
                   5680: =pod
                   5681: 
                   5682: =item * &endbodytag()
                   5683: 
                   5684: Returns a uniform footer for LON-CAPA web pages.
                   5685: 
1.635     raeburn  5686: Inputs: 1 - optional reference to an args hash
                   5687: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5688: a 'Continue' link is not displayed if the page contains an
                   5689: internal redirect in the <head></head> section,
                   5690: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5691: 
                   5692: =cut
                   5693: 
                   5694: sub endbodytag {
1.635     raeburn  5695:     my ($args) = @_;
1.1075.2.6  raeburn  5696:     my $endbodytag;
                   5697:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5698:         $endbodytag='</body>';
                   5699:     }
1.315     albertel 5700:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5701:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5702: 	    $endbodytag=
                   5703: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5704: 	        &mt('Continue').'</a>'.
                   5705: 	        $endbodytag;
                   5706:         }
1.315     albertel 5707:     }
1.251     albertel 5708:     return $endbodytag;
                   5709: }
                   5710: 
1.352     albertel 5711: =pod
                   5712: 
                   5713: =item * &standard_css()
                   5714: 
                   5715: Returns a style sheet
                   5716: 
                   5717: Inputs: (all optional)
                   5718:             domain         -> force to color decorate a page for a specific
                   5719:                                domain
                   5720:             function       -> force usage of a specific rolish color scheme
                   5721:             bgcolor        -> override the default page bgcolor
                   5722: 
                   5723: =cut
                   5724: 
1.343     albertel 5725: sub standard_css {
1.345     albertel 5726:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5727:     $function  = &get_users_function() if (!$function);
                   5728:     my $img    = &designparm($function.'.img',   $domain);
                   5729:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5730:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5731:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5732: #second colour for later usage
1.345     albertel 5733:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5734:     my $pgbg_or_bgcolor =
                   5735: 	         $bgcolor ||
1.352     albertel 5736: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5737:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5738:     my $alink  = &designparm($function.'.alink', $domain);
                   5739:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5740:     my $link   = &designparm($function.'.link',  $domain);
                   5741: 
1.602     albertel 5742:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5743:     my $mono                 = 'monospace';
1.850     bisitz   5744:     my $data_table_head      = $sidebg;
                   5745:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5746:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5747:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5748:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5749:     my $mail_new             = '#FFBB77';
                   5750:     my $mail_new_hover       = '#DD9955';
                   5751:     my $mail_read            = '#BBBB77';
                   5752:     my $mail_read_hover      = '#999944';
                   5753:     my $mail_replied         = '#AAAA88';
                   5754:     my $mail_replied_hover   = '#888855';
                   5755:     my $mail_other           = '#99BBBB';
                   5756:     my $mail_other_hover     = '#669999';
1.391     albertel 5757:     my $table_header         = '#DDDDDD';
1.489     raeburn  5758:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5759:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5760:     my $button_hover         = '#BF2317';
1.392     albertel 5761: 
1.608     albertel 5762:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5763:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5764:                                              : '0 3px 0 4px';
1.448     albertel 5765: 
1.523     albertel 5766: 
1.343     albertel 5767:     return <<END;
1.947     droeschl 5768: 
                   5769: /* needed for iframe to allow 100% height in FF */
                   5770: body, html { 
                   5771:     margin: 0;
                   5772:     padding: 0 0.5%;
                   5773:     height: 99%; /* to avoid scrollbars */
                   5774: }
                   5775: 
1.795     www      5776: body {
1.911     bisitz   5777:   font-family: $sans;
                   5778:   line-height:130%;
                   5779:   font-size:0.83em;
                   5780:   color:$font;
1.795     www      5781: }
                   5782: 
1.959     onken    5783: a:focus,
                   5784: a:focus img {
1.795     www      5785:   color: red;
                   5786: }
1.698     harmsja  5787: 
1.911     bisitz   5788: form, .inline {
                   5789:   display: inline;
1.795     www      5790: }
1.721     harmsja  5791: 
1.795     www      5792: .LC_right {
1.911     bisitz   5793:   text-align:right;
1.795     www      5794: }
                   5795: 
                   5796: .LC_middle {
1.911     bisitz   5797:   vertical-align:middle;
1.795     www      5798: }
1.721     harmsja  5799: 
1.1075.2.38  raeburn  5800: .LC_floatleft {
                   5801:   float: left;
                   5802: }
                   5803: 
                   5804: .LC_floatright {
                   5805:   float: right;
                   5806: }
                   5807: 
1.911     bisitz   5808: .LC_400Box {
                   5809:   width:400px;
                   5810: }
1.721     harmsja  5811: 
1.947     droeschl 5812: .LC_iframecontainer {
                   5813:     width: 98%;
                   5814:     margin: 0;
                   5815:     position: fixed;
                   5816:     top: 8.5em;
                   5817:     bottom: 0;
                   5818: }
                   5819: 
                   5820: .LC_iframecontainer iframe{
                   5821:     border: none;
                   5822:     width: 100%;
                   5823:     height: 100%;
                   5824: }
                   5825: 
1.778     bisitz   5826: .LC_filename {
                   5827:   font-family: $mono;
                   5828:   white-space:pre;
1.921     bisitz   5829:   font-size: 120%;
1.778     bisitz   5830: }
                   5831: 
                   5832: .LC_fileicon {
                   5833:   border: none;
                   5834:   height: 1.3em;
                   5835:   vertical-align: text-bottom;
                   5836:   margin-right: 0.3em;
                   5837:   text-decoration:none;
                   5838: }
                   5839: 
1.1008    www      5840: .LC_setting {
                   5841:   text-decoration:underline;
                   5842: }
                   5843: 
1.350     albertel 5844: .LC_error {
                   5845:   color: red;
                   5846: }
1.795     www      5847: 
1.1075.2.15  raeburn  5848: .LC_warning {
                   5849:   color: darkorange;
                   5850: }
                   5851: 
1.457     albertel 5852: .LC_diff_removed {
1.733     bisitz   5853:   color: red;
1.394     albertel 5854: }
1.532     albertel 5855: 
                   5856: .LC_info,
1.457     albertel 5857: .LC_success,
                   5858: .LC_diff_added {
1.350     albertel 5859:   color: green;
                   5860: }
1.795     www      5861: 
1.802     bisitz   5862: div.LC_confirm_box {
                   5863:   background-color: #FAFAFA;
                   5864:   border: 1px solid $lg_border_color;
                   5865:   margin-right: 0;
                   5866:   padding: 5px;
                   5867: }
                   5868: 
                   5869: div.LC_confirm_box .LC_error img,
                   5870: div.LC_confirm_box .LC_success img {
                   5871:   vertical-align: middle;
                   5872: }
                   5873: 
1.1075.2.108  raeburn  5874: .LC_maxwidth {
                   5875:   max-width: 100%;
                   5876:   height: auto;
                   5877: }
                   5878: 
                   5879: .LC_textsize_mobile {
                   5880:   \@media only screen and (max-device-width: 480px) {
                   5881:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   5882:   }
                   5883: }
                   5884: 
1.440     albertel 5885: .LC_icon {
1.771     droeschl 5886:   border: none;
1.790     droeschl 5887:   vertical-align: middle;
1.771     droeschl 5888: }
                   5889: 
1.543     albertel 5890: .LC_docs_spacer {
                   5891:   width: 25px;
                   5892:   height: 1px;
1.771     droeschl 5893:   border: none;
1.543     albertel 5894: }
1.346     albertel 5895: 
1.532     albertel 5896: .LC_internal_info {
1.735     bisitz   5897:   color: #999999;
1.532     albertel 5898: }
                   5899: 
1.794     www      5900: .LC_discussion {
1.1050    www      5901:   background: $data_table_dark;
1.911     bisitz   5902:   border: 1px solid black;
                   5903:   margin: 2px;
1.794     www      5904: }
                   5905: 
                   5906: .LC_disc_action_left {
1.1050    www      5907:   background: $sidebg;
1.911     bisitz   5908:   text-align: left;
1.1050    www      5909:   padding: 4px;
                   5910:   margin: 2px;
1.794     www      5911: }
                   5912: 
                   5913: .LC_disc_action_right {
1.1050    www      5914:   background: $sidebg;
1.911     bisitz   5915:   text-align: right;
1.1050    www      5916:   padding: 4px;
                   5917:   margin: 2px;
1.794     www      5918: }
                   5919: 
                   5920: .LC_disc_new_item {
1.911     bisitz   5921:   background: white;
                   5922:   border: 2px solid red;
1.1050    www      5923:   margin: 4px;
                   5924:   padding: 4px;
1.794     www      5925: }
                   5926: 
                   5927: .LC_disc_old_item {
1.911     bisitz   5928:   background: white;
1.1050    www      5929:   margin: 4px;
                   5930:   padding: 4px;
1.794     www      5931: }
                   5932: 
1.458     albertel 5933: table.LC_pastsubmission {
                   5934:   border: 1px solid black;
                   5935:   margin: 2px;
                   5936: }
                   5937: 
1.924     bisitz   5938: table#LC_menubuttons {
1.345     albertel 5939:   width: 100%;
                   5940:   background: $pgbg;
1.392     albertel 5941:   border: 2px;
1.402     albertel 5942:   border-collapse: separate;
1.803     bisitz   5943:   padding: 0;
1.345     albertel 5944: }
1.392     albertel 5945: 
1.801     tempelho 5946: table#LC_title_bar a {
                   5947:   color: $fontmenu;
                   5948: }
1.836     bisitz   5949: 
1.807     droeschl 5950: table#LC_title_bar {
1.819     tempelho 5951:   clear: both;
1.836     bisitz   5952:   display: none;
1.807     droeschl 5953: }
                   5954: 
1.795     www      5955: table#LC_title_bar,
1.933     droeschl 5956: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5957: table#LC_title_bar.LC_with_remote {
1.359     albertel 5958:   width: 100%;
1.392     albertel 5959:   border-color: $pgbg;
                   5960:   border-style: solid;
                   5961:   border-width: $border;
1.379     albertel 5962:   background: $pgbg;
1.801     tempelho 5963:   color: $fontmenu;
1.392     albertel 5964:   border-collapse: collapse;
1.803     bisitz   5965:   padding: 0;
1.819     tempelho 5966:   margin: 0;
1.359     albertel 5967: }
1.795     www      5968: 
1.933     droeschl 5969: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5970:     margin: 0;
                   5971:     padding: 0;
1.933     droeschl 5972:     position: relative;
                   5973:     list-style: none;
1.913     droeschl 5974: }
1.933     droeschl 5975: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5976:     display: inline;
                   5977: }
1.933     droeschl 5978: 
                   5979: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5980:     padding: 0;
1.933     droeschl 5981:     margin: 0;
                   5982:     float: left;
1.913     droeschl 5983: }
1.933     droeschl 5984: .LC_breadcrumb_tools_tools {
                   5985:     padding: 0;
                   5986:     margin: 0;
1.913     droeschl 5987:     float: right;
                   5988: }
                   5989: 
1.359     albertel 5990: table#LC_title_bar td {
                   5991:   background: $tabbg;
                   5992: }
1.795     www      5993: 
1.911     bisitz   5994: table#LC_menubuttons img {
1.803     bisitz   5995:   border: none;
1.346     albertel 5996: }
1.795     www      5997: 
1.842     droeschl 5998: .LC_breadcrumbs_component {
1.911     bisitz   5999:   float: right;
                   6000:   margin: 0 1em;
1.357     albertel 6001: }
1.842     droeschl 6002: .LC_breadcrumbs_component img {
1.911     bisitz   6003:   vertical-align: middle;
1.777     tempelho 6004: }
1.795     www      6005: 
1.1075.2.108  raeburn  6006: .LC_breadcrumbs_hoverable {
                   6007:   background: $sidebg;
                   6008: }
                   6009: 
1.383     albertel 6010: td.LC_table_cell_checkbox {
                   6011:   text-align: center;
                   6012: }
1.795     www      6013: 
                   6014: .LC_fontsize_small {
1.911     bisitz   6015:   font-size: 70%;
1.705     tempelho 6016: }
                   6017: 
1.844     bisitz   6018: #LC_breadcrumbs {
1.911     bisitz   6019:   clear:both;
                   6020:   background: $sidebg;
                   6021:   border-bottom: 1px solid $lg_border_color;
                   6022:   line-height: 2.5em;
1.933     droeschl 6023:   overflow: hidden;
1.911     bisitz   6024:   margin: 0;
                   6025:   padding: 0;
1.995     raeburn  6026:   text-align: left;
1.819     tempelho 6027: }
1.862     bisitz   6028: 
1.1075.2.16  raeburn  6029: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6030:   clear:both;
                   6031:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6032:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  6033:   margin: 0 0 10px 0;
1.966     bisitz   6034:   padding: 3px;
1.995     raeburn  6035:   text-align: left;
1.822     bisitz   6036: }
                   6037: 
1.795     www      6038: .LC_fontsize_medium {
1.911     bisitz   6039:   font-size: 85%;
1.705     tempelho 6040: }
                   6041: 
1.795     www      6042: .LC_fontsize_large {
1.911     bisitz   6043:   font-size: 120%;
1.705     tempelho 6044: }
                   6045: 
1.346     albertel 6046: .LC_menubuttons_inline_text {
                   6047:   color: $font;
1.698     harmsja  6048:   font-size: 90%;
1.701     harmsja  6049:   padding-left:3px;
1.346     albertel 6050: }
                   6051: 
1.934     droeschl 6052: .LC_menubuttons_inline_text img{
                   6053:   vertical-align: middle;
                   6054: }
                   6055: 
1.1051    www      6056: li.LC_menubuttons_inline_text img {
1.951     onken    6057:   cursor:pointer;
1.1002    droeschl 6058:   text-decoration: none;
1.951     onken    6059: }
                   6060: 
1.526     www      6061: .LC_menubuttons_link {
                   6062:   text-decoration: none;
                   6063: }
1.795     www      6064: 
1.522     albertel 6065: .LC_menubuttons_category {
1.521     www      6066:   color: $font;
1.526     www      6067:   background: $pgbg;
1.521     www      6068:   font-size: larger;
                   6069:   font-weight: bold;
                   6070: }
                   6071: 
1.346     albertel 6072: td.LC_menubuttons_text {
1.911     bisitz   6073:   color: $font;
1.346     albertel 6074: }
1.706     harmsja  6075: 
1.346     albertel 6076: .LC_current_location {
                   6077:   background: $tabbg;
                   6078: }
1.795     www      6079: 
1.938     bisitz   6080: table.LC_data_table {
1.347     albertel 6081:   border: 1px solid #000000;
1.402     albertel 6082:   border-collapse: separate;
1.426     albertel 6083:   border-spacing: 1px;
1.610     albertel 6084:   background: $pgbg;
1.347     albertel 6085: }
1.795     www      6086: 
1.422     albertel 6087: .LC_data_table_dense {
                   6088:   font-size: small;
                   6089: }
1.795     www      6090: 
1.507     raeburn  6091: table.LC_nested_outer {
                   6092:   border: 1px solid #000000;
1.589     raeburn  6093:   border-collapse: collapse;
1.803     bisitz   6094:   border-spacing: 0;
1.507     raeburn  6095:   width: 100%;
                   6096: }
1.795     www      6097: 
1.879     raeburn  6098: table.LC_innerpickbox,
1.507     raeburn  6099: table.LC_nested {
1.803     bisitz   6100:   border: none;
1.589     raeburn  6101:   border-collapse: collapse;
1.803     bisitz   6102:   border-spacing: 0;
1.507     raeburn  6103:   width: 100%;
                   6104: }
1.795     www      6105: 
1.911     bisitz   6106: table.LC_data_table tr th,
                   6107: table.LC_calendar tr th,
1.879     raeburn  6108: table.LC_prior_tries tr th,
                   6109: table.LC_innerpickbox tr th {
1.349     albertel 6110:   font-weight: bold;
                   6111:   background-color: $data_table_head;
1.801     tempelho 6112:   color:$fontmenu;
1.701     harmsja  6113:   font-size:90%;
1.347     albertel 6114: }
1.795     www      6115: 
1.879     raeburn  6116: table.LC_innerpickbox tr th,
                   6117: table.LC_innerpickbox tr td {
                   6118:   vertical-align: top;
                   6119: }
                   6120: 
1.711     raeburn  6121: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6122:   background-color: #CCCCCC;
1.711     raeburn  6123:   font-weight: bold;
                   6124:   text-align: left;
                   6125: }
1.795     www      6126: 
1.912     bisitz   6127: table.LC_data_table tr.LC_odd_row > td {
                   6128:   background-color: $data_table_light;
                   6129:   padding: 2px;
                   6130:   vertical-align: top;
                   6131: }
                   6132: 
1.809     bisitz   6133: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6134:   background-color: $data_table_light;
1.912     bisitz   6135:   vertical-align: top;
                   6136: }
                   6137: 
                   6138: table.LC_data_table tr.LC_even_row > td {
                   6139:   background-color: $data_table_dark;
1.425     albertel 6140:   padding: 2px;
1.900     bisitz   6141:   vertical-align: top;
1.347     albertel 6142: }
1.795     www      6143: 
1.809     bisitz   6144: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6145:   background-color: $data_table_dark;
1.900     bisitz   6146:   vertical-align: top;
1.347     albertel 6147: }
1.795     www      6148: 
1.425     albertel 6149: table.LC_data_table tr.LC_data_table_highlight td {
                   6150:   background-color: $data_table_darker;
                   6151: }
1.795     www      6152: 
1.639     raeburn  6153: table.LC_data_table tr td.LC_leftcol_header {
                   6154:   background-color: $data_table_head;
                   6155:   font-weight: bold;
                   6156: }
1.795     www      6157: 
1.451     albertel 6158: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6159: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6160:   font-weight: bold;
                   6161:   font-style: italic;
                   6162:   text-align: center;
                   6163:   padding: 8px;
1.347     albertel 6164: }
1.795     www      6165: 
1.1075.2.30  raeburn  6166: table.LC_data_table tr.LC_empty_row td,
                   6167: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6168:   background-color: $sidebg;
                   6169: }
                   6170: 
                   6171: table.LC_nested tr.LC_empty_row td {
                   6172:   background-color: #FFFFFF;
                   6173: }
                   6174: 
1.890     droeschl 6175: table.LC_caption {
                   6176: }
                   6177: 
1.507     raeburn  6178: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6179:   padding: 4ex
                   6180: }
1.795     www      6181: 
1.507     raeburn  6182: table.LC_nested_outer tr th {
                   6183:   font-weight: bold;
1.801     tempelho 6184:   color:$fontmenu;
1.507     raeburn  6185:   background-color: $data_table_head;
1.701     harmsja  6186:   font-size: small;
1.507     raeburn  6187:   border-bottom: 1px solid #000000;
                   6188: }
1.795     www      6189: 
1.507     raeburn  6190: table.LC_nested_outer tr td.LC_subheader {
                   6191:   background-color: $data_table_head;
                   6192:   font-weight: bold;
                   6193:   font-size: small;
                   6194:   border-bottom: 1px solid #000000;
                   6195:   text-align: right;
1.451     albertel 6196: }
1.795     www      6197: 
1.507     raeburn  6198: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6199:   background-color: #CCCCCC;
1.451     albertel 6200:   font-weight: bold;
                   6201:   font-size: small;
1.507     raeburn  6202:   text-align: center;
                   6203: }
1.795     www      6204: 
1.589     raeburn  6205: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6206: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6207:   text-align: left;
1.451     albertel 6208: }
1.795     www      6209: 
1.507     raeburn  6210: table.LC_nested td {
1.735     bisitz   6211:   background-color: #FFFFFF;
1.451     albertel 6212:   font-size: small;
1.507     raeburn  6213: }
1.795     www      6214: 
1.507     raeburn  6215: table.LC_nested_outer tr th.LC_right_item,
                   6216: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6217: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6218: table.LC_nested tr td.LC_right_item {
1.451     albertel 6219:   text-align: right;
                   6220: }
                   6221: 
1.507     raeburn  6222: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6223:   background-color: #EEEEEE;
1.451     albertel 6224: }
                   6225: 
1.473     raeburn  6226: table.LC_createuser {
                   6227: }
                   6228: 
                   6229: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6230:   font-size: small;
1.473     raeburn  6231: }
                   6232: 
                   6233: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6234:   background-color: #CCCCCC;
1.473     raeburn  6235:   font-weight: bold;
                   6236:   text-align: center;
                   6237: }
                   6238: 
1.349     albertel 6239: table.LC_calendar {
                   6240:   border: 1px solid #000000;
                   6241:   border-collapse: collapse;
1.917     raeburn  6242:   width: 98%;
1.349     albertel 6243: }
1.795     www      6244: 
1.349     albertel 6245: table.LC_calendar_pickdate {
                   6246:   font-size: xx-small;
                   6247: }
1.795     www      6248: 
1.349     albertel 6249: table.LC_calendar tr td {
                   6250:   border: 1px solid #000000;
                   6251:   vertical-align: top;
1.917     raeburn  6252:   width: 14%;
1.349     albertel 6253: }
1.795     www      6254: 
1.349     albertel 6255: table.LC_calendar tr td.LC_calendar_day_empty {
                   6256:   background-color: $data_table_dark;
                   6257: }
1.795     www      6258: 
1.779     bisitz   6259: table.LC_calendar tr td.LC_calendar_day_current {
                   6260:   background-color: $data_table_highlight;
1.777     tempelho 6261: }
1.795     www      6262: 
1.938     bisitz   6263: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6264:   background-color: $mail_new;
                   6265: }
1.795     www      6266: 
1.938     bisitz   6267: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6268:   background-color: $mail_new_hover;
                   6269: }
1.795     www      6270: 
1.938     bisitz   6271: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6272:   background-color: $mail_read;
                   6273: }
1.795     www      6274: 
1.938     bisitz   6275: /*
                   6276: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6277:   background-color: $mail_read_hover;
                   6278: }
1.938     bisitz   6279: */
1.795     www      6280: 
1.938     bisitz   6281: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6282:   background-color: $mail_replied;
                   6283: }
1.795     www      6284: 
1.938     bisitz   6285: /*
                   6286: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6287:   background-color: $mail_replied_hover;
                   6288: }
1.938     bisitz   6289: */
1.795     www      6290: 
1.938     bisitz   6291: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6292:   background-color: $mail_other;
                   6293: }
1.795     www      6294: 
1.938     bisitz   6295: /*
                   6296: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6297:   background-color: $mail_other_hover;
                   6298: }
1.938     bisitz   6299: */
1.494     raeburn  6300: 
1.777     tempelho 6301: table.LC_data_table tr > td.LC_browser_file,
                   6302: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6303:   background: #AAEE77;
1.389     albertel 6304: }
1.795     www      6305: 
1.777     tempelho 6306: table.LC_data_table tr > td.LC_browser_file_locked,
                   6307: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6308:   background: #FFAA99;
1.387     albertel 6309: }
1.795     www      6310: 
1.777     tempelho 6311: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6312:   background: #888888;
1.779     bisitz   6313: }
1.795     www      6314: 
1.777     tempelho 6315: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6316: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6317:   background: #F8F866;
1.777     tempelho 6318: }
1.795     www      6319: 
1.696     bisitz   6320: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6321:   background: #E0E8FF;
1.387     albertel 6322: }
1.696     bisitz   6323: 
1.707     bisitz   6324: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6325:   /* background: #77FF77; */
1.707     bisitz   6326: }
1.795     www      6327: 
1.707     bisitz   6328: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6329:   border-right: 8px solid #FFFF77;
1.707     bisitz   6330: }
1.795     www      6331: 
1.707     bisitz   6332: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6333:   border-right: 8px solid #FFAA77;
1.707     bisitz   6334: }
1.795     www      6335: 
1.707     bisitz   6336: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6337:   border-right: 8px solid #FF7777;
1.707     bisitz   6338: }
1.795     www      6339: 
1.707     bisitz   6340: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6341:   border-right: 8px solid #AAFF77;
1.707     bisitz   6342: }
1.795     www      6343: 
1.707     bisitz   6344: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6345:   border-right: 8px solid #11CC55;
1.707     bisitz   6346: }
                   6347: 
1.388     albertel 6348: span.LC_current_location {
1.701     harmsja  6349:   font-size:larger;
1.388     albertel 6350:   background: $pgbg;
                   6351: }
1.387     albertel 6352: 
1.1029    www      6353: span.LC_current_nav_location {
                   6354:   font-weight:bold;
                   6355:   background: $sidebg;
                   6356: }
                   6357: 
1.395     albertel 6358: span.LC_parm_menu_item {
                   6359:   font-size: larger;
                   6360: }
1.795     www      6361: 
1.395     albertel 6362: span.LC_parm_scope_all {
                   6363:   color: red;
                   6364: }
1.795     www      6365: 
1.395     albertel 6366: span.LC_parm_scope_folder {
                   6367:   color: green;
                   6368: }
1.795     www      6369: 
1.395     albertel 6370: span.LC_parm_scope_resource {
                   6371:   color: orange;
                   6372: }
1.795     www      6373: 
1.395     albertel 6374: span.LC_parm_part {
                   6375:   color: blue;
                   6376: }
1.795     www      6377: 
1.911     bisitz   6378: span.LC_parm_folder,
                   6379: span.LC_parm_symb {
1.395     albertel 6380:   font-size: x-small;
                   6381:   font-family: $mono;
                   6382:   color: #AAAAAA;
                   6383: }
                   6384: 
1.977     bisitz   6385: ul.LC_parm_parmlist li {
                   6386:   display: inline-block;
                   6387:   padding: 0.3em 0.8em;
                   6388:   vertical-align: top;
                   6389:   width: 150px;
                   6390:   border-top:1px solid $lg_border_color;
                   6391: }
                   6392: 
1.795     www      6393: td.LC_parm_overview_level_menu,
                   6394: td.LC_parm_overview_map_menu,
                   6395: td.LC_parm_overview_parm_selectors,
                   6396: td.LC_parm_overview_restrictions  {
1.396     albertel 6397:   border: 1px solid black;
                   6398:   border-collapse: collapse;
                   6399: }
1.795     www      6400: 
1.396     albertel 6401: table.LC_parm_overview_restrictions td {
                   6402:   border-width: 1px 4px 1px 4px;
                   6403:   border-style: solid;
                   6404:   border-color: $pgbg;
                   6405:   text-align: center;
                   6406: }
1.795     www      6407: 
1.396     albertel 6408: table.LC_parm_overview_restrictions th {
                   6409:   background: $tabbg;
                   6410:   border-width: 1px 4px 1px 4px;
                   6411:   border-style: solid;
                   6412:   border-color: $pgbg;
                   6413: }
1.795     www      6414: 
1.398     albertel 6415: table#LC_helpmenu {
1.803     bisitz   6416:   border: none;
1.398     albertel 6417:   height: 55px;
1.803     bisitz   6418:   border-spacing: 0;
1.398     albertel 6419: }
                   6420: 
                   6421: table#LC_helpmenu fieldset legend {
                   6422:   font-size: larger;
                   6423: }
1.795     www      6424: 
1.397     albertel 6425: table#LC_helpmenu_links {
                   6426:   width: 100%;
                   6427:   border: 1px solid black;
                   6428:   background: $pgbg;
1.803     bisitz   6429:   padding: 0;
1.397     albertel 6430:   border-spacing: 1px;
                   6431: }
1.795     www      6432: 
1.397     albertel 6433: table#LC_helpmenu_links tr td {
                   6434:   padding: 1px;
                   6435:   background: $tabbg;
1.399     albertel 6436:   text-align: center;
                   6437:   font-weight: bold;
1.397     albertel 6438: }
1.396     albertel 6439: 
1.795     www      6440: table#LC_helpmenu_links a:link,
                   6441: table#LC_helpmenu_links a:visited,
1.397     albertel 6442: table#LC_helpmenu_links a:active {
                   6443:   text-decoration: none;
                   6444:   color: $font;
                   6445: }
1.795     www      6446: 
1.397     albertel 6447: table#LC_helpmenu_links a:hover {
                   6448:   text-decoration: underline;
                   6449:   color: $vlink;
                   6450: }
1.396     albertel 6451: 
1.417     albertel 6452: .LC_chrt_popup_exists {
                   6453:   border: 1px solid #339933;
                   6454:   margin: -1px;
                   6455: }
1.795     www      6456: 
1.417     albertel 6457: .LC_chrt_popup_up {
                   6458:   border: 1px solid yellow;
                   6459:   margin: -1px;
                   6460: }
1.795     www      6461: 
1.417     albertel 6462: .LC_chrt_popup {
                   6463:   border: 1px solid #8888FF;
                   6464:   background: #CCCCFF;
                   6465: }
1.795     www      6466: 
1.421     albertel 6467: table.LC_pick_box {
                   6468:   border-collapse: separate;
                   6469:   background: white;
                   6470:   border: 1px solid black;
                   6471:   border-spacing: 1px;
                   6472: }
1.795     www      6473: 
1.421     albertel 6474: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6475:   background: $sidebg;
1.421     albertel 6476:   font-weight: bold;
1.900     bisitz   6477:   text-align: left;
1.740     bisitz   6478:   vertical-align: top;
1.421     albertel 6479:   width: 184px;
                   6480:   padding: 8px;
                   6481: }
1.795     www      6482: 
1.579     raeburn  6483: table.LC_pick_box td.LC_pick_box_value {
                   6484:   text-align: left;
                   6485:   padding: 8px;
                   6486: }
1.795     www      6487: 
1.579     raeburn  6488: table.LC_pick_box td.LC_pick_box_select {
                   6489:   text-align: left;
                   6490:   padding: 8px;
                   6491: }
1.795     www      6492: 
1.424     albertel 6493: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6494:   padding: 0;
1.421     albertel 6495:   height: 1px;
                   6496:   background: black;
                   6497: }
1.795     www      6498: 
1.421     albertel 6499: table.LC_pick_box td.LC_pick_box_submit {
                   6500:   text-align: right;
                   6501: }
1.795     www      6502: 
1.579     raeburn  6503: table.LC_pick_box td.LC_evenrow_value {
                   6504:   text-align: left;
                   6505:   padding: 8px;
                   6506:   background-color: $data_table_light;
                   6507: }
1.795     www      6508: 
1.579     raeburn  6509: table.LC_pick_box td.LC_oddrow_value {
                   6510:   text-align: left;
                   6511:   padding: 8px;
                   6512:   background-color: $data_table_light;
                   6513: }
1.795     www      6514: 
1.579     raeburn  6515: span.LC_helpform_receipt_cat {
                   6516:   font-weight: bold;
                   6517: }
1.795     www      6518: 
1.424     albertel 6519: table.LC_group_priv_box {
                   6520:   background: white;
                   6521:   border: 1px solid black;
                   6522:   border-spacing: 1px;
                   6523: }
1.795     www      6524: 
1.424     albertel 6525: table.LC_group_priv_box td.LC_pick_box_title {
                   6526:   background: $tabbg;
                   6527:   font-weight: bold;
                   6528:   text-align: right;
                   6529:   width: 184px;
                   6530: }
1.795     www      6531: 
1.424     albertel 6532: table.LC_group_priv_box td.LC_groups_fixed {
                   6533:   background: $data_table_light;
                   6534:   text-align: center;
                   6535: }
1.795     www      6536: 
1.424     albertel 6537: table.LC_group_priv_box td.LC_groups_optional {
                   6538:   background: $data_table_dark;
                   6539:   text-align: center;
                   6540: }
1.795     www      6541: 
1.424     albertel 6542: table.LC_group_priv_box td.LC_groups_functionality {
                   6543:   background: $data_table_darker;
                   6544:   text-align: center;
                   6545:   font-weight: bold;
                   6546: }
1.795     www      6547: 
1.424     albertel 6548: table.LC_group_priv td {
                   6549:   text-align: left;
1.803     bisitz   6550:   padding: 0;
1.424     albertel 6551: }
                   6552: 
                   6553: .LC_navbuttons {
                   6554:   margin: 2ex 0ex 2ex 0ex;
                   6555: }
1.795     www      6556: 
1.423     albertel 6557: .LC_topic_bar {
                   6558:   font-weight: bold;
                   6559:   background: $tabbg;
1.918     wenzelju 6560:   margin: 1em 0em 1em 2em;
1.805     bisitz   6561:   padding: 3px;
1.918     wenzelju 6562:   font-size: 1.2em;
1.423     albertel 6563: }
1.795     www      6564: 
1.423     albertel 6565: .LC_topic_bar span {
1.918     wenzelju 6566:   left: 0.5em;
                   6567:   position: absolute;
1.423     albertel 6568:   vertical-align: middle;
1.918     wenzelju 6569:   font-size: 1.2em;
1.423     albertel 6570: }
1.795     www      6571: 
1.423     albertel 6572: table.LC_course_group_status {
                   6573:   margin: 20px;
                   6574: }
1.795     www      6575: 
1.423     albertel 6576: table.LC_status_selector td {
                   6577:   vertical-align: top;
                   6578:   text-align: center;
1.424     albertel 6579:   padding: 4px;
                   6580: }
1.795     www      6581: 
1.599     albertel 6582: div.LC_feedback_link {
1.616     albertel 6583:   clear: both;
1.829     kalberla 6584:   background: $sidebg;
1.779     bisitz   6585:   width: 100%;
1.829     kalberla 6586:   padding-bottom: 10px;
                   6587:   border: 1px $tabbg solid;
1.833     kalberla 6588:   height: 22px;
                   6589:   line-height: 22px;
                   6590:   padding-top: 5px;
                   6591: }
                   6592: 
                   6593: div.LC_feedback_link img {
                   6594:   height: 22px;
1.867     kalberla 6595:   vertical-align:middle;
1.829     kalberla 6596: }
                   6597: 
1.911     bisitz   6598: div.LC_feedback_link a {
1.829     kalberla 6599:   text-decoration: none;
1.489     raeburn  6600: }
1.795     www      6601: 
1.867     kalberla 6602: div.LC_comblock {
1.911     bisitz   6603:   display:inline;
1.867     kalberla 6604:   color:$font;
                   6605:   font-size:90%;
                   6606: }
                   6607: 
                   6608: div.LC_feedback_link div.LC_comblock {
                   6609:   padding-left:5px;
                   6610: }
                   6611: 
                   6612: div.LC_feedback_link div.LC_comblock a {
                   6613:   color:$font;
                   6614: }
                   6615: 
1.489     raeburn  6616: span.LC_feedback_link {
1.858     bisitz   6617:   /* background: $feedback_link_bg; */
1.599     albertel 6618:   font-size: larger;
                   6619: }
1.795     www      6620: 
1.599     albertel 6621: span.LC_message_link {
1.858     bisitz   6622:   /* background: $feedback_link_bg; */
1.599     albertel 6623:   font-size: larger;
                   6624:   position: absolute;
                   6625:   right: 1em;
1.489     raeburn  6626: }
1.421     albertel 6627: 
1.515     albertel 6628: table.LC_prior_tries {
1.524     albertel 6629:   border: 1px solid #000000;
                   6630:   border-collapse: separate;
                   6631:   border-spacing: 1px;
1.515     albertel 6632: }
1.523     albertel 6633: 
1.515     albertel 6634: table.LC_prior_tries td {
1.524     albertel 6635:   padding: 2px;
1.515     albertel 6636: }
1.523     albertel 6637: 
                   6638: .LC_answer_correct {
1.795     www      6639:   background: lightgreen;
                   6640:   color: darkgreen;
                   6641:   padding: 6px;
1.523     albertel 6642: }
1.795     www      6643: 
1.523     albertel 6644: .LC_answer_charged_try {
1.797     www      6645:   background: #FFAAAA;
1.795     www      6646:   color: darkred;
                   6647:   padding: 6px;
1.523     albertel 6648: }
1.795     www      6649: 
1.779     bisitz   6650: .LC_answer_not_charged_try,
1.523     albertel 6651: .LC_answer_no_grade,
                   6652: .LC_answer_late {
1.795     www      6653:   background: lightyellow;
1.523     albertel 6654:   color: black;
1.795     www      6655:   padding: 6px;
1.523     albertel 6656: }
1.795     www      6657: 
1.523     albertel 6658: .LC_answer_previous {
1.795     www      6659:   background: lightblue;
                   6660:   color: darkblue;
                   6661:   padding: 6px;
1.523     albertel 6662: }
1.795     www      6663: 
1.779     bisitz   6664: .LC_answer_no_message {
1.777     tempelho 6665:   background: #FFFFFF;
                   6666:   color: black;
1.795     www      6667:   padding: 6px;
1.779     bisitz   6668: }
1.795     www      6669: 
1.779     bisitz   6670: .LC_answer_unknown {
                   6671:   background: orange;
                   6672:   color: black;
1.795     www      6673:   padding: 6px;
1.777     tempelho 6674: }
1.795     www      6675: 
1.529     albertel 6676: span.LC_prior_numerical,
                   6677: span.LC_prior_string,
                   6678: span.LC_prior_custom,
                   6679: span.LC_prior_reaction,
                   6680: span.LC_prior_math {
1.925     bisitz   6681:   font-family: $mono;
1.523     albertel 6682:   white-space: pre;
                   6683: }
                   6684: 
1.525     albertel 6685: span.LC_prior_string {
1.925     bisitz   6686:   font-family: $mono;
1.525     albertel 6687:   white-space: pre;
                   6688: }
                   6689: 
1.523     albertel 6690: table.LC_prior_option {
                   6691:   width: 100%;
                   6692:   border-collapse: collapse;
                   6693: }
1.795     www      6694: 
1.911     bisitz   6695: table.LC_prior_rank,
1.795     www      6696: table.LC_prior_match {
1.528     albertel 6697:   border-collapse: collapse;
                   6698: }
1.795     www      6699: 
1.528     albertel 6700: table.LC_prior_option tr td,
                   6701: table.LC_prior_rank tr td,
                   6702: table.LC_prior_match tr td {
1.524     albertel 6703:   border: 1px solid #000000;
1.515     albertel 6704: }
                   6705: 
1.855     bisitz   6706: .LC_nobreak {
1.544     albertel 6707:   white-space: nowrap;
1.519     raeburn  6708: }
                   6709: 
1.576     raeburn  6710: span.LC_cusr_emph {
                   6711:   font-style: italic;
                   6712: }
                   6713: 
1.633     raeburn  6714: span.LC_cusr_subheading {
                   6715:   font-weight: normal;
                   6716:   font-size: 85%;
                   6717: }
                   6718: 
1.861     bisitz   6719: div.LC_docs_entry_move {
1.859     bisitz   6720:   border: 1px solid #BBBBBB;
1.545     albertel 6721:   background: #DDDDDD;
1.861     bisitz   6722:   width: 22px;
1.859     bisitz   6723:   padding: 1px;
                   6724:   margin: 0;
1.545     albertel 6725: }
                   6726: 
1.861     bisitz   6727: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6728: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6729:   font-size: x-small;
                   6730: }
1.795     www      6731: 
1.861     bisitz   6732: .LC_docs_entry_parameter {
                   6733:   white-space: nowrap;
                   6734: }
                   6735: 
1.544     albertel 6736: .LC_docs_copy {
1.545     albertel 6737:   color: #000099;
1.544     albertel 6738: }
1.795     www      6739: 
1.544     albertel 6740: .LC_docs_cut {
1.545     albertel 6741:   color: #550044;
1.544     albertel 6742: }
1.795     www      6743: 
1.544     albertel 6744: .LC_docs_rename {
1.545     albertel 6745:   color: #009900;
1.544     albertel 6746: }
1.795     www      6747: 
1.544     albertel 6748: .LC_docs_remove {
1.545     albertel 6749:   color: #990000;
                   6750: }
                   6751: 
1.547     albertel 6752: .LC_docs_reinit_warn,
                   6753: .LC_docs_ext_edit {
                   6754:   font-size: x-small;
                   6755: }
                   6756: 
1.545     albertel 6757: table.LC_docs_adddocs td,
                   6758: table.LC_docs_adddocs th {
                   6759:   border: 1px solid #BBBBBB;
                   6760:   padding: 4px;
                   6761:   background: #DDDDDD;
1.543     albertel 6762: }
                   6763: 
1.584     albertel 6764: table.LC_sty_begin {
                   6765:   background: #BBFFBB;
                   6766: }
1.795     www      6767: 
1.584     albertel 6768: table.LC_sty_end {
                   6769:   background: #FFBBBB;
                   6770: }
                   6771: 
1.589     raeburn  6772: table.LC_double_column {
1.803     bisitz   6773:   border-width: 0;
1.589     raeburn  6774:   border-collapse: collapse;
                   6775:   width: 100%;
                   6776:   padding: 2px;
                   6777: }
                   6778: 
                   6779: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6780:   top: 2px;
1.589     raeburn  6781:   left: 2px;
                   6782:   width: 47%;
                   6783:   vertical-align: top;
                   6784: }
                   6785: 
                   6786: table.LC_double_column tr td.LC_right_col {
                   6787:   top: 2px;
1.779     bisitz   6788:   right: 2px;
1.589     raeburn  6789:   width: 47%;
                   6790:   vertical-align: top;
                   6791: }
                   6792: 
1.591     raeburn  6793: div.LC_left_float {
                   6794:   float: left;
                   6795:   padding-right: 5%;
1.597     albertel 6796:   padding-bottom: 4px;
1.591     raeburn  6797: }
                   6798: 
                   6799: div.LC_clear_float_header {
1.597     albertel 6800:   padding-bottom: 2px;
1.591     raeburn  6801: }
                   6802: 
                   6803: div.LC_clear_float_footer {
1.597     albertel 6804:   padding-top: 10px;
1.591     raeburn  6805:   clear: both;
                   6806: }
                   6807: 
1.597     albertel 6808: div.LC_grade_show_user {
1.941     bisitz   6809: /*  border-left: 5px solid $sidebg; */
                   6810:   border-top: 5px solid #000000;
                   6811:   margin: 50px 0 0 0;
1.936     bisitz   6812:   padding: 15px 0 5px 10px;
1.597     albertel 6813: }
1.795     www      6814: 
1.936     bisitz   6815: div.LC_grade_show_user_odd_row {
1.941     bisitz   6816: /*  border-left: 5px solid #000000; */
                   6817: }
                   6818: 
                   6819: div.LC_grade_show_user div.LC_Box {
                   6820:   margin-right: 50px;
1.597     albertel 6821: }
                   6822: 
                   6823: div.LC_grade_submissions,
                   6824: div.LC_grade_message_center,
1.936     bisitz   6825: div.LC_grade_info_links {
1.597     albertel 6826:   margin: 5px;
                   6827:   width: 99%;
                   6828:   background: #FFFFFF;
                   6829: }
1.795     www      6830: 
1.597     albertel 6831: div.LC_grade_submissions_header,
1.936     bisitz   6832: div.LC_grade_message_center_header {
1.705     tempelho 6833:   font-weight: bold;
                   6834:   font-size: large;
1.597     albertel 6835: }
1.795     www      6836: 
1.597     albertel 6837: div.LC_grade_submissions_body,
1.936     bisitz   6838: div.LC_grade_message_center_body {
1.597     albertel 6839:   border: 1px solid black;
                   6840:   width: 99%;
                   6841:   background: #FFFFFF;
                   6842: }
1.795     www      6843: 
1.613     albertel 6844: table.LC_scantron_action {
                   6845:   width: 100%;
                   6846: }
1.795     www      6847: 
1.613     albertel 6848: table.LC_scantron_action tr th {
1.698     harmsja  6849:   font-weight:bold;
                   6850:   font-style:normal;
1.613     albertel 6851: }
1.795     www      6852: 
1.779     bisitz   6853: .LC_edit_problem_header,
1.614     albertel 6854: div.LC_edit_problem_footer {
1.705     tempelho 6855:   font-weight: normal;
                   6856:   font-size:  medium;
1.602     albertel 6857:   margin: 2px;
1.1060    bisitz   6858:   background-color: $sidebg;
1.600     albertel 6859: }
1.795     www      6860: 
1.600     albertel 6861: div.LC_edit_problem_header,
1.602     albertel 6862: div.LC_edit_problem_header div,
1.614     albertel 6863: div.LC_edit_problem_footer,
                   6864: div.LC_edit_problem_footer div,
1.602     albertel 6865: div.LC_edit_problem_editxml_header,
                   6866: div.LC_edit_problem_editxml_header div {
1.1075.2.112  raeburn  6867:   z-index: 100;
1.600     albertel 6868: }
1.795     www      6869: 
1.600     albertel 6870: div.LC_edit_problem_header_title {
1.705     tempelho 6871:   font-weight: bold;
                   6872:   font-size: larger;
1.602     albertel 6873:   background: $tabbg;
                   6874:   padding: 3px;
1.1060    bisitz   6875:   margin: 0 0 5px 0;
1.602     albertel 6876: }
1.795     www      6877: 
1.602     albertel 6878: table.LC_edit_problem_header_title {
                   6879:   width: 100%;
1.600     albertel 6880:   background: $tabbg;
1.602     albertel 6881: }
                   6882: 
1.1075.2.112  raeburn  6883: div.LC_edit_actionbar {
                   6884:     background-color: $sidebg;
                   6885:     margin: 0;
                   6886:     padding: 0;
                   6887:     line-height: 200%;
1.602     albertel 6888: }
1.795     www      6889: 
1.1075.2.112  raeburn  6890: div.LC_edit_actionbar div{
                   6891:     padding: 0;
                   6892:     margin: 0;
                   6893:     display: inline-block;
1.600     albertel 6894: }
1.795     www      6895: 
1.1075.2.34  raeburn  6896: .LC_edit_opt {
                   6897:   padding-left: 1em;
                   6898:   white-space: nowrap;
                   6899: }
                   6900: 
1.1075.2.57  raeburn  6901: .LC_edit_problem_latexhelper{
                   6902:     text-align: right;
                   6903: }
                   6904: 
                   6905: #LC_edit_problem_colorful div{
                   6906:     margin-left: 40px;
                   6907: }
                   6908: 
1.1075.2.112  raeburn  6909: #LC_edit_problem_codemirror div{
                   6910:     margin-left: 0px;
                   6911: }
                   6912: 
1.911     bisitz   6913: img.stift {
1.803     bisitz   6914:   border-width: 0;
                   6915:   vertical-align: middle;
1.677     riegler  6916: }
1.680     riegler  6917: 
1.923     bisitz   6918: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6919:   vertical-align: top;
1.777     tempelho 6920: }
1.795     www      6921: 
1.716     raeburn  6922: div.LC_createcourse {
1.911     bisitz   6923:   margin: 10px 10px 10px 10px;
1.716     raeburn  6924: }
                   6925: 
1.917     raeburn  6926: .LC_dccid {
1.1075.2.38  raeburn  6927:   float: right;
1.917     raeburn  6928:   margin: 0.2em 0 0 0;
                   6929:   padding: 0;
                   6930:   font-size: 90%;
                   6931:   display:none;
                   6932: }
                   6933: 
1.897     wenzelju 6934: ol.LC_primary_menu a:hover,
1.721     harmsja  6935: ol#LC_MenuBreadcrumbs a:hover,
                   6936: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6937: ul#LC_secondary_menu a:hover,
1.721     harmsja  6938: .LC_FormSectionClearButton input:hover
1.795     www      6939: ul.LC_TabContent   li:hover a {
1.952     onken    6940:   color:$button_hover;
1.911     bisitz   6941:   text-decoration:none;
1.693     droeschl 6942: }
                   6943: 
1.779     bisitz   6944: h1 {
1.911     bisitz   6945:   padding: 0;
                   6946:   line-height:130%;
1.693     droeschl 6947: }
1.698     harmsja  6948: 
1.911     bisitz   6949: h2,
                   6950: h3,
                   6951: h4,
                   6952: h5,
                   6953: h6 {
                   6954:   margin: 5px 0 5px 0;
                   6955:   padding: 0;
                   6956:   line-height:130%;
1.693     droeschl 6957: }
1.795     www      6958: 
                   6959: .LC_hcell {
1.911     bisitz   6960:   padding:3px 15px 3px 15px;
                   6961:   margin: 0;
                   6962:   background-color:$tabbg;
                   6963:   color:$fontmenu;
                   6964:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6965: }
1.795     www      6966: 
1.840     bisitz   6967: .LC_Box > .LC_hcell {
1.911     bisitz   6968:   margin: 0 -10px 10px -10px;
1.835     bisitz   6969: }
                   6970: 
1.721     harmsja  6971: .LC_noBorder {
1.911     bisitz   6972:   border: 0;
1.698     harmsja  6973: }
1.693     droeschl 6974: 
1.721     harmsja  6975: .LC_FormSectionClearButton input {
1.911     bisitz   6976:   background-color:transparent;
                   6977:   border: none;
                   6978:   cursor:pointer;
                   6979:   text-decoration:underline;
1.693     droeschl 6980: }
1.763     bisitz   6981: 
                   6982: .LC_help_open_topic {
1.911     bisitz   6983:   color: #FFFFFF;
                   6984:   background-color: #EEEEFF;
                   6985:   margin: 1px;
                   6986:   padding: 4px;
                   6987:   border: 1px solid #000033;
                   6988:   white-space: nowrap;
                   6989:   /* vertical-align: middle; */
1.759     neumanie 6990: }
1.693     droeschl 6991: 
1.911     bisitz   6992: dl,
                   6993: ul,
                   6994: div,
                   6995: fieldset {
                   6996:   margin: 10px 10px 10px 0;
                   6997:   /* overflow: hidden; */
1.693     droeschl 6998: }
1.795     www      6999: 
1.1075.2.90  raeburn  7000: article.geogebraweb div {
                   7001:     margin: 0;
                   7002: }
                   7003: 
1.838     bisitz   7004: fieldset > legend {
1.911     bisitz   7005:   font-weight: bold;
                   7006:   padding: 0 5px 0 5px;
1.838     bisitz   7007: }
                   7008: 
1.813     bisitz   7009: #LC_nav_bar {
1.911     bisitz   7010:   float: left;
1.995     raeburn  7011:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7012:   margin: 0 0 2px 0;
1.807     droeschl 7013: }
                   7014: 
1.916     droeschl 7015: #LC_realm {
                   7016:   margin: 0.2em 0 0 0;
                   7017:   padding: 0;
                   7018:   font-weight: bold;
                   7019:   text-align: center;
1.995     raeburn  7020:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7021: }
                   7022: 
1.911     bisitz   7023: #LC_nav_bar em {
                   7024:   font-weight: bold;
                   7025:   font-style: normal;
1.807     droeschl 7026: }
                   7027: 
1.897     wenzelju 7028: ol.LC_primary_menu {
1.934     droeschl 7029:   margin: 0;
1.1075.2.2  raeburn  7030:   padding: 0;
1.807     droeschl 7031: }
                   7032: 
1.852     droeschl 7033: ol#LC_PathBreadcrumbs {
1.911     bisitz   7034:   margin: 0;
1.693     droeschl 7035: }
                   7036: 
1.897     wenzelju 7037: ol.LC_primary_menu li {
1.1075.2.2  raeburn  7038:   color: RGB(80, 80, 80);
                   7039:   vertical-align: middle;
                   7040:   text-align: left;
                   7041:   list-style: none;
1.1075.2.112  raeburn  7042:   position: relative;
1.1075.2.2  raeburn  7043:   float: left;
1.1075.2.112  raeburn  7044:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7045:   line-height: 1.5em;
1.1075.2.2  raeburn  7046: }
                   7047: 
1.1075.2.113  raeburn  7048: ol.LC_primary_menu li a, 
1.1075.2.112  raeburn  7049: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  7050:   display: block;
                   7051:   margin: 0;
                   7052:   padding: 0 5px 0 10px;
                   7053:   text-decoration: none;
                   7054: }
                   7055: 
1.1075.2.112  raeburn  7056: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7057:   display: inline-block;
                   7058:   width: 95%;
                   7059:   text-align: left;
                   7060: }
                   7061: 
                   7062: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7063:   display: inline-block;
                   7064:   width: 5%;
                   7065:   float: right;
                   7066:   text-align: right;
                   7067:   font-size: 70%;
                   7068: }
                   7069: 
                   7070: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  7071:   display: none;
1.1075.2.112  raeburn  7072:   width: 15em;
1.1075.2.2  raeburn  7073:   background-color: $data_table_light;
1.1075.2.112  raeburn  7074:   position: absolute;
                   7075:   top: 100%;
                   7076: }
                   7077: 
                   7078: ol.LC_primary_menu ul ul {
                   7079:   left: 100%;
                   7080:   top: 0;
1.1075.2.2  raeburn  7081: }
                   7082: 
1.1075.2.112  raeburn  7083: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  7084:   display: block;
                   7085:   position: absolute;
                   7086:   margin: 0;
                   7087:   padding: 0;
1.1075.2.5  raeburn  7088:   z-index: 2;
1.1075.2.2  raeburn  7089: }
                   7090: 
                   7091: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112  raeburn  7092: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  7093:   font-size: 90%;
1.911     bisitz   7094:   vertical-align: top;
1.1075.2.2  raeburn  7095:   float: none;
1.1075.2.5  raeburn  7096:   border-left: 1px solid black;
                   7097:   border-right: 1px solid black;
1.1075.2.112  raeburn  7098: /* A dark bottom border to visualize different menu options;
                   7099: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7100:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  7101: }
                   7102: 
1.1075.2.112  raeburn  7103: ol.LC_primary_menu li li p:hover {
                   7104:   color:$button_hover;
                   7105:   text-decoration:none;
                   7106:   background-color:$data_table_dark;
1.1075.2.2  raeburn  7107: }
                   7108: 
                   7109: ol.LC_primary_menu li li a:hover {
                   7110:    color:$button_hover;
                   7111:    background-color:$data_table_dark;
1.693     droeschl 7112: }
                   7113: 
1.1075.2.112  raeburn  7114: /* Font-size equal to the size of the predecessors*/
                   7115: ol.LC_primary_menu li:hover li li {
                   7116:   font-size: 100%;
                   7117: }
                   7118: 
1.897     wenzelju 7119: ol.LC_primary_menu li img {
1.911     bisitz   7120:   vertical-align: bottom;
1.934     droeschl 7121:   height: 1.1em;
1.1075.2.3  raeburn  7122:   margin: 0.2em 0 0 0;
1.693     droeschl 7123: }
                   7124: 
1.897     wenzelju 7125: ol.LC_primary_menu a {
1.911     bisitz   7126:   color: RGB(80, 80, 80);
                   7127:   text-decoration: none;
1.693     droeschl 7128: }
1.795     www      7129: 
1.949     droeschl 7130: ol.LC_primary_menu a.LC_new_message {
                   7131:   font-weight:bold;
                   7132:   color: darkred;
                   7133: }
                   7134: 
1.975     raeburn  7135: ol.LC_docs_parameters {
                   7136:   margin-left: 0;
                   7137:   padding: 0;
                   7138:   list-style: none;
                   7139: }
                   7140: 
                   7141: ol.LC_docs_parameters li {
                   7142:   margin: 0;
                   7143:   padding-right: 20px;
                   7144:   display: inline;
                   7145: }
                   7146: 
1.976     raeburn  7147: ol.LC_docs_parameters li:before {
                   7148:   content: "\\002022 \\0020";
                   7149: }
                   7150: 
                   7151: li.LC_docs_parameters_title {
                   7152:   font-weight: bold;
                   7153: }
                   7154: 
                   7155: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7156:   content: "";
                   7157: }
                   7158: 
1.897     wenzelju 7159: ul#LC_secondary_menu {
1.1075.2.23  raeburn  7160:   clear: right;
1.911     bisitz   7161:   color: $fontmenu;
                   7162:   background: $tabbg;
                   7163:   list-style: none;
                   7164:   padding: 0;
                   7165:   margin: 0;
                   7166:   width: 100%;
1.995     raeburn  7167:   text-align: left;
1.1075.2.4  raeburn  7168:   float: left;
1.808     droeschl 7169: }
                   7170: 
1.897     wenzelju 7171: ul#LC_secondary_menu li {
1.911     bisitz   7172:   font-weight: bold;
                   7173:   line-height: 1.8em;
                   7174:   border-right: 1px solid black;
1.1075.2.4  raeburn  7175:   float: left;
                   7176: }
                   7177: 
                   7178: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7179:   background-color: $data_table_light;
                   7180: }
                   7181: 
                   7182: ul#LC_secondary_menu li a {
                   7183:   padding: 0 0.8em;
                   7184: }
                   7185: 
                   7186: ul#LC_secondary_menu li ul {
                   7187:   display: none;
                   7188: }
                   7189: 
                   7190: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7191:   display: block;
                   7192:   position: absolute;
                   7193:   margin: 0;
                   7194:   padding: 0;
                   7195:   list-style:none;
                   7196:   float: none;
                   7197:   background-color: $data_table_light;
1.1075.2.5  raeburn  7198:   z-index: 2;
1.1075.2.10  raeburn  7199:   margin-left: -1px;
1.1075.2.4  raeburn  7200: }
                   7201: 
                   7202: ul#LC_secondary_menu li ul li {
                   7203:   font-size: 90%;
                   7204:   vertical-align: top;
                   7205:   border-left: 1px solid black;
                   7206:   border-right: 1px solid black;
1.1075.2.33  raeburn  7207:   background-color: $data_table_light;
1.1075.2.4  raeburn  7208:   list-style:none;
                   7209:   float: none;
                   7210: }
                   7211: 
                   7212: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7213:   background-color: $data_table_dark;
1.807     droeschl 7214: }
                   7215: 
1.847     tempelho 7216: ul.LC_TabContent {
1.911     bisitz   7217:   display:block;
                   7218:   background: $sidebg;
                   7219:   border-bottom: solid 1px $lg_border_color;
                   7220:   list-style:none;
1.1020    raeburn  7221:   margin: -1px -10px 0 -10px;
1.911     bisitz   7222:   padding: 0;
1.693     droeschl 7223: }
                   7224: 
1.795     www      7225: ul.LC_TabContent li,
                   7226: ul.LC_TabContentBigger li {
1.911     bisitz   7227:   float:left;
1.741     harmsja  7228: }
1.795     www      7229: 
1.897     wenzelju 7230: ul#LC_secondary_menu li a {
1.911     bisitz   7231:   color: $fontmenu;
                   7232:   text-decoration: none;
1.693     droeschl 7233: }
1.795     www      7234: 
1.721     harmsja  7235: ul.LC_TabContent {
1.952     onken    7236:   min-height:20px;
1.721     harmsja  7237: }
1.795     www      7238: 
                   7239: ul.LC_TabContent li {
1.911     bisitz   7240:   vertical-align:middle;
1.959     onken    7241:   padding: 0 16px 0 10px;
1.911     bisitz   7242:   background-color:$tabbg;
                   7243:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7244:   border-left: solid 1px $font;
1.721     harmsja  7245: }
1.795     www      7246: 
1.847     tempelho 7247: ul.LC_TabContent .right {
1.911     bisitz   7248:   float:right;
1.847     tempelho 7249: }
                   7250: 
1.911     bisitz   7251: ul.LC_TabContent li a,
                   7252: ul.LC_TabContent li {
                   7253:   color:rgb(47,47,47);
                   7254:   text-decoration:none;
                   7255:   font-size:95%;
                   7256:   font-weight:bold;
1.952     onken    7257:   min-height:20px;
                   7258: }
                   7259: 
1.959     onken    7260: ul.LC_TabContent li a:hover,
                   7261: ul.LC_TabContent li a:focus {
1.952     onken    7262:   color: $button_hover;
1.959     onken    7263:   background:none;
                   7264:   outline:none;
1.952     onken    7265: }
                   7266: 
                   7267: ul.LC_TabContent li:hover {
                   7268:   color: $button_hover;
                   7269:   cursor:pointer;
1.721     harmsja  7270: }
1.795     www      7271: 
1.911     bisitz   7272: ul.LC_TabContent li.active {
1.952     onken    7273:   color: $font;
1.911     bisitz   7274:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7275:   border-bottom:solid 1px #FFFFFF;
                   7276:   cursor: default;
1.744     ehlerst  7277: }
1.795     www      7278: 
1.959     onken    7279: ul.LC_TabContent li.active a {
                   7280:   color:$font;
                   7281:   background:#FFFFFF;
                   7282:   outline: none;
                   7283: }
1.1047    raeburn  7284: 
                   7285: ul.LC_TabContent li.goback {
                   7286:   float: left;
                   7287:   border-left: none;
                   7288: }
                   7289: 
1.870     tempelho 7290: #maincoursedoc {
1.911     bisitz   7291:   clear:both;
1.870     tempelho 7292: }
                   7293: 
                   7294: ul.LC_TabContentBigger {
1.911     bisitz   7295:   display:block;
                   7296:   list-style:none;
                   7297:   padding: 0;
1.870     tempelho 7298: }
                   7299: 
1.795     www      7300: ul.LC_TabContentBigger li {
1.911     bisitz   7301:   vertical-align:bottom;
                   7302:   height: 30px;
                   7303:   font-size:110%;
                   7304:   font-weight:bold;
                   7305:   color: #737373;
1.841     tempelho 7306: }
                   7307: 
1.957     onken    7308: ul.LC_TabContentBigger li.active {
                   7309:   position: relative;
                   7310:   top: 1px;
                   7311: }
                   7312: 
1.870     tempelho 7313: ul.LC_TabContentBigger li a {
1.911     bisitz   7314:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7315:   height: 30px;
                   7316:   line-height: 30px;
                   7317:   text-align: center;
                   7318:   display: block;
                   7319:   text-decoration: none;
1.958     onken    7320:   outline: none;  
1.741     harmsja  7321: }
1.795     www      7322: 
1.870     tempelho 7323: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7324:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7325:   color:$font;
1.744     ehlerst  7326: }
1.795     www      7327: 
1.870     tempelho 7328: ul.LC_TabContentBigger li b {
1.911     bisitz   7329:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7330:   display: block;
                   7331:   float: left;
                   7332:   padding: 0 30px;
1.957     onken    7333:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7334: }
                   7335: 
1.956     onken    7336: ul.LC_TabContentBigger li:hover b {
                   7337:   color:$button_hover;
                   7338: }
                   7339: 
1.870     tempelho 7340: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7341:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7342:   color:$font;
1.957     onken    7343:   border: 0;
1.741     harmsja  7344: }
1.693     droeschl 7345: 
1.870     tempelho 7346: 
1.862     bisitz   7347: ul.LC_CourseBreadcrumbs {
                   7348:   background: $sidebg;
1.1020    raeburn  7349:   height: 2em;
1.862     bisitz   7350:   padding-left: 10px;
1.1020    raeburn  7351:   margin: 0;
1.862     bisitz   7352:   list-style-position: inside;
                   7353: }
                   7354: 
1.911     bisitz   7355: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7356: ol#LC_PathBreadcrumbs {
1.911     bisitz   7357:   padding-left: 10px;
                   7358:   margin: 0;
1.933     droeschl 7359:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7360: }
                   7361: 
1.911     bisitz   7362: ol#LC_MenuBreadcrumbs li,
                   7363: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7364: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7365:   display: inline;
1.933     droeschl 7366:   white-space: normal;  
1.693     droeschl 7367: }
                   7368: 
1.823     bisitz   7369: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7370: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7371:   text-decoration: none;
                   7372:   font-size:90%;
1.693     droeschl 7373: }
1.795     www      7374: 
1.969     droeschl 7375: ol#LC_MenuBreadcrumbs h1 {
                   7376:   display: inline;
                   7377:   font-size: 90%;
                   7378:   line-height: 2.5em;
                   7379:   margin: 0;
                   7380:   padding: 0;
                   7381: }
                   7382: 
1.795     www      7383: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7384:   text-decoration:none;
                   7385:   font-size:100%;
                   7386:   font-weight:bold;
1.693     droeschl 7387: }
1.795     www      7388: 
1.840     bisitz   7389: .LC_Box {
1.911     bisitz   7390:   border: solid 1px $lg_border_color;
                   7391:   padding: 0 10px 10px 10px;
1.746     neumanie 7392: }
1.795     www      7393: 
1.1020    raeburn  7394: .LC_DocsBox {
                   7395:   border: solid 1px $lg_border_color;
                   7396:   padding: 0 0 10px 10px;
                   7397: }
                   7398: 
1.795     www      7399: .LC_AboutMe_Image {
1.911     bisitz   7400:   float:left;
                   7401:   margin-right:10px;
1.747     neumanie 7402: }
1.795     www      7403: 
                   7404: .LC_Clear_AboutMe_Image {
1.911     bisitz   7405:   clear:left;
1.747     neumanie 7406: }
1.795     www      7407: 
1.721     harmsja  7408: dl.LC_ListStyleClean dt {
1.911     bisitz   7409:   padding-right: 5px;
                   7410:   display: table-header-group;
1.693     droeschl 7411: }
                   7412: 
1.721     harmsja  7413: dl.LC_ListStyleClean dd {
1.911     bisitz   7414:   display: table-row;
1.693     droeschl 7415: }
                   7416: 
1.721     harmsja  7417: .LC_ListStyleClean,
                   7418: .LC_ListStyleSimple,
                   7419: .LC_ListStyleNormal,
1.795     www      7420: .LC_ListStyleSpecial {
1.911     bisitz   7421:   /* display:block; */
                   7422:   list-style-position: inside;
                   7423:   list-style-type: none;
                   7424:   overflow: hidden;
                   7425:   padding: 0;
1.693     droeschl 7426: }
                   7427: 
1.721     harmsja  7428: .LC_ListStyleSimple li,
                   7429: .LC_ListStyleSimple dd,
                   7430: .LC_ListStyleNormal li,
                   7431: .LC_ListStyleNormal dd,
                   7432: .LC_ListStyleSpecial li,
1.795     www      7433: .LC_ListStyleSpecial dd {
1.911     bisitz   7434:   margin: 0;
                   7435:   padding: 5px 5px 5px 10px;
                   7436:   clear: both;
1.693     droeschl 7437: }
                   7438: 
1.721     harmsja  7439: .LC_ListStyleClean li,
                   7440: .LC_ListStyleClean dd {
1.911     bisitz   7441:   padding-top: 0;
                   7442:   padding-bottom: 0;
1.693     droeschl 7443: }
                   7444: 
1.721     harmsja  7445: .LC_ListStyleSimple dd,
1.795     www      7446: .LC_ListStyleSimple li {
1.911     bisitz   7447:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7448: }
                   7449: 
1.721     harmsja  7450: .LC_ListStyleSpecial li,
                   7451: .LC_ListStyleSpecial dd {
1.911     bisitz   7452:   list-style-type: none;
                   7453:   background-color: RGB(220, 220, 220);
                   7454:   margin-bottom: 4px;
1.693     droeschl 7455: }
                   7456: 
1.721     harmsja  7457: table.LC_SimpleTable {
1.911     bisitz   7458:   margin:5px;
                   7459:   border:solid 1px $lg_border_color;
1.795     www      7460: }
1.693     droeschl 7461: 
1.721     harmsja  7462: table.LC_SimpleTable tr {
1.911     bisitz   7463:   padding: 0;
                   7464:   border:solid 1px $lg_border_color;
1.693     droeschl 7465: }
1.795     www      7466: 
                   7467: table.LC_SimpleTable thead {
1.911     bisitz   7468:   background:rgb(220,220,220);
1.693     droeschl 7469: }
                   7470: 
1.721     harmsja  7471: div.LC_columnSection {
1.911     bisitz   7472:   display: block;
                   7473:   clear: both;
                   7474:   overflow: hidden;
                   7475:   margin: 0;
1.693     droeschl 7476: }
                   7477: 
1.721     harmsja  7478: div.LC_columnSection>* {
1.911     bisitz   7479:   float: left;
                   7480:   margin: 10px 20px 10px 0;
                   7481:   overflow:hidden;
1.693     droeschl 7482: }
1.721     harmsja  7483: 
1.795     www      7484: table em {
1.911     bisitz   7485:   font-weight: bold;
                   7486:   font-style: normal;
1.748     schulted 7487: }
1.795     www      7488: 
1.779     bisitz   7489: table.LC_tableBrowseRes,
1.795     www      7490: table.LC_tableOfContent {
1.911     bisitz   7491:   border:none;
                   7492:   border-spacing: 1px;
                   7493:   padding: 3px;
                   7494:   background-color: #FFFFFF;
                   7495:   font-size: 90%;
1.753     droeschl 7496: }
1.789     droeschl 7497: 
1.911     bisitz   7498: table.LC_tableOfContent {
                   7499:   border-collapse: collapse;
1.789     droeschl 7500: }
                   7501: 
1.771     droeschl 7502: table.LC_tableBrowseRes a,
1.768     schulted 7503: table.LC_tableOfContent a {
1.911     bisitz   7504:   background-color: transparent;
                   7505:   text-decoration: none;
1.753     droeschl 7506: }
                   7507: 
1.795     www      7508: table.LC_tableOfContent img {
1.911     bisitz   7509:   border: none;
                   7510:   height: 1.3em;
                   7511:   vertical-align: text-bottom;
                   7512:   margin-right: 0.3em;
1.753     droeschl 7513: }
1.757     schulted 7514: 
1.795     www      7515: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7516:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7517: }
                   7518: 
1.795     www      7519: a#LC_content_toolbar_everything {
1.911     bisitz   7520:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7521: }
                   7522: 
1.795     www      7523: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7524:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7525: }
                   7526: 
1.795     www      7527: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7528:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7529: }
                   7530: 
1.795     www      7531: a#LC_content_toolbar_changefolder {
1.911     bisitz   7532:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7533: }
                   7534: 
1.795     www      7535: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7536:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7537: }
                   7538: 
1.1043    raeburn  7539: a#LC_content_toolbar_edittoplevel {
                   7540:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7541: }
                   7542: 
1.795     www      7543: ul#LC_toolbar li a:hover {
1.911     bisitz   7544:   background-position: bottom center;
1.757     schulted 7545: }
                   7546: 
1.795     www      7547: ul#LC_toolbar {
1.911     bisitz   7548:   padding: 0;
                   7549:   margin: 2px;
                   7550:   list-style:none;
                   7551:   position:relative;
                   7552:   background-color:white;
1.1075.2.9  raeburn  7553:   overflow: auto;
1.757     schulted 7554: }
                   7555: 
1.795     www      7556: ul#LC_toolbar li {
1.911     bisitz   7557:   border:1px solid white;
                   7558:   padding: 0;
                   7559:   margin: 0;
                   7560:   float: left;
                   7561:   display:inline;
                   7562:   vertical-align:middle;
1.1075.2.9  raeburn  7563:   white-space: nowrap;
1.911     bisitz   7564: }
1.757     schulted 7565: 
1.783     amueller 7566: 
1.795     www      7567: a.LC_toolbarItem {
1.911     bisitz   7568:   display:block;
                   7569:   padding: 0;
                   7570:   margin: 0;
                   7571:   height: 32px;
                   7572:   width: 32px;
                   7573:   color:white;
                   7574:   border: none;
                   7575:   background-repeat:no-repeat;
                   7576:   background-color:transparent;
1.757     schulted 7577: }
                   7578: 
1.915     droeschl 7579: ul.LC_funclist {
                   7580:     margin: 0;
                   7581:     padding: 0.5em 1em 0.5em 0;
                   7582: }
                   7583: 
1.933     droeschl 7584: ul.LC_funclist > li:first-child {
                   7585:     font-weight:bold; 
                   7586:     margin-left:0.8em;
                   7587: }
                   7588: 
1.915     droeschl 7589: ul.LC_funclist + ul.LC_funclist {
                   7590:     /* 
                   7591:        left border as a seperator if we have more than
                   7592:        one list 
                   7593:     */
                   7594:     border-left: 1px solid $sidebg;
                   7595:     /* 
                   7596:        this hides the left border behind the border of the 
                   7597:        outer box if element is wrapped to the next 'line' 
                   7598:     */
                   7599:     margin-left: -1px;
                   7600: }
                   7601: 
1.843     bisitz   7602: ul.LC_funclist li {
1.915     droeschl 7603:   display: inline;
1.782     bisitz   7604:   white-space: nowrap;
1.915     droeschl 7605:   margin: 0 0 0 25px;
                   7606:   line-height: 150%;
1.782     bisitz   7607: }
                   7608: 
1.974     wenzelju 7609: .LC_hidden {
                   7610:   display: none;
                   7611: }
                   7612: 
1.1030    www      7613: .LCmodal-overlay {
                   7614: 		position:fixed;
                   7615: 		top:0;
                   7616: 		right:0;
                   7617: 		bottom:0;
                   7618: 		left:0;
                   7619: 		height:100%;
                   7620: 		width:100%;
                   7621: 		margin:0;
                   7622: 		padding:0;
                   7623: 		background:#999;
                   7624: 		opacity:.75;
                   7625: 		filter: alpha(opacity=75);
                   7626: 		-moz-opacity: 0.75;
                   7627: 		z-index:101;
                   7628: }
                   7629: 
                   7630: * html .LCmodal-overlay {   
                   7631: 		position: absolute;
                   7632: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7633: }
                   7634: 
                   7635: .LCmodal-window {
                   7636: 		position:fixed;
                   7637: 		top:50%;
                   7638: 		left:50%;
                   7639: 		margin:0;
                   7640: 		padding:0;
                   7641: 		z-index:102;
                   7642: 	}
                   7643: 
                   7644: * html .LCmodal-window {
                   7645: 		position:absolute;
                   7646: }
                   7647: 
                   7648: .LCclose-window {
                   7649: 		position:absolute;
                   7650: 		width:32px;
                   7651: 		height:32px;
                   7652: 		right:8px;
                   7653: 		top:8px;
                   7654: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7655: 		text-indent:-99999px;
                   7656: 		overflow:hidden;
                   7657: 		cursor:pointer;
                   7658: }
                   7659: 
1.1075.2.17  raeburn  7660: /*
                   7661:   styles used by TTH when "Default set of options to pass to tth/m
                   7662:   when converting TeX" in course settings has been set
                   7663: 
                   7664:   option passed: -t
                   7665: 
                   7666: */
                   7667: 
                   7668: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7669: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7670: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7671: td div.norm {line-height:normal;}
                   7672: 
                   7673: /*
                   7674:   option passed -y3
                   7675: */
                   7676: 
                   7677: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7678: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7679: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7680: 
1.1075.2.121  raeburn  7681: #LC_minitab_header {
                   7682:   float:left;
                   7683:   width:100%;
                   7684:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   7685:   font-size:93%;
                   7686:   line-height:normal;
                   7687:   margin: 0.5em 0 0.5em 0;
                   7688: }
                   7689: #LC_minitab_header ul {
                   7690:   margin:0;
                   7691:   padding:10px 10px 0;
                   7692:   list-style:none;
                   7693: }
                   7694: #LC_minitab_header li {
                   7695:   float:left;
                   7696:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   7697:   margin:0;
                   7698:   padding:0 0 0 9px;
                   7699: }
                   7700: #LC_minitab_header a {
                   7701:   display:block;
                   7702:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   7703:   padding:5px 15px 4px 6px;
                   7704: }
                   7705: #LC_minitab_header #LC_current_minitab {
                   7706:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   7707: }
                   7708: #LC_minitab_header #LC_current_minitab a {
                   7709:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   7710:   padding-bottom:5px;
                   7711: }
                   7712: 
                   7713: 
1.343     albertel 7714: END
                   7715: }
                   7716: 
1.306     albertel 7717: =pod
                   7718: 
                   7719: =item * &headtag()
                   7720: 
                   7721: Returns a uniform footer for LON-CAPA web pages.
                   7722: 
1.307     albertel 7723: Inputs: $title - optional title for the head
                   7724:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7725:         $args - optional arguments
1.319     albertel 7726:             force_register - if is true call registerurl so the remote is 
                   7727:                              informed
1.415     albertel 7728:             redirect       -> array ref of
                   7729:                                    1- seconds before redirect occurs
                   7730:                                    2- url to redirect to
                   7731:                                    3- whether the side effect should occur
1.315     albertel 7732:                            (side effect of setting 
                   7733:                                $env{'internal.head.redirect'} to the url 
                   7734:                                redirected too)
1.352     albertel 7735:             domain         -> force to color decorate a page for a specific
                   7736:                                domain
                   7737:             function       -> force usage of a specific rolish color scheme
                   7738:             bgcolor        -> override the default page bgcolor
1.460     albertel 7739:             no_auto_mt_title
                   7740:                            -> prevent &mt()ing the title arg
1.464     albertel 7741: 
1.306     albertel 7742: =cut
                   7743: 
                   7744: sub headtag {
1.313     albertel 7745:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7746:     
1.363     albertel 7747:     my $function = $args->{'function'} || &get_users_function();
                   7748:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7749:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  7750:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7751:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7752: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7753: 		   #time(),
1.418     albertel 7754: 		   $env{'environment.color.timestamp'},
1.363     albertel 7755: 		   $function,$domain,$bgcolor);
                   7756: 
1.369     www      7757:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7758: 
1.308     albertel 7759:     my $result =
                   7760: 	'<head>'.
1.1075.2.56  raeburn  7761: 	&font_settings($args);
1.319     albertel 7762: 
1.1075.2.72  raeburn  7763:     my $inhibitprint;
                   7764:     if ($args->{'print_suppress'}) {
                   7765:         $inhibitprint = &print_suppression();
                   7766:     }
1.1064    raeburn  7767: 
1.461     albertel 7768:     if (!$args->{'frameset'}) {
                   7769: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7770:     }
1.1075.2.12  raeburn  7771:     if ($args->{'force_register'}) {
                   7772:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 7773:     }
1.436     albertel 7774:     if (!$args->{'no_nav_bar'} 
                   7775: 	&& !$args->{'only_body'}
                   7776: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  7777: 	$result .= &help_menu_js($httphost);
1.1032    www      7778:         $result.=&modal_window();
1.1038    www      7779:         $result.=&togglebox_script();
1.1034    www      7780:         $result.=&wishlist_window();
1.1041    www      7781:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7782:     } else {
                   7783:         if ($args->{'add_modal'}) {
                   7784:            $result.=&modal_window();
                   7785:         }
                   7786:         if ($args->{'add_wishlist'}) {
                   7787:            $result.=&wishlist_window();
                   7788:         }
1.1038    www      7789:         if ($args->{'add_togglebox'}) {
                   7790:            $result.=&togglebox_script();
                   7791:         }
1.1041    www      7792:         if ($args->{'add_progressbar'}) {
                   7793:            $result.=&LCprogressbarUpdate_script();
                   7794:         }
1.436     albertel 7795:     }
1.314     albertel 7796:     if (ref($args->{'redirect'})) {
1.414     albertel 7797: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7798: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7799: 	if (!$inhibit_continue) {
                   7800: 	    $env{'internal.head.redirect'} = $url;
                   7801: 	}
1.313     albertel 7802: 	$result.=<<ADDMETA
                   7803: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7804: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7805: ADDMETA
1.1075.2.89  raeburn  7806:     } else {
                   7807:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7808:             my $requrl = $env{'request.uri'};
                   7809:             if ($requrl eq '') {
                   7810:                 $requrl = $ENV{'REQUEST_URI'};
                   7811:                 $requrl =~ s/\?.+$//;
                   7812:             }
                   7813:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7814:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7815:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7816:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7817:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7818:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   7819:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7820:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7821:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   7822:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   7823:                             if (($newserver) && ($newserver ne $lonhost)) {
                   7824:                                 my $numsec = 5;
                   7825:                                 my $timeout = $numsec * 1000;
                   7826:                                 my ($newurl,$locknum,%locks,$msg);
                   7827:                                 if ($env{'request.role.adv'}) {
                   7828:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   7829:                                 }
                   7830:                                 my $disable_submit = 0;
                   7831:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   7832:                                     $disable_submit = 1;
                   7833:                                 }
                   7834:                                 if ($locknum) {
                   7835:                                     my @lockinfo = sort(values(%locks));
                   7836:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   7837:                                            join(", ",sort(values(%locks)))."\\n".
                   7838:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   7839:                                 } else {
                   7840:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   7841:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   7842:                                     }
                   7843:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   7844:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   7845:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   7846:                                         $newurl .= '&role='.$env{'request.role'};
                   7847:                                     }
                   7848:                                     if ($env{'request.symb'}) {
                   7849:                                         $newurl .= '&symb='.$env{'request.symb'};
                   7850:                                     } else {
                   7851:                                         $newurl .= '&origurl='.$requrl;
                   7852:                                     }
                   7853:                                 }
1.1075.2.98  raeburn  7854:                                 &js_escape(\$msg);
1.1075.2.89  raeburn  7855:                                 $result.=<<OFFLOAD
                   7856: <meta http-equiv="pragma" content="no-cache" />
                   7857: <script type="text/javascript">
1.1075.2.92  raeburn  7858: // <![CDATA[
1.1075.2.89  raeburn  7859: function LC_Offload_Now() {
                   7860:     var dest = "$newurl";
                   7861:     if (dest != '') {
                   7862:         window.location.href="$newurl";
                   7863:     }
                   7864: }
1.1075.2.92  raeburn  7865: \$(document).ready(function () {
                   7866:     window.alert('$msg');
                   7867:     if ($disable_submit) {
1.1075.2.89  raeburn  7868:         \$(".LC_hwk_submit").prop("disabled", true);
                   7869:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  7870:     }
                   7871:     setTimeout('LC_Offload_Now()', $timeout);
                   7872: });
                   7873: // ]]>
1.1075.2.89  raeburn  7874: </script>
                   7875: OFFLOAD
                   7876:                             }
                   7877:                         }
                   7878:                     }
                   7879:                 }
                   7880:             }
                   7881:         }
1.313     albertel 7882:     }
1.306     albertel 7883:     if (!defined($title)) {
                   7884: 	$title = 'The LearningOnline Network with CAPA';
                   7885:     }
1.460     albertel 7886:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7887:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  7888: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   7889:     if (!$args->{'frameset'}) {
                   7890:         $result .= ' /';
                   7891:     }
                   7892:     $result .= '>'
1.1064    raeburn  7893:         .$inhibitprint
1.414     albertel 7894: 	.$head_extra;
1.1075.2.108  raeburn  7895:     my $clientmobile;
                   7896:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   7897:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   7898:     } else {
                   7899:         $clientmobile = $env{'browser.mobile'};
                   7900:     }
                   7901:     if ($clientmobile) {
1.1075.2.42  raeburn  7902:         $result .= '
                   7903: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   7904: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   7905:     }
1.1075.2.126  raeburn  7906:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 7907:     return $result.'</head>';
1.306     albertel 7908: }
                   7909: 
                   7910: =pod
                   7911: 
1.340     albertel 7912: =item * &font_settings()
                   7913: 
                   7914: Returns neccessary <meta> to set the proper encoding
                   7915: 
1.1075.2.56  raeburn  7916: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 7917: 
                   7918: =cut
                   7919: 
                   7920: sub font_settings {
1.1075.2.56  raeburn  7921:     my ($args) = @_;
1.340     albertel 7922:     my $headerstring='';
1.1075.2.56  raeburn  7923:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   7924:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 7925: 	$headerstring.=
1.1075.2.61  raeburn  7926: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   7927:         if (!$args->{'frameset'}) {
                   7928:             $headerstring.= ' /';
                   7929:         }
                   7930:         $headerstring .= '>'."\n";
1.340     albertel 7931:     }
                   7932:     return $headerstring;
                   7933: }
                   7934: 
1.341     albertel 7935: =pod
                   7936: 
1.1064    raeburn  7937: =item * &print_suppression()
                   7938: 
                   7939: In course context returns css which causes the body to be blank when media="print",
                   7940: if printout generation is unavailable for the current resource.
                   7941: 
                   7942: This could be because:
                   7943: 
                   7944: (a) printstartdate is in the future
                   7945: 
                   7946: (b) printenddate is in the past
                   7947: 
                   7948: (c) there is an active exam block with "printout"
                   7949: functionality blocked
                   7950: 
                   7951: Users with pav, pfo or evb privileges are exempt.
                   7952: 
                   7953: Inputs: none
                   7954: 
                   7955: =cut
                   7956: 
                   7957: 
                   7958: sub print_suppression {
                   7959:     my $noprint;
                   7960:     if ($env{'request.course.id'}) {
                   7961:         my $scope = $env{'request.course.id'};
                   7962:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7963:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7964:             return;
                   7965:         }
                   7966:         if ($env{'request.course.sec'} ne '') {
                   7967:             $scope .= "/$env{'request.course.sec'}";
                   7968:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7969:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7970:                 return;
1.1064    raeburn  7971:             }
                   7972:         }
                   7973:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7974:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.73  raeburn  7975:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  7976:         if ($blocked) {
                   7977:             my $checkrole = "cm./$cdom/$cnum";
                   7978:             if ($env{'request.course.sec'} ne '') {
                   7979:                 $checkrole .= "/$env{'request.course.sec'}";
                   7980:             }
                   7981:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7982:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7983:                 $noprint = 1;
                   7984:             }
                   7985:         }
                   7986:         unless ($noprint) {
                   7987:             my $symb = &Apache::lonnet::symbread();
                   7988:             if ($symb ne '') {
                   7989:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7990:                 if (ref($navmap)) {
                   7991:                     my $res = $navmap->getBySymb($symb);
                   7992:                     if (ref($res)) {
                   7993:                         if (!$res->resprintable()) {
                   7994:                             $noprint = 1;
                   7995:                         }
                   7996:                     }
                   7997:                 }
                   7998:             }
                   7999:         }
                   8000:         if ($noprint) {
                   8001:             return <<"ENDSTYLE";
                   8002: <style type="text/css" media="print">
                   8003:     body { display:none }
                   8004: </style>
                   8005: ENDSTYLE
                   8006:         }
                   8007:     }
                   8008:     return;
                   8009: }
                   8010: 
                   8011: =pod
                   8012: 
1.341     albertel 8013: =item * &xml_begin()
                   8014: 
                   8015: Returns the needed doctype and <html>
                   8016: 
                   8017: Inputs: none
                   8018: 
                   8019: =cut
                   8020: 
                   8021: sub xml_begin {
1.1075.2.61  raeburn  8022:     my ($is_frameset) = @_;
1.341     albertel 8023:     my $output='';
                   8024: 
                   8025:     if ($env{'browser.mathml'}) {
                   8026: 	$output='<?xml version="1.0"?>'
                   8027:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8028: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8029:             
                   8030: #	    .'<!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">] >'
                   8031: 	    .'<!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">'
                   8032:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8033: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  8034:     } elsif ($is_frameset) {
                   8035:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8036:                 '<html>'."\n";
1.341     albertel 8037:     } else {
1.1075.2.61  raeburn  8038: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8039:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8040:     }
                   8041:     return $output;
                   8042: }
1.340     albertel 8043: 
                   8044: =pod
                   8045: 
1.306     albertel 8046: =item * &start_page()
                   8047: 
                   8048: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8049: 
1.648     raeburn  8050: Inputs:
                   8051: 
                   8052: =over 4
                   8053: 
                   8054: $title - optional title for the page
                   8055: 
                   8056: $head_extra - optional extra HTML to incude inside the <head>
                   8057: 
                   8058: $args - additional optional args supported are:
                   8059: 
                   8060: =over 8
                   8061: 
                   8062:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8063:                                     arg on
1.814     bisitz   8064:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8065:              add_entries    -> additional attributes to add to the  <body>
                   8066:              domain         -> force to color decorate a page for a 
1.317     albertel 8067:                                     specific domain
1.648     raeburn  8068:              function       -> force usage of a specific rolish color
1.317     albertel 8069:                                     scheme
1.648     raeburn  8070:              redirect       -> see &headtag()
                   8071:              bgcolor        -> override the default page bg color
                   8072:              js_ready       -> return a string ready for being used in 
1.317     albertel 8073:                                     a javascript writeln
1.648     raeburn  8074:              html_encode    -> return a string ready for being used in 
1.320     albertel 8075:                                     a html attribute
1.648     raeburn  8076:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8077:                                     $forcereg arg
1.648     raeburn  8078:              frameset       -> if true will start with a <frameset>
1.330     albertel 8079:                                     rather than <body>
1.648     raeburn  8080:              skip_phases    -> hash ref of 
1.338     albertel 8081:                                     head -> skip the <html><head> generation
                   8082:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  8083:              no_inline_link -> if true and in remote mode, don't show the
                   8084:                                     'Switch To Inline Menu' link
1.648     raeburn  8085:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8086:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8087:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.123  raeburn  8088:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8089:                                     to lonhtmlcommon::breadcrumbs
1.1075.2.15  raeburn  8090:              group          -> includes the current group, if page is for a
                   8091:                                specific group
1.361     albertel 8092: 
1.648     raeburn  8093: =back
1.460     albertel 8094: 
1.648     raeburn  8095: =back
1.562     albertel 8096: 
1.306     albertel 8097: =cut
                   8098: 
                   8099: sub start_page {
1.309     albertel 8100:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8101:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8102: 
1.315     albertel 8103:     $env{'internal.start_page'}++;
1.1075.2.15  raeburn  8104:     my ($result,@advtools);
1.964     droeschl 8105: 
1.338     albertel 8106:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  8107:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8108:     }
                   8109:     
                   8110:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8111: 	if ($args->{'frameset'}) {
                   8112: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8113: 						$args->{'add_entries'});
                   8114: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8115:         } else {
                   8116:             $result .=
                   8117:                 &bodytag($title, 
                   8118:                          $args->{'function'},       $args->{'add_entries'},
                   8119:                          $args->{'only_body'},      $args->{'domain'},
                   8120:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  8121:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.15  raeburn  8122:                          $args,                     \@advtools);
1.831     bisitz   8123:         }
1.330     albertel 8124:     }
1.338     albertel 8125: 
1.315     albertel 8126:     if ($args->{'js_ready'}) {
1.713     kaisler  8127: 		$result = &js_ready($result);
1.315     albertel 8128:     }
1.320     albertel 8129:     if ($args->{'html_encode'}) {
1.713     kaisler  8130: 		$result = &html_encode($result);
                   8131:     }
                   8132: 
1.813     bisitz   8133:     # Preparation for new and consistent functionlist at top of screen
                   8134:     # if ($args->{'functionlist'}) {
                   8135:     #            $result .= &build_functionlist();
                   8136:     #}
                   8137: 
1.964     droeschl 8138:     # Don't add anything more if only_body wanted or in const space
                   8139:     return $result if    $args->{'only_body'} 
                   8140:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8141: 
                   8142:     #Breadcrumbs
1.758     kaisler  8143:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8144: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8145: 		#if any br links exists, add them to the breadcrumbs
                   8146: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8147: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8148: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8149: 			}
                   8150: 		}
1.1075.2.19  raeburn  8151:                 # if @advtools array contains items add then to the breadcrumbs
                   8152:                 if (@advtools > 0) {
                   8153:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8154:                 }
1.1075.2.123  raeburn  8155:                 my $menulink;
                   8156:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   8157:                 if (exists($args->{'bread_crumbs_nomenu'})) {
                   8158:                     $menulink = 0;
                   8159:                 } else {
                   8160:                     undef($menulink);
                   8161:                 }
1.758     kaisler  8162: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8163: 		if(exists($args->{'bread_crumbs_component'})){
1.1075.2.123  raeburn  8164: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.758     kaisler  8165: 		}else{
1.1075.2.123  raeburn  8166: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8167: 		}
1.1075.2.24  raeburn  8168:     } elsif (($env{'environment.remote'} eq 'on') &&
                   8169:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   8170:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   8171:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  8172:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 8173:     }
1.315     albertel 8174:     return $result;
1.306     albertel 8175: }
                   8176: 
                   8177: sub end_page {
1.315     albertel 8178:     my ($args) = @_;
                   8179:     $env{'internal.end_page'}++;
1.330     albertel 8180:     my $result;
1.335     albertel 8181:     if ($args->{'discussion'}) {
                   8182: 	my ($target,$parser);
                   8183: 	if (ref($args->{'discussion'})) {
                   8184: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8185: 				$args->{'discussion'}{'parser'});
                   8186: 	}
                   8187: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8188:     }
1.330     albertel 8189:     if ($args->{'frameset'}) {
                   8190: 	$result .= '</frameset>';
                   8191:     } else {
1.635     raeburn  8192: 	$result .= &endbodytag($args);
1.330     albertel 8193:     }
1.1075.2.6  raeburn  8194:     unless ($args->{'notbody'}) {
                   8195:         $result .= "\n</html>";
                   8196:     }
1.330     albertel 8197: 
1.315     albertel 8198:     if ($args->{'js_ready'}) {
1.317     albertel 8199: 	$result = &js_ready($result);
1.315     albertel 8200:     }
1.335     albertel 8201: 
1.320     albertel 8202:     if ($args->{'html_encode'}) {
                   8203: 	$result = &html_encode($result);
                   8204:     }
1.335     albertel 8205: 
1.315     albertel 8206:     return $result;
                   8207: }
                   8208: 
1.1034    www      8209: sub wishlist_window {
                   8210:     return(<<'ENDWISHLIST');
1.1046    raeburn  8211: <script type="text/javascript">
1.1034    www      8212: // <![CDATA[
                   8213: // <!-- BEGIN LON-CAPA Internal
                   8214: function set_wishlistlink(title, path) {
                   8215:     if (!title) {
                   8216:         title = document.title;
                   8217:         title = title.replace(/^LON-CAPA /,'');
                   8218:     }
1.1075.2.65  raeburn  8219:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  8220:     title = title.replace("'","\\\'");
1.1034    www      8221:     if (!path) {
                   8222:         path = location.pathname;
                   8223:     }
1.1075.2.65  raeburn  8224:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  8225:     path = path.replace("'","\\\'");
1.1034    www      8226:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8227:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8228: }
                   8229: // END LON-CAPA Internal -->
                   8230: // ]]>
                   8231: </script>
                   8232: ENDWISHLIST
                   8233: }
                   8234: 
1.1030    www      8235: sub modal_window {
                   8236:     return(<<'ENDMODAL');
1.1046    raeburn  8237: <script type="text/javascript">
1.1030    www      8238: // <![CDATA[
                   8239: // <!-- BEGIN LON-CAPA Internal
                   8240: var modalWindow = {
                   8241: 	parent:"body",
                   8242: 	windowId:null,
                   8243: 	content:null,
                   8244: 	width:null,
                   8245: 	height:null,
                   8246: 	close:function()
                   8247: 	{
                   8248: 	        $(".LCmodal-window").remove();
                   8249: 	        $(".LCmodal-overlay").remove();
                   8250: 	},
                   8251: 	open:function()
                   8252: 	{
                   8253: 		var modal = "";
                   8254: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8255: 		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;\">";
                   8256: 		modal += this.content;
                   8257: 		modal += "</div>";	
                   8258: 
                   8259: 		$(this.parent).append(modal);
                   8260: 
                   8261: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8262: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8263: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8264: 	}
                   8265: };
1.1075.2.42  raeburn  8266: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8267: 	{
1.1075.2.119  raeburn  8268:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8269: 		modalWindow.windowId = "myModal";
                   8270: 		modalWindow.width = width;
                   8271: 		modalWindow.height = height;
1.1075.2.80  raeburn  8272: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8273: 		modalWindow.open();
1.1075.2.87  raeburn  8274: 	};
1.1030    www      8275: // END LON-CAPA Internal -->
                   8276: // ]]>
                   8277: </script>
                   8278: ENDMODAL
                   8279: }
                   8280: 
                   8281: sub modal_link {
1.1075.2.42  raeburn  8282:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8283:     unless ($width) { $width=480; }
                   8284:     unless ($height) { $height=400; }
1.1031    www      8285:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  8286:     unless ($transparency) { $transparency='true'; }
                   8287: 
1.1074    raeburn  8288:     my $target_attr;
                   8289:     if (defined($target)) {
                   8290:         $target_attr = 'target="'.$target.'"';
                   8291:     }
                   8292:     return <<"ENDLINK";
1.1075.2.42  raeburn  8293: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8294:            $linktext</a>
                   8295: ENDLINK
1.1030    www      8296: }
                   8297: 
1.1032    www      8298: sub modal_adhoc_script {
                   8299:     my ($funcname,$width,$height,$content)=@_;
                   8300:     return (<<ENDADHOC);
1.1046    raeburn  8301: <script type="text/javascript">
1.1032    www      8302: // <![CDATA[
                   8303:         var $funcname = function()
                   8304:         {
                   8305:                 modalWindow.windowId = "myModal";
                   8306:                 modalWindow.width = $width;
                   8307:                 modalWindow.height = $height;
                   8308:                 modalWindow.content = '$content';
                   8309:                 modalWindow.open();
                   8310:         };  
                   8311: // ]]>
                   8312: </script>
                   8313: ENDADHOC
                   8314: }
                   8315: 
1.1041    www      8316: sub modal_adhoc_inner {
                   8317:     my ($funcname,$width,$height,$content)=@_;
                   8318:     my $innerwidth=$width-20;
                   8319:     $content=&js_ready(
1.1042    www      8320:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  8321:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8322:                  $content.
1.1041    www      8323:                  &end_scrollbox().
1.1075.2.42  raeburn  8324:                  &end_page()
1.1041    www      8325:              );
                   8326:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8327: }
                   8328: 
                   8329: sub modal_adhoc_window {
                   8330:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8331:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8332:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8333: }
                   8334: 
                   8335: sub modal_adhoc_launch {
                   8336:     my ($funcname,$width,$height,$content)=@_;
                   8337:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8338: <script type="text/javascript">
                   8339: // <![CDATA[
                   8340: $funcname();
                   8341: // ]]>
                   8342: </script>
                   8343: ENDLAUNCH
                   8344: }
                   8345: 
                   8346: sub modal_adhoc_close {
                   8347:     return (<<ENDCLOSE);
                   8348: <script type="text/javascript">
                   8349: // <![CDATA[
                   8350: modalWindow.close();
                   8351: // ]]>
                   8352: </script>
                   8353: ENDCLOSE
                   8354: }
                   8355: 
1.1038    www      8356: sub togglebox_script {
                   8357:    return(<<ENDTOGGLE);
                   8358: <script type="text/javascript"> 
                   8359: // <![CDATA[
                   8360: function LCtoggleDisplay(id,hidetext,showtext) {
                   8361:    link = document.getElementById(id + "link").childNodes[0];
                   8362:    with (document.getElementById(id).style) {
                   8363:       if (display == "none" ) {
                   8364:           display = "inline";
                   8365:           link.nodeValue = hidetext;
                   8366:         } else {
                   8367:           display = "none";
                   8368:           link.nodeValue = showtext;
                   8369:        }
                   8370:    }
                   8371: }
                   8372: // ]]>
                   8373: </script>
                   8374: ENDTOGGLE
                   8375: }
                   8376: 
1.1039    www      8377: sub start_togglebox {
                   8378:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8379:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8380:     unless ($showtext) { $showtext=&mt('show'); }
                   8381:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8382:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8383:     return &start_data_table().
                   8384:            &start_data_table_header_row().
                   8385:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8386:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8387:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8388:            &end_data_table_header_row().
                   8389:            '<tr id="'.$id.'" style="display:none""><td>';
                   8390: }
                   8391: 
                   8392: sub end_togglebox {
                   8393:     return '</td></tr>'.&end_data_table();
                   8394: }
                   8395: 
1.1041    www      8396: sub LCprogressbar_script {
1.1045    www      8397:    my ($id)=@_;
1.1041    www      8398:    return(<<ENDPROGRESS);
                   8399: <script type="text/javascript">
                   8400: // <![CDATA[
1.1045    www      8401: \$('#progressbar$id').progressbar({
1.1041    www      8402:   value: 0,
                   8403:   change: function(event, ui) {
                   8404:     var newVal = \$(this).progressbar('option', 'value');
                   8405:     \$('.pblabel', this).text(LCprogressTxt);
                   8406:   }
                   8407: });
                   8408: // ]]>
                   8409: </script>
                   8410: ENDPROGRESS
                   8411: }
                   8412: 
                   8413: sub LCprogressbarUpdate_script {
                   8414:    return(<<ENDPROGRESSUPDATE);
                   8415: <style type="text/css">
                   8416: .ui-progressbar { position:relative; }
                   8417: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8418: </style>
                   8419: <script type="text/javascript">
                   8420: // <![CDATA[
1.1045    www      8421: var LCprogressTxt='---';
                   8422: 
                   8423: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8424:    LCprogressTxt=progresstext;
1.1045    www      8425:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8426: }
                   8427: // ]]>
                   8428: </script>
                   8429: ENDPROGRESSUPDATE
                   8430: }
                   8431: 
1.1042    www      8432: my $LClastpercent;
1.1045    www      8433: my $LCidcnt;
                   8434: my $LCcurrentid;
1.1042    www      8435: 
1.1041    www      8436: sub LCprogressbar {
1.1042    www      8437:     my ($r)=(@_);
                   8438:     $LClastpercent=0;
1.1045    www      8439:     $LCidcnt++;
                   8440:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8441:     my $starting=&mt('Starting');
                   8442:     my $content=(<<ENDPROGBAR);
1.1045    www      8443:   <div id="progressbar$LCcurrentid">
1.1041    www      8444:     <span class="pblabel">$starting</span>
                   8445:   </div>
                   8446: ENDPROGBAR
1.1045    www      8447:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8448: }
                   8449: 
                   8450: sub LCprogressbarUpdate {
1.1042    www      8451:     my ($r,$val,$text)=@_;
                   8452:     unless ($val) { 
                   8453:        if ($LClastpercent) {
                   8454:            $val=$LClastpercent;
                   8455:        } else {
                   8456:            $val=0;
                   8457:        }
                   8458:     }
1.1041    www      8459:     if ($val<0) { $val=0; }
                   8460:     if ($val>100) { $val=0; }
1.1042    www      8461:     $LClastpercent=$val;
1.1041    www      8462:     unless ($text) { $text=$val.'%'; }
                   8463:     $text=&js_ready($text);
1.1044    www      8464:     &r_print($r,<<ENDUPDATE);
1.1041    www      8465: <script type="text/javascript">
                   8466: // <![CDATA[
1.1045    www      8467: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8468: // ]]>
                   8469: </script>
                   8470: ENDUPDATE
1.1035    www      8471: }
                   8472: 
1.1042    www      8473: sub LCprogressbarClose {
                   8474:     my ($r)=@_;
                   8475:     $LClastpercent=0;
1.1044    www      8476:     &r_print($r,<<ENDCLOSE);
1.1042    www      8477: <script type="text/javascript">
                   8478: // <![CDATA[
1.1045    www      8479: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8480: // ]]>
                   8481: </script>
                   8482: ENDCLOSE
1.1044    www      8483: }
                   8484: 
                   8485: sub r_print {
                   8486:     my ($r,$to_print)=@_;
                   8487:     if ($r) {
                   8488:       $r->print($to_print);
                   8489:       $r->rflush();
                   8490:     } else {
                   8491:       print($to_print);
                   8492:     }
1.1042    www      8493: }
                   8494: 
1.320     albertel 8495: sub html_encode {
                   8496:     my ($result) = @_;
                   8497: 
1.322     albertel 8498:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8499:     
                   8500:     return $result;
                   8501: }
1.1044    www      8502: 
1.317     albertel 8503: sub js_ready {
                   8504:     my ($result) = @_;
                   8505: 
1.323     albertel 8506:     $result =~ s/[\n\r]/ /xmsg;
                   8507:     $result =~ s/\\/\\\\/xmsg;
                   8508:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8509:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8510:     
                   8511:     return $result;
                   8512: }
                   8513: 
1.315     albertel 8514: sub validate_page {
                   8515:     if (  exists($env{'internal.start_page'})
1.316     albertel 8516: 	  &&     $env{'internal.start_page'} > 1) {
                   8517: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8518: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8519: 				 $ENV{'request.filename'});
1.315     albertel 8520:     }
                   8521:     if (  exists($env{'internal.end_page'})
1.316     albertel 8522: 	  &&     $env{'internal.end_page'} > 1) {
                   8523: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8524: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8525: 				 $env{'request.filename'});
1.315     albertel 8526:     }
                   8527:     if (     exists($env{'internal.start_page'})
                   8528: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8529: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8530: 				 $env{'request.filename'});
1.315     albertel 8531:     }
                   8532:     if (   ! exists($env{'internal.start_page'})
                   8533: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8534: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8535: 				 $env{'request.filename'});
1.315     albertel 8536:     }
1.306     albertel 8537: }
1.315     albertel 8538: 
1.996     www      8539: 
                   8540: sub start_scrollbox {
1.1075.2.56  raeburn  8541:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8542:     unless ($outerwidth) { $outerwidth='520px'; }
                   8543:     unless ($width) { $width='500px'; }
                   8544:     unless ($height) { $height='200px'; }
1.1075    raeburn  8545:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8546:     if ($id ne '') {
1.1075.2.42  raeburn  8547:         $table_id = ' id="table_'.$id.'"';
                   8548:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8549:     }
1.1075    raeburn  8550:     if ($bgcolor ne '') {
                   8551:         $tdcol = "background-color: $bgcolor;";
                   8552:     }
1.1075.2.42  raeburn  8553:     my $nicescroll_js;
                   8554:     if ($env{'browser.mobile'}) {
                   8555:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8556:     }
1.1075    raeburn  8557:     return <<"END";
1.1075.2.42  raeburn  8558: $nicescroll_js
                   8559: 
                   8560: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  8561: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  8562: END
1.996     www      8563: }
                   8564: 
                   8565: sub end_scrollbox {
1.1036    www      8566:     return '</div></td></tr></table>';
1.996     www      8567: }
                   8568: 
1.1075.2.42  raeburn  8569: sub nicescroll_javascript {
                   8570:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8571:     my %options;
                   8572:     if (ref($cursor) eq 'HASH') {
                   8573:         %options = %{$cursor};
                   8574:     }
                   8575:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8576:         $options{'railalign'} = 'left';
                   8577:     }
                   8578:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8579:         my $function  = &get_users_function();
                   8580:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   8581:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8582:             $options{'cursorcolor'} = '#00F';
                   8583:         }
                   8584:     }
                   8585:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8586:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   8587:             $options{'cursoropacity'}='1.0';
                   8588:         }
                   8589:     } else {
                   8590:         $options{'cursoropacity'}='1.0';
                   8591:     }
                   8592:     if ($options{'cursorfixedheight'} eq 'none') {
                   8593:         delete($options{'cursorfixedheight'});
                   8594:     } else {
                   8595:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8596:     }
                   8597:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8598:         delete($options{'railoffset'});
                   8599:     }
                   8600:     my @niceoptions;
                   8601:     while (my($key,$value) = each(%options)) {
                   8602:         if ($value =~ /^\{.+\}$/) {
                   8603:             push(@niceoptions,$key.':'.$value);
                   8604:         } else {
                   8605:             push(@niceoptions,$key.':"'.$value.'"');
                   8606:         }
                   8607:     }
                   8608:     my $nicescroll_js = '
                   8609: $(document).ready(
                   8610:       function() {
                   8611:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8612:       }
                   8613: );
                   8614: ';
                   8615:     if ($framecheck) {
                   8616:         $nicescroll_js .= '
                   8617: function expand_div(caller) {
                   8618:     if (top === self) {
                   8619:         document.getElementById("'.$id.'").style.width = "auto";
                   8620:         document.getElementById("'.$id.'").style.height = "auto";
                   8621:     } else {
                   8622:         try {
                   8623:             if (parent.frames) {
                   8624:                 if (parent.frames.length > 1) {
                   8625:                     var framesrc = parent.frames[1].location.href;
                   8626:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8627:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8628:                         document.getElementById("'.$id.'").style.width = "auto";
                   8629:                         document.getElementById("'.$id.'").style.height = "auto";
                   8630:                     }
                   8631:                 }
                   8632:             }
                   8633:         } catch (e) {
                   8634:             return;
                   8635:         }
                   8636:     }
                   8637:     return;
                   8638: }
                   8639: ';
                   8640:     }
                   8641:     if ($needjsready) {
                   8642:         $nicescroll_js = '
                   8643: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8644:     } else {
                   8645:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8646:     }
                   8647:     return $nicescroll_js;
                   8648: }
                   8649: 
1.318     albertel 8650: sub simple_error_page {
1.1075.2.49  raeburn  8651:     my ($r,$title,$msg,$args) = @_;
                   8652:     if (ref($args) eq 'HASH') {
                   8653:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8654:     } else {
                   8655:         $msg = &mt($msg);
                   8656:     }
                   8657: 
1.318     albertel 8658:     my $page =
                   8659: 	&Apache::loncommon::start_page($title).
1.1075.2.49  raeburn  8660: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8661: 	&Apache::loncommon::end_page();
                   8662:     if (ref($r)) {
                   8663: 	$r->print($page);
1.327     albertel 8664: 	return;
1.318     albertel 8665:     }
                   8666:     return $page;
                   8667: }
1.347     albertel 8668: 
                   8669: {
1.610     albertel 8670:     my @row_count;
1.961     onken    8671: 
                   8672:     sub start_data_table_count {
                   8673:         unshift(@row_count, 0);
                   8674:         return;
                   8675:     }
                   8676: 
                   8677:     sub end_data_table_count {
                   8678:         shift(@row_count);
                   8679:         return;
                   8680:     }
                   8681: 
1.347     albertel 8682:     sub start_data_table {
1.1018    raeburn  8683: 	my ($add_class,$id) = @_;
1.422     albertel 8684: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8685:         my $table_id;
                   8686:         if (defined($id)) {
                   8687:             $table_id = ' id="'.$id.'"';
                   8688:         }
1.961     onken    8689: 	&start_data_table_count();
1.1018    raeburn  8690: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8691:     }
                   8692: 
                   8693:     sub end_data_table {
1.961     onken    8694: 	&end_data_table_count();
1.389     albertel 8695: 	return '</table>'."\n";;
1.347     albertel 8696:     }
                   8697: 
                   8698:     sub start_data_table_row {
1.974     wenzelju 8699: 	my ($add_class, $id) = @_;
1.610     albertel 8700: 	$row_count[0]++;
                   8701: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8702: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8703:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8704:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8705:     }
1.471     banghart 8706:     
                   8707:     sub continue_data_table_row {
1.974     wenzelju 8708: 	my ($add_class, $id) = @_;
1.610     albertel 8709: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8710: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8711:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8712:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8713:     }
1.347     albertel 8714: 
                   8715:     sub end_data_table_row {
1.389     albertel 8716: 	return '</tr>'."\n";;
1.347     albertel 8717:     }
1.367     www      8718: 
1.421     albertel 8719:     sub start_data_table_empty_row {
1.707     bisitz   8720: #	$row_count[0]++;
1.421     albertel 8721: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8722:     }
                   8723: 
                   8724:     sub end_data_table_empty_row {
                   8725: 	return '</tr>'."\n";;
                   8726:     }
                   8727: 
1.367     www      8728:     sub start_data_table_header_row {
1.389     albertel 8729: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8730:     }
                   8731: 
                   8732:     sub end_data_table_header_row {
1.389     albertel 8733: 	return '</tr>'."\n";;
1.367     www      8734:     }
1.890     droeschl 8735: 
                   8736:     sub data_table_caption {
                   8737:         my $caption = shift;
                   8738:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8739:     }
1.347     albertel 8740: }
                   8741: 
1.548     albertel 8742: =pod
                   8743: 
                   8744: =item * &inhibit_menu_check($arg)
                   8745: 
                   8746: Checks for a inhibitmenu state and generates output to preserve it
                   8747: 
                   8748: Inputs:         $arg - can be any of
                   8749:                      - undef - in which case the return value is a string 
                   8750:                                to add  into arguments list of a uri
                   8751:                      - 'input' - in which case the return value is a HTML
                   8752:                                  <form> <input> field of type hidden to
                   8753:                                  preserve the value
                   8754:                      - a url - in which case the return value is the url with
                   8755:                                the neccesary cgi args added to preserve the
                   8756:                                inhibitmenu state
                   8757:                      - a ref to a url - no return value, but the string is
                   8758:                                         updated to include the neccessary cgi
                   8759:                                         args to preserve the inhibitmenu state
                   8760: 
                   8761: =cut
                   8762: 
                   8763: sub inhibit_menu_check {
                   8764:     my ($arg) = @_;
                   8765:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8766:     if ($arg eq 'input') {
                   8767: 	if ($env{'form.inhibitmenu'}) {
                   8768: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8769: 	} else {
                   8770: 	    return
                   8771: 	}
                   8772:     }
                   8773:     if ($env{'form.inhibitmenu'}) {
                   8774: 	if (ref($arg)) {
                   8775: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8776: 	} elsif ($arg eq '') {
                   8777: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8778: 	} else {
                   8779: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8780: 	}
                   8781:     }
                   8782:     if (!ref($arg)) {
                   8783: 	return $arg;
                   8784:     }
                   8785: }
                   8786: 
1.251     albertel 8787: ###############################################
1.182     matthew  8788: 
                   8789: =pod
                   8790: 
1.549     albertel 8791: =back
                   8792: 
                   8793: =head1 User Information Routines
                   8794: 
                   8795: =over 4
                   8796: 
1.405     albertel 8797: =item * &get_users_function()
1.182     matthew  8798: 
                   8799: Used by &bodytag to determine the current users primary role.
                   8800: Returns either 'student','coordinator','admin', or 'author'.
                   8801: 
                   8802: =cut
                   8803: 
                   8804: ###############################################
                   8805: sub get_users_function {
1.815     tempelho 8806:     my $function = 'norole';
1.818     tempelho 8807:     if ($env{'request.role'}=~/^(st)/) {
                   8808:         $function='student';
                   8809:     }
1.907     raeburn  8810:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8811:         $function='coordinator';
                   8812:     }
1.258     albertel 8813:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8814:         $function='admin';
                   8815:     }
1.826     bisitz   8816:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8817:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8818:         $function='author';
                   8819:     }
                   8820:     return $function;
1.54      www      8821: }
1.99      www      8822: 
                   8823: ###############################################
                   8824: 
1.233     raeburn  8825: =pod
                   8826: 
1.821     raeburn  8827: =item * &show_course()
                   8828: 
                   8829: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8830: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8831: 
                   8832: Inputs:
                   8833: None
                   8834: 
                   8835: Outputs:
                   8836: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8837: 
                   8838: =cut
                   8839: 
                   8840: ###############################################
                   8841: sub show_course {
                   8842:     my $course = !$env{'user.adv'};
                   8843:     if (!$env{'user.adv'}) {
                   8844:         foreach my $env (keys(%env)) {
                   8845:             next if ($env !~ m/^user\.priv\./);
                   8846:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8847:                 $course = 0;
                   8848:                 last;
                   8849:             }
                   8850:         }
                   8851:     }
                   8852:     return $course;
                   8853: }
                   8854: 
                   8855: ###############################################
                   8856: 
                   8857: =pod
                   8858: 
1.542     raeburn  8859: =item * &check_user_status()
1.274     raeburn  8860: 
                   8861: Determines current status of supplied role for a
                   8862: specific user. Roles can be active, previous or future.
                   8863: 
                   8864: Inputs: 
                   8865: user's domain, user's username, course's domain,
1.375     raeburn  8866: course's number, optional section ID.
1.274     raeburn  8867: 
                   8868: Outputs:
                   8869: role status: active, previous or future. 
                   8870: 
                   8871: =cut
                   8872: 
                   8873: sub check_user_status {
1.412     raeburn  8874:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8875:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  8876:     my @uroles = keys(%userinfo);
1.274     raeburn  8877:     my $srchstr;
                   8878:     my $active_chk = 'none';
1.412     raeburn  8879:     my $now = time;
1.274     raeburn  8880:     if (@uroles > 0) {
1.908     raeburn  8881:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8882:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8883:         } else {
1.412     raeburn  8884:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8885:         }
                   8886:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8887:             my $role_end = 0;
                   8888:             my $role_start = 0;
                   8889:             $active_chk = 'active';
1.412     raeburn  8890:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8891:                 $role_end = $1;
                   8892:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8893:                     $role_start = $1;
1.274     raeburn  8894:                 }
                   8895:             }
                   8896:             if ($role_start > 0) {
1.412     raeburn  8897:                 if ($now < $role_start) {
1.274     raeburn  8898:                     $active_chk = 'future';
                   8899:                 }
                   8900:             }
                   8901:             if ($role_end > 0) {
1.412     raeburn  8902:                 if ($now > $role_end) {
1.274     raeburn  8903:                     $active_chk = 'previous';
                   8904:                 }
                   8905:             }
                   8906:         }
                   8907:     }
                   8908:     return $active_chk;
                   8909: }
                   8910: 
                   8911: ###############################################
                   8912: 
                   8913: =pod
                   8914: 
1.405     albertel 8915: =item * &get_sections()
1.233     raeburn  8916: 
                   8917: Determines all the sections for a course including
                   8918: sections with students and sections containing other roles.
1.419     raeburn  8919: Incoming parameters: 
                   8920: 
                   8921: 1. domain
                   8922: 2. course number 
                   8923: 3. reference to array containing roles for which sections should 
                   8924: be gathered (optional).
                   8925: 4. reference to array containing status types for which sections 
                   8926: should be gathered (optional).
                   8927: 
                   8928: If the third argument is undefined, sections are gathered for any role. 
                   8929: If the fourth argument is undefined, sections are gathered for any status.
                   8930: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8931:  
1.374     raeburn  8932: Returns section hash (keys are section IDs, values are
                   8933: number of users in each section), subject to the
1.419     raeburn  8934: optional roles filter, optional status filter 
1.233     raeburn  8935: 
                   8936: =cut
                   8937: 
                   8938: ###############################################
                   8939: sub get_sections {
1.419     raeburn  8940:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8941:     if (!defined($cdom) || !defined($cnum)) {
                   8942:         my $cid =  $env{'request.course.id'};
                   8943: 
                   8944: 	return if (!defined($cid));
                   8945: 
                   8946:         $cdom = $env{'course.'.$cid.'.domain'};
                   8947:         $cnum = $env{'course.'.$cid.'.num'};
                   8948:     }
                   8949: 
                   8950:     my %sectioncount;
1.419     raeburn  8951:     my $now = time;
1.240     albertel 8952: 
1.1075.2.33  raeburn  8953:     my $check_students = 1;
                   8954:     my $only_students = 0;
                   8955:     if (ref($possible_roles) eq 'ARRAY') {
                   8956:         if (grep(/^st$/,@{$possible_roles})) {
                   8957:             if (@{$possible_roles} == 1) {
                   8958:                 $only_students = 1;
                   8959:             }
                   8960:         } else {
                   8961:             $check_students = 0;
                   8962:         }
                   8963:     }
                   8964: 
                   8965:     if ($check_students) {
1.276     albertel 8966: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8967: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8968: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8969:         my $start_index = &Apache::loncoursedata::CL_START();
                   8970:         my $end_index = &Apache::loncoursedata::CL_END();
                   8971:         my $status;
1.366     albertel 8972: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8973: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8974: 				                     $data->[$status_index],
                   8975:                                                      $data->[$start_index],
                   8976:                                                      $data->[$end_index]);
                   8977:             if ($stu_status eq 'Active') {
                   8978:                 $status = 'active';
                   8979:             } elsif ($end < $now) {
                   8980:                 $status = 'previous';
                   8981:             } elsif ($start > $now) {
                   8982:                 $status = 'future';
                   8983:             } 
                   8984: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8985:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8986:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8987: 		    $sectioncount{$section}++;
                   8988:                 }
1.240     albertel 8989: 	    }
                   8990: 	}
                   8991:     }
1.1075.2.33  raeburn  8992:     if ($only_students) {
                   8993:         return %sectioncount;
                   8994:     }
1.240     albertel 8995:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8996:     foreach my $user (sort(keys(%courseroles))) {
                   8997: 	if ($user !~ /^(\w{2})/) { next; }
                   8998: 	my ($role) = ($user =~ /^(\w{2})/);
                   8999: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9000: 	my ($section,$status);
1.240     albertel 9001: 	if ($role eq 'cr' &&
                   9002: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9003: 	    $section=$1;
                   9004: 	}
                   9005: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9006: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9007:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9008:         if ($end == -1 && $start == -1) {
                   9009:             next; #deleted role
                   9010:         }
                   9011:         if (!defined($possible_status)) { 
                   9012:             $sectioncount{$section}++;
                   9013:         } else {
                   9014:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9015:                 $status = 'active';
                   9016:             } elsif ($end < $now) {
                   9017:                 $status = 'future';
                   9018:             } elsif ($start > $now) {
                   9019:                 $status = 'previous';
                   9020:             }
                   9021:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9022:                 $sectioncount{$section}++;
                   9023:             }
                   9024:         }
1.233     raeburn  9025:     }
1.366     albertel 9026:     return %sectioncount;
1.233     raeburn  9027: }
                   9028: 
1.274     raeburn  9029: ###############################################
1.294     raeburn  9030: 
                   9031: =pod
1.405     albertel 9032: 
                   9033: =item * &get_course_users()
                   9034: 
1.275     raeburn  9035: Retrieves usernames:domains for users in the specified course
                   9036: with specific role(s), and access status. 
                   9037: 
                   9038: Incoming parameters:
1.277     albertel 9039: 1. course domain
                   9040: 2. course number
                   9041: 3. access status: users must have - either active, 
1.275     raeburn  9042: previous, future, or all.
1.277     albertel 9043: 4. reference to array of permissible roles
1.288     raeburn  9044: 5. reference to array of section restrictions (optional)
                   9045: 6. reference to results object (hash of hashes).
                   9046: 7. reference to optional userdata hash
1.609     raeburn  9047: 8. reference to optional statushash
1.630     raeburn  9048: 9. flag if privileged users (except those set to unhide in
                   9049:    course settings) should be excluded    
1.609     raeburn  9050: Keys of top level results hash are roles.
1.275     raeburn  9051: Keys of inner hashes are username:domain, with 
                   9052: values set to access type.
1.288     raeburn  9053: Optional userdata hash returns an array with arguments in the 
                   9054: same order as loncoursedata::get_classlist() for student data.
                   9055: 
1.609     raeburn  9056: Optional statushash returns
                   9057: 
1.288     raeburn  9058: Entries for end, start, section and status are blank because
                   9059: of the possibility of multiple values for non-student roles.
                   9060: 
1.275     raeburn  9061: =cut
1.405     albertel 9062: 
1.275     raeburn  9063: ###############################################
1.405     albertel 9064: 
1.275     raeburn  9065: sub get_course_users {
1.630     raeburn  9066:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9067:     my %idx = ();
1.419     raeburn  9068:     my %seclists;
1.288     raeburn  9069: 
                   9070:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9071:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9072:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9073:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9074:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9075:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9076:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9077:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9078: 
1.290     albertel 9079:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9080:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9081:         my $now = time;
1.277     albertel 9082:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9083:             my $match = 0;
1.412     raeburn  9084:             my $secmatch = 0;
1.419     raeburn  9085:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9086:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9087:             if ($section eq '') {
                   9088:                 $section = 'none';
                   9089:             }
1.291     albertel 9090:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9091:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9092:                     $secmatch = 1;
                   9093:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9094:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9095:                         $secmatch = 1;
                   9096:                     }
                   9097:                 } else {  
1.419     raeburn  9098: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9099: 		        $secmatch = 1;
                   9100:                     }
1.290     albertel 9101: 		}
1.412     raeburn  9102:                 if (!$secmatch) {
                   9103:                     next;
                   9104:                 }
1.419     raeburn  9105:             }
1.275     raeburn  9106:             if (defined($$types{'active'})) {
1.288     raeburn  9107:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9108:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9109:                     $match = 1;
1.275     raeburn  9110:                 }
                   9111:             }
                   9112:             if (defined($$types{'previous'})) {
1.609     raeburn  9113:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9114:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9115:                     $match = 1;
1.275     raeburn  9116:                 }
                   9117:             }
                   9118:             if (defined($$types{'future'})) {
1.609     raeburn  9119:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9120:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9121:                     $match = 1;
1.275     raeburn  9122:                 }
                   9123:             }
1.609     raeburn  9124:             if ($match) {
                   9125:                 push(@{$seclists{$student}},$section);
                   9126:                 if (ref($userdata) eq 'HASH') {
                   9127:                     $$userdata{$student} = $$classlist{$student};
                   9128:                 }
                   9129:                 if (ref($statushash) eq 'HASH') {
                   9130:                     $statushash->{$student}{'st'}{$section} = $status;
                   9131:                 }
1.288     raeburn  9132:             }
1.275     raeburn  9133:         }
                   9134:     }
1.412     raeburn  9135:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9136:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9137:         my $now = time;
1.609     raeburn  9138:         my %displaystatus = ( previous => 'Expired',
                   9139:                               active   => 'Active',
                   9140:                               future   => 'Future',
                   9141:                             );
1.1075.2.36  raeburn  9142:         my (%nothide,@possdoms);
1.630     raeburn  9143:         if ($hidepriv) {
                   9144:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9145:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9146:                 if ($user !~ /:/) {
                   9147:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9148:                 } else {
                   9149:                     $nothide{$user} = 1;
                   9150:                 }
                   9151:             }
1.1075.2.36  raeburn  9152:             my @possdoms = ($cdom);
                   9153:             if ($coursehash{'checkforpriv'}) {
                   9154:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9155:             }
1.630     raeburn  9156:         }
1.439     raeburn  9157:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9158:             my $match = 0;
1.412     raeburn  9159:             my $secmatch = 0;
1.439     raeburn  9160:             my $status;
1.412     raeburn  9161:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9162:             $user =~ s/:$//;
1.439     raeburn  9163:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9164:             if ($end == -1 || $start == -1) {
                   9165:                 next;
                   9166:             }
                   9167:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9168:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9169:                 my ($uname,$udom) = split(/:/,$user);
                   9170:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9171:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9172:                         $secmatch = 1;
                   9173:                     } elsif ($usec eq '') {
1.420     albertel 9174:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9175:                             $secmatch = 1;
                   9176:                         }
                   9177:                     } else {
                   9178:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9179:                             $secmatch = 1;
                   9180:                         }
                   9181:                     }
                   9182:                     if (!$secmatch) {
                   9183:                         next;
                   9184:                     }
1.288     raeburn  9185:                 }
1.419     raeburn  9186:                 if ($usec eq '') {
                   9187:                     $usec = 'none';
                   9188:                 }
1.275     raeburn  9189:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9190:                     if ($hidepriv) {
1.1075.2.36  raeburn  9191:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9192:                             (!$nothide{$uname.':'.$udom})) {
                   9193:                             next;
                   9194:                         }
                   9195:                     }
1.503     raeburn  9196:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9197:                         $status = 'previous';
                   9198:                     } elsif ($start > $now) {
                   9199:                         $status = 'future';
                   9200:                     } else {
                   9201:                         $status = 'active';
                   9202:                     }
1.277     albertel 9203:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9204:                         if ($status eq $type) {
1.420     albertel 9205:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9206:                                 push(@{$$users{$role}{$user}},$type);
                   9207:                             }
1.288     raeburn  9208:                             $match = 1;
                   9209:                         }
                   9210:                     }
1.419     raeburn  9211:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9212:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9213: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9214:                         }
1.420     albertel 9215:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9216:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9217:                         }
1.609     raeburn  9218:                         if (ref($statushash) eq 'HASH') {
                   9219:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9220:                         }
1.275     raeburn  9221:                     }
                   9222:                 }
                   9223:             }
                   9224:         }
1.290     albertel 9225:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9226:             if ((defined($cdom)) && (defined($cnum))) {
                   9227:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9228:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9229:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9230:                     next if ($owner eq '');
                   9231:                     my ($ownername,$ownerdom);
                   9232:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9233:                         $ownername = $1;
                   9234:                         $ownerdom = $2;
                   9235:                     } else {
                   9236:                         $ownername = $owner;
                   9237:                         $ownerdom = $cdom;
                   9238:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9239:                     }
                   9240:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9241:                     if (defined($userdata) && 
1.609     raeburn  9242: 			!exists($$userdata{$owner})) {
                   9243: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9244:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9245:                             push(@{$seclists{$owner}},'none');
                   9246:                         }
                   9247:                         if (ref($statushash) eq 'HASH') {
                   9248:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9249:                         }
1.290     albertel 9250: 		    }
1.279     raeburn  9251:                 }
                   9252:             }
                   9253:         }
1.419     raeburn  9254:         foreach my $user (keys(%seclists)) {
                   9255:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9256:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9257:         }
1.275     raeburn  9258:     }
                   9259:     return;
                   9260: }
                   9261: 
1.288     raeburn  9262: sub get_user_info {
                   9263:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9264:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9265: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9266:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9267:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9268:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9269:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9270:     return;
                   9271: }
1.275     raeburn  9272: 
1.472     raeburn  9273: ###############################################
                   9274: 
                   9275: =pod
                   9276: 
                   9277: =item * &get_user_quota()
                   9278: 
1.1075.2.41  raeburn  9279: Retrieves quota assigned for storage of user files.
                   9280: Default is to report quota for portfolio files.
1.472     raeburn  9281: 
                   9282: Incoming parameters:
                   9283: 1. user's username
                   9284: 2. user's domain
1.1075.2.41  raeburn  9285: 3. quota name - portfolio, author, or course
                   9286:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  9287: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  9288:    course
1.472     raeburn  9289: 
                   9290: Returns:
1.1075.2.58  raeburn  9291: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9292: 2. (Optional) Type of setting: custom or default
                   9293:    (individually assigned or default for user's 
                   9294:    institutional status).
                   9295: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9296:    or student - types as defined in localenroll::inst_usertypes 
                   9297:    for user's domain, which determines default quota for user.
                   9298: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9299: 
                   9300: If a value has been stored in the user's environment, 
1.536     raeburn  9301: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  9302: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9303: 
                   9304: =cut
                   9305: 
                   9306: ###############################################
                   9307: 
                   9308: 
                   9309: sub get_user_quota {
1.1075.2.42  raeburn  9310:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9311:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9312:     if (!defined($udom)) {
                   9313:         $udom = $env{'user.domain'};
                   9314:     }
                   9315:     if (!defined($uname)) {
                   9316:         $uname = $env{'user.name'};
                   9317:     }
                   9318:     if (($udom eq '' || $uname eq '') ||
                   9319:         ($udom eq 'public') && ($uname eq 'public')) {
                   9320:         $quota = 0;
1.536     raeburn  9321:         $quotatype = 'default';
                   9322:         $defquota = 0; 
1.472     raeburn  9323:     } else {
1.536     raeburn  9324:         my $inststatus;
1.1075.2.41  raeburn  9325:         if ($quotaname eq 'course') {
                   9326:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9327:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9328:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9329:             } else {
                   9330:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9331:                 $quota = $cenv{'internal.uploadquota'};
                   9332:             }
1.536     raeburn  9333:         } else {
1.1075.2.41  raeburn  9334:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9335:                 if ($quotaname eq 'author') {
                   9336:                     $quota = $env{'environment.authorquota'};
                   9337:                 } else {
                   9338:                     $quota = $env{'environment.portfolioquota'};
                   9339:                 }
                   9340:                 $inststatus = $env{'environment.inststatus'};
                   9341:             } else {
                   9342:                 my %userenv = 
                   9343:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9344:                                          'authorquota','inststatus'],$udom,$uname);
                   9345:                 my ($tmp) = keys(%userenv);
                   9346:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9347:                     if ($quotaname eq 'author') {
                   9348:                         $quota = $userenv{'authorquota'};
                   9349:                     } else {
                   9350:                         $quota = $userenv{'portfolioquota'};
                   9351:                     }
                   9352:                     $inststatus = $userenv{'inststatus'};
                   9353:                 } else {
                   9354:                     undef(%userenv);
                   9355:                 }
                   9356:             }
                   9357:         }
                   9358:         if ($quota eq '' || wantarray) {
                   9359:             if ($quotaname eq 'course') {
                   9360:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  9361:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   9362:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  9363:                     $defquota = $domdefs{$crstype.'quota'};
                   9364:                 }
                   9365:                 if ($defquota eq '') {
                   9366:                     $defquota = 500;
                   9367:                 }
1.1075.2.41  raeburn  9368:             } else {
                   9369:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9370:             }
                   9371:             if ($quota eq '') {
                   9372:                 $quota = $defquota;
                   9373:                 $quotatype = 'default';
                   9374:             } else {
                   9375:                 $quotatype = 'custom';
                   9376:             }
1.472     raeburn  9377:         }
                   9378:     }
1.536     raeburn  9379:     if (wantarray) {
                   9380:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9381:     } else {
                   9382:         return $quota;
                   9383:     }
1.472     raeburn  9384: }
                   9385: 
                   9386: ###############################################
                   9387: 
                   9388: =pod
                   9389: 
                   9390: =item * &default_quota()
                   9391: 
1.536     raeburn  9392: Retrieves default quota assigned for storage of user portfolio files,
                   9393: given an (optional) user's institutional status.
1.472     raeburn  9394: 
                   9395: Incoming parameters:
1.1075.2.42  raeburn  9396: 
1.472     raeburn  9397: 1. domain
1.536     raeburn  9398: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9399:    status types (e.g., faculty, staff, student etc.)
                   9400:    which apply to the user for whom the default is being retrieved.
                   9401:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  9402:    default quota will be returned.
                   9403: 3.  quota name - portfolio, author, or course
                   9404:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9405: 
                   9406: Returns:
1.1075.2.42  raeburn  9407: 
1.1075.2.58  raeburn  9408: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9409: 2. (Optional) institutional type which determined the value of the
                   9410:    default quota.
1.472     raeburn  9411: 
                   9412: If a value has been stored in the domain's configuration db,
                   9413: it will return that, otherwise it returns 20 (for backwards 
                   9414: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  9415: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9416: 
1.536     raeburn  9417: If the user's status includes multiple types (e.g., staff and student),
                   9418: the largest default quota which applies to the user determines the
                   9419: default quota returned.
                   9420: 
1.472     raeburn  9421: =cut
                   9422: 
                   9423: ###############################################
                   9424: 
                   9425: 
                   9426: sub default_quota {
1.1075.2.41  raeburn  9427:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9428:     my ($defquota,$settingstatus);
                   9429:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9430:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  9431:     my $key = 'defaultquota';
                   9432:     if ($quotaname eq 'author') {
                   9433:         $key = 'authorquota';
                   9434:     }
1.622     raeburn  9435:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9436:         if ($inststatus ne '') {
1.765     raeburn  9437:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9438:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  9439:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9440:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9441:                         if ($defquota eq '') {
1.1075.2.41  raeburn  9442:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9443:                             $settingstatus = $item;
1.1075.2.41  raeburn  9444:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9445:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9446:                             $settingstatus = $item;
                   9447:                         }
                   9448:                     }
1.1075.2.41  raeburn  9449:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9450:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9451:                         if ($defquota eq '') {
                   9452:                             $defquota = $quotahash{'quotas'}{$item};
                   9453:                             $settingstatus = $item;
                   9454:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9455:                             $defquota = $quotahash{'quotas'}{$item};
                   9456:                             $settingstatus = $item;
                   9457:                         }
1.536     raeburn  9458:                     }
                   9459:                 }
                   9460:             }
                   9461:         }
                   9462:         if ($defquota eq '') {
1.1075.2.41  raeburn  9463:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9464:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9465:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9466:                 $defquota = $quotahash{'quotas'}{'default'};
                   9467:             }
1.536     raeburn  9468:             $settingstatus = 'default';
1.1075.2.42  raeburn  9469:             if ($defquota eq '') {
                   9470:                 if ($quotaname eq 'author') {
                   9471:                     $defquota = 500;
                   9472:                 }
                   9473:             }
1.536     raeburn  9474:         }
                   9475:     } else {
                   9476:         $settingstatus = 'default';
1.1075.2.41  raeburn  9477:         if ($quotaname eq 'author') {
                   9478:             $defquota = 500;
                   9479:         } else {
                   9480:             $defquota = 20;
                   9481:         }
1.536     raeburn  9482:     }
                   9483:     if (wantarray) {
                   9484:         return ($defquota,$settingstatus);
1.472     raeburn  9485:     } else {
1.536     raeburn  9486:         return $defquota;
1.472     raeburn  9487:     }
                   9488: }
                   9489: 
1.1075.2.41  raeburn  9490: ###############################################
                   9491: 
                   9492: =pod
                   9493: 
1.1075.2.42  raeburn  9494: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  9495: 
                   9496: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  9497: of existing file within authoring space will cause quota for the authoring
                   9498: space to be exceeded.
                   9499: 
                   9500: Same, if upload of a file directly to a course/community via Course Editor
                   9501: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  9502: 
1.1075.2.61  raeburn  9503: Inputs: 7 
1.1075.2.42  raeburn  9504: 1. username or coursenum
1.1075.2.41  raeburn  9505: 2. domain
1.1075.2.42  raeburn  9506: 3. context ('author' or 'course')
1.1075.2.41  raeburn  9507: 4. filename of file for which action is being requested
                   9508: 5. filesize (kB) of file
                   9509: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  9510: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  9511: 
                   9512: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   9513:          otherwise return null.
                   9514: 
1.1075.2.42  raeburn  9515: =back
                   9516: 
1.1075.2.41  raeburn  9517: =cut
                   9518: 
1.1075.2.42  raeburn  9519: sub excess_filesize_warning {
1.1075.2.59  raeburn  9520:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  9521:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  9522:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  9523:     if ($context eq 'author') {
                   9524:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9525:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9526:     } else {
                   9527:         foreach my $subdir ('docs','supplemental') {
                   9528:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9529:         }
                   9530:     }
1.1075.2.41  raeburn  9531:     $disk_quota = int($disk_quota * 1000);
                   9532:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  9533:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  9534:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  9535:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9536:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  9537:                             $disk_quota,$current_disk_usage).
                   9538:                '</p>';
                   9539:     }
                   9540:     return;
                   9541: }
                   9542: 
                   9543: ###############################################
                   9544: 
                   9545: 
1.384     raeburn  9546: sub get_secgrprole_info {
                   9547:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9548:     my %sections_count = &get_sections($cdom,$cnum);
                   9549:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9550:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9551:     my @groups = sort(keys(%curr_groups));
                   9552:     my $allroles = [];
                   9553:     my $rolehash;
                   9554:     my $accesshash = {
                   9555:                      active => 'Currently has access',
                   9556:                      future => 'Will have future access',
                   9557:                      previous => 'Previously had access',
                   9558:                   };
                   9559:     if ($needroles) {
                   9560:         $rolehash = {'all' => 'all'};
1.385     albertel 9561:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9562: 	if (&Apache::lonnet::error(%user_roles)) {
                   9563: 	    undef(%user_roles);
                   9564: 	}
                   9565:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9566:             my ($role)=split(/\:/,$item,2);
                   9567:             if ($role eq 'cr') { next; }
                   9568:             if ($role =~ /^cr/) {
                   9569:                 $$rolehash{$role} = (split('/',$role))[3];
                   9570:             } else {
                   9571:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9572:             }
                   9573:         }
                   9574:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9575:             push(@{$allroles},$key);
                   9576:         }
                   9577:         push (@{$allroles},'st');
                   9578:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9579:     }
                   9580:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9581: }
                   9582: 
1.555     raeburn  9583: sub user_picker {
1.1075.2.127  raeburn  9584:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  9585:     my $currdom = $dom;
1.1075.2.114  raeburn  9586:     my @alldoms = &Apache::lonnet::all_domains();
                   9587:     if (@alldoms == 1) {
                   9588:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   9589:                                                ['directorysrch'],$alldoms[0]);
                   9590:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   9591:         my $showdom = $domdesc;
                   9592:         if ($showdom eq '') {
                   9593:             $showdom = $dom;
                   9594:         }
                   9595:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   9596:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   9597:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   9598:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   9599:             }
                   9600:         }
                   9601:     }
1.555     raeburn  9602:     my %curr_selected = (
                   9603:                         srchin => 'dom',
1.580     raeburn  9604:                         srchby => 'lastname',
1.555     raeburn  9605:                       );
                   9606:     my $srchterm;
1.625     raeburn  9607:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9608:         if ($srch->{'srchby'} ne '') {
                   9609:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9610:         }
                   9611:         if ($srch->{'srchin'} ne '') {
                   9612:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9613:         }
                   9614:         if ($srch->{'srchtype'} ne '') {
                   9615:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9616:         }
                   9617:         if ($srch->{'srchdomain'} ne '') {
                   9618:             $currdom = $srch->{'srchdomain'};
                   9619:         }
                   9620:         $srchterm = $srch->{'srchterm'};
                   9621:     }
1.1075.2.98  raeburn  9622:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  9623:                     'usr'       => 'Search criteria',
1.563     raeburn  9624:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9625:                     'uname'     => 'username',
                   9626:                     'lastname'  => 'last name',
1.555     raeburn  9627:                     'lastfirst' => 'last name, first name',
1.558     albertel 9628:                     'crs'       => 'in this course',
1.576     raeburn  9629:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9630:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9631:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9632:                     'exact'     => 'is',
                   9633:                     'contains'  => 'contains',
1.569     raeburn  9634:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  9635:                                        );
                   9636:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  9637:                     'youm'      => "You must include some text to search for.",
                   9638:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9639:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9640:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9641:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9642:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9643:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9644:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9645:                                        );
1.1075.2.98  raeburn  9646:     &html_escape(\%html_lt);
                   9647:     &js_escape(\%js_lt);
1.1075.2.115  raeburn  9648:     my $domform;
1.1075.2.126  raeburn  9649:     my $allow_blank = 1;
1.1075.2.115  raeburn  9650:     if ($fixeddom) {
1.1075.2.126  raeburn  9651:         $allow_blank = 0;
                   9652:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1075.2.115  raeburn  9653:     } else {
1.1075.2.126  raeburn  9654:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
1.1075.2.115  raeburn  9655:     }
1.563     raeburn  9656:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9657: 
                   9658:     my @srchins = ('crs','dom','alc','instd');
                   9659: 
                   9660:     foreach my $option (@srchins) {
                   9661:         # FIXME 'alc' option unavailable until 
                   9662:         #       loncreateuser::print_user_query_page()
                   9663:         #       has been completed.
                   9664:         next if ($option eq 'alc');
1.880     raeburn  9665:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9666:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1075.2.127  raeburn  9667:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  9668:         if ($curr_selected{'srchin'} eq $option) {
                   9669:             $srchinsel .= ' 
1.1075.2.98  raeburn  9670:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  9671:         } else {
                   9672:             $srchinsel .= '
1.1075.2.98  raeburn  9673:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  9674:         }
1.555     raeburn  9675:     }
1.563     raeburn  9676:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9677: 
                   9678:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9679:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9680:         if ($curr_selected{'srchby'} eq $option) {
                   9681:             $srchbysel .= '
1.1075.2.98  raeburn  9682:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9683:         } else {
                   9684:             $srchbysel .= '
1.1075.2.98  raeburn  9685:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9686:          }
                   9687:     }
                   9688:     $srchbysel .= "\n  </select>\n";
                   9689: 
                   9690:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9691:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9692:         if ($curr_selected{'srchtype'} eq $option) {
                   9693:             $srchtypesel .= '
1.1075.2.98  raeburn  9694:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9695:         } else {
                   9696:             $srchtypesel .= '
1.1075.2.98  raeburn  9697:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9698:         }
                   9699:     }
                   9700:     $srchtypesel .= "\n  </select>\n";
                   9701: 
1.558     albertel 9702:     my ($newuserscript,$new_user_create);
1.994     raeburn  9703:     my $context_dom = $env{'request.role.domain'};
                   9704:     if ($context eq 'requestcrs') {
                   9705:         if ($env{'form.coursedom'} ne '') { 
                   9706:             $context_dom = $env{'form.coursedom'};
                   9707:         }
                   9708:     }
1.556     raeburn  9709:     if ($forcenewuser) {
1.576     raeburn  9710:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9711:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9712:                 if ($cancreate) {
                   9713:                     $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>';
                   9714:                 } else {
1.799     bisitz   9715:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9716:                     my %usertypetext = (
                   9717:                         official   => 'institutional',
                   9718:                         unofficial => 'non-institutional',
                   9719:                     );
1.799     bisitz   9720:                     $new_user_create = '<p class="LC_warning">'
                   9721:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9722:                                       .' '
                   9723:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9724:                                           ,'<a href="'.$helplink.'">','</a>')
                   9725:                                       .'</p><br />';
1.627     raeburn  9726:                 }
1.576     raeburn  9727:             }
                   9728:         }
                   9729: 
1.556     raeburn  9730:         $newuserscript = <<"ENDSCRIPT";
                   9731: 
1.570     raeburn  9732: function setSearch(createnew,callingForm) {
1.556     raeburn  9733:     if (createnew == 1) {
1.570     raeburn  9734:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9735:             if (callingForm.srchby.options[i].value == 'uname') {
                   9736:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9737:             }
                   9738:         }
1.570     raeburn  9739:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9740:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9741: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9742:             }
                   9743:         }
1.570     raeburn  9744:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9745:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9746:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9747:             }
                   9748:         }
1.570     raeburn  9749:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9750:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9751:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9752:             }
                   9753:         }
                   9754:     }
                   9755: }
                   9756: ENDSCRIPT
1.558     albertel 9757: 
1.556     raeburn  9758:     }
                   9759: 
1.555     raeburn  9760:     my $output = <<"END_BLOCK";
1.556     raeburn  9761: <script type="text/javascript">
1.824     bisitz   9762: // <![CDATA[
1.570     raeburn  9763: function validateEntry(callingForm) {
1.558     albertel 9764: 
1.556     raeburn  9765:     var checkok = 1;
1.558     albertel 9766:     var srchin;
1.570     raeburn  9767:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9768: 	if ( callingForm.srchin[i].checked ) {
                   9769: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9770: 	}
                   9771:     }
                   9772: 
1.570     raeburn  9773:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9774:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9775:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9776:     var srchterm =  callingForm.srchterm.value;
                   9777:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9778:     var msg = "";
                   9779: 
                   9780:     if (srchterm == "") {
                   9781:         checkok = 0;
1.1075.2.98  raeburn  9782:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  9783:     }
                   9784: 
1.569     raeburn  9785:     if (srchtype== 'begins') {
                   9786:         if (srchterm.length < 2) {
                   9787:             checkok = 0;
1.1075.2.98  raeburn  9788:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  9789:         }
                   9790:     }
                   9791: 
1.556     raeburn  9792:     if (srchtype== 'contains') {
                   9793:         if (srchterm.length < 3) {
                   9794:             checkok = 0;
1.1075.2.98  raeburn  9795:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  9796:         }
                   9797:     }
                   9798:     if (srchin == 'instd') {
                   9799:         if (srchdomain == '') {
                   9800:             checkok = 0;
1.1075.2.98  raeburn  9801:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  9802:         }
                   9803:     }
                   9804:     if (srchin == 'dom') {
                   9805:         if (srchdomain == '') {
                   9806:             checkok = 0;
1.1075.2.98  raeburn  9807:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  9808:         }
                   9809:     }
                   9810:     if (srchby == 'lastfirst') {
                   9811:         if (srchterm.indexOf(",") == -1) {
                   9812:             checkok = 0;
1.1075.2.98  raeburn  9813:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  9814:         }
                   9815:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9816:             checkok = 0;
1.1075.2.98  raeburn  9817:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  9818:         }
                   9819:     }
                   9820:     if (checkok == 0) {
1.1075.2.98  raeburn  9821:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  9822:         return;
                   9823:     }
                   9824:     if (checkok == 1) {
1.570     raeburn  9825:         callingForm.submit();
1.556     raeburn  9826:     }
                   9827: }
                   9828: 
                   9829: $newuserscript
                   9830: 
1.824     bisitz   9831: // ]]>
1.556     raeburn  9832: </script>
1.558     albertel 9833: 
                   9834: $new_user_create
                   9835: 
1.555     raeburn  9836: END_BLOCK
1.558     albertel 9837: 
1.876     raeburn  9838:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  9839:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  9840:                $domform.
                   9841:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  9842:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  9843:                $srchbysel.
                   9844:                $srchtypesel. 
                   9845:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9846:                $srchinsel.
                   9847:                &Apache::lonhtmlcommon::row_closure(1). 
                   9848:                &Apache::lonhtmlcommon::end_pick_box().
                   9849:                '<br />';
1.1075.2.114  raeburn  9850:     return ($output,1);
1.555     raeburn  9851: }
                   9852: 
1.612     raeburn  9853: sub user_rule_check {
1.615     raeburn  9854:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  9855:     my ($response,%inst_response);
1.612     raeburn  9856:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  9857:         if (keys(%{$usershash}) > 1) {
                   9858:             my (%by_username,%by_id,%userdoms);
                   9859:             my $checkid;
1.612     raeburn  9860:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  9861:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   9862:                     $checkid = 1;
                   9863:                 }
                   9864:             }
                   9865:             foreach my $user (keys(%{$usershash})) {
                   9866:                 my ($uname,$udom) = split(/:/,$user);
                   9867:                 if ($checkid) {
                   9868:                     if (ref($usershash->{$user}) eq 'HASH') {
                   9869:                         if ($usershash->{$user}->{'id'} ne '') {
                   9870:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   9871:                             $userdoms{$udom} = 1;
                   9872:                             if (ref($inst_results) eq 'HASH') {
                   9873:                                 $inst_results->{$uname.':'.$udom} = {};
                   9874:                             }
                   9875:                         }
                   9876:                     }
                   9877:                 } else {
                   9878:                     $by_username{$udom}{$uname} = 1;
                   9879:                     $userdoms{$udom} = 1;
                   9880:                     if (ref($inst_results) eq 'HASH') {
                   9881:                         $inst_results->{$uname.':'.$udom} = {};
                   9882:                     }
                   9883:                 }
                   9884:             }
                   9885:             foreach my $udom (keys(%userdoms)) {
                   9886:                 if (!$got_rules->{$udom}) {
                   9887:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9888:                                                              ['usercreation'],$udom);
                   9889:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   9890:                         foreach my $item ('username','id') {
                   9891:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9892:                                 $$curr_rules{$udom}{$item} =
                   9893:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   9894:                             }
                   9895:                         }
                   9896:                     }
                   9897:                     $got_rules->{$udom} = 1;
                   9898:                 }
                   9899:             }
                   9900:             if ($checkid) {
                   9901:                 foreach my $udom (keys(%by_id)) {
                   9902:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   9903:                     if ($outcome eq 'ok') {
                   9904:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   9905:                             my $uname = $by_id{$udom}{$id};
                   9906:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9907:                         }
                   9908:                         if (ref($results) eq 'HASH') {
                   9909:                             foreach my $uname (keys(%{$results})) {
                   9910:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   9911:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   9912:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   9913:                                 }
                   9914:                             }
                   9915:                         }
                   9916:                     }
1.612     raeburn  9917:                 }
1.615     raeburn  9918:             } else {
1.1075.2.99  raeburn  9919:                 foreach my $udom (keys(%by_username)) {
                   9920:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   9921:                     if ($outcome eq 'ok') {
                   9922:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   9923:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9924:                         }
                   9925:                         if (ref($results) eq 'HASH') {
                   9926:                             foreach my $uname (keys(%{$results})) {
                   9927:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   9928:                             }
                   9929:                         }
                   9930:                     }
                   9931:                 }
1.612     raeburn  9932:             }
1.1075.2.99  raeburn  9933:         } elsif (keys(%{$usershash}) == 1) {
                   9934:             my $user = (keys(%{$usershash}))[0];
                   9935:             my ($uname,$udom) = split(/:/,$user);
                   9936:             if (($udom ne '') && ($uname ne '')) {
                   9937:                 if (ref($usershash->{$user}) eq 'HASH') {
                   9938:                     if (ref($checks) eq 'HASH') {
                   9939:                         if (defined($checks->{'username'})) {
                   9940:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   9941:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   9942:                         } elsif (defined($checks->{'id'})) {
                   9943:                             if ($usershash->{$user}->{'id'} ne '') {
                   9944:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   9945:                                     &Apache::lonnet::get_instuser($udom,undef,
                   9946:                                                                   $usershash->{$user}->{'id'});
                   9947:                             } else {
                   9948:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   9949:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   9950:                             }
                   9951:                         }
                   9952:                     } else {
                   9953:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   9954:                             &Apache::lonnet::get_instuser($udom,$uname);
                   9955:                        return;
                   9956:                     }
                   9957:                     if (!$got_rules->{$udom}) {
                   9958:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9959:                                                                  ['usercreation'],$udom);
                   9960:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   9961:                             foreach my $item ('username','id') {
                   9962:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9963:                                    $$curr_rules{$udom}{$item} =
                   9964:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   9965:                                 }
                   9966:                             }
1.585     raeburn  9967:                         }
1.1075.2.99  raeburn  9968:                         $got_rules->{$udom} = 1;
1.585     raeburn  9969:                     }
                   9970:                 }
1.1075.2.99  raeburn  9971:             } else {
                   9972:                 return;
                   9973:             }
                   9974:         } else {
                   9975:             return;
                   9976:         }
                   9977:         foreach my $user (keys(%{$usershash})) {
                   9978:             my ($uname,$udom) = split(/:/,$user);
                   9979:             next if (($udom eq '') || ($uname eq ''));
                   9980:             my $id;
                   9981:             if (ref($inst_results) eq 'HASH') {
                   9982:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   9983:                     $id = $inst_results->{$user}->{'id'};
                   9984:                 }
                   9985:             }
                   9986:             if ($id eq '') {
                   9987:                 if (ref($usershash->{$user})) {
                   9988:                     $id = $usershash->{$user}->{'id'};
                   9989:                 }
1.585     raeburn  9990:             }
1.612     raeburn  9991:             foreach my $item (keys(%{$checks})) {
                   9992:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   9993:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   9994:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  9995:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   9996:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  9997:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   9998:                                 if ($rule_check{$rule}) {
                   9999:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  10000:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10001:                                         if (ref($inst_results) eq 'HASH') {
                   10002:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10003:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10004:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  10005:                                                 } elsif ($item eq 'id') {
                   10006:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10007:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10008:                                                     }
1.615     raeburn  10009:                                                 }
1.612     raeburn  10010:                                             }
                   10011:                                         }
1.615     raeburn  10012:                                     }
                   10013:                                     last;
1.585     raeburn  10014:                                 }
                   10015:                             }
                   10016:                         }
                   10017:                     }
                   10018:                 }
                   10019:             }
                   10020:         }
                   10021:     }
1.612     raeburn  10022:     return;
                   10023: }
                   10024: 
                   10025: sub user_rule_formats {
                   10026:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10027:     my %text = ( 
                   10028:                  'username' => 'Usernames',
                   10029:                  'id'       => 'IDs',
                   10030:                );
                   10031:     my $output;
                   10032:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10033:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10034:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  10035:             $output = '<br />'.
                   10036:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10037:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10038:                       ' <ul>';
1.612     raeburn  10039:             foreach my $rule (@{$ruleorder}) {
                   10040:                 if (ref($curr_rules) eq 'ARRAY') {
                   10041:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10042:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10043:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10044:                                         $rules->{$rule}{'desc'}.'</li>';
                   10045:                         }
                   10046:                     }
                   10047:                 }
                   10048:             }
                   10049:             $output .= '</ul>';
                   10050:         }
                   10051:     }
                   10052:     return $output;
                   10053: }
                   10054: 
                   10055: sub instrule_disallow_msg {
1.615     raeburn  10056:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10057:     my $response;
                   10058:     my %text = (
                   10059:                   item   => 'username',
                   10060:                   items  => 'usernames',
                   10061:                   match  => 'matches',
                   10062:                   do     => 'does',
                   10063:                   action => 'a username',
                   10064:                   one    => 'one',
                   10065:                );
                   10066:     if ($count > 1) {
                   10067:         $text{'item'} = 'usernames';
                   10068:         $text{'match'} ='match';
                   10069:         $text{'do'} = 'do';
                   10070:         $text{'action'} = 'usernames',
                   10071:         $text{'one'} = 'ones';
                   10072:     }
                   10073:     if ($checkitem eq 'id') {
                   10074:         $text{'items'} = 'IDs';
                   10075:         $text{'item'} = 'ID';
                   10076:         $text{'action'} = 'an ID';
1.615     raeburn  10077:         if ($count > 1) {
                   10078:             $text{'item'} = 'IDs';
                   10079:             $text{'action'} = 'IDs';
                   10080:         }
1.612     raeburn  10081:     }
1.674     bisitz   10082:     $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  10083:     if ($mode eq 'upload') {
                   10084:         if ($checkitem eq 'username') {
                   10085:             $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'}.");
                   10086:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10087:             $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  10088:         }
1.669     raeburn  10089:     } elsif ($mode eq 'selfcreate') {
                   10090:         if ($checkitem eq 'id') {
                   10091:             $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.");
                   10092:         }
1.615     raeburn  10093:     } else {
                   10094:         if ($checkitem eq 'username') {
                   10095:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10096:         } elsif ($checkitem eq 'id') {
                   10097:             $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.");
                   10098:         }
1.612     raeburn  10099:     }
                   10100:     return $response;
1.585     raeburn  10101: }
                   10102: 
1.624     raeburn  10103: sub personal_data_fieldtitles {
                   10104:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10105:                         id => 'Student/Employee ID',
                   10106:                         permanentemail => 'E-mail address',
                   10107:                         lastname => 'Last Name',
                   10108:                         firstname => 'First Name',
                   10109:                         middlename => 'Middle Name',
                   10110:                         generation => 'Generation',
                   10111:                         gen => 'Generation',
1.765     raeburn  10112:                         inststatus => 'Affiliation',
1.624     raeburn  10113:                    );
                   10114:     return %fieldtitles;
                   10115: }
                   10116: 
1.642     raeburn  10117: sub sorted_inst_types {
                   10118:     my ($dom) = @_;
1.1075.2.70  raeburn  10119:     my ($usertypes,$order);
                   10120:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10121:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10122:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10123:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10124:     } else {
                   10125:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10126:     }
1.642     raeburn  10127:     my $othertitle = &mt('All users');
                   10128:     if ($env{'request.course.id'}) {
1.668     raeburn  10129:         $othertitle  = &mt('Any users');
1.642     raeburn  10130:     }
                   10131:     my @types;
                   10132:     if (ref($order) eq 'ARRAY') {
                   10133:         @types = @{$order};
                   10134:     }
                   10135:     if (@types == 0) {
                   10136:         if (ref($usertypes) eq 'HASH') {
                   10137:             @types = sort(keys(%{$usertypes}));
                   10138:         }
                   10139:     }
                   10140:     if (keys(%{$usertypes}) > 0) {
                   10141:         $othertitle = &mt('Other users');
                   10142:     }
                   10143:     return ($othertitle,$usertypes,\@types);
                   10144: }
                   10145: 
1.645     raeburn  10146: sub get_institutional_codes {
                   10147:     my ($settings,$allcourses,$LC_code) = @_;
                   10148: # Get complete list of course sections to update
                   10149:     my @currsections = ();
                   10150:     my @currxlists = ();
                   10151:     my $coursecode = $$settings{'internal.coursecode'};
                   10152: 
                   10153:     if ($$settings{'internal.sectionnums'} ne '') {
                   10154:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10155:     }
                   10156: 
                   10157:     if ($$settings{'internal.crosslistings'} ne '') {
                   10158:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10159:     }
                   10160: 
                   10161:     if (@currxlists > 0) {
                   10162:         foreach (@currxlists) {
                   10163:             if (m/^([^:]+):(\w*)$/) {
                   10164:                 unless (grep/^$1$/,@{$allcourses}) {
1.1075.2.119  raeburn  10165:                     push(@{$allcourses},$1);
1.645     raeburn  10166:                     $$LC_code{$1} = $2;
                   10167:                 }
                   10168:             }
                   10169:         }
                   10170:     }
                   10171:  
                   10172:     if (@currsections > 0) {
                   10173:         foreach (@currsections) {
                   10174:             if (m/^(\w+):(\w*)$/) {
                   10175:                 my $sec = $coursecode.$1;
                   10176:                 my $lc_sec = $2;
                   10177:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1075.2.119  raeburn  10178:                     push(@{$allcourses},$sec);
1.645     raeburn  10179:                     $$LC_code{$sec} = $lc_sec;
                   10180:                 }
                   10181:             }
                   10182:         }
                   10183:     }
                   10184:     return;
                   10185: }
                   10186: 
1.971     raeburn  10187: sub get_standard_codeitems {
                   10188:     return ('Year','Semester','Department','Number','Section');
                   10189: }
                   10190: 
1.112     bowersj2 10191: =pod
                   10192: 
1.780     raeburn  10193: =head1 Slot Helpers
                   10194: 
                   10195: =over 4
                   10196: 
                   10197: =item * sorted_slots()
                   10198: 
1.1040    raeburn  10199: Sorts an array of slot names in order of an optional sort key,
                   10200: default sort is by slot start time (earliest first). 
1.780     raeburn  10201: 
                   10202: Inputs:
                   10203: 
                   10204: =over 4
                   10205: 
                   10206: slotsarr  - Reference to array of unsorted slot names.
                   10207: 
                   10208: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10209: 
1.1040    raeburn  10210: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10211: 
1.549     albertel 10212: =back
                   10213: 
1.780     raeburn  10214: Returns:
                   10215: 
                   10216: =over 4
                   10217: 
1.1040    raeburn  10218: sorted   - An array of slot names sorted by a specified sort key 
                   10219:            (default sort key is start time of the slot).
1.780     raeburn  10220: 
                   10221: =back
                   10222: 
                   10223: =cut
                   10224: 
                   10225: 
                   10226: sub sorted_slots {
1.1040    raeburn  10227:     my ($slotsarr,$slots,$sortkey) = @_;
                   10228:     if ($sortkey eq '') {
                   10229:         $sortkey = 'starttime';
                   10230:     }
1.780     raeburn  10231:     my @sorted;
                   10232:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10233:         @sorted =
                   10234:             sort {
                   10235:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10236:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10237:                      }
                   10238:                      if (ref($slots->{$a})) { return -1;}
                   10239:                      if (ref($slots->{$b})) { return 1;}
                   10240:                      return 0;
                   10241:                  } @{$slotsarr};
                   10242:     }
                   10243:     return @sorted;
                   10244: }
                   10245: 
1.1040    raeburn  10246: =pod
                   10247: 
                   10248: =item * get_future_slots()
                   10249: 
                   10250: Inputs:
                   10251: 
                   10252: =over 4
                   10253: 
                   10254: cnum - course number
                   10255: 
                   10256: cdom - course domain
                   10257: 
                   10258: now - current UNIX time
                   10259: 
                   10260: symb - optional symb
                   10261: 
                   10262: =back
                   10263: 
                   10264: Returns:
                   10265: 
                   10266: =over 4
                   10267: 
                   10268: sorted_reservable - ref to array of student_schedulable slots currently 
                   10269:                     reservable, ordered by end date of reservation period.
                   10270: 
                   10271: reservable_now - ref to hash of student_schedulable slots currently
                   10272:                  reservable.
                   10273: 
                   10274:     Keys in inner hash are:
                   10275:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  10276:     (b) endreserve: end date of reservation period.
                   10277:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10278:         selected.
1.1040    raeburn  10279: 
                   10280: sorted_future - ref to array of student_schedulable slots reservable in
                   10281:                 the future, ordered by start date of reservation period.
                   10282: 
                   10283: future_reservable - ref to hash of student_schedulable slots reservable
                   10284:                     in the future.
                   10285: 
                   10286:     Keys in inner hash are:
                   10287:     (a) symb: either blank or symb to which slot use is restricted.
                   10288:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  10289:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10290:         selected.
1.1040    raeburn  10291: 
                   10292: =back
                   10293: 
                   10294: =cut
                   10295: 
                   10296: sub get_future_slots {
                   10297:     my ($cnum,$cdom,$now,$symb) = @_;
                   10298:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10299:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10300:     foreach my $slot (keys(%slots)) {
                   10301:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10302:         if ($symb) {
                   10303:             next if (($slots{$slot}->{'symb'} ne '') && 
                   10304:                      ($slots{$slot}->{'symb'} ne $symb));
                   10305:         }
                   10306:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10307:             ($slots{$slot}->{'endtime'} > $now)) {
                   10308:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10309:                 my $userallowed = 0;
                   10310:                 if ($slots{$slot}->{'allowedsections'}) {
                   10311:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10312:                     if (!defined($env{'request.role.sec'})
                   10313:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10314:                         $userallowed=1;
                   10315:                     } else {
                   10316:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10317:                             $userallowed=1;
                   10318:                         }
                   10319:                     }
                   10320:                     unless ($userallowed) {
                   10321:                         if (defined($env{'request.course.groups'})) {
                   10322:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10323:                             foreach my $group (@groups) {
                   10324:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10325:                                     $userallowed=1;
                   10326:                                     last;
                   10327:                                 }
                   10328:                             }
                   10329:                         }
                   10330:                     }
                   10331:                 }
                   10332:                 if ($slots{$slot}->{'allowedusers'}) {
                   10333:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10334:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10335:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10336:                         $userallowed = 1;
                   10337:                     }
                   10338:                 }
                   10339:                 next unless($userallowed);
                   10340:             }
                   10341:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10342:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10343:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  10344:             my $uniqueperiod;
                   10345:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10346:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10347:             }
1.1040    raeburn  10348:             if (($startreserve < $now) &&
                   10349:                 (!$endreserve || $endreserve > $now)) {
                   10350:                 my $lastres = $endreserve;
                   10351:                 if (!$lastres) {
                   10352:                     $lastres = $slots{$slot}->{'starttime'};
                   10353:                 }
                   10354:                 $reservable_now{$slot} = {
                   10355:                                            symb       => $symb,
1.1075.2.104  raeburn  10356:                                            endreserve => $lastres,
                   10357:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  10358:                                          };
                   10359:             } elsif (($startreserve > $now) &&
                   10360:                      (!$endreserve || $endreserve > $startreserve)) {
                   10361:                 $future_reservable{$slot} = {
                   10362:                                               symb         => $symb,
1.1075.2.104  raeburn  10363:                                               startreserve => $startreserve,
                   10364:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10365:                                             };
                   10366:             }
                   10367:         }
                   10368:     }
                   10369:     my @unsorted_reservable = keys(%reservable_now);
                   10370:     if (@unsorted_reservable > 0) {
                   10371:         @sorted_reservable = 
                   10372:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10373:     }
                   10374:     my @unsorted_future = keys(%future_reservable);
                   10375:     if (@unsorted_future > 0) {
                   10376:         @sorted_future =
                   10377:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10378:     }
                   10379:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10380: }
1.780     raeburn  10381: 
                   10382: =pod
                   10383: 
1.1057    foxr     10384: =back
                   10385: 
1.549     albertel 10386: =head1 HTTP Helpers
                   10387: 
                   10388: =over 4
                   10389: 
1.648     raeburn  10390: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10391: 
1.258     albertel 10392: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10393: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10394: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10395: 
                   10396: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10397: $possible_names is an ref to an array of form element names.  As an example:
                   10398: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10399: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10400: 
                   10401: =cut
1.1       albertel 10402: 
1.6       albertel 10403: sub get_unprocessed_cgi {
1.25      albertel 10404:   my ($query,$possible_names)= @_;
1.26      matthew  10405:   # $Apache::lonxml::debug=1;
1.356     albertel 10406:   foreach my $pair (split(/&/,$query)) {
                   10407:     my ($name, $value) = split(/=/,$pair);
1.369     www      10408:     $name = &unescape($name);
1.25      albertel 10409:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10410:       $value =~ tr/+/ /;
                   10411:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10412:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10413:     }
1.16      harris41 10414:   }
1.6       albertel 10415: }
                   10416: 
1.112     bowersj2 10417: =pod
                   10418: 
1.648     raeburn  10419: =item * &cacheheader() 
1.112     bowersj2 10420: 
                   10421: returns cache-controlling header code
                   10422: 
                   10423: =cut
                   10424: 
1.7       albertel 10425: sub cacheheader {
1.258     albertel 10426:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10427:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10428:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10429:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10430:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10431:     return $output;
1.7       albertel 10432: }
                   10433: 
1.112     bowersj2 10434: =pod
                   10435: 
1.648     raeburn  10436: =item * &no_cache($r) 
1.112     bowersj2 10437: 
                   10438: specifies header code to not have cache
                   10439: 
                   10440: =cut
                   10441: 
1.9       albertel 10442: sub no_cache {
1.216     albertel 10443:     my ($r) = @_;
                   10444:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10445: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10446:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10447:     $r->no_cache(1);
                   10448:     $r->header_out("Expires" => $date);
                   10449:     $r->header_out("Pragma" => "no-cache");
1.123     www      10450: }
                   10451: 
                   10452: sub content_type {
1.181     albertel 10453:     my ($r,$type,$charset) = @_;
1.299     foxr     10454:     if ($r) {
                   10455: 	#  Note that printout.pl calls this with undef for $r.
                   10456: 	&no_cache($r);
                   10457:     }
1.258     albertel 10458:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10459:     unless ($charset) {
                   10460: 	$charset=&Apache::lonlocal::current_encoding;
                   10461:     }
                   10462:     if ($charset) { $type.='; charset='.$charset; }
                   10463:     if ($r) {
                   10464: 	$r->content_type($type);
                   10465:     } else {
                   10466: 	print("Content-type: $type\n\n");
                   10467:     }
1.9       albertel 10468: }
1.25      albertel 10469: 
1.112     bowersj2 10470: =pod
                   10471: 
1.648     raeburn  10472: =item * &add_to_env($name,$value) 
1.112     bowersj2 10473: 
1.258     albertel 10474: adds $name to the %env hash with value
1.112     bowersj2 10475: $value, if $name already exists, the entry is converted to an array
                   10476: reference and $value is added to the array.
                   10477: 
                   10478: =cut
                   10479: 
1.25      albertel 10480: sub add_to_env {
                   10481:   my ($name,$value)=@_;
1.258     albertel 10482:   if (defined($env{$name})) {
                   10483:     if (ref($env{$name})) {
1.25      albertel 10484:       #already have multiple values
1.258     albertel 10485:       push(@{ $env{$name} },$value);
1.25      albertel 10486:     } else {
                   10487:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10488:       my $first=$env{$name};
                   10489:       undef($env{$name});
                   10490:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10491:     }
                   10492:   } else {
1.258     albertel 10493:     $env{$name}=$value;
1.25      albertel 10494:   }
1.31      albertel 10495: }
1.149     albertel 10496: 
                   10497: =pod
                   10498: 
1.648     raeburn  10499: =item * &get_env_multiple($name) 
1.149     albertel 10500: 
1.258     albertel 10501: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10502: values may be defined and end up as an array ref.
                   10503: 
                   10504: returns an array of values
                   10505: 
                   10506: =cut
                   10507: 
                   10508: sub get_env_multiple {
                   10509:     my ($name) = @_;
                   10510:     my @values;
1.258     albertel 10511:     if (defined($env{$name})) {
1.149     albertel 10512:         # exists is it an array
1.258     albertel 10513:         if (ref($env{$name})) {
                   10514:             @values=@{ $env{$name} };
1.149     albertel 10515:         } else {
1.258     albertel 10516:             $values[0]=$env{$name};
1.149     albertel 10517:         }
                   10518:     }
                   10519:     return(@values);
                   10520: }
                   10521: 
1.660     raeburn  10522: sub ask_for_embedded_content {
                   10523:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10524:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  10525:         %currsubfile,%unused,$rem);
1.1071    raeburn  10526:     my $counter = 0;
                   10527:     my $numnew = 0;
1.987     raeburn  10528:     my $numremref = 0;
                   10529:     my $numinvalid = 0;
                   10530:     my $numpathchg = 0;
                   10531:     my $numexisting = 0;
1.1071    raeburn  10532:     my $numunused = 0;
                   10533:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  10534:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10535:     my $heading = &mt('Upload embedded files');
                   10536:     my $buttontext = &mt('Upload');
                   10537: 
1.1075.2.11  raeburn  10538:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  10539:         if ($actionurl eq '/adm/dependencies') {
                   10540:             $navmap = Apache::lonnavmaps::navmap->new();
                   10541:         }
                   10542:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10543:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  10544:     }
1.1075.2.35  raeburn  10545:     if (($actionurl eq '/adm/portfolio') ||
                   10546:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10547:         my $current_path='/';
                   10548:         if ($env{'form.currentpath'}) {
                   10549:             $current_path = $env{'form.currentpath'};
                   10550:         }
                   10551:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  10552:             $udom = $cdom;
                   10553:             $uname = $cnum;
1.984     raeburn  10554:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10555:         } else {
                   10556:             $udom = $env{'user.domain'};
                   10557:             $uname = $env{'user.name'};
                   10558:             $url = '/userfiles/portfolio';
                   10559:         }
1.987     raeburn  10560:         $toplevel = $url.'/';
1.984     raeburn  10561:         $url .= $current_path;
                   10562:         $getpropath = 1;
1.987     raeburn  10563:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10564:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10565:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10566:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10567:         $toplevel = $url;
1.984     raeburn  10568:         if ($rest ne '') {
1.987     raeburn  10569:             $url .= $rest;
                   10570:         }
                   10571:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10572:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10573:             $url = $args->{'docs_url'};
                   10574:             $toplevel = $url;
1.1075.2.11  raeburn  10575:             if ($args->{'context'} eq 'paste') {
                   10576:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10577:                 ($path) =
                   10578:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10579:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10580:                 $fileloc =~ s{^/}{};
                   10581:             }
1.1071    raeburn  10582:         }
                   10583:     } elsif ($actionurl eq '/adm/dependencies') {
                   10584:         if ($env{'request.course.id'} ne '') {
                   10585:             if (ref($args) eq 'HASH') {
                   10586:                 $url = $args->{'docs_url'};
                   10587:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  10588:                 $toplevel = $url;
                   10589:                 unless ($toplevel =~ m{^/}) {
                   10590:                     $toplevel = "/$url";
                   10591:                 }
1.1075.2.11  raeburn  10592:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  10593:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10594:                     $path = $1;
                   10595:                 } else {
                   10596:                     ($path) =
                   10597:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10598:                 }
1.1075.2.79  raeburn  10599:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10600:                     $fileloc = $toplevel;
                   10601:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10602:                     my ($udom,$uname,$fname) =
                   10603:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10604:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10605:                 } else {
                   10606:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10607:                 }
1.1071    raeburn  10608:                 $fileloc =~ s{^/}{};
                   10609:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10610:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10611:             }
1.987     raeburn  10612:         }
1.1075.2.35  raeburn  10613:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10614:         $udom = $cdom;
                   10615:         $uname = $cnum;
                   10616:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10617:         $toplevel = $url;
                   10618:         $path = $url;
                   10619:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10620:         $fileloc =~ s{^/}{};
                   10621:     }
                   10622:     foreach my $file (keys(%{$allfiles})) {
                   10623:         my $embed_file;
                   10624:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10625:             $embed_file = $1;
                   10626:         } else {
                   10627:             $embed_file = $file;
                   10628:         }
1.1075.2.55  raeburn  10629:         my ($absolutepath,$cleaned_file);
                   10630:         if ($embed_file =~ m{^\w+://}) {
                   10631:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  10632:             $newfiles{$cleaned_file} = 1;
                   10633:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10634:         } else {
1.1075.2.55  raeburn  10635:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10636:             if ($embed_file =~ m{^/}) {
                   10637:                 $absolutepath = $embed_file;
                   10638:             }
1.1075.2.47  raeburn  10639:             if ($cleaned_file =~ m{/}) {
                   10640:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10641:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10642:                 my $item = $fname;
                   10643:                 if ($path ne '') {
                   10644:                     $item = $path.'/'.$fname;
                   10645:                     $subdependencies{$path}{$fname} = 1;
                   10646:                 } else {
                   10647:                     $dependencies{$item} = 1;
                   10648:                 }
                   10649:                 if ($absolutepath) {
                   10650:                     $mapping{$item} = $absolutepath;
                   10651:                 } else {
                   10652:                     $mapping{$item} = $embed_file;
                   10653:                 }
                   10654:             } else {
                   10655:                 $dependencies{$embed_file} = 1;
                   10656:                 if ($absolutepath) {
1.1075.2.47  raeburn  10657:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10658:                 } else {
1.1075.2.47  raeburn  10659:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10660:                 }
                   10661:             }
1.984     raeburn  10662:         }
                   10663:     }
1.1071    raeburn  10664:     my $dirptr = 16384;
1.984     raeburn  10665:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10666:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  10667:         if (($actionurl eq '/adm/portfolio') ||
                   10668:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  10669:             my ($sublistref,$listerror) =
                   10670:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10671:             if (ref($sublistref) eq 'ARRAY') {
                   10672:                 foreach my $line (@{$sublistref}) {
                   10673:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10674:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10675:                 }
1.984     raeburn  10676:             }
1.987     raeburn  10677:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10678:             if (opendir(my $dir,$url.'/'.$path)) {
                   10679:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10680:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10681:             }
1.1075.2.11  raeburn  10682:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10683:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10684:                   ($args->{'context'} eq 'paste')) ||
                   10685:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10686:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  10687:                 my $dir;
                   10688:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10689:                     $dir = $fileloc;
                   10690:                 } else {
                   10691:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10692:                 }
1.1071    raeburn  10693:                 if ($dir ne '') {
                   10694:                     my ($sublistref,$listerror) =
                   10695:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10696:                     if (ref($sublistref) eq 'ARRAY') {
                   10697:                         foreach my $line (@{$sublistref}) {
                   10698:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10699:                                 undef,$mtime)=split(/\&/,$line,12);
                   10700:                             unless (($testdir&$dirptr) ||
                   10701:                                     ($file_name =~ /^\.\.?$/)) {
                   10702:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10703:                             }
                   10704:                         }
                   10705:                     }
                   10706:                 }
1.984     raeburn  10707:             }
                   10708:         }
                   10709:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10710:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10711:                 my $item = $path.'/'.$file;
                   10712:                 unless ($mapping{$item} eq $item) {
                   10713:                     $pathchanges{$item} = 1;
                   10714:                 }
                   10715:                 $existing{$item} = 1;
                   10716:                 $numexisting ++;
                   10717:             } else {
                   10718:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10719:             }
                   10720:         }
1.1071    raeburn  10721:         if ($actionurl eq '/adm/dependencies') {
                   10722:             foreach my $path (keys(%currsubfile)) {
                   10723:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10724:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10725:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  10726:                              next if (($rem ne '') &&
                   10727:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10728:                                        (ref($navmap) &&
                   10729:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10730:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10731:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10732:                              $unused{$path.'/'.$file} = 1; 
                   10733:                          }
                   10734:                     }
                   10735:                 }
                   10736:             }
                   10737:         }
1.984     raeburn  10738:     }
1.987     raeburn  10739:     my %currfile;
1.1075.2.35  raeburn  10740:     if (($actionurl eq '/adm/portfolio') ||
                   10741:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10742:         my ($dirlistref,$listerror) =
                   10743:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10744:         if (ref($dirlistref) eq 'ARRAY') {
                   10745:             foreach my $line (@{$dirlistref}) {
                   10746:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10747:                 $currfile{$file_name} = 1;
                   10748:             }
1.984     raeburn  10749:         }
1.987     raeburn  10750:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10751:         if (opendir(my $dir,$url)) {
1.987     raeburn  10752:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10753:             map {$currfile{$_} = 1;} @dir_list;
                   10754:         }
1.1075.2.11  raeburn  10755:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10756:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10757:               ($args->{'context'} eq 'paste')) ||
                   10758:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10759:         if ($env{'request.course.id'} ne '') {
                   10760:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10761:             if ($dir ne '') {
                   10762:                 my ($dirlistref,$listerror) =
                   10763:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10764:                 if (ref($dirlistref) eq 'ARRAY') {
                   10765:                     foreach my $line (@{$dirlistref}) {
                   10766:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10767:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10768:                         unless (($testdir&$dirptr) ||
                   10769:                                 ($file_name =~ /^\.\.?$/)) {
                   10770:                             $currfile{$file_name} = [$size,$mtime];
                   10771:                         }
                   10772:                     }
                   10773:                 }
                   10774:             }
                   10775:         }
1.984     raeburn  10776:     }
                   10777:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10778:         if (exists($currfile{$file})) {
1.987     raeburn  10779:             unless ($mapping{$file} eq $file) {
                   10780:                 $pathchanges{$file} = 1;
                   10781:             }
                   10782:             $existing{$file} = 1;
                   10783:             $numexisting ++;
                   10784:         } else {
1.984     raeburn  10785:             $newfiles{$file} = 1;
                   10786:         }
                   10787:     }
1.1071    raeburn  10788:     foreach my $file (keys(%currfile)) {
                   10789:         unless (($file eq $filename) ||
                   10790:                 ($file eq $filename.'.bak') ||
                   10791:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  10792:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  10793:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10794:                     next if (($rem ne '') &&
                   10795:                              (($env{"httpref.$rem".$file} ne '') ||
                   10796:                               (ref($navmap) &&
                   10797:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10798:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10799:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10800:                 }
1.1075.2.11  raeburn  10801:             }
1.1071    raeburn  10802:             $unused{$file} = 1;
                   10803:         }
                   10804:     }
1.1075.2.11  raeburn  10805:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10806:         ($args->{'context'} eq 'paste')) {
                   10807:         $counter = scalar(keys(%existing));
                   10808:         $numpathchg = scalar(keys(%pathchanges));
                   10809:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  10810:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   10811:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10812:         $counter = scalar(keys(%existing));
                   10813:         $numpathchg = scalar(keys(%pathchanges));
                   10814:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  10815:     }
1.984     raeburn  10816:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10817:         if ($actionurl eq '/adm/dependencies') {
                   10818:             next if ($embed_file =~ m{^\w+://});
                   10819:         }
1.660     raeburn  10820:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10821:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  10822:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  10823:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  10824:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   10825:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  10826:         }
1.1075.2.35  raeburn  10827:         $upload_output .= '</td>';
1.1071    raeburn  10828:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  10829:             $upload_output.='<td align="right">'.
                   10830:                             '<span class="LC_info LC_fontsize_medium">'.
                   10831:                             &mt("URL points to web address").'</span>';
1.987     raeburn  10832:             $numremref++;
1.660     raeburn  10833:         } elsif ($args->{'error_on_invalid_names'}
                   10834:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  10835:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   10836:                             &mt('Invalid characters').'</span>';
1.987     raeburn  10837:             $numinvalid++;
1.660     raeburn  10838:         } else {
1.1075.2.35  raeburn  10839:             $upload_output .= '<td>'.
                   10840:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  10841:                                                      $embed_file,\%mapping,
1.1071    raeburn  10842:                                                      $allfiles,$codebase,'upload');
                   10843:             $counter ++;
                   10844:             $numnew ++;
1.987     raeburn  10845:         }
                   10846:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   10847:     }
                   10848:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  10849:         if ($actionurl eq '/adm/dependencies') {
                   10850:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   10851:             $modify_output .= &start_data_table_row().
                   10852:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   10853:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   10854:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   10855:                               '<td>'.$size.'</td>'.
                   10856:                               '<td>'.$mtime.'</td>'.
                   10857:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   10858:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   10859:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   10860:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   10861:                               &embedded_file_element('upload_embedded',$counter,
                   10862:                                                      $embed_file,\%mapping,
                   10863:                                                      $allfiles,$codebase,'modify').
                   10864:                               '</div></td>'.
                   10865:                               &end_data_table_row()."\n";
                   10866:             $counter ++;
                   10867:         } else {
                   10868:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10869:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   10870:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   10871:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  10872:                               &Apache::loncommon::end_data_table_row()."\n";
                   10873:         }
                   10874:     }
                   10875:     my $delidx = $counter;
                   10876:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   10877:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   10878:         $delete_output .= &start_data_table_row().
                   10879:                           '<td><img src="'.&icon($oldfile).'" />'.
                   10880:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   10881:                           '<td>'.$size.'</td>'.
                   10882:                           '<td>'.$mtime.'</td>'.
                   10883:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   10884:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   10885:                           &embedded_file_element('upload_embedded',$delidx,
                   10886:                                                  $oldfile,\%mapping,$allfiles,
                   10887:                                                  $codebase,'delete').'</td>'.
                   10888:                           &end_data_table_row()."\n"; 
                   10889:         $numunused ++;
                   10890:         $delidx ++;
1.987     raeburn  10891:     }
                   10892:     if ($upload_output) {
                   10893:         $upload_output = &start_data_table().
                   10894:                          $upload_output.
                   10895:                          &end_data_table()."\n";
                   10896:     }
1.1071    raeburn  10897:     if ($modify_output) {
                   10898:         $modify_output = &start_data_table().
                   10899:                          &start_data_table_header_row().
                   10900:                          '<th>'.&mt('File').'</th>'.
                   10901:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10902:                          '<th>'.&mt('Modified').'</th>'.
                   10903:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   10904:                          &end_data_table_header_row().
                   10905:                          $modify_output.
                   10906:                          &end_data_table()."\n";
                   10907:     }
                   10908:     if ($delete_output) {
                   10909:         $delete_output = &start_data_table().
                   10910:                          &start_data_table_header_row().
                   10911:                          '<th>'.&mt('File').'</th>'.
                   10912:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10913:                          '<th>'.&mt('Modified').'</th>'.
                   10914:                          '<th>'.&mt('Delete?').'</th>'.
                   10915:                          &end_data_table_header_row().
                   10916:                          $delete_output.
                   10917:                          &end_data_table()."\n";
                   10918:     }
1.987     raeburn  10919:     my $applies = 0;
                   10920:     if ($numremref) {
                   10921:         $applies ++;
                   10922:     }
                   10923:     if ($numinvalid) {
                   10924:         $applies ++;
                   10925:     }
                   10926:     if ($numexisting) {
                   10927:         $applies ++;
                   10928:     }
1.1071    raeburn  10929:     if ($counter || $numunused) {
1.987     raeburn  10930:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   10931:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  10932:                   $state.'<h3>'.$heading.'</h3>'; 
                   10933:         if ($actionurl eq '/adm/dependencies') {
                   10934:             if ($numnew) {
                   10935:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   10936:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   10937:                            $upload_output.'<br />'."\n";
                   10938:             }
                   10939:             if ($numexisting) {
                   10940:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   10941:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   10942:                            $modify_output.'<br />'."\n";
                   10943:                            $buttontext = &mt('Save changes');
                   10944:             }
                   10945:             if ($numunused) {
                   10946:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   10947:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   10948:                            $delete_output.'<br />'."\n";
                   10949:                            $buttontext = &mt('Save changes');
                   10950:             }
                   10951:         } else {
                   10952:             $output .= $upload_output.'<br />'."\n";
                   10953:         }
                   10954:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   10955:                    $counter.'" />'."\n";
                   10956:         if ($actionurl eq '/adm/dependencies') { 
                   10957:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   10958:                        $numnew.'" />'."\n";
                   10959:         } elsif ($actionurl eq '') {
1.987     raeburn  10960:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   10961:         }
                   10962:     } elsif ($applies) {
                   10963:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   10964:         if ($applies > 1) {
                   10965:             $output .=  
1.1075.2.35  raeburn  10966:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  10967:             if ($numremref) {
                   10968:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   10969:             }
                   10970:             if ($numinvalid) {
                   10971:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   10972:             }
                   10973:             if ($numexisting) {
                   10974:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   10975:             }
                   10976:             $output .= '</ul><br />';
                   10977:         } elsif ($numremref) {
                   10978:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   10979:         } elsif ($numinvalid) {
                   10980:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   10981:         } elsif ($numexisting) {
                   10982:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   10983:         }
                   10984:         $output .= $upload_output.'<br />';
                   10985:     }
                   10986:     my ($pathchange_output,$chgcount);
1.1071    raeburn  10987:     $chgcount = $counter;
1.987     raeburn  10988:     if (keys(%pathchanges) > 0) {
                   10989:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  10990:             if ($counter) {
1.987     raeburn  10991:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   10992:                                                   $embed_file,\%mapping,
1.1071    raeburn  10993:                                                   $allfiles,$codebase,'change');
1.987     raeburn  10994:             } else {
                   10995:                 $pathchange_output .= 
                   10996:                     &start_data_table_row().
                   10997:                     '<td><input type ="checkbox" name="namechange" value="'.
                   10998:                     $chgcount.'" checked="checked" /></td>'.
                   10999:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11000:                     '<td>'.$embed_file.
                   11001:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11002:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11003:                     '</td>'.&end_data_table_row();
1.660     raeburn  11004:             }
1.987     raeburn  11005:             $numpathchg ++;
                   11006:             $chgcount ++;
1.660     raeburn  11007:         }
                   11008:     }
1.1075.2.35  raeburn  11009:     if (($counter) || ($numunused)) {
1.987     raeburn  11010:         if ($numpathchg) {
                   11011:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11012:                        $numpathchg.'" />'."\n";
                   11013:         }
                   11014:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11015:             ($actionurl eq '/adm/imsimport')) {
                   11016:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11017:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11018:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11019:         } elsif ($actionurl eq '/adm/dependencies') {
                   11020:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11021:         }
1.1075.2.35  raeburn  11022:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11023:     } elsif ($numpathchg) {
                   11024:         my %pathchange = ();
                   11025:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11026:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11027:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  11028:         }
1.987     raeburn  11029:     }
1.1071    raeburn  11030:     return ($output,$counter,$numpathchg);
1.987     raeburn  11031: }
                   11032: 
1.1075.2.47  raeburn  11033: =pod
                   11034: 
                   11035: =item * clean_path($name)
                   11036: 
                   11037: Performs clean-up of directories, subdirectories and filename in an
                   11038: embedded object, referenced in an HTML file which is being uploaded
                   11039: to a course or portfolio, where
                   11040: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11041: checked.
                   11042: 
                   11043: Clean-up is similar to replacements in lonnet::clean_filename()
                   11044: except each / between sub-directory and next level is preserved.
                   11045: 
                   11046: =cut
                   11047: 
                   11048: sub clean_path {
                   11049:     my ($embed_file) = @_;
                   11050:     $embed_file =~s{^/+}{};
                   11051:     my @contents;
                   11052:     if ($embed_file =~ m{/}) {
                   11053:         @contents = split(/\//,$embed_file);
                   11054:     } else {
                   11055:         @contents = ($embed_file);
                   11056:     }
                   11057:     my $lastidx = scalar(@contents)-1;
                   11058:     for (my $i=0; $i<=$lastidx; $i++) {
                   11059:         $contents[$i]=~s{\\}{/}g;
                   11060:         $contents[$i]=~s/\s+/\_/g;
                   11061:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11062:         if ($i == $lastidx) {
                   11063:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11064:         }
                   11065:     }
                   11066:     if ($lastidx > 0) {
                   11067:         return join('/',@contents);
                   11068:     } else {
                   11069:         return $contents[0];
                   11070:     }
                   11071: }
                   11072: 
1.987     raeburn  11073: sub embedded_file_element {
1.1071    raeburn  11074:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11075:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11076:                    (ref($codebase) eq 'HASH'));
                   11077:     my $output;
1.1071    raeburn  11078:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11079:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11080:     }
                   11081:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11082:                &escape($embed_file).'" />';
                   11083:     unless (($context eq 'upload_embedded') && 
                   11084:             ($mapping->{$embed_file} eq $embed_file)) {
                   11085:         $output .='
                   11086:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11087:     }
                   11088:     my $attrib;
                   11089:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11090:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11091:     }
                   11092:     $output .=
                   11093:         "\n\t\t".
                   11094:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11095:         $attrib.'" />';
                   11096:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11097:         $output .=
                   11098:             "\n\t\t".
                   11099:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11100:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11101:     }
1.987     raeburn  11102:     return $output;
1.660     raeburn  11103: }
                   11104: 
1.1071    raeburn  11105: sub get_dependency_details {
                   11106:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11107:     my ($size,$mtime,$showsize,$showmtime);
                   11108:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11109:         if ($embed_file =~ m{/}) {
                   11110:             my ($path,$fname) = split(/\//,$embed_file);
                   11111:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11112:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11113:             }
                   11114:         } else {
                   11115:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11116:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11117:             }
                   11118:         }
                   11119:         $showsize = $size/1024.0;
                   11120:         $showsize = sprintf("%.1f",$showsize);
                   11121:         if ($mtime > 0) {
                   11122:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11123:         }
                   11124:     }
                   11125:     return ($showsize,$showmtime);
                   11126: }
                   11127: 
                   11128: sub ask_embedded_js {
                   11129:     return <<"END";
                   11130: <script type="text/javascript"">
                   11131: // <![CDATA[
                   11132: function toggleBrowse(counter) {
                   11133:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11134:     var fileid = document.getElementById('embedded_item_'+counter);
                   11135:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11136:     if (chkboxid.checked == true) {
                   11137:         uploaddivid.style.display='block';
                   11138:     } else {
                   11139:         uploaddivid.style.display='none';
                   11140:         fileid.value = '';
                   11141:     }
                   11142: }
                   11143: // ]]>
                   11144: </script>
                   11145: 
                   11146: END
                   11147: }
                   11148: 
1.661     raeburn  11149: sub upload_embedded {
                   11150:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11151:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11152:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11153:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11154:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11155:         my $orig_uploaded_filename =
                   11156:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11157:         foreach my $type ('orig','ref','attrib','codebase') {
                   11158:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11159:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11160:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11161:             }
                   11162:         }
1.661     raeburn  11163:         my ($path,$fname) =
                   11164:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11165:         # no path, whole string is fname
                   11166:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11167:         $fname = &Apache::lonnet::clean_filename($fname);
                   11168:         # See if there is anything left
                   11169:         next if ($fname eq '');
                   11170: 
                   11171:         # Check if file already exists as a file or directory.
                   11172:         my ($state,$msg);
                   11173:         if ($context eq 'portfolio') {
                   11174:             my $port_path = $dirpath;
                   11175:             if ($group ne '') {
                   11176:                 $port_path = "groups/$group/$port_path";
                   11177:             }
1.987     raeburn  11178:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11179:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11180:                                               $dir_root,$port_path,$disk_quota,
                   11181:                                               $current_disk_usage,$uname,$udom);
                   11182:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11183:                 || $state eq 'file_locked') {
1.661     raeburn  11184:                 $output .= $msg;
                   11185:                 next;
                   11186:             }
                   11187:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11188:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11189:             if ($state eq 'exists') {
                   11190:                 $output .= $msg;
                   11191:                 next;
                   11192:             }
                   11193:         }
                   11194:         # Check if extension is valid
                   11195:         if (($fname =~ /\.(\w+)$/) &&
                   11196:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  11197:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11198:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11199:             next;
                   11200:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11201:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11202:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11203:             next;
                   11204:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  11205:             $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  11206:             next;
                   11207:         }
                   11208:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  11209:         my $subdir = $path;
                   11210:         $subdir =~ s{/+$}{};
1.661     raeburn  11211:         if ($context eq 'portfolio') {
1.984     raeburn  11212:             my $result;
                   11213:             if ($state eq 'existingfile') {
                   11214:                 $result=
                   11215:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  11216:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11217:             } else {
1.984     raeburn  11218:                 $result=
                   11219:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11220:                                                     $dirpath.
1.1075.2.35  raeburn  11221:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11222:                 if ($result !~ m|^/uploaded/|) {
                   11223:                     $output .= '<span class="LC_error">'
                   11224:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11225:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11226:                                .'</span><br />';
                   11227:                     next;
                   11228:                 } else {
1.987     raeburn  11229:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11230:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11231:                 }
1.661     raeburn  11232:             }
1.1075.2.35  raeburn  11233:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   11234:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11235:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11236:             my $result =
1.1075.2.35  raeburn  11237:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11238:             if ($result !~ m|^/uploaded/|) {
                   11239:                 $output .= '<span class="LC_error">'
                   11240:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11241:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11242:                            .'</span><br />';
                   11243:                     next;
                   11244:             } else {
                   11245:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11246:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  11247:                 if ($context eq 'syllabus') {
                   11248:                     &Apache::lonnet::make_public_indefinitely($result);
                   11249:                 }
1.987     raeburn  11250:             }
1.661     raeburn  11251:         } else {
                   11252: # Save the file
                   11253:             my $target = $env{'form.embedded_item_'.$i};
                   11254:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11255:             my $dest = $fullpath.$fname;
                   11256:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11257:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11258:             my $count;
                   11259:             my $filepath = $dir_root;
1.1027    raeburn  11260:             foreach my $subdir (@parts) {
                   11261:                 $filepath .= "/$subdir";
                   11262:                 if (!-e $filepath) {
1.661     raeburn  11263:                     mkdir($filepath,0770);
                   11264:                 }
                   11265:             }
                   11266:             my $fh;
                   11267:             if (!open($fh,'>'.$dest)) {
                   11268:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11269:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11270:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11271:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11272:                            '</span><br />';
                   11273:             } else {
                   11274:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11275:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11276:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11277:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11278:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11279:                               '</span><br />';
                   11280:                 } else {
1.987     raeburn  11281:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11282:                                $url.'</span>').'<br />';
                   11283:                     unless ($context eq 'testbank') {
                   11284:                         $footer .= &mt('View embedded file: [_1]',
                   11285:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11286:                     }
                   11287:                 }
                   11288:                 close($fh);
                   11289:             }
                   11290:         }
                   11291:         if ($env{'form.embedded_ref_'.$i}) {
                   11292:             $pathchange{$i} = 1;
                   11293:         }
                   11294:     }
                   11295:     if ($output) {
                   11296:         $output = '<p>'.$output.'</p>';
                   11297:     }
                   11298:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11299:     $returnflag = 'ok';
1.1071    raeburn  11300:     my $numpathchgs = scalar(keys(%pathchange));
                   11301:     if ($numpathchgs > 0) {
1.987     raeburn  11302:         if ($context eq 'portfolio') {
                   11303:             $output .= '<p>'.&mt('or').'</p>';
                   11304:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11305:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11306:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11307:             $returnflag = 'modify_orightml';
                   11308:         }
                   11309:     }
1.1071    raeburn  11310:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11311: }
                   11312: 
                   11313: sub modify_html_form {
                   11314:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11315:     my $end = 0;
                   11316:     my $modifyform;
                   11317:     if ($context eq 'upload_embedded') {
                   11318:         return unless (ref($pathchange) eq 'HASH');
                   11319:         if ($env{'form.number_embedded_items'}) {
                   11320:             $end += $env{'form.number_embedded_items'};
                   11321:         }
                   11322:         if ($env{'form.number_pathchange_items'}) {
                   11323:             $end += $env{'form.number_pathchange_items'};
                   11324:         }
                   11325:         if ($end) {
                   11326:             for (my $i=0; $i<$end; $i++) {
                   11327:                 if ($i < $env{'form.number_embedded_items'}) {
                   11328:                     next unless($pathchange->{$i});
                   11329:                 }
                   11330:                 $modifyform .=
                   11331:                     &start_data_table_row().
                   11332:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11333:                     'checked="checked" /></td>'.
                   11334:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11335:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11336:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11337:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11338:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11339:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11340:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11341:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11342:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11343:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11344:                     &end_data_table_row();
1.1071    raeburn  11345:             }
1.987     raeburn  11346:         }
                   11347:     } else {
                   11348:         $modifyform = $pathchgtable;
                   11349:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11350:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11351:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11352:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11353:         }
                   11354:     }
                   11355:     if ($modifyform) {
1.1071    raeburn  11356:         if ($actionurl eq '/adm/dependencies') {
                   11357:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11358:         }
1.987     raeburn  11359:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11360:                '<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".
                   11361:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11362:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11363:                '</ol></p>'."\n".'<p>'.
                   11364:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11365:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11366:                &start_data_table()."\n".
                   11367:                &start_data_table_header_row().
                   11368:                '<th>'.&mt('Change?').'</th>'.
                   11369:                '<th>'.&mt('Current reference').'</th>'.
                   11370:                '<th>'.&mt('Required reference').'</th>'.
                   11371:                &end_data_table_header_row()."\n".
                   11372:                $modifyform.
                   11373:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11374:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11375:                '</form>'."\n";
                   11376:     }
                   11377:     return;
                   11378: }
                   11379: 
                   11380: sub modify_html_refs {
1.1075.2.35  raeburn  11381:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11382:     my $container;
                   11383:     if ($context eq 'portfolio') {
                   11384:         $container = $env{'form.container'};
                   11385:     } elsif ($context eq 'coursedoc') {
                   11386:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11387:     } elsif ($context eq 'manage_dependencies') {
                   11388:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11389:         $container = "/$container";
1.1075.2.35  raeburn  11390:     } elsif ($context eq 'syllabus') {
                   11391:         $container = $url;
1.987     raeburn  11392:     } else {
1.1027    raeburn  11393:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11394:     }
                   11395:     my (%allfiles,%codebase,$output,$content);
                   11396:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  11397:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  11398:         if (wantarray) {
                   11399:             return ('',0,0); 
                   11400:         } else {
                   11401:             return;
                   11402:         }
                   11403:     }
                   11404:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11405:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11406:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11407:             if (wantarray) {
                   11408:                 return ('',0,0);
                   11409:             } else {
                   11410:                 return;
                   11411:             }
                   11412:         } 
1.987     raeburn  11413:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11414:         if ($content eq '-1') {
                   11415:             if (wantarray) {
                   11416:                 return ('',0,0);
                   11417:             } else {
                   11418:                 return;
                   11419:             }
                   11420:         }
1.987     raeburn  11421:     } else {
1.1071    raeburn  11422:         unless ($container =~ /^\Q$dir_root\E/) {
                   11423:             if (wantarray) {
                   11424:                 return ('',0,0);
                   11425:             } else {
                   11426:                 return;
                   11427:             }
                   11428:         } 
1.987     raeburn  11429:         if (open(my $fh,"<$container")) {
                   11430:             $content = join('', <$fh>);
                   11431:             close($fh);
                   11432:         } else {
1.1071    raeburn  11433:             if (wantarray) {
                   11434:                 return ('',0,0);
                   11435:             } else {
                   11436:                 return;
                   11437:             }
1.987     raeburn  11438:         }
                   11439:     }
                   11440:     my ($count,$codebasecount) = (0,0);
                   11441:     my $mm = new File::MMagic;
                   11442:     my $mime_type = $mm->checktype_contents($content);
                   11443:     if ($mime_type eq 'text/html') {
                   11444:         my $parse_result = 
                   11445:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11446:                                                     \%codebase,\$content);
                   11447:         if ($parse_result eq 'ok') {
                   11448:             foreach my $i (@changes) {
                   11449:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11450:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11451:                 if ($allfiles{$ref}) {
                   11452:                     my $newname =  $orig;
                   11453:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11454:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11455:                     if ($attrib_regexp =~ /:/) {
                   11456:                         $attrib_regexp =~ s/\:/|/g;
                   11457:                     }
                   11458:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11459:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11460:                         $count += $numchg;
1.1075.2.35  raeburn  11461:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  11462:                         delete($allfiles{$ref});
1.987     raeburn  11463:                     }
                   11464:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11465:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11466:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11467:                         $codebasecount ++;
                   11468:                     }
                   11469:                 }
                   11470:             }
1.1075.2.35  raeburn  11471:             my $skiprewrites;
1.987     raeburn  11472:             if ($count || $codebasecount) {
                   11473:                 my $saveresult;
1.1071    raeburn  11474:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11475:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11476:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11477:                     if ($url eq $container) {
                   11478:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11479:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11480:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11481:                                             $fname.'</span>').'</p>';
1.987     raeburn  11482:                     } else {
                   11483:                          $output = '<p class="LC_error">'.
                   11484:                                    &mt('Error: update failed for: [_1].',
                   11485:                                    '<span class="LC_filename">'.
                   11486:                                    $container.'</span>').'</p>';
                   11487:                     }
1.1075.2.35  raeburn  11488:                     if ($context eq 'syllabus') {
                   11489:                         unless ($saveresult eq 'ok') {
                   11490:                             $skiprewrites = 1;
                   11491:                         }
                   11492:                     }
1.987     raeburn  11493:                 } else {
                   11494:                     if (open(my $fh,">$container")) {
                   11495:                         print $fh $content;
                   11496:                         close($fh);
                   11497:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11498:                                   $count,'<span class="LC_filename">'.
                   11499:                                   $container.'</span>').'</p>';
1.661     raeburn  11500:                     } else {
1.987     raeburn  11501:                          $output = '<p class="LC_error">'.
                   11502:                                    &mt('Error: could not update [_1].',
                   11503:                                    '<span class="LC_filename">'.
                   11504:                                    $container.'</span>').'</p>';
1.661     raeburn  11505:                     }
                   11506:                 }
                   11507:             }
1.1075.2.35  raeburn  11508:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11509:                 my ($actionurl,$state);
                   11510:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11511:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11512:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11513:                                               \%codebase,
                   11514:                                               {'context' => 'rewrites',
                   11515:                                                'ignore_remote_references' => 1,});
                   11516:                 if (ref($mapping) eq 'HASH') {
                   11517:                     my $rewrites = 0;
                   11518:                     foreach my $key (keys(%{$mapping})) {
                   11519:                         next if ($key =~ m{^https?://});
                   11520:                         my $ref = $mapping->{$key};
                   11521:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11522:                         my $attrib;
                   11523:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11524:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11525:                         }
                   11526:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11527:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11528:                             $rewrites += $numchg;
                   11529:                         }
                   11530:                     }
                   11531:                     if ($rewrites) {
                   11532:                         my $saveresult;
                   11533:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11534:                         if ($url eq $container) {
                   11535:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11536:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11537:                                             $count,'<span class="LC_filename">'.
                   11538:                                             $fname.'</span>').'</p>';
                   11539:                         } else {
                   11540:                             $output .= '<p class="LC_error">'.
                   11541:                                        &mt('Error: could not update links in [_1].',
                   11542:                                        '<span class="LC_filename">'.
                   11543:                                        $container.'</span>').'</p>';
                   11544: 
                   11545:                         }
                   11546:                     }
                   11547:                 }
                   11548:             }
1.987     raeburn  11549:         } else {
                   11550:             &logthis('Failed to parse '.$container.
                   11551:                      ' to modify references: '.$parse_result);
1.661     raeburn  11552:         }
                   11553:     }
1.1071    raeburn  11554:     if (wantarray) {
                   11555:         return ($output,$count,$codebasecount);
                   11556:     } else {
                   11557:         return $output;
                   11558:     }
1.661     raeburn  11559: }
                   11560: 
                   11561: sub check_for_existing {
                   11562:     my ($path,$fname,$element) = @_;
                   11563:     my ($state,$msg);
                   11564:     if (-d $path.'/'.$fname) {
                   11565:         $state = 'exists';
                   11566:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11567:     } elsif (-e $path.'/'.$fname) {
                   11568:         $state = 'exists';
                   11569:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11570:     }
                   11571:     if ($state eq 'exists') {
                   11572:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11573:     }
                   11574:     return ($state,$msg);
                   11575: }
                   11576: 
                   11577: sub check_for_upload {
                   11578:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11579:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11580:     my $filesize = length($env{'form.'.$element});
                   11581:     if (!$filesize) {
                   11582:         my $msg = '<span class="LC_error">'.
                   11583:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11584:                       '<span class="LC_filename">'.$fname.'</span>',
                   11585:                       $filesize).'<br />'.
1.1007    raeburn  11586:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11587:                   '</span>';
                   11588:         return ('zero_bytes',$msg);
                   11589:     }
                   11590:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11591:     my $getpropath = 1;
1.1021    raeburn  11592:     my ($dirlistref,$listerror) =
                   11593:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11594:     my $found_file = 0;
                   11595:     my $locked_file = 0;
1.991     raeburn  11596:     my @lockers;
                   11597:     my $navmap;
                   11598:     if ($env{'request.course.id'}) {
                   11599:         $navmap = Apache::lonnavmaps::navmap->new();
                   11600:     }
1.1021    raeburn  11601:     if (ref($dirlistref) eq 'ARRAY') {
                   11602:         foreach my $line (@{$dirlistref}) {
                   11603:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11604:             if ($file_name eq $fname){
                   11605:                 $file_name = $path.$file_name;
                   11606:                 if ($group ne '') {
                   11607:                     $file_name = $group.$file_name;
                   11608:                 }
                   11609:                 $found_file = 1;
                   11610:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11611:                     foreach my $lock (@lockers) {
                   11612:                         if (ref($lock) eq 'ARRAY') {
                   11613:                             my ($symb,$crsid) = @{$lock};
                   11614:                             if ($crsid eq $env{'request.course.id'}) {
                   11615:                                 if (ref($navmap)) {
                   11616:                                     my $res = $navmap->getBySymb($symb);
                   11617:                                     foreach my $part (@{$res->parts()}) { 
                   11618:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11619:                                         unless (($slot_status == $res->RESERVED) ||
                   11620:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11621:                                             $locked_file = 1;
                   11622:                                         }
1.991     raeburn  11623:                                     }
1.1021    raeburn  11624:                                 } else {
                   11625:                                     $locked_file = 1;
1.991     raeburn  11626:                                 }
                   11627:                             } else {
                   11628:                                 $locked_file = 1;
                   11629:                             }
                   11630:                         }
1.1021    raeburn  11631:                    }
                   11632:                 } else {
                   11633:                     my @info = split(/\&/,$rest);
                   11634:                     my $currsize = $info[6]/1000;
                   11635:                     if ($currsize < $filesize) {
                   11636:                         my $extra = $filesize - $currsize;
                   11637:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  11638:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11639:                                       &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  11640:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11641:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11642:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11643:                             return ('will_exceed_quota',$msg);
                   11644:                         }
1.984     raeburn  11645:                     }
                   11646:                 }
1.661     raeburn  11647:             }
                   11648:         }
                   11649:     }
                   11650:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  11651:         my $msg = '<p class="LC_warning">'.
                   11652:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   11653:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11654:         return ('will_exceed_quota',$msg);
                   11655:     } elsif ($found_file) {
                   11656:         if ($locked_file) {
1.1075.2.69  raeburn  11657:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11658:             $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  11659:             $msg .= '</p>';
1.661     raeburn  11660:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11661:             return ('file_locked',$msg);
                   11662:         } else {
1.1075.2.69  raeburn  11663:             my $msg = '<p class="LC_error">';
1.984     raeburn  11664:             $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  11665:             $msg .= '</p>';
1.984     raeburn  11666:             return ('existingfile',$msg);
1.661     raeburn  11667:         }
                   11668:     }
                   11669: }
                   11670: 
1.987     raeburn  11671: sub check_for_traversal {
                   11672:     my ($path,$url,$toplevel) = @_;
                   11673:     my @parts=split(/\//,$path);
                   11674:     my $cleanpath;
                   11675:     my $fullpath = $url;
                   11676:     for (my $i=0;$i<@parts;$i++) {
                   11677:         next if ($parts[$i] eq '.');
                   11678:         if ($parts[$i] eq '..') {
                   11679:             $fullpath =~ s{([^/]+/)$}{};
                   11680:         } else {
                   11681:             $fullpath .= $parts[$i].'/';
                   11682:         }
                   11683:     }
                   11684:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11685:         $cleanpath = $1;
                   11686:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11687:         my $curr_toprel = $1;
                   11688:         my @parts = split(/\//,$curr_toprel);
                   11689:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11690:         my @urlparts = split(/\//,$url_toprel);
                   11691:         my $doubledots;
                   11692:         my $startdiff = -1;
                   11693:         for (my $i=0; $i<@urlparts; $i++) {
                   11694:             if ($startdiff == -1) {
                   11695:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11696:                     $startdiff = $i;
                   11697:                     $doubledots .= '../';
                   11698:                 }
                   11699:             } else {
                   11700:                 $doubledots .= '../';
                   11701:             }
                   11702:         }
                   11703:         if ($startdiff > -1) {
                   11704:             $cleanpath = $doubledots;
                   11705:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11706:                 $cleanpath .= $parts[$i].'/';
                   11707:             }
                   11708:         }
                   11709:     }
                   11710:     $cleanpath =~ s{(/)$}{};
                   11711:     return $cleanpath;
                   11712: }
1.31      albertel 11713: 
1.1053    raeburn  11714: sub is_archive_file {
                   11715:     my ($mimetype) = @_;
                   11716:     if (($mimetype eq 'application/octet-stream') ||
                   11717:         ($mimetype eq 'application/x-stuffit') ||
                   11718:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11719:         return 1;
                   11720:     }
                   11721:     return;
                   11722: }
                   11723: 
                   11724: sub decompress_form {
1.1065    raeburn  11725:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11726:     my %lt = &Apache::lonlocal::texthash (
                   11727:         this => 'This file is an archive file.',
1.1067    raeburn  11728:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11729:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11730:         youm => 'You may wish to extract its contents.',
                   11731:         extr => 'Extract contents',
1.1067    raeburn  11732:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11733:         proa => 'Process automatically?',
1.1053    raeburn  11734:         yes  => 'Yes',
                   11735:         no   => 'No',
1.1067    raeburn  11736:         fold => 'Title for folder containing movie',
                   11737:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11738:     );
1.1065    raeburn  11739:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11740:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11741:     my $info = &list_archive_contents($fileloc,\@paths);
                   11742:     if (@paths) {
                   11743:         foreach my $path (@paths) {
                   11744:             $path =~ s{^/}{};
1.1067    raeburn  11745:             if ($path =~ m{^([^/]+)/$}) {
                   11746:                 $topdir = $1;
                   11747:             }
1.1065    raeburn  11748:             if ($path =~ m{^([^/]+)/}) {
                   11749:                 $toplevel{$1} = $path;
                   11750:             } else {
                   11751:                 $toplevel{$path} = $path;
                   11752:             }
                   11753:         }
                   11754:     }
1.1067    raeburn  11755:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  11756:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11757:                         "$topdir/media/",
                   11758:                         "$topdir/media/$topdir.mp4",
                   11759:                         "$topdir/media/FirstFrame.png",
                   11760:                         "$topdir/media/player.swf",
                   11761:                         "$topdir/media/swfobject.js",
                   11762:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  11763:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  11764:                          "$topdir/$topdir.mp4",
                   11765:                          "$topdir/$topdir\_config.xml",
                   11766:                          "$topdir/$topdir\_controller.swf",
                   11767:                          "$topdir/$topdir\_embed.css",
                   11768:                          "$topdir/$topdir\_First_Frame.png",
                   11769:                          "$topdir/$topdir\_player.html",
                   11770:                          "$topdir/$topdir\_Thumbnails.png",
                   11771:                          "$topdir/playerProductInstall.swf",
                   11772:                          "$topdir/scripts/",
                   11773:                          "$topdir/scripts/config_xml.js",
                   11774:                          "$topdir/scripts/handlebars.js",
                   11775:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11776:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11777:                          "$topdir/scripts/modernizr.js",
                   11778:                          "$topdir/scripts/player-min.js",
                   11779:                          "$topdir/scripts/swfobject.js",
                   11780:                          "$topdir/skins/",
                   11781:                          "$topdir/skins/configuration_express.xml",
                   11782:                          "$topdir/skins/express_show/",
                   11783:                          "$topdir/skins/express_show/player-min.css",
                   11784:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  11785:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   11786:                          "$topdir/$topdir.mp4",
                   11787:                          "$topdir/$topdir\_config.xml",
                   11788:                          "$topdir/$topdir\_controller.swf",
                   11789:                          "$topdir/$topdir\_embed.css",
                   11790:                          "$topdir/$topdir\_First_Frame.png",
                   11791:                          "$topdir/$topdir\_player.html",
                   11792:                          "$topdir/$topdir\_Thumbnails.png",
                   11793:                          "$topdir/playerProductInstall.swf",
                   11794:                          "$topdir/scripts/",
                   11795:                          "$topdir/scripts/config_xml.js",
                   11796:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   11797:                          "$topdir/skins/",
                   11798:                          "$topdir/skins/configuration_express.xml",
                   11799:                          "$topdir/skins/express_show/",
                   11800:                          "$topdir/skins/express_show/spritesheet.min.css",
                   11801:                          "$topdir/skins/express_show/spritesheet.png",
                   11802:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  11803:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11804:         if (@diffs == 0) {
1.1075.2.59  raeburn  11805:             $is_camtasia = 6;
                   11806:         } else {
1.1075.2.81  raeburn  11807:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  11808:             if (@diffs == 0) {
                   11809:                 $is_camtasia = 8;
1.1075.2.81  raeburn  11810:             } else {
                   11811:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   11812:                 if (@diffs == 0) {
                   11813:                     $is_camtasia = 8;
                   11814:                 }
1.1075.2.59  raeburn  11815:             }
1.1067    raeburn  11816:         }
                   11817:     }
                   11818:     my $output;
                   11819:     if ($is_camtasia) {
                   11820:         $output = <<"ENDCAM";
                   11821: <script type="text/javascript" language="Javascript">
                   11822: // <![CDATA[
                   11823: 
                   11824: function camtasiaToggle() {
                   11825:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   11826:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  11827:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  11828:                 document.getElementById('camtasia_titles').style.display='block';
                   11829:             } else {
                   11830:                 document.getElementById('camtasia_titles').style.display='none';
                   11831:             }
                   11832:         }
                   11833:     }
                   11834:     return;
                   11835: }
                   11836: 
                   11837: // ]]>
                   11838: </script>
                   11839: <p>$lt{'camt'}</p>
                   11840: ENDCAM
1.1065    raeburn  11841:     } else {
1.1067    raeburn  11842:         $output = '<p>'.$lt{'this'};
                   11843:         if ($info eq '') {
                   11844:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   11845:         } else {
                   11846:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   11847:                        '<div><pre>'.$info.'</pre></div>';
                   11848:         }
1.1065    raeburn  11849:     }
1.1067    raeburn  11850:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  11851:     my $duplicates;
                   11852:     my $num = 0;
                   11853:     if (ref($dirlist) eq 'ARRAY') {
                   11854:         foreach my $item (@{$dirlist}) {
                   11855:             if (ref($item) eq 'ARRAY') {
                   11856:                 if (exists($toplevel{$item->[0]})) {
                   11857:                     $duplicates .= 
                   11858:                         &start_data_table_row().
                   11859:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11860:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   11861:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11862:                         'value="1" />'.&mt('Yes').'</label>'.
                   11863:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   11864:                         '<td>'.$item->[0].'</td>';
                   11865:                     if ($item->[2]) {
                   11866:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   11867:                     } else {
                   11868:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   11869:                     }
                   11870:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   11871:                                    '<td>'.
                   11872:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   11873:                                    '</td>'.
                   11874:                                    &end_data_table_row();
                   11875:                     $num ++;
                   11876:                 }
                   11877:             }
                   11878:         }
                   11879:     }
                   11880:     my $itemcount;
                   11881:     if (@paths > 0) {
                   11882:         $itemcount = scalar(@paths);
                   11883:     } else {
                   11884:         $itemcount = 1;
                   11885:     }
1.1067    raeburn  11886:     if ($is_camtasia) {
                   11887:         $output .= $lt{'auto'}.'<br />'.
                   11888:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  11889:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  11890:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   11891:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   11892:                    $lt{'no'}.'</label></span><br />'.
                   11893:                    '<div id="camtasia_titles" style="display:block">'.
                   11894:                    &Apache::lonhtmlcommon::start_pick_box().
                   11895:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   11896:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   11897:                    &Apache::lonhtmlcommon::row_closure().
                   11898:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   11899:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   11900:                    &Apache::lonhtmlcommon::row_closure(1).
                   11901:                    &Apache::lonhtmlcommon::end_pick_box().
                   11902:                    '</div>';
                   11903:     }
1.1065    raeburn  11904:     $output .= 
                   11905:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  11906:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   11907:         "\n";
1.1065    raeburn  11908:     if ($duplicates ne '') {
                   11909:         $output .= '<p><span class="LC_warning">'.
                   11910:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   11911:                    &start_data_table().
                   11912:                    &start_data_table_header_row().
                   11913:                    '<th>'.&mt('Overwrite?').'</th>'.
                   11914:                    '<th>'.&mt('Name').'</th>'.
                   11915:                    '<th>'.&mt('Type').'</th>'.
                   11916:                    '<th>'.&mt('Size').'</th>'.
                   11917:                    '<th>'.&mt('Last modified').'</th>'.
                   11918:                    &end_data_table_header_row().
                   11919:                    $duplicates.
                   11920:                    &end_data_table().
                   11921:                    '</p>';
                   11922:     }
1.1067    raeburn  11923:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  11924:     if (ref($hiddenelements) eq 'HASH') {
                   11925:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   11926:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   11927:         }
                   11928:     }
                   11929:     $output .= <<"END";
1.1067    raeburn  11930: <br />
1.1053    raeburn  11931: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   11932: </form>
                   11933: $noextract
                   11934: END
                   11935:     return $output;
                   11936: }
                   11937: 
1.1065    raeburn  11938: sub decompression_utility {
                   11939:     my ($program) = @_;
                   11940:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   11941:     my $location;
                   11942:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   11943:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   11944:                          '/usr/sbin/') {
                   11945:             if (-x $dir.$program) {
                   11946:                 $location = $dir.$program;
                   11947:                 last;
                   11948:             }
                   11949:         }
                   11950:     }
                   11951:     return $location;
                   11952: }
                   11953: 
                   11954: sub list_archive_contents {
                   11955:     my ($file,$pathsref) = @_;
                   11956:     my (@cmd,$output);
                   11957:     my $needsregexp;
                   11958:     if ($file =~ /\.zip$/) {
                   11959:         @cmd = (&decompression_utility('unzip'),"-l");
                   11960:         $needsregexp = 1;
                   11961:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   11962:              ($file =~ /\.tgz$/)) {
                   11963:         @cmd = (&decompression_utility('tar'),"-ztf");
                   11964:     } elsif ($file =~ /\.tar\.bz2$/) {
                   11965:         @cmd = (&decompression_utility('tar'),"-jtf");
                   11966:     } elsif ($file =~ m|\.tar$|) {
                   11967:         @cmd = (&decompression_utility('tar'),"-tf");
                   11968:     }
                   11969:     if (@cmd) {
                   11970:         undef($!);
                   11971:         undef($@);
                   11972:         if (open(my $fh,"-|", @cmd, $file)) {
                   11973:             while (my $line = <$fh>) {
                   11974:                 $output .= $line;
                   11975:                 chomp($line);
                   11976:                 my $item;
                   11977:                 if ($needsregexp) {
                   11978:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   11979:                 } else {
                   11980:                     $item = $line;
                   11981:                 }
                   11982:                 if ($item ne '') {
                   11983:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   11984:                         push(@{$pathsref},$item);
                   11985:                     } 
                   11986:                 }
                   11987:             }
                   11988:             close($fh);
                   11989:         }
                   11990:     }
                   11991:     return $output;
                   11992: }
                   11993: 
1.1053    raeburn  11994: sub decompress_uploaded_file {
                   11995:     my ($file,$dir) = @_;
                   11996:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   11997:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   11998:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   11999:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12000:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12001:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12002:     my $decompressed = $env{'cgi.decompressed'};
                   12003:     &Apache::lonnet::delenv('cgi.file');
                   12004:     &Apache::lonnet::delenv('cgi.dir');
                   12005:     &Apache::lonnet::delenv('cgi.decompressed');
                   12006:     return ($decompressed,$result);
                   12007: }
                   12008: 
1.1055    raeburn  12009: sub process_decompression {
                   12010:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   12011:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  12012:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  12013:         $error = &mt('Filename not a supported archive file type.').
                   12014:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12015:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12016:     } else {
                   12017:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12018:         if ($docuhome eq 'no_host') {
                   12019:             $error = &mt('Could not determine home server for course.');
                   12020:         } else {
                   12021:             my @ids=&Apache::lonnet::current_machine_ids();
                   12022:             my $currdir = "$dir_root/$destination";
                   12023:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12024:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12025:                        "$dir_root/$destination";
                   12026:             } else {
                   12027:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12028:                        "$dir_root/$docudom/$docuname/$destination";
                   12029:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12030:                     $error = &mt('Archive file not found.');
                   12031:                 }
                   12032:             }
1.1065    raeburn  12033:             my (@to_overwrite,@to_skip);
                   12034:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12035:                 my $total = $env{'form.archive_overwrite_total'};
                   12036:                 for (my $i=0; $i<$total; $i++) {
                   12037:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12038:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12039:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12040:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12041:                     }
                   12042:                 }
                   12043:             }
                   12044:             my $numskip = scalar(@to_skip);
                   12045:             if (($numskip > 0) && 
                   12046:                 ($numskip == $env{'form.archive_itemcount'})) {
                   12047:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12048:             } elsif ($dir eq '') {
1.1055    raeburn  12049:                 $error = &mt('Directory containing archive file unavailable.');
                   12050:             } elsif (!$error) {
1.1065    raeburn  12051:                 my ($decompressed,$display);
                   12052:                 if ($numskip > 0) {
                   12053:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12054:                     mkdir("$dir/$tempdir",0755);
                   12055:                     system("mv $dir/$file $dir/$tempdir/$file");
                   12056:                     ($decompressed,$display) = 
                   12057:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   12058:                     foreach my $item (@to_skip) {
                   12059:                         if (($item ne '') && ($item !~ /\.\./)) {
                   12060:                             if (-f "$dir/$tempdir/$item") { 
                   12061:                                 unlink("$dir/$tempdir/$item");
                   12062:                             } elsif (-d "$dir/$tempdir/$item") {
                   12063:                                 system("rm -rf $dir/$tempdir/$item");
                   12064:                             }
                   12065:                         }
                   12066:                     }
                   12067:                     system("mv $dir/$tempdir/* $dir");
                   12068:                     rmdir("$dir/$tempdir");   
                   12069:                 } else {
                   12070:                     ($decompressed,$display) = 
                   12071:                         &decompress_uploaded_file($file,$dir);
                   12072:                 }
1.1055    raeburn  12073:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12074:                     $output = '<p class="LC_info">'.
                   12075:                               &mt('Files extracted successfully from archive.').
                   12076:                               '</p>'."\n";
1.1055    raeburn  12077:                     my ($warning,$result,@contents);
                   12078:                     my ($newdirlistref,$newlisterror) =
                   12079:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12080:                                                  $docuname,1);
                   12081:                     my (%is_dir,%changes,@newitems);
                   12082:                     my $dirptr = 16384;
1.1065    raeburn  12083:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12084:                         foreach my $dir_line (@{$newdirlistref}) {
                   12085:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  12086:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   12087:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  12088:                                 push(@newitems,$item);
                   12089:                                 if ($dirptr&$testdir) {
                   12090:                                     $is_dir{$item} = 1;
                   12091:                                 }
                   12092:                                 $changes{$item} = 1;
                   12093:                             }
                   12094:                         }
                   12095:                     }
                   12096:                     if (keys(%changes) > 0) {
                   12097:                         foreach my $item (sort(@newitems)) {
                   12098:                             if ($changes{$item}) {
                   12099:                                 push(@contents,$item);
                   12100:                             }
                   12101:                         }
                   12102:                     }
                   12103:                     if (@contents > 0) {
1.1067    raeburn  12104:                         my $wantform;
                   12105:                         unless ($env{'form.autoextract_camtasia'}) {
                   12106:                             $wantform = 1;
                   12107:                         }
1.1056    raeburn  12108:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12109:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12110:                                                                 $currdir,\%is_dir,
                   12111:                                                                 \%children,\%parent,
1.1056    raeburn  12112:                                                                 \@contents,\%dirorder,
                   12113:                                                                 \%titles,$wantform);
1.1055    raeburn  12114:                         if ($datatable ne '') {
                   12115:                             $output .= &archive_options_form('decompressed',$datatable,
                   12116:                                                              $count,$hiddenelem);
1.1065    raeburn  12117:                             my $startcount = 6;
1.1055    raeburn  12118:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12119:                                                            \%titles,\%children);
1.1055    raeburn  12120:                         }
1.1067    raeburn  12121:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  12122:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12123:                             my %displayed;
                   12124:                             my $total = 1;
                   12125:                             $env{'form.archive_directory'} = [];
                   12126:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12127:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12128:                                 $path =~ s{/$}{};
                   12129:                                 my $item;
                   12130:                                 if ($path ne '') {
                   12131:                                     $item = "$path/$titles{$i}";
                   12132:                                 } else {
                   12133:                                     $item = $titles{$i};
                   12134:                                 }
                   12135:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12136:                                 if ($item eq $contents[0]) {
                   12137:                                     push(@{$env{'form.archive_directory'}},$i);
                   12138:                                     $env{'form.archive_'.$i} = 'display';
                   12139:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12140:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  12141:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12142:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  12143:                                     $env{'form.archive_'.$i} = 'display';
                   12144:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12145:                                     $displayed{'web'} = $i;
                   12146:                                 } else {
1.1075.2.59  raeburn  12147:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12148:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12149:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12150:                                         push(@{$env{'form.archive_directory'}},$i);
                   12151:                                     }
                   12152:                                     $env{'form.archive_'.$i} = 'dependency';
                   12153:                                 }
                   12154:                                 $total ++;
                   12155:                             }
                   12156:                             for (my $i=1; $i<$total; $i++) {
                   12157:                                 next if ($i == $displayed{'web'});
                   12158:                                 next if ($i == $displayed{'folder'});
                   12159:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12160:                             }
                   12161:                             $env{'form.phase'} = 'decompress_cleanup';
                   12162:                             $env{'form.archivedelete'} = 1;
                   12163:                             $env{'form.archive_count'} = $total-1;
                   12164:                             $output .=
                   12165:                                 &process_extracted_files('coursedocs',$docudom,
                   12166:                                                          $docuname,$destination,
                   12167:                                                          $dir_root,$hiddenelem);
                   12168:                         }
1.1055    raeburn  12169:                     } else {
                   12170:                         $warning = &mt('No new items extracted from archive file.');
                   12171:                     }
                   12172:                 } else {
                   12173:                     $output = $display;
                   12174:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12175:                 }
                   12176:             }
                   12177:         }
                   12178:     }
                   12179:     if ($error) {
                   12180:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12181:                    $error.'</p>'."\n";
                   12182:     }
                   12183:     if ($warning) {
                   12184:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12185:     }
                   12186:     return $output;
                   12187: }
                   12188: 
                   12189: sub get_extracted {
1.1056    raeburn  12190:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12191:         $titles,$wantform) = @_;
1.1055    raeburn  12192:     my $count = 0;
                   12193:     my $depth = 0;
                   12194:     my $datatable;
1.1056    raeburn  12195:     my @hierarchy;
1.1055    raeburn  12196:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12197:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12198:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12199:     foreach my $item (@{$contents}) {
                   12200:         $count ++;
1.1056    raeburn  12201:         @{$dirorder->{$count}} = @hierarchy;
                   12202:         $titles->{$count} = $item;
1.1055    raeburn  12203:         &archive_hierarchy($depth,$count,$parent,$children);
                   12204:         if ($wantform) {
                   12205:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12206:                                        $currdir,$depth,$count);
                   12207:         }
                   12208:         if ($is_dir->{$item}) {
                   12209:             $depth ++;
1.1056    raeburn  12210:             push(@hierarchy,$count);
                   12211:             $parent->{$depth} = $count;
1.1055    raeburn  12212:             $datatable .=
                   12213:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12214:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12215:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12216:             $depth --;
1.1056    raeburn  12217:             pop(@hierarchy);
1.1055    raeburn  12218:         }
                   12219:     }
                   12220:     return ($count,$datatable);
                   12221: }
                   12222: 
                   12223: sub recurse_extracted_archive {
1.1056    raeburn  12224:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12225:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12226:     my $result='';
1.1056    raeburn  12227:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12228:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12229:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12230:         return $result;
                   12231:     }
                   12232:     my $dirptr = 16384;
                   12233:     my ($newdirlistref,$newlisterror) =
                   12234:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12235:     if (ref($newdirlistref) eq 'ARRAY') {
                   12236:         foreach my $dir_line (@{$newdirlistref}) {
                   12237:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12238:             unless ($item =~ /^\.+$/) {
                   12239:                 $$count ++;
1.1056    raeburn  12240:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12241:                 $titles->{$$count} = $item;
1.1055    raeburn  12242:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12243: 
1.1055    raeburn  12244:                 my $is_dir;
                   12245:                 if ($dirptr&$testdir) {
                   12246:                     $is_dir = 1;
                   12247:                 }
                   12248:                 if ($wantform) {
                   12249:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12250:                 }
                   12251:                 if ($is_dir) {
                   12252:                     $$depth ++;
1.1056    raeburn  12253:                     push(@{$hierarchy},$$count);
                   12254:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12255:                     $result .=
                   12256:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12257:                                                    $docuname,$depth,$count,
1.1056    raeburn  12258:                                                    $hierarchy,$dirorder,$children,
                   12259:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12260:                     $$depth --;
1.1056    raeburn  12261:                     pop(@{$hierarchy});
1.1055    raeburn  12262:                 }
                   12263:             }
                   12264:         }
                   12265:     }
                   12266:     return $result;
                   12267: }
                   12268: 
                   12269: sub archive_hierarchy {
                   12270:     my ($depth,$count,$parent,$children) =@_;
                   12271:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12272:         if (exists($parent->{$depth})) {
                   12273:              $children->{$parent->{$depth}} .= $count.':';
                   12274:         }
                   12275:     }
                   12276:     return;
                   12277: }
                   12278: 
                   12279: sub archive_row {
                   12280:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12281:     my ($name) = ($item =~ m{([^/]+)$});
                   12282:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12283:                                        'display'    => 'Add as file',
1.1055    raeburn  12284:                                        'dependency' => 'Include as dependency',
                   12285:                                        'discard'    => 'Discard',
                   12286:                                       );
                   12287:     if ($is_dir) {
1.1059    raeburn  12288:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12289:     }
1.1056    raeburn  12290:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12291:     my $offset = 0;
1.1055    raeburn  12292:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12293:         $offset ++;
1.1065    raeburn  12294:         if ($action ne 'display') {
                   12295:             $offset ++;
                   12296:         }  
1.1055    raeburn  12297:         $output .= '<td><span class="LC_nobreak">'.
                   12298:                    '<label><input type="radio" name="archive_'.$count.
                   12299:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12300:         my $text = $choices{$action};
                   12301:         if ($is_dir) {
                   12302:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12303:             if ($action eq 'display') {
1.1059    raeburn  12304:                 $text = &mt('Add as folder');
1.1055    raeburn  12305:             }
1.1056    raeburn  12306:         } else {
                   12307:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12308: 
                   12309:         }
                   12310:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12311:         if ($action eq 'dependency') {
                   12312:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12313:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12314:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12315:                        '<option value=""></option>'."\n".
                   12316:                        '</select>'."\n".
                   12317:                        '</div>';
1.1059    raeburn  12318:         } elsif ($action eq 'display') {
                   12319:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12320:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12321:                        '</div>';
1.1055    raeburn  12322:         }
1.1056    raeburn  12323:         $output .= '</td>';
1.1055    raeburn  12324:     }
                   12325:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12326:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12327:     for (my $i=0; $i<$depth; $i++) {
                   12328:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12329:     }
                   12330:     if ($is_dir) {
                   12331:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12332:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12333:     } else {
                   12334:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12335:     }
                   12336:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12337:                &end_data_table_row();
                   12338:     return $output;
                   12339: }
                   12340: 
                   12341: sub archive_options_form {
1.1065    raeburn  12342:     my ($form,$display,$count,$hiddenelem) = @_;
                   12343:     my %lt = &Apache::lonlocal::texthash(
                   12344:                perm => 'Permanently remove archive file?',
                   12345:                hows => 'How should each extracted item be incorporated in the course?',
                   12346:                cont => 'Content actions for all',
                   12347:                addf => 'Add as folder/file',
                   12348:                incd => 'Include as dependency for a displayed file',
                   12349:                disc => 'Discard',
                   12350:                no   => 'No',
                   12351:                yes  => 'Yes',
                   12352:                save => 'Save',
                   12353:     );
                   12354:     my $output = <<"END";
                   12355: <form name="$form" method="post" action="">
                   12356: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12357: <label>
                   12358:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12359: </label>
                   12360: &nbsp;
                   12361: <label>
                   12362:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12363: </span>
                   12364: </p>
                   12365: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12366: <br />$lt{'hows'}
                   12367: <div class="LC_columnSection">
                   12368:   <fieldset>
                   12369:     <legend>$lt{'cont'}</legend>
                   12370:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12371:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12372:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12373:   </fieldset>
                   12374: </div>
                   12375: END
                   12376:     return $output.
1.1055    raeburn  12377:            &start_data_table()."\n".
1.1065    raeburn  12378:            $display."\n".
1.1055    raeburn  12379:            &end_data_table()."\n".
                   12380:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12381:            $hiddenelem.
1.1065    raeburn  12382:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12383:            '</form>';
                   12384: }
                   12385: 
                   12386: sub archive_javascript {
1.1056    raeburn  12387:     my ($startcount,$numitems,$titles,$children) = @_;
                   12388:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12389:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12390:     my $scripttag = <<START;
                   12391: <script type="text/javascript">
                   12392: // <![CDATA[
                   12393: 
                   12394: function checkAll(form,prefix) {
                   12395:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12396:     for (var i=0; i < form.elements.length; i++) {
                   12397:         var id = form.elements[i].id;
                   12398:         if ((id != '') && (id != undefined)) {
                   12399:             if (idstr.test(id)) {
                   12400:                 if (form.elements[i].type == 'radio') {
                   12401:                     form.elements[i].checked = true;
1.1056    raeburn  12402:                     var nostart = i-$startcount;
1.1059    raeburn  12403:                     var offset = nostart%7;
                   12404:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12405:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12406:                 }
                   12407:             }
                   12408:         }
                   12409:     }
                   12410: }
                   12411: 
                   12412: function propagateCheck(form,count) {
                   12413:     if (count > 0) {
1.1059    raeburn  12414:         var startelement = $startcount + ((count-1) * 7);
                   12415:         for (var j=1; j<6; j++) {
                   12416:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12417:                 var item = startelement + j; 
                   12418:                 if (form.elements[item].type == 'radio') {
                   12419:                     if (form.elements[item].checked) {
                   12420:                         containerCheck(form,count,j);
                   12421:                         break;
                   12422:                     }
1.1055    raeburn  12423:                 }
                   12424:             }
                   12425:         }
                   12426:     }
                   12427: }
                   12428: 
                   12429: numitems = $numitems
1.1056    raeburn  12430: var titles = new Array(numitems);
                   12431: var parents = new Array(numitems);
1.1055    raeburn  12432: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12433:     parents[i] = new Array;
1.1055    raeburn  12434: }
1.1059    raeburn  12435: var maintitle = '$maintitle';
1.1055    raeburn  12436: 
                   12437: START
                   12438: 
1.1056    raeburn  12439:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12440:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12441:         for (my $i=0; $i<@contents; $i ++) {
                   12442:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12443:         }
                   12444:     }
                   12445: 
1.1056    raeburn  12446:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12447:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12448:     }
                   12449: 
1.1055    raeburn  12450:     $scripttag .= <<END;
                   12451: 
                   12452: function containerCheck(form,count,offset) {
                   12453:     if (count > 0) {
1.1056    raeburn  12454:         dependencyCheck(form,count,offset);
1.1059    raeburn  12455:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12456:         form.elements[item].checked = true;
                   12457:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12458:             if (parents[count].length > 0) {
                   12459:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12460:                     containerCheck(form,parents[count][j],offset);
                   12461:                 }
                   12462:             }
                   12463:         }
                   12464:     }
                   12465: }
                   12466: 
                   12467: function dependencyCheck(form,count,offset) {
                   12468:     if (count > 0) {
1.1059    raeburn  12469:         var chosen = (offset+$startcount)+7*(count-1);
                   12470:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12471:         var currtype = form.elements[depitem].type;
                   12472:         if (form.elements[chosen].value == 'dependency') {
                   12473:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12474:             form.elements[depitem].options.length = 0;
                   12475:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  12476:             for (var i=1; i<=numitems; i++) {
                   12477:                 if (i == count) {
                   12478:                     continue;
                   12479:                 }
1.1059    raeburn  12480:                 var startelement = $startcount + (i-1) * 7;
                   12481:                 for (var j=1; j<6; j++) {
                   12482:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12483:                         var item = startelement + j;
                   12484:                         if (form.elements[item].type == 'radio') {
                   12485:                             if (form.elements[item].checked) {
                   12486:                                 if (form.elements[item].value == 'display') {
                   12487:                                     var n = form.elements[depitem].options.length;
                   12488:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12489:                                 }
                   12490:                             }
                   12491:                         }
                   12492:                     }
                   12493:                 }
                   12494:             }
                   12495:         } else {
                   12496:             document.getElementById('arc_depon_'+count).style.display='none';
                   12497:             form.elements[depitem].options.length = 0;
                   12498:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12499:         }
1.1059    raeburn  12500:         titleCheck(form,count,offset);
1.1056    raeburn  12501:     }
                   12502: }
                   12503: 
                   12504: function propagateSelect(form,count,offset) {
                   12505:     if (count > 0) {
1.1065    raeburn  12506:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12507:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12508:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12509:             if (parents[count].length > 0) {
                   12510:                 for (var j=0; j<parents[count].length; j++) {
                   12511:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12512:                 }
                   12513:             }
                   12514:         }
                   12515:     }
                   12516: }
1.1056    raeburn  12517: 
                   12518: function containerSelect(form,count,offset,picked) {
                   12519:     if (count > 0) {
1.1065    raeburn  12520:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12521:         if (form.elements[item].type == 'radio') {
                   12522:             if (form.elements[item].value == 'dependency') {
                   12523:                 if (form.elements[item+1].type == 'select-one') {
                   12524:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12525:                         if (form.elements[item+1].options[i].value == picked) {
                   12526:                             form.elements[item+1].selectedIndex = i;
                   12527:                             break;
                   12528:                         }
                   12529:                     }
                   12530:                 }
                   12531:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12532:                     if (parents[count].length > 0) {
                   12533:                         for (var j=0; j<parents[count].length; j++) {
                   12534:                             containerSelect(form,parents[count][j],offset,picked);
                   12535:                         }
                   12536:                     }
                   12537:                 }
                   12538:             }
                   12539:         }
                   12540:     }
                   12541: }
                   12542: 
1.1059    raeburn  12543: function titleCheck(form,count,offset) {
                   12544:     if (count > 0) {
                   12545:         var chosen = (offset+$startcount)+7*(count-1);
                   12546:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12547:         var currtype = form.elements[depitem].type;
                   12548:         if (form.elements[chosen].value == 'display') {
                   12549:             document.getElementById('arc_title_'+count).style.display='block';
                   12550:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12551:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12552:             }
                   12553:         } else {
                   12554:             document.getElementById('arc_title_'+count).style.display='none';
                   12555:             if (currtype == 'text') { 
                   12556:                 document.getElementById('archive_title_'+count).value='';
                   12557:             }
                   12558:         }
                   12559:     }
                   12560:     return;
                   12561: }
                   12562: 
1.1055    raeburn  12563: // ]]>
                   12564: </script>
                   12565: END
                   12566:     return $scripttag;
                   12567: }
                   12568: 
                   12569: sub process_extracted_files {
1.1067    raeburn  12570:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12571:     my $numitems = $env{'form.archive_count'};
                   12572:     return unless ($numitems);
                   12573:     my @ids=&Apache::lonnet::current_machine_ids();
                   12574:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12575:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12576:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12577:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12578:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12579:         $pathtocheck = "$dir_root/$destination";
                   12580:         $dir = $dir_root;
                   12581:         $ishome = 1;
                   12582:     } else {
                   12583:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12584:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   12585:         $dir = "$dir_root/$docudom/$docuname";    
                   12586:     }
                   12587:     my $currdir = "$dir_root/$destination";
                   12588:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12589:     if ($env{'form.folderpath'}) {
                   12590:         my @items = split('&',$env{'form.folderpath'});
                   12591:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  12592:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12593:             $containers{'0'}='page';
                   12594:         } else {
                   12595:             $containers{'0'}='sequence';
                   12596:         }
1.1055    raeburn  12597:     }
                   12598:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12599:     if ($numitems) {
                   12600:         for (my $i=1; $i<=$numitems; $i++) {
                   12601:             my $path = $env{'form.archive_content_'.$i};
                   12602:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12603:                 my $item = $1;
                   12604:                 $toplevelitems{$item} = $i;
                   12605:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12606:                     $is_dir{$item} = 1;
                   12607:                 }
                   12608:             }
                   12609:         }
                   12610:     }
1.1067    raeburn  12611:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12612:     if (keys(%toplevelitems) > 0) {
                   12613:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12614:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12615:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12616:     }
1.1066    raeburn  12617:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12618:     if ($numitems) {
                   12619:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  12620:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12621:             my $path = $env{'form.archive_content_'.$i};
                   12622:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12623:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12624:                     if ($prefix ne '' && $path ne '') {
                   12625:                         if (-e $prefix.$path) {
1.1066    raeburn  12626:                             if ((@archdirs > 0) && 
                   12627:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12628:                                 $todeletedir{$prefix.$path} = 1;
                   12629:                             } else {
                   12630:                                 $todelete{$prefix.$path} = 1;
                   12631:                             }
1.1055    raeburn  12632:                         }
                   12633:                     }
                   12634:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12635:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12636:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12637:                     $docstitle = $env{'form.archive_title_'.$i};
                   12638:                     if ($docstitle eq '') {
                   12639:                         $docstitle = $title;
                   12640:                     }
1.1055    raeburn  12641:                     $outer = 0;
1.1056    raeburn  12642:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12643:                         if (@{$dirorder{$i}} > 0) {
                   12644:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12645:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12646:                                     $outer = $item;
                   12647:                                     last;
                   12648:                                 }
                   12649:                             }
                   12650:                         }
                   12651:                     }
                   12652:                     my ($errtext,$fatal) = 
                   12653:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12654:                                                '/'.$folders{$outer}.'.'.
                   12655:                                                $containers{$outer});
                   12656:                     next if ($fatal);
                   12657:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12658:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12659:                             $mapinner{$i} = time;
1.1055    raeburn  12660:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12661:                             $containers{$i} = 'sequence';
                   12662:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12663:                                       $folders{$i}.'.'.$containers{$i};
                   12664:                             my $newidx = &LONCAPA::map::getresidx();
                   12665:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12666:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12667:                             push(@LONCAPA::map::order,$newidx);
                   12668:                             my ($outtext,$errtext) =
                   12669:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12670:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12671:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12672:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12673:                             unless ($errtext) {
                   12674:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   12675:                             }
1.1055    raeburn  12676:                         }
                   12677:                     } else {
                   12678:                         if ($context eq 'coursedocs') {
                   12679:                             my $newidx=&LONCAPA::map::getresidx();
                   12680:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12681:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12682:                                       $title;
                   12683:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12684:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   12685:                             }
                   12686:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12687:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12688:                             }
                   12689:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12690:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  12691:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  12692:                                 unless ($ishome) {
                   12693:                                     my $fetch = "$newdest{$i}/$title";
                   12694:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   12695:                                     $prompttofetch{$fetch} = 1;
                   12696:                                 }
1.1055    raeburn  12697:                             }
                   12698:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12699:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12700:                             push(@LONCAPA::map::order, $newidx);
                   12701:                             my ($outtext,$errtext)=
                   12702:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12703:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12704:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  12705:                             unless ($errtext) {
                   12706:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12707:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   12708:                                 }
                   12709:                             }
1.1055    raeburn  12710:                         }
                   12711:                     }
1.1075.2.11  raeburn  12712:                 }
                   12713:             } else {
                   12714:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
                   12715:             }
                   12716:         }
                   12717:         for (my $i=1; $i<=$numitems; $i++) {
                   12718:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12719:             my $path = $env{'form.archive_content_'.$i};
                   12720:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12721:                 my ($title) = ($path =~ m{/([^/]+)$});
                   12722:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   12723:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   12724:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12725:                         my ($itemidx,$fullpath,$relpath);
                   12726:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   12727:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  12728:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  12729:                                 if ($dirorder{$i}->[$j] eq $container) {
                   12730:                                     $itemidx = $j;
1.1056    raeburn  12731:                                 }
                   12732:                             }
1.1075.2.11  raeburn  12733:                         }
                   12734:                         if ($itemidx eq '') {
                   12735:                             $itemidx =  0;
                   12736:                         }
                   12737:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   12738:                             if ($mapinner{$referrer{$i}}) {
                   12739:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   12740:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12741:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12742:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12743:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12744:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12745:                                             if (!-e $fullpath) {
                   12746:                                                 mkdir($fullpath,0755);
1.1056    raeburn  12747:                                             }
                   12748:                                         }
1.1075.2.11  raeburn  12749:                                     } else {
                   12750:                                         last;
1.1056    raeburn  12751:                                     }
1.1075.2.11  raeburn  12752:                                 }
                   12753:                             }
                   12754:                         } elsif ($newdest{$referrer{$i}}) {
                   12755:                             $fullpath = $newdest{$referrer{$i}};
                   12756:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12757:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   12758:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   12759:                                     last;
                   12760:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12761:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12762:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12763:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12764:                                         if (!-e $fullpath) {
                   12765:                                             mkdir($fullpath,0755);
1.1056    raeburn  12766:                                         }
                   12767:                                     }
1.1075.2.11  raeburn  12768:                                 } else {
                   12769:                                     last;
1.1056    raeburn  12770:                                 }
1.1075.2.11  raeburn  12771:                             }
                   12772:                         }
                   12773:                         if ($fullpath ne '') {
                   12774:                             if (-e "$prefix$path") {
                   12775:                                 system("mv $prefix$path $fullpath/$title");
                   12776:                             }
                   12777:                             if (-e "$fullpath/$title") {
                   12778:                                 my $showpath;
                   12779:                                 if ($relpath ne '') {
                   12780:                                     $showpath = "$relpath/$title";
                   12781:                                 } else {
                   12782:                                     $showpath = "/$title";
1.1056    raeburn  12783:                                 }
1.1075.2.11  raeburn  12784:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   12785:                             }
                   12786:                             unless ($ishome) {
                   12787:                                 my $fetch = "$fullpath/$title";
                   12788:                                 $fetch =~ s/^\Q$prefix$dir\E//;
                   12789:                                 $prompttofetch{$fetch} = 1;
1.1055    raeburn  12790:                             }
                   12791:                         }
                   12792:                     }
1.1075.2.11  raeburn  12793:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   12794:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   12795:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  12796:                 }
                   12797:             } else {
1.1075.2.11  raeburn  12798:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
1.1055    raeburn  12799:             }
                   12800:         }
                   12801:         if (keys(%todelete)) {
                   12802:             foreach my $key (keys(%todelete)) {
                   12803:                 unlink($key);
1.1066    raeburn  12804:             }
                   12805:         }
                   12806:         if (keys(%todeletedir)) {
                   12807:             foreach my $key (keys(%todeletedir)) {
                   12808:                 rmdir($key);
                   12809:             }
                   12810:         }
                   12811:         foreach my $dir (sort(keys(%is_dir))) {
                   12812:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   12813:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  12814:             }
                   12815:         }
1.1067    raeburn  12816:         if ($result ne '') {
                   12817:             $output .= '<ul>'."\n".
                   12818:                        $result."\n".
                   12819:                        '</ul>';
                   12820:         }
                   12821:         unless ($ishome) {
                   12822:             my $replicationfail;
                   12823:             foreach my $item (keys(%prompttofetch)) {
                   12824:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   12825:                 unless ($fetchresult eq 'ok') {
                   12826:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   12827:                 }
                   12828:             }
                   12829:             if ($replicationfail) {
                   12830:                 $output .= '<p class="LC_error">'.
                   12831:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   12832:                            $replicationfail.
                   12833:                            '</ul></p>';
                   12834:             }
                   12835:         }
1.1055    raeburn  12836:     } else {
                   12837:         $warning = &mt('No items found in archive.');
                   12838:     }
                   12839:     if ($error) {
                   12840:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12841:                    $error.'</p>'."\n";
                   12842:     }
                   12843:     if ($warning) {
                   12844:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12845:     }
                   12846:     return $output;
                   12847: }
                   12848: 
1.1066    raeburn  12849: sub cleanup_empty_dirs {
                   12850:     my ($path) = @_;
                   12851:     if (($path ne '') && (-d $path)) {
                   12852:         if (opendir(my $dirh,$path)) {
                   12853:             my @dircontents = grep(!/^\./,readdir($dirh));
                   12854:             my $numitems = 0;
                   12855:             foreach my $item (@dircontents) {
                   12856:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  12857:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  12858:                     if (-e "$path/$item") {
                   12859:                         $numitems ++;
                   12860:                     }
                   12861:                 } else {
                   12862:                     $numitems ++;
                   12863:                 }
                   12864:             }
                   12865:             if ($numitems == 0) {
                   12866:                 rmdir($path);
                   12867:             }
                   12868:             closedir($dirh);
                   12869:         }
                   12870:     }
                   12871:     return;
                   12872: }
                   12873: 
1.41      ng       12874: =pod
1.45      matthew  12875: 
1.1075.2.56  raeburn  12876: =item * &get_folder_hierarchy()
1.1068    raeburn  12877: 
                   12878: Provides hierarchy of names of folders/sub-folders containing the current
                   12879: item,
                   12880: 
                   12881: Inputs: 3
                   12882:      - $navmap - navmaps object
                   12883: 
                   12884:      - $map - url for map (either the trigger itself, or map containing
                   12885:                            the resource, which is the trigger).
                   12886: 
                   12887:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   12888: 
                   12889: Outputs: 1 @pathitems - array of folder/subfolder names.
                   12890: 
                   12891: =cut
                   12892: 
                   12893: sub get_folder_hierarchy {
                   12894:     my ($navmap,$map,$showitem) = @_;
                   12895:     my @pathitems;
                   12896:     if (ref($navmap)) {
                   12897:         my $mapres = $navmap->getResourceByUrl($map);
                   12898:         if (ref($mapres)) {
                   12899:             my $pcslist = $mapres->map_hierarchy();
                   12900:             if ($pcslist ne '') {
                   12901:                 my @pcs = split(/,/,$pcslist);
                   12902:                 foreach my $pc (@pcs) {
                   12903:                     if ($pc == 1) {
1.1075.2.38  raeburn  12904:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  12905:                     } else {
                   12906:                         my $res = $navmap->getByMapPc($pc);
                   12907:                         if (ref($res)) {
                   12908:                             my $title = $res->compTitle();
                   12909:                             $title =~ s/\W+/_/g;
                   12910:                             if ($title ne '') {
                   12911:                                 push(@pathitems,$title);
                   12912:                             }
                   12913:                         }
                   12914:                     }
                   12915:                 }
                   12916:             }
1.1071    raeburn  12917:             if ($showitem) {
                   12918:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  12919:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  12920:                 } else {
                   12921:                     my $maptitle = $mapres->compTitle();
                   12922:                     $maptitle =~ s/\W+/_/g;
                   12923:                     if ($maptitle ne '') {
                   12924:                         push(@pathitems,$maptitle);
                   12925:                     }
1.1068    raeburn  12926:                 }
                   12927:             }
                   12928:         }
                   12929:     }
                   12930:     return @pathitems;
                   12931: }
                   12932: 
                   12933: =pod
                   12934: 
1.1015    raeburn  12935: =item * &get_turnedin_filepath()
                   12936: 
                   12937: Determines path in a user's portfolio file for storage of files uploaded
                   12938: to a specific essayresponse or dropbox item.
                   12939: 
                   12940: Inputs: 3 required + 1 optional.
                   12941: $symb is symb for resource, $uname and $udom are for current user (required).
                   12942: $caller is optional (can be "submission", if routine is called when storing
                   12943: an upoaded file when "Submit Answer" button was pressed).
                   12944: 
                   12945: Returns array containing $path and $multiresp. 
                   12946: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   12947: than one file upload item.  Callers of routine should append partid as a 
                   12948: subdirectory to $path in cases where $multiresp is 1.
                   12949: 
                   12950: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   12951: 
                   12952: =cut
                   12953: 
                   12954: sub get_turnedin_filepath {
                   12955:     my ($symb,$uname,$udom,$caller) = @_;
                   12956:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   12957:     my $turnindir;
                   12958:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   12959:     $turnindir = $userhash{'turnindir'};
                   12960:     my ($path,$multiresp);
                   12961:     if ($turnindir eq '') {
                   12962:         if ($caller eq 'submission') {
                   12963:             $turnindir = &mt('turned in');
                   12964:             $turnindir =~ s/\W+/_/g;
                   12965:             my %newhash = (
                   12966:                             'turnindir' => $turnindir,
                   12967:                           );
                   12968:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   12969:         }
                   12970:     }
                   12971:     if ($turnindir ne '') {
                   12972:         $path = '/'.$turnindir.'/';
                   12973:         my ($multipart,$turnin,@pathitems);
                   12974:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12975:         if (defined($navmap)) {
                   12976:             my $mapres = $navmap->getResourceByUrl($map);
                   12977:             if (ref($mapres)) {
                   12978:                 my $pcslist = $mapres->map_hierarchy();
                   12979:                 if ($pcslist ne '') {
                   12980:                     foreach my $pc (split(/,/,$pcslist)) {
                   12981:                         my $res = $navmap->getByMapPc($pc);
                   12982:                         if (ref($res)) {
                   12983:                             my $title = $res->compTitle();
                   12984:                             $title =~ s/\W+/_/g;
                   12985:                             if ($title ne '') {
1.1075.2.48  raeburn  12986:                                 if (($pc > 1) && (length($title) > 12)) {
                   12987:                                     $title = substr($title,0,12);
                   12988:                                 }
1.1015    raeburn  12989:                                 push(@pathitems,$title);
                   12990:                             }
                   12991:                         }
                   12992:                     }
                   12993:                 }
                   12994:                 my $maptitle = $mapres->compTitle();
                   12995:                 $maptitle =~ s/\W+/_/g;
                   12996:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  12997:                     if (length($maptitle) > 12) {
                   12998:                         $maptitle = substr($maptitle,0,12);
                   12999:                     }
1.1015    raeburn  13000:                     push(@pathitems,$maptitle);
                   13001:                 }
                   13002:                 unless ($env{'request.state'} eq 'construct') {
                   13003:                     my $res = $navmap->getBySymb($symb);
                   13004:                     if (ref($res)) {
                   13005:                         my $partlist = $res->parts();
                   13006:                         my $totaluploads = 0;
                   13007:                         if (ref($partlist) eq 'ARRAY') {
                   13008:                             foreach my $part (@{$partlist}) {
                   13009:                                 my @types = $res->responseType($part);
                   13010:                                 my @ids = $res->responseIds($part);
                   13011:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13012:                                     if ($types[$i] eq 'essay') {
                   13013:                                         my $partid = $part.'_'.$ids[$i];
                   13014:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13015:                                             $totaluploads ++;
                   13016:                                         }
                   13017:                                     }
                   13018:                                 }
                   13019:                             }
                   13020:                             if ($totaluploads > 1) {
                   13021:                                 $multiresp = 1;
                   13022:                             }
                   13023:                         }
                   13024:                     }
                   13025:                 }
                   13026:             } else {
                   13027:                 return;
                   13028:             }
                   13029:         } else {
                   13030:             return;
                   13031:         }
                   13032:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13033:         $restitle =~ s/\W+/_/g;
                   13034:         if ($restitle eq '') {
                   13035:             $restitle = ($resurl =~ m{/[^/]+$});
                   13036:             if ($restitle eq '') {
                   13037:                 $restitle = time;
                   13038:             }
                   13039:         }
1.1075.2.48  raeburn  13040:         if (length($restitle) > 12) {
                   13041:             $restitle = substr($restitle,0,12);
                   13042:         }
1.1015    raeburn  13043:         push(@pathitems,$restitle);
                   13044:         $path .= join('/',@pathitems);
                   13045:     }
                   13046:     return ($path,$multiresp);
                   13047: }
                   13048: 
                   13049: =pod
                   13050: 
1.464     albertel 13051: =back
1.41      ng       13052: 
1.112     bowersj2 13053: =head1 CSV Upload/Handling functions
1.38      albertel 13054: 
1.41      ng       13055: =over 4
                   13056: 
1.648     raeburn  13057: =item * &upfile_store($r)
1.41      ng       13058: 
                   13059: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13060: needs $env{'form.upfile'}
1.41      ng       13061: returns $datatoken to be put into hidden field
                   13062: 
                   13063: =cut
1.31      albertel 13064: 
                   13065: sub upfile_store {
                   13066:     my $r=shift;
1.258     albertel 13067:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13068:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13069:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13070:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13071: 
1.258     albertel 13072:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   13073: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 13074:     {
1.158     raeburn  13075:         my $datafile = $r->dir_config('lonDaemons').
                   13076:                            '/tmp/'.$datatoken.'.tmp';
                   13077:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 13078:             print $fh $env{'form.upfile'};
1.158     raeburn  13079:             close($fh);
                   13080:         }
1.31      albertel 13081:     }
                   13082:     return $datatoken;
                   13083: }
                   13084: 
1.56      matthew  13085: =pod
                   13086: 
1.648     raeburn  13087: =item * &load_tmp_file($r)
1.41      ng       13088: 
                   13089: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 13090: needs $env{'form.datatoken'},
                   13091: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13092: 
                   13093: =cut
1.31      albertel 13094: 
                   13095: sub load_tmp_file {
                   13096:     my $r=shift;
                   13097:     my @studentdata=();
                   13098:     {
1.158     raeburn  13099:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 13100:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  13101:         if ( open(my $fh,"<$studentfile") ) {
                   13102:             @studentdata=<$fh>;
                   13103:             close($fh);
                   13104:         }
1.31      albertel 13105:     }
1.258     albertel 13106:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13107: }
                   13108: 
1.56      matthew  13109: =pod
                   13110: 
1.648     raeburn  13111: =item * &upfile_record_sep()
1.41      ng       13112: 
                   13113: Separate uploaded file into records
                   13114: returns array of records,
1.258     albertel 13115: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13116: 
                   13117: =cut
1.31      albertel 13118: 
                   13119: sub upfile_record_sep {
1.258     albertel 13120:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13121:     } else {
1.248     albertel 13122: 	my @records;
1.258     albertel 13123: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13124: 	    if ($line=~/^\s*$/) { next; }
                   13125: 	    push(@records,$line);
                   13126: 	}
                   13127: 	return @records;
1.31      albertel 13128:     }
                   13129: }
                   13130: 
1.56      matthew  13131: =pod
                   13132: 
1.648     raeburn  13133: =item * &record_sep($record)
1.41      ng       13134: 
1.258     albertel 13135: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13136: 
                   13137: =cut
                   13138: 
1.263     www      13139: sub takeleft {
                   13140:     my $index=shift;
                   13141:     return substr('0000'.$index,-4,4);
                   13142: }
                   13143: 
1.31      albertel 13144: sub record_sep {
                   13145:     my $record=shift;
                   13146:     my %components=();
1.258     albertel 13147:     if ($env{'form.upfiletype'} eq 'xml') {
                   13148:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13149:         my $i=0;
1.356     albertel 13150:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13151:             $field=~s/^(\"|\')//;
                   13152:             $field=~s/(\"|\')$//;
1.263     www      13153:             $components{&takeleft($i)}=$field;
1.31      albertel 13154:             $i++;
                   13155:         }
1.258     albertel 13156:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13157:         my $i=0;
1.356     albertel 13158:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13159:             $field=~s/^(\"|\')//;
                   13160:             $field=~s/(\"|\')$//;
1.263     www      13161:             $components{&takeleft($i)}=$field;
1.31      albertel 13162:             $i++;
                   13163:         }
                   13164:     } else {
1.561     www      13165:         my $separator=',';
1.480     banghart 13166:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13167:             $separator=';';
1.480     banghart 13168:         }
1.31      albertel 13169:         my $i=0;
1.561     www      13170: # the character we are looking for to indicate the end of a quote or a record 
                   13171:         my $looking_for=$separator;
                   13172: # do not add the characters to the fields
                   13173:         my $ignore=0;
                   13174: # we just encountered a separator (or the beginning of the record)
                   13175:         my $just_found_separator=1;
                   13176: # store the field we are working on here
                   13177:         my $field='';
                   13178: # work our way through all characters in record
                   13179:         foreach my $character ($record=~/(.)/g) {
                   13180:             if ($character eq $looking_for) {
                   13181:                if ($character ne $separator) {
                   13182: # Found the end of a quote, again looking for separator
                   13183:                   $looking_for=$separator;
                   13184:                   $ignore=1;
                   13185:                } else {
                   13186: # Found a separator, store away what we got
                   13187:                   $components{&takeleft($i)}=$field;
                   13188: 	          $i++;
                   13189:                   $just_found_separator=1;
                   13190:                   $ignore=0;
                   13191:                   $field='';
                   13192:                }
                   13193:                next;
                   13194:             }
                   13195: # single or double quotation marks after a separator indicate beginning of a quote
                   13196: # we are now looking for the end of the quote and need to ignore separators
                   13197:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13198:                $looking_for=$character;
                   13199:                next;
                   13200:             }
                   13201: # ignore would be true after we reached the end of a quote
                   13202:             if ($ignore) { next; }
                   13203:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13204:             $field.=$character;
                   13205:             $just_found_separator=0; 
1.31      albertel 13206:         }
1.561     www      13207: # catch the very last entry, since we never encountered the separator
                   13208:         $components{&takeleft($i)}=$field;
1.31      albertel 13209:     }
                   13210:     return %components;
                   13211: }
                   13212: 
1.144     matthew  13213: ######################################################
                   13214: ######################################################
                   13215: 
1.56      matthew  13216: =pod
                   13217: 
1.648     raeburn  13218: =item * &upfile_select_html()
1.41      ng       13219: 
1.144     matthew  13220: Return HTML code to select a file from the users machine and specify 
                   13221: the file type.
1.41      ng       13222: 
                   13223: =cut
                   13224: 
1.144     matthew  13225: ######################################################
                   13226: ######################################################
1.31      albertel 13227: sub upfile_select_html {
1.144     matthew  13228:     my %Types = (
                   13229:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13230:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13231:                  space => &mt('Space separated'),
                   13232:                  tab   => &mt('Tabulator separated'),
                   13233: #                 xml   => &mt('HTML/XML'),
                   13234:                  );
                   13235:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13236:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13237:     foreach my $type (sort(keys(%Types))) {
                   13238:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13239:     }
                   13240:     $Str .= "</select>\n";
                   13241:     return $Str;
1.31      albertel 13242: }
                   13243: 
1.301     albertel 13244: sub get_samples {
                   13245:     my ($records,$toget) = @_;
                   13246:     my @samples=({});
                   13247:     my $got=0;
                   13248:     foreach my $rec (@$records) {
                   13249: 	my %temp = &record_sep($rec);
                   13250: 	if (! grep(/\S/, values(%temp))) { next; }
                   13251: 	if (%temp) {
                   13252: 	    $samples[$got]=\%temp;
                   13253: 	    $got++;
                   13254: 	    if ($got == $toget) { last; }
                   13255: 	}
                   13256:     }
                   13257:     return \@samples;
                   13258: }
                   13259: 
1.144     matthew  13260: ######################################################
                   13261: ######################################################
                   13262: 
1.56      matthew  13263: =pod
                   13264: 
1.648     raeburn  13265: =item * &csv_print_samples($r,$records)
1.41      ng       13266: 
                   13267: Prints a table of sample values from each column uploaded $r is an
                   13268: Apache Request ref, $records is an arrayref from
                   13269: &Apache::loncommon::upfile_record_sep
                   13270: 
                   13271: =cut
                   13272: 
1.144     matthew  13273: ######################################################
                   13274: ######################################################
1.31      albertel 13275: sub csv_print_samples {
                   13276:     my ($r,$records) = @_;
1.662     bisitz   13277:     my $samples = &get_samples($records,5);
1.301     albertel 13278: 
1.594     raeburn  13279:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13280:               &start_data_table_header_row());
1.356     albertel 13281:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13282:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13283:     $r->print(&end_data_table_header_row());
1.301     albertel 13284:     foreach my $hash (@$samples) {
1.594     raeburn  13285: 	$r->print(&start_data_table_row());
1.356     albertel 13286: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13287: 	    $r->print('<td>');
1.356     albertel 13288: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13289: 	    $r->print('</td>');
                   13290: 	}
1.594     raeburn  13291: 	$r->print(&end_data_table_row());
1.31      albertel 13292:     }
1.594     raeburn  13293:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13294: }
                   13295: 
1.144     matthew  13296: ######################################################
                   13297: ######################################################
                   13298: 
1.56      matthew  13299: =pod
                   13300: 
1.648     raeburn  13301: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13302: 
                   13303: Prints a table to create associations between values and table columns.
1.144     matthew  13304: 
1.41      ng       13305: $r is an Apache Request ref,
                   13306: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13307: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13308: 
                   13309: =cut
                   13310: 
1.144     matthew  13311: ######################################################
                   13312: ######################################################
1.31      albertel 13313: sub csv_print_select_table {
                   13314:     my ($r,$records,$d) = @_;
1.301     albertel 13315:     my $i=0;
                   13316:     my $samples = &get_samples($records,1);
1.144     matthew  13317:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13318: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13319:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13320:               '<th>'.&mt('Column').'</th>'.
                   13321:               &end_data_table_header_row()."\n");
1.356     albertel 13322:     foreach my $array_ref (@$d) {
                   13323: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13324: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13325: 
1.875     bisitz   13326: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13327: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13328: 	$r->print('<option value="none"></option>');
1.356     albertel 13329: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13330: 	    $r->print('<option value="'.$sample.'"'.
                   13331:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13332:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13333: 	}
1.594     raeburn  13334: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13335: 	$i++;
                   13336:     }
1.594     raeburn  13337:     $r->print(&end_data_table());
1.31      albertel 13338:     $i--;
                   13339:     return $i;
                   13340: }
1.56      matthew  13341: 
1.144     matthew  13342: ######################################################
                   13343: ######################################################
                   13344: 
1.56      matthew  13345: =pod
1.31      albertel 13346: 
1.648     raeburn  13347: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13348: 
                   13349: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13350: 
                   13351: $r is an Apache Request ref,
                   13352: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13353: $d is an array of 2 element arrays (internal name, displayed name)
                   13354: 
                   13355: =cut
                   13356: 
1.144     matthew  13357: ######################################################
                   13358: ######################################################
1.31      albertel 13359: sub csv_samples_select_table {
                   13360:     my ($r,$records,$d) = @_;
                   13361:     my $i=0;
1.144     matthew  13362:     #
1.662     bisitz   13363:     my $max_samples = 5;
                   13364:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13365:     $r->print(&start_data_table().
                   13366:               &start_data_table_header_row().'<th>'.
                   13367:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13368:               &end_data_table_header_row());
1.301     albertel 13369: 
                   13370:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13371: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13372: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13373: 	foreach my $option (@$d) {
                   13374: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13375: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13376:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13377:                       $display.'</option>');
1.31      albertel 13378: 	}
                   13379: 	$r->print('</select></td><td>');
1.662     bisitz   13380: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13381: 	    if (defined($samples->[$line]{$key})) { 
                   13382: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13383: 	    }
                   13384: 	}
1.594     raeburn  13385: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13386: 	$i++;
                   13387:     }
1.594     raeburn  13388:     $r->print(&end_data_table());
1.31      albertel 13389:     $i--;
                   13390:     return($i);
1.115     matthew  13391: }
                   13392: 
1.144     matthew  13393: ######################################################
                   13394: ######################################################
                   13395: 
1.115     matthew  13396: =pod
                   13397: 
1.648     raeburn  13398: =item * &clean_excel_name($name)
1.115     matthew  13399: 
                   13400: Returns a replacement for $name which does not contain any illegal characters.
                   13401: 
                   13402: =cut
                   13403: 
1.144     matthew  13404: ######################################################
                   13405: ######################################################
1.115     matthew  13406: sub clean_excel_name {
                   13407:     my ($name) = @_;
                   13408:     $name =~ s/[:\*\?\/\\]//g;
                   13409:     if (length($name) > 31) {
                   13410:         $name = substr($name,0,31);
                   13411:     }
                   13412:     return $name;
1.25      albertel 13413: }
1.84      albertel 13414: 
1.85      albertel 13415: =pod
                   13416: 
1.648     raeburn  13417: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13418: 
                   13419: Returns either 1 or undef
                   13420: 
                   13421: 1 if the part is to be hidden, undef if it is to be shown
                   13422: 
                   13423: Arguments are:
                   13424: 
                   13425: $id the id of the part to be checked
                   13426: $symb, optional the symb of the resource to check
                   13427: $udom, optional the domain of the user to check for
                   13428: $uname, optional the username of the user to check for
                   13429: 
                   13430: =cut
1.84      albertel 13431: 
                   13432: sub check_if_partid_hidden {
                   13433:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13434:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13435: 					 $symb,$udom,$uname);
1.141     albertel 13436:     my $truth=1;
                   13437:     #if the string starts with !, then the list is the list to show not hide
                   13438:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13439:     my @hiddenlist=split(/,/,$hiddenparts);
                   13440:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13441: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13442:     }
1.141     albertel 13443:     return !$truth;
1.84      albertel 13444: }
1.127     matthew  13445: 
1.138     matthew  13446: 
                   13447: ############################################################
                   13448: ############################################################
                   13449: 
                   13450: =pod
                   13451: 
1.157     matthew  13452: =back 
                   13453: 
1.138     matthew  13454: =head1 cgi-bin script and graphing routines
                   13455: 
1.157     matthew  13456: =over 4
                   13457: 
1.648     raeburn  13458: =item * &get_cgi_id()
1.138     matthew  13459: 
                   13460: Inputs: none
                   13461: 
                   13462: Returns an id which can be used to pass environment variables
                   13463: to various cgi-bin scripts.  These environment variables will
                   13464: be removed from the users environment after a given time by
                   13465: the routine &Apache::lonnet::transfer_profile_to_env.
                   13466: 
                   13467: =cut
                   13468: 
                   13469: ############################################################
                   13470: ############################################################
1.152     albertel 13471: my $uniq=0;
1.136     matthew  13472: sub get_cgi_id {
1.154     albertel 13473:     $uniq=($uniq+1)%100000;
1.280     albertel 13474:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13475: }
                   13476: 
1.127     matthew  13477: ############################################################
                   13478: ############################################################
                   13479: 
                   13480: =pod
                   13481: 
1.648     raeburn  13482: =item * &DrawBarGraph()
1.127     matthew  13483: 
1.138     matthew  13484: Facilitates the plotting of data in a (stacked) bar graph.
                   13485: Puts plot definition data into the users environment in order for 
                   13486: graph.png to plot it.  Returns an <img> tag for the plot.
                   13487: The bars on the plot are labeled '1','2',...,'n'.
                   13488: 
                   13489: Inputs:
                   13490: 
                   13491: =over 4
                   13492: 
                   13493: =item $Title: string, the title of the plot
                   13494: 
                   13495: =item $xlabel: string, text describing the X-axis of the plot
                   13496: 
                   13497: =item $ylabel: string, text describing the Y-axis of the plot
                   13498: 
                   13499: =item $Max: scalar, the maximum Y value to use in the plot
                   13500: If $Max is < any data point, the graph will not be rendered.
                   13501: 
1.140     matthew  13502: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13503: they are plotted.  If undefined, default values will be used.
                   13504: 
1.178     matthew  13505: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13506: 
1.138     matthew  13507: =item @Values: An array of array references.  Each array reference holds data
                   13508: to be plotted in a stacked bar chart.
                   13509: 
1.239     matthew  13510: =item If the final element of @Values is a hash reference the key/value
                   13511: pairs will be added to the graph definition.
                   13512: 
1.138     matthew  13513: =back
                   13514: 
                   13515: Returns:
                   13516: 
                   13517: An <img> tag which references graph.png and the appropriate identifying
                   13518: information for the plot.
                   13519: 
1.127     matthew  13520: =cut
                   13521: 
                   13522: ############################################################
                   13523: ############################################################
1.134     matthew  13524: sub DrawBarGraph {
1.178     matthew  13525:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13526:     #
                   13527:     if (! defined($colors)) {
                   13528:         $colors = ['#33ff00', 
                   13529:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13530:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13531:                   ]; 
                   13532:     }
1.228     matthew  13533:     my $extra_settings = {};
                   13534:     if (ref($Values[-1]) eq 'HASH') {
                   13535:         $extra_settings = pop(@Values);
                   13536:     }
1.127     matthew  13537:     #
1.136     matthew  13538:     my $identifier = &get_cgi_id();
                   13539:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13540:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13541:         return '';
                   13542:     }
1.225     matthew  13543:     #
                   13544:     my @Labels;
                   13545:     if (defined($labels)) {
                   13546:         @Labels = @$labels;
                   13547:     } else {
                   13548:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1075.2.119  raeburn  13549:             push(@Labels,$i+1);
1.225     matthew  13550:         }
                   13551:     }
                   13552:     #
1.129     matthew  13553:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13554:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13555:     my %ValuesHash;
                   13556:     my $NumSets=1;
                   13557:     foreach my $array (@Values) {
                   13558:         next if (! ref($array));
1.136     matthew  13559:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13560:             join(',',@$array);
1.129     matthew  13561:     }
1.127     matthew  13562:     #
1.136     matthew  13563:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13564:     if ($NumBars < 3) {
                   13565:         $width = 120+$NumBars*32;
1.220     matthew  13566:         $xskip = 1;
1.225     matthew  13567:         $bar_width = 30;
                   13568:     } elsif ($NumBars < 5) {
                   13569:         $width = 120+$NumBars*20;
                   13570:         $xskip = 1;
                   13571:         $bar_width = 20;
1.220     matthew  13572:     } elsif ($NumBars < 10) {
1.136     matthew  13573:         $width = 120+$NumBars*15;
                   13574:         $xskip = 1;
                   13575:         $bar_width = 15;
                   13576:     } elsif ($NumBars <= 25) {
                   13577:         $width = 120+$NumBars*11;
                   13578:         $xskip = 5;
                   13579:         $bar_width = 8;
                   13580:     } elsif ($NumBars <= 50) {
                   13581:         $width = 120+$NumBars*8;
                   13582:         $xskip = 5;
                   13583:         $bar_width = 4;
                   13584:     } else {
                   13585:         $width = 120+$NumBars*8;
                   13586:         $xskip = 5;
                   13587:         $bar_width = 4;
                   13588:     }
                   13589:     #
1.137     matthew  13590:     $Max = 1 if ($Max < 1);
                   13591:     if ( int($Max) < $Max ) {
                   13592:         $Max++;
                   13593:         $Max = int($Max);
                   13594:     }
1.127     matthew  13595:     $Title  = '' if (! defined($Title));
                   13596:     $xlabel = '' if (! defined($xlabel));
                   13597:     $ylabel = '' if (! defined($ylabel));
1.369     www      13598:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13599:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13600:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13601:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13602:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13603:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13604:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13605:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13606:     $ValuesHash{$id.'.height'}   = $height;
                   13607:     $ValuesHash{$id.'.width'}    = $width;
                   13608:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13609:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13610:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13611:     #
1.228     matthew  13612:     # Deal with other parameters
                   13613:     while (my ($key,$value) = each(%$extra_settings)) {
                   13614:         $ValuesHash{$id.'.'.$key} = $value;
                   13615:     }
                   13616:     #
1.646     raeburn  13617:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13618:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13619: }
                   13620: 
                   13621: ############################################################
                   13622: ############################################################
                   13623: 
                   13624: =pod
                   13625: 
1.648     raeburn  13626: =item * &DrawXYGraph()
1.137     matthew  13627: 
1.138     matthew  13628: Facilitates the plotting of data in an XY graph.
                   13629: Puts plot definition data into the users environment in order for 
                   13630: graph.png to plot it.  Returns an <img> tag for the plot.
                   13631: 
                   13632: Inputs:
                   13633: 
                   13634: =over 4
                   13635: 
                   13636: =item $Title: string, the title of the plot
                   13637: 
                   13638: =item $xlabel: string, text describing the X-axis of the plot
                   13639: 
                   13640: =item $ylabel: string, text describing the Y-axis of the plot
                   13641: 
                   13642: =item $Max: scalar, the maximum Y value to use in the plot
                   13643: If $Max is < any data point, the graph will not be rendered.
                   13644: 
                   13645: =item $colors: Array ref containing the hex color codes for the data to be 
                   13646: plotted in.  If undefined, default values will be used.
                   13647: 
                   13648: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13649: 
                   13650: =item $Ydata: Array ref containing Array refs.  
1.185     www      13651: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13652: 
                   13653: =item %Values: hash indicating or overriding any default values which are 
                   13654: passed to graph.png.  
                   13655: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13656: 
                   13657: =back
                   13658: 
                   13659: Returns:
                   13660: 
                   13661: An <img> tag which references graph.png and the appropriate identifying
                   13662: information for the plot.
                   13663: 
1.137     matthew  13664: =cut
                   13665: 
                   13666: ############################################################
                   13667: ############################################################
                   13668: sub DrawXYGraph {
                   13669:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13670:     #
                   13671:     # Create the identifier for the graph
                   13672:     my $identifier = &get_cgi_id();
                   13673:     my $id = 'cgi.'.$identifier;
                   13674:     #
                   13675:     $Title  = '' if (! defined($Title));
                   13676:     $xlabel = '' if (! defined($xlabel));
                   13677:     $ylabel = '' if (! defined($ylabel));
                   13678:     my %ValuesHash = 
                   13679:         (
1.369     www      13680:          $id.'.title'  => &escape($Title),
                   13681:          $id.'.xlabel' => &escape($xlabel),
                   13682:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13683:          $id.'.y_max_value'=> $Max,
                   13684:          $id.'.labels'     => join(',',@$Xlabels),
                   13685:          $id.'.PlotType'   => 'XY',
                   13686:          );
                   13687:     #
                   13688:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13689:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13690:     }
                   13691:     #
                   13692:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13693:         return '';
                   13694:     }
                   13695:     my $NumSets=1;
1.138     matthew  13696:     foreach my $array (@{$Ydata}){
1.137     matthew  13697:         next if (! ref($array));
                   13698:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13699:     }
1.138     matthew  13700:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  13701:     #
                   13702:     # Deal with other parameters
                   13703:     while (my ($key,$value) = each(%Values)) {
                   13704:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  13705:     }
                   13706:     #
1.646     raeburn  13707:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  13708:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13709: }
                   13710: 
                   13711: ############################################################
                   13712: ############################################################
                   13713: 
                   13714: =pod
                   13715: 
1.648     raeburn  13716: =item * &DrawXYYGraph()
1.138     matthew  13717: 
                   13718: Facilitates the plotting of data in an XY graph with two Y axes.
                   13719: Puts plot definition data into the users environment in order for 
                   13720: graph.png to plot it.  Returns an <img> tag for the plot.
                   13721: 
                   13722: Inputs:
                   13723: 
                   13724: =over 4
                   13725: 
                   13726: =item $Title: string, the title of the plot
                   13727: 
                   13728: =item $xlabel: string, text describing the X-axis of the plot
                   13729: 
                   13730: =item $ylabel: string, text describing the Y-axis of the plot
                   13731: 
                   13732: =item $colors: Array ref containing the hex color codes for the data to be 
                   13733: plotted in.  If undefined, default values will be used.
                   13734: 
                   13735: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13736: 
                   13737: =item $Ydata1: The first data set
                   13738: 
                   13739: =item $Min1: The minimum value of the left Y-axis
                   13740: 
                   13741: =item $Max1: The maximum value of the left Y-axis
                   13742: 
                   13743: =item $Ydata2: The second data set
                   13744: 
                   13745: =item $Min2: The minimum value of the right Y-axis
                   13746: 
                   13747: =item $Max2: The maximum value of the left Y-axis
                   13748: 
                   13749: =item %Values: hash indicating or overriding any default values which are 
                   13750: passed to graph.png.  
                   13751: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13752: 
                   13753: =back
                   13754: 
                   13755: Returns:
                   13756: 
                   13757: An <img> tag which references graph.png and the appropriate identifying
                   13758: information for the plot.
1.136     matthew  13759: 
                   13760: =cut
                   13761: 
                   13762: ############################################################
                   13763: ############################################################
1.137     matthew  13764: sub DrawXYYGraph {
                   13765:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   13766:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  13767:     #
                   13768:     # Create the identifier for the graph
                   13769:     my $identifier = &get_cgi_id();
                   13770:     my $id = 'cgi.'.$identifier;
                   13771:     #
                   13772:     $Title  = '' if (! defined($Title));
                   13773:     $xlabel = '' if (! defined($xlabel));
                   13774:     $ylabel = '' if (! defined($ylabel));
                   13775:     my %ValuesHash = 
                   13776:         (
1.369     www      13777:          $id.'.title'  => &escape($Title),
                   13778:          $id.'.xlabel' => &escape($xlabel),
                   13779:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  13780:          $id.'.labels' => join(',',@$Xlabels),
                   13781:          $id.'.PlotType' => 'XY',
                   13782:          $id.'.NumSets' => 2,
1.137     matthew  13783:          $id.'.two_axes' => 1,
                   13784:          $id.'.y1_max_value' => $Max1,
                   13785:          $id.'.y1_min_value' => $Min1,
                   13786:          $id.'.y2_max_value' => $Max2,
                   13787:          $id.'.y2_min_value' => $Min2,
1.136     matthew  13788:          );
                   13789:     #
1.137     matthew  13790:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13791:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13792:     }
                   13793:     #
                   13794:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   13795:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  13796:         return '';
                   13797:     }
                   13798:     my $NumSets=1;
1.137     matthew  13799:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  13800:         next if (! ref($array));
                   13801:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  13802:     }
                   13803:     #
                   13804:     # Deal with other parameters
                   13805:     while (my ($key,$value) = each(%Values)) {
                   13806:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  13807:     }
                   13808:     #
1.646     raeburn  13809:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 13810:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  13811: }
                   13812: 
                   13813: ############################################################
                   13814: ############################################################
                   13815: 
                   13816: =pod
                   13817: 
1.157     matthew  13818: =back 
                   13819: 
1.139     matthew  13820: =head1 Statistics helper routines?  
                   13821: 
                   13822: Bad place for them but what the hell.
                   13823: 
1.157     matthew  13824: =over 4
                   13825: 
1.648     raeburn  13826: =item * &chartlink()
1.139     matthew  13827: 
                   13828: Returns a link to the chart for a specific student.  
                   13829: 
                   13830: Inputs:
                   13831: 
                   13832: =over 4
                   13833: 
                   13834: =item $linktext: The text of the link
                   13835: 
                   13836: =item $sname: The students username
                   13837: 
                   13838: =item $sdomain: The students domain
                   13839: 
                   13840: =back
                   13841: 
1.157     matthew  13842: =back
                   13843: 
1.139     matthew  13844: =cut
                   13845: 
                   13846: ############################################################
                   13847: ############################################################
                   13848: sub chartlink {
                   13849:     my ($linktext, $sname, $sdomain) = @_;
                   13850:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      13851:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 13852:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  13853:        '">'.$linktext.'</a>';
1.153     matthew  13854: }
                   13855: 
                   13856: #######################################################
                   13857: #######################################################
                   13858: 
                   13859: =pod
                   13860: 
                   13861: =head1 Course Environment Routines
1.157     matthew  13862: 
                   13863: =over 4
1.153     matthew  13864: 
1.648     raeburn  13865: =item * &restore_course_settings()
1.153     matthew  13866: 
1.648     raeburn  13867: =item * &store_course_settings()
1.153     matthew  13868: 
                   13869: Restores/Store indicated form parameters from the course environment.
                   13870: Will not overwrite existing values of the form parameters.
                   13871: 
                   13872: Inputs: 
                   13873: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   13874: 
                   13875: a hash ref describing the data to be stored.  For example:
                   13876:    
                   13877: %Save_Parameters = ('Status' => 'scalar',
                   13878:     'chartoutputmode' => 'scalar',
                   13879:     'chartoutputdata' => 'scalar',
                   13880:     'Section' => 'array',
1.373     raeburn  13881:     'Group' => 'array',
1.153     matthew  13882:     'StudentData' => 'array',
                   13883:     'Maps' => 'array');
                   13884: 
                   13885: Returns: both routines return nothing
                   13886: 
1.631     raeburn  13887: =back
                   13888: 
1.153     matthew  13889: =cut
                   13890: 
                   13891: #######################################################
                   13892: #######################################################
                   13893: sub store_course_settings {
1.496     albertel 13894:     return &store_settings($env{'request.course.id'},@_);
                   13895: }
                   13896: 
                   13897: sub store_settings {
1.153     matthew  13898:     # save to the environment
                   13899:     # appenv the same items, just to be safe
1.300     albertel 13900:     my $udom  = $env{'user.domain'};
                   13901:     my $uname = $env{'user.name'};
1.496     albertel 13902:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13903:     my %SaveHash;
                   13904:     my %AppHash;
                   13905:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 13906:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 13907:         my $envname = 'environment.'.$basename;
1.258     albertel 13908:         if (exists($env{'form.'.$setting})) {
1.153     matthew  13909:             # Save this value away
                   13910:             if ($type eq 'scalar' &&
1.258     albertel 13911:                 (! exists($env{$envname}) || 
                   13912:                  $env{$envname} ne $env{'form.'.$setting})) {
                   13913:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   13914:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  13915:             } elsif ($type eq 'array') {
                   13916:                 my $stored_form;
1.258     albertel 13917:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  13918:                     $stored_form = join(',',
                   13919:                                         map {
1.369     www      13920:                                             &escape($_);
1.258     albertel 13921:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  13922:                 } else {
                   13923:                     $stored_form = 
1.369     www      13924:                         &escape($env{'form.'.$setting});
1.153     matthew  13925:                 }
                   13926:                 # Determine if the array contents are the same.
1.258     albertel 13927:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  13928:                     $SaveHash{$basename} = $stored_form;
                   13929:                     $AppHash{$envname}   = $stored_form;
                   13930:                 }
                   13931:             }
                   13932:         }
                   13933:     }
                   13934:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 13935:                                           $udom,$uname);
1.153     matthew  13936:     if ($put_result !~ /^(ok|delayed)/) {
                   13937:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   13938:                                  'got error:'.$put_result);
                   13939:     }
                   13940:     # Make sure these settings stick around in this session, too
1.646     raeburn  13941:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  13942:     return;
                   13943: }
                   13944: 
                   13945: sub restore_course_settings {
1.499     albertel 13946:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 13947: }
                   13948: 
                   13949: sub restore_settings {
                   13950:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13951:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 13952:         next if (exists($env{'form.'.$setting}));
1.496     albertel 13953:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  13954:             '.'.$setting;
1.258     albertel 13955:         if (exists($env{$envname})) {
1.153     matthew  13956:             if ($type eq 'scalar') {
1.258     albertel 13957:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  13958:             } elsif ($type eq 'array') {
1.258     albertel 13959:                 $env{'form.'.$setting} = [ 
1.153     matthew  13960:                                            map { 
1.369     www      13961:                                                &unescape($_); 
1.258     albertel 13962:                                            } split(',',$env{$envname})
1.153     matthew  13963:                                            ];
                   13964:             }
                   13965:         }
                   13966:     }
1.127     matthew  13967: }
                   13968: 
1.618     raeburn  13969: #######################################################
                   13970: #######################################################
                   13971: 
                   13972: =pod
                   13973: 
                   13974: =head1 Domain E-mail Routines  
                   13975: 
                   13976: =over 4
                   13977: 
1.648     raeburn  13978: =item * &build_recipient_list()
1.618     raeburn  13979: 
1.1075.2.44  raeburn  13980: Build recipient lists for following types of e-mail:
1.766     raeburn  13981: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  13982: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   13983: module change checking, student/employee ID conflict checks, as
                   13984: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   13985: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  13986: 
                   13987: Inputs:
1.1075.2.44  raeburn  13988: defmail (scalar - email address of default recipient),
                   13989: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   13990: requestsmail, updatesmail, or idconflictsmail).
                   13991: 
1.619     raeburn  13992: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  13993: 
                   13994: origmail (scalar - email address of recipient from loncapa.conf,
                   13995: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  13996: 
1.655     raeburn  13997: Returns: comma separated list of addresses to which to send e-mail.
                   13998: 
                   13999: =back
1.618     raeburn  14000: 
                   14001: =cut
                   14002: 
                   14003: ############################################################
                   14004: ############################################################
                   14005: sub build_recipient_list {
1.619     raeburn  14006:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  14007:     my @recipients;
1.1075.2.122  raeburn  14008:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  14009:     my %domconfig =
1.1075.2.122  raeburn  14010:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14011:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14012:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14013:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14014:                 my @contacts = ('adminemail','supportemail');
                   14015:                 foreach my $item (@contacts) {
                   14016:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14017:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14018:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14019:                             push(@recipients,$addr);
                   14020:                         }
1.619     raeburn  14021:                     }
1.1075.2.122  raeburn  14022:                 }
                   14023:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   14024:                 if ($mailing eq 'helpdeskmail') {
                   14025:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   14026:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   14027:                         my @ok_bccs;
                   14028:                         foreach my $bcc (@bccs) {
                   14029:                             $bcc =~ s/^\s+//g;
                   14030:                             $bcc =~ s/\s+$//g;
                   14031:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14032:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14033:                                     push(@ok_bccs,$bcc);
                   14034:                                 }
                   14035:                             }
                   14036:                         }
                   14037:                         if (@ok_bccs > 0) {
                   14038:                             $allbcc = join(', ',@ok_bccs);
                   14039:                         }
                   14040:                     }
                   14041:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  14042:                 }
                   14043:             }
1.766     raeburn  14044:         } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14045:             $lastresort = $origmail;
1.618     raeburn  14046:         }
1.619     raeburn  14047:     } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14048:         $lastresort = $origmail;
                   14049:     }
                   14050: 
                   14051:     if (($mailing eq 'helpdesk') && ($lastresort ne '')) {
                   14052:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   14053:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   14054:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14055:             my %what = (
                   14056:                           perlvar => 1,
                   14057:                        );
                   14058:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   14059:             if ($primary) {
                   14060:                 my $gotaddr;
                   14061:                 my ($result,$returnhash) =
                   14062:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   14063:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   14064:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   14065:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   14066:                         $gotaddr = 1;
                   14067:                     }
                   14068:                 }
                   14069:                 unless ($gotaddr) {
                   14070:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   14071:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   14072:                     unless ($uintdom eq $intdom) {
                   14073:                         my %domconfig =
                   14074:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   14075:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   14076:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   14077:                                 my @contacts = ('adminemail','supportemail');
                   14078:                                 foreach my $item (@contacts) {
                   14079:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   14080:                                         my $addr = $domconfig{'contacts'}{$item};
                   14081:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14082:                                             push(@recipients,$addr);
                   14083:                                         }
                   14084:                                     }
                   14085:                                 }
                   14086:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   14087:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   14088:                                 }
                   14089:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   14090:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   14091:                                     my @ok_bccs;
                   14092:                                     foreach my $bcc (@bccs) {
                   14093:                                         $bcc =~ s/^\s+//g;
                   14094:                                         $bcc =~ s/\s+$//g;
                   14095:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14096:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14097:                                                 push(@ok_bccs,$bcc);
                   14098:                                             }
                   14099:                                         }
                   14100:                                     }
                   14101:                                     if (@ok_bccs > 0) {
                   14102:                                         $allbcc = join(', ',@ok_bccs);
                   14103:                                     }
                   14104:                                 }
                   14105:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   14106:                             }
                   14107:                         }
                   14108:                     }
                   14109:                 }
                   14110:             }
                   14111:         }
1.618     raeburn  14112:     }
1.688     raeburn  14113:     if (defined($defmail)) {
                   14114:         if ($defmail ne '') {
                   14115:             push(@recipients,$defmail);
                   14116:         }
1.618     raeburn  14117:     }
                   14118:     if ($otheremails) {
1.619     raeburn  14119:         my @others;
                   14120:         if ($otheremails =~ /,/) {
                   14121:             @others = split(/,/,$otheremails);
1.618     raeburn  14122:         } else {
1.619     raeburn  14123:             push(@others,$otheremails);
                   14124:         }
                   14125:         foreach my $addr (@others) {
                   14126:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14127:                 push(@recipients,$addr);
                   14128:             }
1.618     raeburn  14129:         }
                   14130:     }
1.1075.2.122  raeburn  14131:     if ($mailing eq 'helpdesk') {
                   14132:         if ((!@recipients) && ($lastresort ne '')) {
                   14133:             push(@recipients,$lastresort);
                   14134:         }
                   14135:     } elsif ($lastresort ne '') {
                   14136:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   14137:             push(@recipients,$lastresort);
                   14138:         }
                   14139:     }
                   14140:     my $recipientlist = join(',',@recipients);
                   14141:     if (wantarray) {
                   14142:         return ($recipientlist,$allbcc,$addtext);
                   14143:     } else {
                   14144:         return $recipientlist;
                   14145:     }
1.618     raeburn  14146: }
                   14147: 
1.127     matthew  14148: ############################################################
                   14149: ############################################################
1.154     albertel 14150: 
1.655     raeburn  14151: =pod
                   14152: 
                   14153: =head1 Course Catalog Routines
                   14154: 
                   14155: =over 4
                   14156: 
                   14157: =item * &gather_categories()
                   14158: 
                   14159: Converts category definitions - keys of categories hash stored in  
                   14160: coursecategories in configuration.db on the primary library server in a 
                   14161: domain - to an array.  Also generates javascript and idx hash used to 
                   14162: generate Domain Coordinator interface for editing Course Categories.
                   14163: 
                   14164: Inputs:
1.663     raeburn  14165: 
1.655     raeburn  14166: categories (reference to hash of category definitions).
1.663     raeburn  14167: 
1.655     raeburn  14168: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14169:       categories and subcategories).
1.663     raeburn  14170: 
1.655     raeburn  14171: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14172:       editing Course Categories).
1.663     raeburn  14173: 
1.655     raeburn  14174: jsarray (reference to array of categories used to create Javascript arrays for
                   14175:          Domain Coordinator interface for editing Course Categories).
                   14176: 
                   14177: Returns: nothing
                   14178: 
                   14179: Side effects: populates cats, idx and jsarray. 
                   14180: 
                   14181: =cut
                   14182: 
                   14183: sub gather_categories {
                   14184:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14185:     my %counters;
                   14186:     my $num = 0;
                   14187:     foreach my $item (keys(%{$categories})) {
                   14188:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14189:         if ($container eq '' && $depth == 0) {
                   14190:             $cats->[$depth][$categories->{$item}] = $cat;
                   14191:         } else {
                   14192:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14193:         }
                   14194:         my ($escitem,$tail) = split(/:/,$item,2);
                   14195:         if ($counters{$tail} eq '') {
                   14196:             $counters{$tail} = $num;
                   14197:             $num ++;
                   14198:         }
                   14199:         if (ref($idx) eq 'HASH') {
                   14200:             $idx->{$item} = $counters{$tail};
                   14201:         }
                   14202:         if (ref($jsarray) eq 'ARRAY') {
                   14203:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14204:         }
                   14205:     }
                   14206:     return;
                   14207: }
                   14208: 
                   14209: =pod
                   14210: 
                   14211: =item * &extract_categories()
                   14212: 
                   14213: Used to generate breadcrumb trails for course categories.
                   14214: 
                   14215: Inputs:
1.663     raeburn  14216: 
1.655     raeburn  14217: categories (reference to hash of category definitions).
1.663     raeburn  14218: 
1.655     raeburn  14219: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14220:       categories and subcategories).
1.663     raeburn  14221: 
1.655     raeburn  14222: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14223: 
1.655     raeburn  14224: allitems (reference to hash - key is category key 
                   14225:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14226: 
1.655     raeburn  14227: idx (reference to hash of counters used in Domain Coordinator interface for
                   14228:       editing Course Categories).
1.663     raeburn  14229: 
1.655     raeburn  14230: jsarray (reference to array of categories used to create Javascript arrays for
                   14231:          Domain Coordinator interface for editing Course Categories).
                   14232: 
1.665     raeburn  14233: subcats (reference to hash of arrays containing all subcategories within each 
                   14234:          category, -recursive)
                   14235: 
1.655     raeburn  14236: Returns: nothing
                   14237: 
                   14238: Side effects: populates trails and allitems hash references.
                   14239: 
                   14240: =cut
                   14241: 
                   14242: sub extract_categories {
1.665     raeburn  14243:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  14244:     if (ref($categories) eq 'HASH') {
                   14245:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14246:         if (ref($cats->[0]) eq 'ARRAY') {
                   14247:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14248:                 my $name = $cats->[0][$i];
                   14249:                 my $item = &escape($name).'::0';
                   14250:                 my $trailstr;
                   14251:                 if ($name eq 'instcode') {
                   14252:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14253:                 } elsif ($name eq 'communities') {
                   14254:                     $trailstr = &mt('Communities');
1.655     raeburn  14255:                 } else {
                   14256:                     $trailstr = $name;
                   14257:                 }
                   14258:                 if ($allitems->{$item} eq '') {
                   14259:                     push(@{$trails},$trailstr);
                   14260:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14261:                 }
                   14262:                 my @parents = ($name);
                   14263:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14264:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14265:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14266:                         if (ref($subcats) eq 'HASH') {
                   14267:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14268:                         }
                   14269:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   14270:                     }
                   14271:                 } else {
                   14272:                     if (ref($subcats) eq 'HASH') {
                   14273:                         $subcats->{$item} = [];
1.655     raeburn  14274:                     }
                   14275:                 }
                   14276:             }
                   14277:         }
                   14278:     }
                   14279:     return;
                   14280: }
                   14281: 
                   14282: =pod
                   14283: 
1.1075.2.56  raeburn  14284: =item * &recurse_categories()
1.655     raeburn  14285: 
                   14286: Recursively used to generate breadcrumb trails for course categories.
                   14287: 
                   14288: Inputs:
1.663     raeburn  14289: 
1.655     raeburn  14290: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14291:       categories and subcategories).
1.663     raeburn  14292: 
1.655     raeburn  14293: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14294: 
                   14295: category (current course category, for which breadcrumb trail is being generated).
                   14296: 
                   14297: trails (reference to array of breadcrumb trails for each category).
                   14298: 
1.655     raeburn  14299: allitems (reference to hash - key is category key
                   14300:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14301: 
1.655     raeburn  14302: parents (array containing containers directories for current category, 
                   14303:          back to top level). 
                   14304: 
                   14305: Returns: nothing
                   14306: 
                   14307: Side effects: populates trails and allitems hash references
                   14308: 
                   14309: =cut
                   14310: 
                   14311: sub recurse_categories {
1.665     raeburn  14312:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  14313:     my $shallower = $depth - 1;
                   14314:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14315:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14316:             my $name = $cats->[$depth]{$category}[$k];
                   14317:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14318:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14319:             if ($allitems->{$item} eq '') {
                   14320:                 push(@{$trails},$trailstr);
                   14321:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14322:             }
                   14323:             my $deeper = $depth+1;
                   14324:             push(@{$parents},$category);
1.665     raeburn  14325:             if (ref($subcats) eq 'HASH') {
                   14326:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14327:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14328:                     my $higher;
                   14329:                     if ($j > 0) {
                   14330:                         $higher = &escape($parents->[$j]).':'.
                   14331:                                   &escape($parents->[$j-1]).':'.$j;
                   14332:                     } else {
                   14333:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14334:                     }
                   14335:                     push(@{$subcats->{$higher}},$subcat);
                   14336:                 }
                   14337:             }
                   14338:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   14339:                                 $subcats);
1.655     raeburn  14340:             pop(@{$parents});
                   14341:         }
                   14342:     } else {
                   14343:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14344:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14345:         if ($allitems->{$item} eq '') {
                   14346:             push(@{$trails},$trailstr);
                   14347:             $allitems->{$item} = scalar(@{$trails})-1;
                   14348:         }
                   14349:     }
                   14350:     return;
                   14351: }
                   14352: 
1.663     raeburn  14353: =pod
                   14354: 
1.1075.2.56  raeburn  14355: =item * &assign_categories_table()
1.663     raeburn  14356: 
                   14357: Create a datatable for display of hierarchical categories in a domain,
                   14358: with checkboxes to allow a course to be categorized. 
                   14359: 
                   14360: Inputs:
                   14361: 
                   14362: cathash - reference to hash of categories defined for the domain (from
                   14363:           configuration.db)
                   14364: 
                   14365: currcat - scalar with an & separated list of categories assigned to a course. 
                   14366: 
1.919     raeburn  14367: type    - scalar contains course type (Course or Community).
                   14368: 
1.1075.2.117  raeburn  14369: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14370:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14371: 
1.663     raeburn  14372: Returns: $output (markup to be displayed) 
                   14373: 
                   14374: =cut
                   14375: 
                   14376: sub assign_categories_table {
1.1075.2.117  raeburn  14377:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  14378:     my $output;
                   14379:     if (ref($cathash) eq 'HASH') {
                   14380:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   14381:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   14382:         $maxdepth = scalar(@cats);
                   14383:         if (@cats > 0) {
                   14384:             my $itemcount = 0;
                   14385:             if (ref($cats[0]) eq 'ARRAY') {
                   14386:                 my @currcategories;
                   14387:                 if ($currcat ne '') {
                   14388:                     @currcategories = split('&',$currcat);
                   14389:                 }
1.919     raeburn  14390:                 my $table;
1.663     raeburn  14391:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14392:                     my $parent = $cats[0][$i];
1.919     raeburn  14393:                     next if ($parent eq 'instcode');
                   14394:                     if ($type eq 'Community') {
                   14395:                         next unless ($parent eq 'communities');
                   14396:                     } else {
                   14397:                         next if ($parent eq 'communities');
                   14398:                     }
1.663     raeburn  14399:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14400:                     my $item = &escape($parent).'::0';
                   14401:                     my $checked = '';
                   14402:                     if (@currcategories > 0) {
                   14403:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14404:                             $checked = ' checked="checked"';
1.663     raeburn  14405:                         }
                   14406:                     }
1.919     raeburn  14407:                     my $parent_title = $parent;
                   14408:                     if ($parent eq 'communities') {
                   14409:                         $parent_title = &mt('Communities');
                   14410:                     }
                   14411:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14412:                               '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14413:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  14414:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14415:                     my $depth = 1;
                   14416:                     push(@path,$parent);
1.1075.2.117  raeburn  14417:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  14418:                     pop(@path);
1.919     raeburn  14419:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14420:                     $itemcount ++;
                   14421:                 }
1.919     raeburn  14422:                 if ($itemcount) {
                   14423:                     $output = &Apache::loncommon::start_data_table().
                   14424:                               $table.
                   14425:                               &Apache::loncommon::end_data_table();
                   14426:                 }
1.663     raeburn  14427:             }
                   14428:         }
                   14429:     }
                   14430:     return $output;
                   14431: }
                   14432: 
                   14433: =pod
                   14434: 
1.1075.2.56  raeburn  14435: =item * &assign_category_rows()
1.663     raeburn  14436: 
                   14437: Create a datatable row for display of nested categories in a domain,
                   14438: with checkboxes to allow a course to be categorized,called recursively.
                   14439: 
                   14440: Inputs:
                   14441: 
                   14442: itemcount - track row number for alternating colors
                   14443: 
                   14444: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14445:       categories and subcategories.
                   14446: 
                   14447: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14448: 
                   14449: parent - parent of current category item
                   14450: 
                   14451: path - Array containing all categories back up through the hierarchy from the
                   14452:        current category to the top level.
                   14453: 
                   14454: currcategories - reference to array of current categories assigned to the course
                   14455: 
1.1075.2.117  raeburn  14456: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14457:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14458: 
1.663     raeburn  14459: Returns: $output (markup to be displayed).
                   14460: 
                   14461: =cut
                   14462: 
                   14463: sub assign_category_rows {
1.1075.2.117  raeburn  14464:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  14465:     my ($text,$name,$item,$chgstr);
                   14466:     if (ref($cats) eq 'ARRAY') {
                   14467:         my $maxdepth = scalar(@{$cats});
                   14468:         if (ref($cats->[$depth]) eq 'HASH') {
                   14469:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14470:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14471:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  14472:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14473:                 for (my $j=0; $j<$numchildren; $j++) {
                   14474:                     $name = $cats->[$depth]{$parent}[$j];
                   14475:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14476:                     my $deeper = $depth+1;
                   14477:                     my $checked = '';
                   14478:                     if (ref($currcategories) eq 'ARRAY') {
                   14479:                         if (@{$currcategories} > 0) {
                   14480:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14481:                                 $checked = ' checked="checked"';
1.663     raeburn  14482:                             }
                   14483:                         }
                   14484:                     }
1.664     raeburn  14485:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14486:                              '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14487:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  14488:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14489:                              '</td><td>';
1.663     raeburn  14490:                     if (ref($path) eq 'ARRAY') {
                   14491:                         push(@{$path},$name);
1.1075.2.117  raeburn  14492:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  14493:                         pop(@{$path});
                   14494:                     }
                   14495:                     $text .= '</td></tr>';
                   14496:                 }
                   14497:                 $text .= '</table></td>';
                   14498:             }
                   14499:         }
                   14500:     }
                   14501:     return $text;
                   14502: }
                   14503: 
1.1075.2.69  raeburn  14504: =pod
                   14505: 
                   14506: =back
                   14507: 
                   14508: =cut
                   14509: 
1.655     raeburn  14510: ############################################################
                   14511: ############################################################
                   14512: 
                   14513: 
1.443     albertel 14514: sub commit_customrole {
1.664     raeburn  14515:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14516:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14517:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14518:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14519:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14520:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14521:                  '</b><br />';
                   14522:     return $output;
                   14523: }
                   14524: 
                   14525: sub commit_standardrole {
1.1075.2.31  raeburn  14526:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14527:     my ($output,$logmsg,$linefeed);
                   14528:     if ($context eq 'auto') {
                   14529:         $linefeed = "\n";
                   14530:     } else {
                   14531:         $linefeed = "<br />\n";
                   14532:     }  
1.443     albertel 14533:     if ($three eq 'st') {
1.541     raeburn  14534:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  14535:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14536:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14537:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14538:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14539:         } else {
1.541     raeburn  14540:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14541:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14542:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14543:             if ($context eq 'auto') {
                   14544:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14545:             } else {
                   14546:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14547:                &mt('Add to classlist').': <b>ok</b>';
                   14548:             }
                   14549:             $output .= $linefeed;
1.443     albertel 14550:         }
                   14551:     } else {
                   14552:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14553:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14554:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14555:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14556:         if ($context eq 'auto') {
                   14557:             $output .= $result.$linefeed;
                   14558:         } else {
                   14559:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14560:         }
1.443     albertel 14561:     }
                   14562:     return $output;
                   14563: }
                   14564: 
                   14565: sub commit_studentrole {
1.1075.2.31  raeburn  14566:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14567:         $credits) = @_;
1.626     raeburn  14568:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  14569:     if ($context eq 'auto') {
                   14570:         $linefeed = "\n";
                   14571:     } else {
                   14572:         $linefeed = '<br />'."\n";
                   14573:     }
1.443     albertel 14574:     if (defined($one) && defined($two)) {
                   14575:         my $cid=$one.'_'.$two;
                   14576:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   14577:         my $secchange = 0;
                   14578:         my $expire_role_result;
                   14579:         my $modify_section_result;
1.628     raeburn  14580:         if ($oldsec ne '-1') { 
                   14581:             if ($oldsec ne $sec) {
1.443     albertel 14582:                 $secchange = 1;
1.628     raeburn  14583:                 my $now = time;
1.443     albertel 14584:                 my $uurl='/'.$cid;
                   14585:                 $uurl=~s/\_/\//g;
                   14586:                 if ($oldsec) {
                   14587:                     $uurl.='/'.$oldsec;
                   14588:                 }
1.626     raeburn  14589:                 $oldsecurl = $uurl;
1.628     raeburn  14590:                 $expire_role_result = 
1.652     raeburn  14591:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  14592:                 if ($env{'request.course.sec'} ne '') { 
                   14593:                     if ($expire_role_result eq 'refused') {
                   14594:                         my @roles = ('st');
                   14595:                         my @statuses = ('previous');
                   14596:                         my @roledoms = ($one);
                   14597:                         my $withsec = 1;
                   14598:                         my %roleshash = 
                   14599:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   14600:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   14601:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   14602:                             my ($oldstart,$oldend) = 
                   14603:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   14604:                             if ($oldend > 0 && $oldend <= $now) {
                   14605:                                 $expire_role_result = 'ok';
                   14606:                             }
                   14607:                         }
                   14608:                     }
                   14609:                 }
1.443     albertel 14610:                 $result = $expire_role_result;
                   14611:             }
                   14612:         }
                   14613:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  14614:             $modify_section_result = 
                   14615:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   14616:                                                            undef,undef,undef,$sec,
                   14617:                                                            $end,$start,'','',$cid,
                   14618:                                                            '',$context,$credits);
1.443     albertel 14619:             if ($modify_section_result =~ /^ok/) {
                   14620:                 if ($secchange == 1) {
1.628     raeburn  14621:                     if ($sec eq '') {
                   14622:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   14623:                     } else {
                   14624:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   14625:                     }
1.443     albertel 14626:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  14627:                     if ($sec eq '') {
                   14628:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   14629:                     } else {
                   14630:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14631:                     }
1.443     albertel 14632:                 } else {
1.628     raeburn  14633:                     if ($sec eq '') {
                   14634:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   14635:                     } else {
                   14636:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14637:                     }
1.443     albertel 14638:                 }
                   14639:             } else {
1.628     raeburn  14640:                 if ($secchange) {       
                   14641:                     $$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;
                   14642:                 } else {
                   14643:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   14644:                 }
1.443     albertel 14645:             }
                   14646:             $result = $modify_section_result;
                   14647:         } elsif ($secchange == 1) {
1.628     raeburn  14648:             if ($oldsec eq '') {
1.1075.2.20  raeburn  14649:                 $$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  14650:             } else {
                   14651:                 $$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;
                   14652:             }
1.626     raeburn  14653:             if ($expire_role_result eq 'refused') {
                   14654:                 my $newsecurl = '/'.$cid;
                   14655:                 $newsecurl =~ s/\_/\//g;
                   14656:                 if ($sec ne '') {
                   14657:                     $newsecurl.='/'.$sec;
                   14658:                 }
                   14659:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   14660:                     if ($sec eq '') {
                   14661:                         $$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;
                   14662:                     } else {
                   14663:                         $$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;
                   14664:                     }
                   14665:                 }
                   14666:             }
1.443     albertel 14667:         }
                   14668:     } else {
1.626     raeburn  14669:         $$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 14670:         $result = "error: incomplete course id\n";
                   14671:     }
                   14672:     return $result;
                   14673: }
                   14674: 
1.1075.2.25  raeburn  14675: sub show_role_extent {
                   14676:     my ($scope,$context,$role) = @_;
                   14677:     $scope =~ s{^/}{};
                   14678:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   14679:     push(@courseroles,'co');
                   14680:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   14681:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   14682:         $scope =~ s{/}{_};
                   14683:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   14684:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   14685:         my ($audom,$auname) = split(/\//,$scope);
                   14686:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   14687:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   14688:     } else {
                   14689:         $scope =~ s{/$}{};
                   14690:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   14691:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   14692:     }
                   14693: }
                   14694: 
1.443     albertel 14695: ############################################################
                   14696: ############################################################
                   14697: 
1.566     albertel 14698: sub check_clone {
1.578     raeburn  14699:     my ($args,$linefeed) = @_;
1.566     albertel 14700:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   14701:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   14702:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   14703:     my $clonemsg;
                   14704:     my $can_clone = 0;
1.944     raeburn  14705:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  14706:     if ($lctype ne 'community') {
                   14707:         $lctype = 'course';
                   14708:     }
1.566     albertel 14709:     if ($clonehome eq 'no_host') {
1.944     raeburn  14710:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14711:             $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'});
                   14712:         } else {
                   14713:             $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'});
                   14714:         }     
1.566     albertel 14715:     } else {
                   14716: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  14717:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14718:             if ($clonedesc{'type'} ne 'Community') {
                   14719:                  $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'});
                   14720:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14721:             }
                   14722:         }
1.1075.2.119  raeburn  14723: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  14724:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 14725: 	    $can_clone = 1;
                   14726: 	} else {
1.1075.2.95  raeburn  14727: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 14728: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  14729:             if ($clonehash{'cloners'} eq '') {
                   14730:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   14731:                 if ($domdefs{'canclone'}) {
                   14732:                     unless ($domdefs{'canclone'} eq 'none') {
                   14733:                         if ($domdefs{'canclone'} eq 'domain') {
                   14734:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   14735:                                 $can_clone = 1;
                   14736:                             }
                   14737:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   14738:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   14739:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   14740:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   14741:                                 $can_clone = 1;
                   14742:                             }
                   14743:                         }
                   14744:                     }
1.908     raeburn  14745:                 }
1.1075.2.95  raeburn  14746:             } else {
                   14747: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   14748:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  14749:                     $can_clone = 1;
1.1075.2.95  raeburn  14750:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  14751:                     $can_clone = 1;
1.1075.2.96  raeburn  14752:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   14753:                     $can_clone = 1;
1.1075.2.95  raeburn  14754:                 }
                   14755:                 unless ($can_clone) {
1.1075.2.96  raeburn  14756:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   14757:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  14758:                         my (%gotdomdefaults,%gotcodedefaults);
                   14759:                         foreach my $cloner (@cloners) {
                   14760:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   14761:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   14762:                                 my (%codedefaults,@code_order);
                   14763:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   14764:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   14765:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   14766:                                     }
                   14767:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   14768:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   14769:                                     }
                   14770:                                 } else {
                   14771:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   14772:                                                                             \%codedefaults,
                   14773:                                                                             \@code_order);
                   14774:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   14775:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   14776:                                 }
                   14777:                                 if (@code_order > 0) {
                   14778:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   14779:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   14780:                                                                                 $args->{'crscode'})) {
                   14781:                                         $can_clone = 1;
                   14782:                                         last;
                   14783:                                     }
                   14784:                                 }
                   14785:                             }
                   14786:                         }
                   14787:                     }
1.1075.2.96  raeburn  14788:                 }
                   14789:             }
                   14790:             unless ($can_clone) {
                   14791:                 my $ccrole = 'cc';
                   14792:                 if ($args->{'crstype'} eq 'Community') {
                   14793:                     $ccrole = 'co';
                   14794:                 }
                   14795:                 my %roleshash =
                   14796:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   14797:                                                   $args->{'ccdomain'},
                   14798:                                                   'userroles',['active'],[$ccrole],
                   14799:                                                   [$args->{'clonedomain'}]);
                   14800:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   14801:                     $can_clone = 1;
                   14802:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   14803:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   14804:                     $can_clone = 1;
1.1075.2.95  raeburn  14805:                 }
                   14806:             }
                   14807:             unless ($can_clone) {
                   14808:                 if ($args->{'crstype'} eq 'Community') {
                   14809:                     $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'});
                   14810:                 } else {
                   14811:                     $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  14812: 	        }
1.566     albertel 14813: 	    }
1.578     raeburn  14814:         }
1.566     albertel 14815:     }
                   14816:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14817: }
                   14818: 
1.444     albertel 14819: sub construct_course {
1.1075.2.119  raeburn  14820:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
                   14821:         $cnum,$category,$coderef) = @_;
1.444     albertel 14822:     my $outcome;
1.541     raeburn  14823:     my $linefeed =  '<br />'."\n";
                   14824:     if ($context eq 'auto') {
                   14825:         $linefeed = "\n";
                   14826:     }
1.566     albertel 14827: 
                   14828: #
                   14829: # Are we cloning?
                   14830: #
                   14831:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14832:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  14833: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 14834: 	if ($context ne 'auto') {
1.578     raeburn  14835:             if ($clonemsg ne '') {
                   14836: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   14837:             }
1.566     albertel 14838: 	}
                   14839: 	$outcome .= $clonemsg.$linefeed;
                   14840: 
                   14841:         if (!$can_clone) {
                   14842: 	    return (0,$outcome);
                   14843: 	}
                   14844:     }
                   14845: 
1.444     albertel 14846: #
                   14847: # Open course
                   14848: #
                   14849:     my $crstype = lc($args->{'crstype'});
                   14850:     my %cenv=();
                   14851:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   14852:                                              $args->{'cdescr'},
                   14853:                                              $args->{'curl'},
                   14854:                                              $args->{'course_home'},
                   14855:                                              $args->{'nonstandard'},
                   14856:                                              $args->{'crscode'},
                   14857:                                              $args->{'ccuname'}.':'.
                   14858:                                              $args->{'ccdomain'},
1.882     raeburn  14859:                                              $args->{'crstype'},
1.885     raeburn  14860:                                              $cnum,$context,$category);
1.444     albertel 14861: 
                   14862:     # Note: The testing routines depend on this being output; see 
                   14863:     # Utils::Course. This needs to at least be output as a comment
                   14864:     # if anyone ever decides to not show this, and Utils::Course::new
                   14865:     # will need to be suitably modified.
1.541     raeburn  14866:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  14867:     if ($$courseid =~ /^error:/) {
                   14868:         return (0,$outcome);
                   14869:     }
                   14870: 
1.444     albertel 14871: #
                   14872: # Check if created correctly
                   14873: #
1.479     albertel 14874:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 14875:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  14876:     if ($crsuhome eq 'no_host') {
                   14877:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   14878:         return (0,$outcome);
                   14879:     }
1.541     raeburn  14880:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 14881: 
1.444     albertel 14882: #
1.566     albertel 14883: # Do the cloning
                   14884: #   
                   14885:     if ($can_clone && $cloneid) {
                   14886: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   14887: 	if ($context ne 'auto') {
                   14888: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   14889: 	}
                   14890: 	$outcome .= $clonemsg.$linefeed;
                   14891: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 14892: # Copy all files
1.637     www      14893: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 14894: # Restore URL
1.566     albertel 14895: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 14896: # Restore title
1.566     albertel 14897: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  14898: # Restore creation date, creator and creation context.
                   14899:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   14900:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   14901:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 14902: # Mark as cloned
1.566     albertel 14903: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      14904: # Need to clone grading mode
                   14905:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   14906:         $cenv{'grading'}=$newenv{'grading'};
                   14907: # Do not clone these environment entries
                   14908:         &Apache::lonnet::del('environment',
                   14909:                   ['default_enrollment_start_date',
                   14910:                    'default_enrollment_end_date',
                   14911:                    'question.email',
                   14912:                    'policy.email',
                   14913:                    'comment.email',
                   14914:                    'pch.users.denied',
1.725     raeburn  14915:                    'plc.users.denied',
                   14916:                    'hidefromcat',
1.1075.2.36  raeburn  14917:                    'checkforpriv',
1.1075.2.59  raeburn  14918:                    'categories',
                   14919:                    'internal.uniquecode'],
1.638     www      14920:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  14921:         if ($args->{'textbook'}) {
                   14922:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   14923:         }
1.444     albertel 14924:     }
1.566     albertel 14925: 
1.444     albertel 14926: #
                   14927: # Set environment (will override cloned, if existing)
                   14928: #
                   14929:     my @sections = ();
                   14930:     my @xlists = ();
                   14931:     if ($args->{'crstype'}) {
                   14932:         $cenv{'type'}=$args->{'crstype'};
                   14933:     }
                   14934:     if ($args->{'crsid'}) {
                   14935:         $cenv{'courseid'}=$args->{'crsid'};
                   14936:     }
                   14937:     if ($args->{'crscode'}) {
                   14938:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   14939:     }
                   14940:     if ($args->{'crsquota'} ne '') {
                   14941:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   14942:     } else {
                   14943:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   14944:     }
                   14945:     if ($args->{'ccuname'}) {
                   14946:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   14947:                                         ':'.$args->{'ccdomain'};
                   14948:     } else {
                   14949:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   14950:     }
1.1075.2.31  raeburn  14951:     if ($args->{'defaultcredits'}) {
                   14952:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   14953:     }
1.444     albertel 14954:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   14955:     if ($args->{'crssections'}) {
                   14956:         $cenv{'internal.sectionnums'} = '';
                   14957:         if ($args->{'crssections'} =~ m/,/) {
                   14958:             @sections = split/,/,$args->{'crssections'};
                   14959:         } else {
                   14960:             $sections[0] = $args->{'crssections'};
                   14961:         }
                   14962:         if (@sections > 0) {
                   14963:             foreach my $item (@sections) {
                   14964:                 my ($sec,$gp) = split/:/,$item;
                   14965:                 my $class = $args->{'crscode'}.$sec;
                   14966:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   14967:                 $cenv{'internal.sectionnums'} .= $item.',';
                   14968:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  14969:                     push(@badclasses,$class);
1.444     albertel 14970:                 }
                   14971:             }
                   14972:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   14973:         }
                   14974:     }
                   14975: # do not hide course coordinator from staff listing, 
                   14976: # even if privileged
                   14977:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  14978: # add course coordinator's domain to domains to check for privileged users
                   14979: # if different to course domain
                   14980:     if ($$crsudom ne $args->{'ccdomain'}) {
                   14981:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   14982:     }
1.444     albertel 14983: # add crosslistings
                   14984:     if ($args->{'crsxlist'}) {
                   14985:         $cenv{'internal.crosslistings'}='';
                   14986:         if ($args->{'crsxlist'} =~ m/,/) {
                   14987:             @xlists = split/,/,$args->{'crsxlist'};
                   14988:         } else {
                   14989:             $xlists[0] = $args->{'crsxlist'};
                   14990:         }
                   14991:         if (@xlists > 0) {
                   14992:             foreach my $item (@xlists) {
                   14993:                 my ($xl,$gp) = split/:/,$item;
                   14994:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   14995:                 $cenv{'internal.crosslistings'} .= $item.',';
                   14996:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  14997:                     push(@badclasses,$xl);
1.444     albertel 14998:                 }
                   14999:             }
                   15000:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15001:         }
                   15002:     }
                   15003:     if ($args->{'autoadds'}) {
                   15004:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15005:     }
                   15006:     if ($args->{'autodrops'}) {
                   15007:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15008:     }
                   15009: # check for notification of enrollment changes
                   15010:     my @notified = ();
                   15011:     if ($args->{'notify_owner'}) {
                   15012:         if ($args->{'ccuname'} ne '') {
                   15013:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15014:         }
                   15015:     }
                   15016:     if ($args->{'notify_dc'}) {
                   15017:         if ($uname ne '') { 
1.630     raeburn  15018:             push(@notified,$uname.':'.$udom);
1.444     albertel 15019:         }
                   15020:     }
                   15021:     if (@notified > 0) {
                   15022:         my $notifylist;
                   15023:         if (@notified > 1) {
                   15024:             $notifylist = join(',',@notified);
                   15025:         } else {
                   15026:             $notifylist = $notified[0];
                   15027:         }
                   15028:         $cenv{'internal.notifylist'} = $notifylist;
                   15029:     }
                   15030:     if (@badclasses > 0) {
                   15031:         my %lt=&Apache::lonlocal::texthash(
1.1075.2.119  raeburn  15032:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   15033:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   15034:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 15035:         );
1.1075.2.119  raeburn  15036:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   15037:                            &mt('That is because the user identified as the course owner ([_1]) does not have rights to access enrollment in these classes, as determined by the policies of your institution on access to official classlists',$cenv{'internal.courseowner'}).$linefeed.$lt{'itis'};
1.541     raeburn  15038:         if ($context eq 'auto') {
                   15039:             $outcome .= $badclass_msg.$linefeed;
1.1075.2.119  raeburn  15040:         } else {
1.566     albertel 15041:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1075.2.119  raeburn  15042:         }
                   15043:         foreach my $item (@badclasses) {
1.541     raeburn  15044:             if ($context eq 'auto') {
1.1075.2.119  raeburn  15045:                 $outcome .= " - $item\n";
1.541     raeburn  15046:             } else {
1.1075.2.119  raeburn  15047:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  15048:             }
1.1075.2.119  raeburn  15049:         }
                   15050:         if ($context eq 'auto') {
                   15051:             $outcome .= $linefeed;
                   15052:         } else {
                   15053:             $outcome .= "</ul><br /><br /></div>\n";
                   15054:         }
1.444     albertel 15055:     }
                   15056:     if ($args->{'no_end_date'}) {
                   15057:         $args->{'endaccess'} = 0;
                   15058:     }
                   15059:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15060:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15061:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15062:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15063:     if ($args->{'showphotos'}) {
                   15064:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15065:     }
                   15066:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15067:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15068:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15069:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15070:             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'); 
                   15071:             if ($context eq 'auto') {
                   15072:                 $outcome .= $krb_msg;
                   15073:             } else {
1.566     albertel 15074:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15075:             }
                   15076:             $outcome .= $linefeed;
1.444     albertel 15077:         }
                   15078:     }
                   15079:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15080:        if ($args->{'setpolicy'}) {
                   15081:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15082:        }
                   15083:        if ($args->{'setcontent'}) {
                   15084:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15085:        }
1.1075.2.110  raeburn  15086:        if ($args->{'setcomment'}) {
                   15087:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15088:        }
1.444     albertel 15089:     }
                   15090:     if ($args->{'reshome'}) {
                   15091: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15092: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15093:     }
                   15094: #
                   15095: # course has keyed access
                   15096: #
                   15097:     if ($args->{'setkeys'}) {
                   15098:        $cenv{'keyaccess'}='yes';
                   15099:     }
                   15100: # if specified, key authority is not course, but user
                   15101: # only active if keyaccess is yes
                   15102:     if ($args->{'keyauth'}) {
1.487     albertel 15103: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15104: 	$user = &LONCAPA::clean_username($user);
                   15105: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15106: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15107: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15108: 	}
                   15109:     }
                   15110: 
1.1075.2.59  raeburn  15111: #
                   15112: #  generate and store uniquecode (available to course requester), if course should have one.
                   15113: #
                   15114:     if ($args->{'uniquecode'}) {
                   15115:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15116:         if ($code) {
                   15117:             $cenv{'internal.uniquecode'} = $code;
                   15118:             my %crsinfo =
                   15119:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15120:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15121:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15122:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15123:             }
                   15124:             if (ref($coderef)) {
                   15125:                 $$coderef = $code;
                   15126:             }
                   15127:         }
                   15128:     }
                   15129: 
1.444     albertel 15130:     if ($args->{'disresdis'}) {
                   15131:         $cenv{'pch.roles.denied'}='st';
                   15132:     }
                   15133:     if ($args->{'disablechat'}) {
                   15134:         $cenv{'plc.roles.denied'}='st';
                   15135:     }
                   15136: 
                   15137:     # Record we've not yet viewed the Course Initialization Helper for this 
                   15138:     # course
                   15139:     $cenv{'course.helper.not.run'} = 1;
                   15140:     #
                   15141:     # Use new Randomseed
                   15142:     #
                   15143:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   15144:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   15145:     #
                   15146:     # The encryption code and receipt prefix for this course
                   15147:     #
                   15148:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   15149:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   15150:     #
                   15151:     # By default, use standard grading
                   15152:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15153: 
1.541     raeburn  15154:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15155:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15156: #
                   15157: # Open all assignments
                   15158: #
                   15159:     if ($args->{'openall'}) {
                   15160:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   15161:        my %storecontent = ($storeunder         => time,
                   15162:                            $storeunder.'.type' => 'date_start');
                   15163:        
                   15164:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  15165:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15166:    }
                   15167: #
                   15168: # Set first page
                   15169: #
                   15170:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15171: 	    || ($cloneid)) {
1.445     albertel 15172: 	use LONCAPA::map;
1.444     albertel 15173: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15174: 
                   15175: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15176:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15177: 
1.444     albertel 15178:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15179:         my $title; my $url;
                   15180:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15181: 	    $title=&mt('Syllabus');
1.444     albertel 15182:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15183:         } else {
1.963     raeburn  15184:             $title=&mt('Table of Contents');
1.444     albertel 15185:             $url='/adm/navmaps';
                   15186:         }
1.445     albertel 15187: 
                   15188:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15189: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15190: 
                   15191: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15192:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15193:     }
1.566     albertel 15194: 
                   15195:     return (1,$outcome);
1.444     albertel 15196: }
                   15197: 
1.1075.2.59  raeburn  15198: sub make_unique_code {
                   15199:     my ($cdom,$cnum) = @_;
                   15200:     # get lock on uniquecodes db
                   15201:     my $lockhash = {
                   15202:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15203:                                                   ':'.$env{'user.domain'},
                   15204:                    };
                   15205:     my $tries = 0;
                   15206:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15207:     my ($code,$error);
                   15208: 
                   15209:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15210:         $tries ++;
                   15211:         sleep 1;
                   15212:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15213:     }
                   15214:     if ($gotlock eq 'ok') {
                   15215:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15216:         my $gotcode;
                   15217:         my $attempts = 0;
                   15218:         while ((!$gotcode) && ($attempts < 100)) {
                   15219:             $code = &generate_code();
                   15220:             if (!exists($currcodes{$code})) {
                   15221:                 $gotcode = 1;
                   15222:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15223:                     $error = 'nostore';
                   15224:                 }
                   15225:             }
                   15226:             $attempts ++;
                   15227:         }
                   15228:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15229:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15230:     } else {
                   15231:         $error = 'nolock';
                   15232:     }
                   15233:     return ($code,$error);
                   15234: }
                   15235: 
                   15236: sub generate_code {
                   15237:     my $code;
                   15238:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15239:     for (my $i=0; $i<6; $i++) {
                   15240:         my $lettnum = int (rand 2);
                   15241:         my $item = '';
                   15242:         if ($lettnum) {
                   15243:             $item = $letts[int( rand(18) )];
                   15244:         } else {
                   15245:             $item = 1+int( rand(8) );
                   15246:         }
                   15247:         $code .= $item;
                   15248:     }
                   15249:     return $code;
                   15250: }
                   15251: 
1.444     albertel 15252: ############################################################
                   15253: ############################################################
                   15254: 
1.953     droeschl 15255: #SD
                   15256: # only Community and Course, or anything else?
1.378     raeburn  15257: sub course_type {
                   15258:     my ($cid) = @_;
                   15259:     if (!defined($cid)) {
                   15260:         $cid = $env{'request.course.id'};
                   15261:     }
1.404     albertel 15262:     if (defined($env{'course.'.$cid.'.type'})) {
                   15263:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15264:     } else {
                   15265:         return 'Course';
1.377     raeburn  15266:     }
                   15267: }
1.156     albertel 15268: 
1.406     raeburn  15269: sub group_term {
                   15270:     my $crstype = &course_type();
                   15271:     my %names = (
                   15272:                   'Course' => 'group',
1.865     raeburn  15273:                   'Community' => 'group',
1.406     raeburn  15274:                 );
                   15275:     return $names{$crstype};
                   15276: }
                   15277: 
1.902     raeburn  15278: sub course_types {
1.1075.2.59  raeburn  15279:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  15280:     my %typename = (
                   15281:                          official   => 'Official course',
                   15282:                          unofficial => 'Unofficial course',
                   15283:                          community  => 'Community',
1.1075.2.59  raeburn  15284:                          textbook   => 'Textbook course',
1.902     raeburn  15285:                    );
                   15286:     return (\@types,\%typename);
                   15287: }
                   15288: 
1.156     albertel 15289: sub icon {
                   15290:     my ($file)=@_;
1.505     albertel 15291:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15292:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15293:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15294:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15295: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15296: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15297: 	            $curfext.".gif") {
                   15298: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15299: 		$curfext.".gif";
                   15300: 	}
                   15301:     }
1.249     albertel 15302:     return &lonhttpdurl($iconname);
1.154     albertel 15303: } 
1.84      albertel 15304: 
1.575     albertel 15305: sub lonhttpdurl {
1.692     www      15306: #
                   15307: # Had been used for "small fry" static images on separate port 8080.
                   15308: # Modify here if lightweight http functionality desired again.
                   15309: # Currently eliminated due to increasing firewall issues.
                   15310: #
1.575     albertel 15311:     my ($url)=@_;
1.692     www      15312:     return $url;
1.215     albertel 15313: }
                   15314: 
1.213     albertel 15315: sub connection_aborted {
                   15316:     my ($r)=@_;
                   15317:     $r->print(" ");$r->rflush();
                   15318:     my $c = $r->connection;
                   15319:     return $c->aborted();
                   15320: }
                   15321: 
1.221     foxr     15322: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15323: #    strings as 'strings'.
                   15324: sub escape_single {
1.221     foxr     15325:     my ($input) = @_;
1.223     albertel 15326:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15327:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15328:     return $input;
                   15329: }
1.223     albertel 15330: 
1.222     foxr     15331: #  Same as escape_single, but escape's "'s  This 
                   15332: #  can be used for  "strings"
                   15333: sub escape_double {
                   15334:     my ($input) = @_;
                   15335:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15336:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15337:     return $input;
                   15338: }
1.223     albertel 15339:  
1.222     foxr     15340: #   Escapes the last element of a full URL.
                   15341: sub escape_url {
                   15342:     my ($url)   = @_;
1.238     raeburn  15343:     my @urlslices = split(/\//, $url,-1);
1.369     www      15344:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  15345:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15346: }
1.462     albertel 15347: 
1.820     raeburn  15348: sub compare_arrays {
                   15349:     my ($arrayref1,$arrayref2) = @_;
                   15350:     my (@difference,%count);
                   15351:     @difference = ();
                   15352:     %count = ();
                   15353:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   15354:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   15355:         foreach my $element (keys(%count)) {
                   15356:             if ($count{$element} == 1) {
                   15357:                 push(@difference,$element);
                   15358:             }
                   15359:         }
                   15360:     }
                   15361:     return @difference;
                   15362: }
                   15363: 
1.817     bisitz   15364: # -------------------------------------------------------- Initialize user login
1.462     albertel 15365: sub init_user_environment {
1.463     albertel 15366:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 15367:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   15368: 
                   15369:     my $public=($username eq 'public' && $domain eq 'public');
                   15370: 
                   15371: # See if old ID present, if so, remove
                   15372: 
1.1062    raeburn  15373:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 15374:     my $now=time;
                   15375: 
                   15376:     if ($public) {
                   15377: 	my $max_public=100;
                   15378: 	my $oldest;
                   15379: 	my $oldest_time=0;
                   15380: 	for(my $next=1;$next<=$max_public;$next++) {
                   15381: 	    if (-e $lonids."/publicuser_$next.id") {
                   15382: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   15383: 		if ($mtime<$oldest_time || !$oldest_time) {
                   15384: 		    $oldest_time=$mtime;
                   15385: 		    $oldest=$next;
                   15386: 		}
                   15387: 	    } else {
                   15388: 		$cookie="publicuser_$next";
                   15389: 		last;
                   15390: 	    }
                   15391: 	}
                   15392: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   15393:     } else {
1.463     albertel 15394: 	# if this isn't a robot, kill any existing non-robot sessions
                   15395: 	if (!$args->{'robot'}) {
                   15396: 	    opendir(DIR,$lonids);
                   15397: 	    while ($filename=readdir(DIR)) {
                   15398: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   15399: 		    unlink($lonids.'/'.$filename);
                   15400: 		}
1.462     albertel 15401: 	    }
1.463     albertel 15402: 	    closedir(DIR);
1.1075.2.84  raeburn  15403: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   15404:             my $namespace = 'nohist_courseeditor';
                   15405:             my $lockingkey = 'paste'."\0".'locked_num';
                   15406:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15407:                                                 $domain,$username);
                   15408:             if (exists($lockhash{$lockingkey})) {
                   15409:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15410:                 unless ($delresult eq 'ok') {
                   15411:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15412:                 }
                   15413:             }
1.462     albertel 15414: 	}
                   15415: # Give them a new cookie
1.463     albertel 15416: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15417: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15418: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15419:     
                   15420: # Initialize roles
                   15421: 
1.1062    raeburn  15422: 	($userroles,$firstaccenv,$timerintenv) = 
                   15423:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15424:     }
                   15425: # ------------------------------------ Check browser type and MathML capability
                   15426: 
1.1075.2.77  raeburn  15427:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15428:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15429: 
                   15430: # ------------------------------------------------------------- Get environment
                   15431: 
                   15432:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15433:     my ($tmp) = keys(%userenv);
                   15434:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15435:     } else {
                   15436: 	undef(%userenv);
                   15437:     }
                   15438:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15439: 	$form->{'interface'}=$userenv{'interface'};
                   15440:     }
                   15441:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15442: 
                   15443: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15444:     foreach my $option ('interface','localpath','localres') {
                   15445:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15446:     }
                   15447: # --------------------------------------------------------- Write first profile
                   15448: 
                   15449:     {
                   15450: 	my %initial_env = 
                   15451: 	    ("user.name"          => $username,
                   15452: 	     "user.domain"        => $domain,
                   15453: 	     "user.home"          => $authhost,
                   15454: 	     "browser.type"       => $clientbrowser,
                   15455: 	     "browser.version"    => $clientversion,
                   15456: 	     "browser.mathml"     => $clientmathml,
                   15457: 	     "browser.unicode"    => $clientunicode,
                   15458: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  15459:              "browser.mobile"     => $clientmobile,
                   15460:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  15461:              "browser.osversion"  => $clientosversion,
1.462     albertel 15462: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15463: 	     "request.course.fn"  => '',
                   15464: 	     "request.course.uri" => '',
                   15465: 	     "request.course.sec" => '',
                   15466: 	     "request.role"       => 'cm',
                   15467: 	     "request.role.adv"   => $env{'user.adv'},
                   15468: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   15469: 
                   15470:         if ($form->{'localpath'}) {
                   15471: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15472: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15473:         }
                   15474: 	
                   15475: 	if ($form->{'interface'}) {
                   15476: 	    $form->{'interface'}=~s/\W//gs;
                   15477: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15478: 	    $env{'browser.interface'}=$form->{'interface'};
                   15479: 	}
                   15480: 
1.1075.2.54  raeburn  15481:         if ($form->{'iptoken'}) {
                   15482:             my $lonhost = $r->dir_config('lonHostID');
                   15483:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15484:             $env{'user.noloadbalance'} = $lonhost;
                   15485:         }
                   15486: 
1.1075.2.120  raeburn  15487:         if ($form->{'noloadbalance'}) {
                   15488:             my @hosts = &Apache::lonnet::current_machine_ids();
                   15489:             my $hosthere = $form->{'noloadbalance'};
                   15490:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   15491:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   15492:                 $env{'user.noloadbalance'} = $hosthere;
                   15493:             }
                   15494:         }
                   15495: 
1.1016    raeburn  15496:         unless ($domain eq 'public') {
1.1075.2.125  raeburn  15497:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   15498:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
1.980     raeburn  15499: 
1.1075.2.125  raeburn  15500:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   15501:                 $userenv{'availabletools.'.$tool} = 
                   15502:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   15503:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   15504:             }
1.724     raeburn  15505: 
1.1075.2.125  raeburn  15506:             foreach my $crstype ('official','unofficial','community','textbook') {
                   15507:                 $userenv{'canrequest.'.$crstype} =
                   15508:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   15509:                                                       'reload','requestcourses',
                   15510:                                                       \%userenv,\%domdef,\%is_adv);
                   15511:             }
1.765     raeburn  15512: 
1.1075.2.125  raeburn  15513:             $userenv{'canrequest.author'} =
                   15514:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   15515:                                                   'reload','requestauthor',
                   15516:                                                   \%userenv,\%domdef,\%is_adv);
                   15517:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   15518:                                                  $domain,$username);
                   15519:             my $reqstatus = $reqauthor{'author_status'};
                   15520:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   15521:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   15522:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   15523:                                                       $reqauthor{'author'}{'timestamp'};
                   15524:                 }
1.1075.2.14  raeburn  15525:             }
                   15526:         }
                   15527: 
1.462     albertel 15528: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  15529: 
1.462     albertel 15530: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   15531: 		 &GDBM_WRCREAT(),0640)) {
                   15532: 	    &_add_to_env(\%disk_env,\%initial_env);
                   15533: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   15534: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  15535:             if (ref($firstaccenv) eq 'HASH') {
                   15536:                 &_add_to_env(\%disk_env,$firstaccenv);
                   15537:             }
                   15538:             if (ref($timerintenv) eq 'HASH') {
                   15539:                 &_add_to_env(\%disk_env,$timerintenv);
                   15540:             }
1.463     albertel 15541: 	    if (ref($args->{'extra_env'})) {
                   15542: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   15543: 	    }
1.462     albertel 15544: 	    untie(%disk_env);
                   15545: 	} else {
1.705     tempelho 15546: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   15547: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 15548: 	    return 'error: '.$!;
                   15549: 	}
                   15550:     }
                   15551:     $env{'request.role'}='cm';
                   15552:     $env{'request.role.adv'}=$env{'user.adv'};
                   15553:     $env{'browser.type'}=$clientbrowser;
                   15554: 
                   15555:     return $cookie;
                   15556: 
                   15557: }
                   15558: 
                   15559: sub _add_to_env {
                   15560:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  15561:     if (ref($env_data) eq 'HASH') {
                   15562:         while (my ($key,$value) = each(%$env_data)) {
                   15563: 	    $idf->{$prefix.$key} = $value;
                   15564: 	    $env{$prefix.$key}   = $value;
                   15565:         }
1.462     albertel 15566:     }
                   15567: }
                   15568: 
1.685     tempelho 15569: # --- Get the symbolic name of a problem and the url
                   15570: sub get_symb {
                   15571:     my ($request,$silent) = @_;
1.726     raeburn  15572:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 15573:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   15574:     if ($symb eq '') {
                   15575:         if (!$silent) {
1.1071    raeburn  15576:             if (ref($request)) { 
                   15577:                 $request->print("Unable to handle ambiguous references:$url:.");
                   15578:             }
1.685     tempelho 15579:             return ();
                   15580:         }
                   15581:     }
                   15582:     &Apache::lonenc::check_decrypt(\$symb);
                   15583:     return ($symb);
                   15584: }
                   15585: 
                   15586: # --------------------------------------------------------------Get annotation
                   15587: 
                   15588: sub get_annotation {
                   15589:     my ($symb,$enc) = @_;
                   15590: 
                   15591:     my $key = $symb;
                   15592:     if (!$enc) {
                   15593:         $key =
                   15594:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   15595:     }
                   15596:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   15597:     return $annotation{$key};
                   15598: }
                   15599: 
                   15600: sub clean_symb {
1.731     raeburn  15601:     my ($symb,$delete_enc) = @_;
1.685     tempelho 15602: 
                   15603:     &Apache::lonenc::check_decrypt(\$symb);
                   15604:     my $enc = $env{'request.enc'};
1.731     raeburn  15605:     if ($delete_enc) {
1.730     raeburn  15606:         delete($env{'request.enc'});
                   15607:     }
1.685     tempelho 15608: 
                   15609:     return ($symb,$enc);
                   15610: }
1.462     albertel 15611: 
1.1075.2.69  raeburn  15612: ############################################################
                   15613: ############################################################
                   15614: 
                   15615: =pod
                   15616: 
                   15617: =head1 Routines for building display used to search for courses
                   15618: 
                   15619: 
                   15620: =over 4
                   15621: 
                   15622: =item * &build_filters()
                   15623: 
                   15624: Create markup for a table used to set filters to use when selecting
                   15625: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   15626: and quotacheck.pl
                   15627: 
                   15628: 
                   15629: Inputs:
                   15630: 
                   15631: filterlist - anonymous array of fields to include as potential filters
                   15632: 
                   15633: crstype - course type
                   15634: 
                   15635: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   15636:               to pop-open a course selector (will contain "extra element").
                   15637: 
                   15638: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   15639: 
                   15640: filter - anonymous hash of criteria and their values
                   15641: 
                   15642: action - form action
                   15643: 
                   15644: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   15645: 
                   15646: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   15647: 
                   15648: cloneruname - username of owner of new course who wants to clone
                   15649: 
                   15650: clonerudom - domain of owner of new course who wants to clone
                   15651: 
                   15652: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   15653: 
                   15654: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   15655: 
                   15656: codedom - domain
                   15657: 
                   15658: formname - value of form element named "form".
                   15659: 
                   15660: fixeddom - domain, if fixed.
                   15661: 
                   15662: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   15663: 
                   15664: cnameelement - name of form element in form on opener page which will receive title of selected course
                   15665: 
                   15666: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   15667: 
                   15668: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   15669: 
                   15670: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   15671: 
                   15672: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   15673: 
                   15674: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   15675: 
                   15676: 
                   15677: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   15678: 
                   15679: 
                   15680: Side Effects: None
                   15681: 
                   15682: =cut
                   15683: 
                   15684: # ---------------------------------------------- search for courses based on last activity etc.
                   15685: 
                   15686: sub build_filters {
                   15687:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   15688:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   15689:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   15690:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   15691:         $clonetext,$clonewarning) = @_;
                   15692:     my ($list,$jscript);
                   15693:     my $onchange = 'javascript:updateFilters(this)';
                   15694:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   15695:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   15696:         $typeselectform,$instcodetitle);
                   15697:     if ($formname eq '') {
                   15698:         $formname = $caller;
                   15699:     }
                   15700:     foreach my $item (@{$filterlist}) {
                   15701:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   15702:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   15703:             if ($item eq 'domainfilter') {
                   15704:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   15705:             } elsif ($item eq 'coursefilter') {
                   15706:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   15707:             } elsif ($item eq 'ownerfilter') {
                   15708:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15709:             } elsif ($item eq 'ownerdomfilter') {
                   15710:                 $filter->{'ownerdomfilter'} =
                   15711:                     &LONCAPA::clean_domain($filter->{$item});
                   15712:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   15713:                                                        'ownerdomfilter',1);
                   15714:             } elsif ($item eq 'personfilter') {
                   15715:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15716:             } elsif ($item eq 'persondomfilter') {
                   15717:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   15718:                                                         'persondomfilter',1);
                   15719:             } else {
                   15720:                 $filter->{$item} =~ s/\W//g;
                   15721:             }
                   15722:             if (!$filter->{$item}) {
                   15723:                 $filter->{$item} = '';
                   15724:             }
                   15725:         }
                   15726:         if ($item eq 'domainfilter') {
                   15727:             my $allow_blank = 1;
                   15728:             if ($formname eq 'portform') {
                   15729:                 $allow_blank=0;
                   15730:             } elsif ($formname eq 'studentform') {
                   15731:                 $allow_blank=0;
                   15732:             }
                   15733:             if ($fixeddom) {
                   15734:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   15735:                                     ' value="'.$codedom.'" />'.
                   15736:                                     &Apache::lonnet::domain($codedom,'description');
                   15737:             } else {
                   15738:                 $domainselectform = &select_dom_form($filter->{$item},
                   15739:                                                      'domainfilter',
                   15740:                                                       $allow_blank,'',$onchange);
                   15741:             }
                   15742:         } else {
                   15743:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   15744:         }
                   15745:     }
                   15746: 
                   15747:     # last course activity filter and selection
                   15748:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   15749: 
                   15750:     # course created filter and selection
                   15751:     if (exists($filter->{'createdfilter'})) {
                   15752:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   15753:     }
                   15754: 
                   15755:     my %lt = &Apache::lonlocal::texthash(
                   15756:                 'cac' => "$crstype Activity",
                   15757:                 'ccr' => "$crstype Created",
                   15758:                 'cde' => "$crstype Title",
                   15759:                 'cdo' => "$crstype Domain",
                   15760:                 'ins' => 'Institutional Code',
                   15761:                 'inc' => 'Institutional Categorization',
                   15762:                 'cow' => "$crstype Owner/Co-owner",
                   15763:                 'cop' => "$crstype Personnel Includes",
                   15764:                 'cog' => 'Type',
                   15765:              );
                   15766: 
                   15767:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15768:         my $typeval = 'Course';
                   15769:         if ($crstype eq 'Community') {
                   15770:             $typeval = 'Community';
                   15771:         }
                   15772:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   15773:     } else {
                   15774:         $typeselectform =  '<select name="type" size="1"';
                   15775:         if ($onchange) {
                   15776:             $typeselectform .= ' onchange="'.$onchange.'"';
                   15777:         }
                   15778:         $typeselectform .= '>'."\n";
                   15779:         foreach my $posstype ('Course','Community') {
                   15780:             $typeselectform.='<option value="'.$posstype.'"'.
                   15781:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   15782:         }
                   15783:         $typeselectform.="</select>";
                   15784:     }
                   15785: 
                   15786:     my ($cloneableonlyform,$cloneabletitle);
                   15787:     if (exists($filter->{'cloneableonly'})) {
                   15788:         my $cloneableon = '';
                   15789:         my $cloneableoff = ' checked="checked"';
                   15790:         if ($filter->{'cloneableonly'}) {
                   15791:             $cloneableon = $cloneableoff;
                   15792:             $cloneableoff = '';
                   15793:         }
                   15794:         $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>';
                   15795:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  15796:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  15797:         } else {
                   15798:             $cloneabletitle = &mt('Cloneable by you');
                   15799:         }
                   15800:     }
                   15801:     my $officialjs;
                   15802:     if ($crstype eq 'Course') {
                   15803:         if (exists($filter->{'instcodefilter'})) {
                   15804: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   15805: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   15806:             if ($codedom) {
                   15807:                 $officialjs = 1;
                   15808:                 ($instcodeform,$jscript,$$numtitlesref) =
                   15809:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   15810:                                                                   $officialjs,$codetitlesref);
                   15811:                 if ($jscript) {
                   15812:                     $jscript = '<script type="text/javascript">'."\n".
                   15813:                                '// <![CDATA['."\n".
                   15814:                                $jscript."\n".
                   15815:                                '// ]]>'."\n".
                   15816:                                '</script>'."\n";
                   15817:                 }
                   15818:             }
                   15819:             if ($instcodeform eq '') {
                   15820:                 $instcodeform =
                   15821:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   15822:                     $list->{'instcodefilter'}.'" />';
                   15823:                 $instcodetitle = $lt{'ins'};
                   15824:             } else {
                   15825:                 $instcodetitle = $lt{'inc'};
                   15826:             }
                   15827:             if ($fixeddom) {
                   15828:                 $instcodetitle .= '<br />('.$codedom.')';
                   15829:             }
                   15830:         }
                   15831:     }
                   15832:     my $output = qq|
                   15833: <form method="post" name="filterpicker" action="$action">
                   15834: <input type="hidden" name="form" value="$formname" />
                   15835: |;
                   15836:     if ($formname eq 'modifycourse') {
                   15837:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   15838:                    '<input type="hidden" name="prevphase" value="'.
                   15839:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  15840:     } elsif ($formname eq 'quotacheck') {
                   15841:         $output .= qq|
                   15842: <input type="hidden" name="sortby" value="" />
                   15843: <input type="hidden" name="sortorder" value="" />
                   15844: |;
                   15845:     } else {
1.1075.2.69  raeburn  15846:         my $name_input;
                   15847:         if ($cnameelement ne '') {
                   15848:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   15849:                           $cnameelement.'" />';
                   15850:         }
                   15851:         $output .= qq|
                   15852: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   15853: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   15854: $name_input
                   15855: $roleelement
                   15856: $multelement
                   15857: $typeelement
                   15858: |;
                   15859:         if ($formname eq 'portform') {
                   15860:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   15861:         }
                   15862:     }
                   15863:     if ($fixeddom) {
                   15864:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   15865:     }
                   15866:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   15867:     if ($sincefilterform) {
                   15868:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   15869:                   .$sincefilterform
                   15870:                   .&Apache::lonhtmlcommon::row_closure();
                   15871:     }
                   15872:     if ($createdfilterform) {
                   15873:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   15874:                   .$createdfilterform
                   15875:                   .&Apache::lonhtmlcommon::row_closure();
                   15876:     }
                   15877:     if ($domainselectform) {
                   15878:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   15879:                   .$domainselectform
                   15880:                   .&Apache::lonhtmlcommon::row_closure();
                   15881:     }
                   15882:     if ($typeselectform) {
                   15883:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15884:             $output .= $typeselectform;
                   15885:         } else {
                   15886:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   15887:                       .$typeselectform
                   15888:                       .&Apache::lonhtmlcommon::row_closure();
                   15889:         }
                   15890:     }
                   15891:     if ($instcodeform) {
                   15892:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   15893:                   .$instcodeform
                   15894:                   .&Apache::lonhtmlcommon::row_closure();
                   15895:     }
                   15896:     if (exists($filter->{'ownerfilter'})) {
                   15897:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   15898:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15899:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   15900:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15901:                    $ownerdomselectform.'</td></tr></table>'.
                   15902:                    &Apache::lonhtmlcommon::row_closure();
                   15903:     }
                   15904:     if (exists($filter->{'personfilter'})) {
                   15905:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   15906:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15907:                    '<input type="text" name="personfilter" size="20" value="'.
                   15908:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15909:                    $persondomselectform.'</td></tr></table>'.
                   15910:                    &Apache::lonhtmlcommon::row_closure();
                   15911:     }
                   15912:     if (exists($filter->{'coursefilter'})) {
                   15913:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   15914:                   .'<input type="text" name="coursefilter" size="25" value="'
                   15915:                   .$list->{'coursefilter'}.'" />'
                   15916:                   .&Apache::lonhtmlcommon::row_closure();
                   15917:     }
                   15918:     if ($cloneableonlyform) {
                   15919:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   15920:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   15921:     }
                   15922:     if (exists($filter->{'descriptfilter'})) {
                   15923:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   15924:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   15925:                   .$list->{'descriptfilter'}.'" />'
                   15926:                   .&Apache::lonhtmlcommon::row_closure(1);
                   15927:     }
                   15928:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   15929:                '<input type="hidden" name="updater" value="" />'."\n".
                   15930:                '<input type="submit" name="gosearch" value="'.
                   15931:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   15932:     return $jscript.$clonewarning.$output;
                   15933: }
                   15934: 
                   15935: =pod
                   15936: 
                   15937: =item * &timebased_select_form()
                   15938: 
                   15939: Create markup for a dropdown list used to select a time-based
                   15940: filter e.g., Course Activity, Course Created, when searching for courses
                   15941: or communities
                   15942: 
                   15943: Inputs:
                   15944: 
                   15945: item - name of form element (sincefilter or createdfilter)
                   15946: 
                   15947: filter - anonymous hash of criteria and their values
                   15948: 
                   15949: Returns: HTML for a select box contained a blank, then six time selections,
                   15950:          with value set in incoming form variables currently selected.
                   15951: 
                   15952: Side Effects: None
                   15953: 
                   15954: =cut
                   15955: 
                   15956: sub timebased_select_form {
                   15957:     my ($item,$filter) = @_;
                   15958:     if (ref($filter) eq 'HASH') {
                   15959:         $filter->{$item} =~ s/[^\d-]//g;
                   15960:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   15961:         return &select_form(
                   15962:                             $filter->{$item},
                   15963:                             $item,
                   15964:                             {      '-1' => '',
                   15965:                                 '86400' => &mt('today'),
                   15966:                                '604800' => &mt('last week'),
                   15967:                               '2592000' => &mt('last month'),
                   15968:                               '7776000' => &mt('last three months'),
                   15969:                              '15552000' => &mt('last six months'),
                   15970:                              '31104000' => &mt('last year'),
                   15971:                     'select_form_order' =>
                   15972:                            ['-1','86400','604800','2592000','7776000',
                   15973:                             '15552000','31104000']});
                   15974:     }
                   15975: }
                   15976: 
                   15977: =pod
                   15978: 
                   15979: =item * &js_changer()
                   15980: 
                   15981: Create script tag containing Javascript used to submit course search form
                   15982: when course type or domain is changed, and also to hide 'Searching ...' on
                   15983: page load completion for page showing search result.
                   15984: 
                   15985: Inputs: None
                   15986: 
                   15987: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   15988: 
                   15989: Side Effects: None
                   15990: 
                   15991: =cut
                   15992: 
                   15993: sub js_changer {
                   15994:     return <<ENDJS;
                   15995: <script type="text/javascript">
                   15996: // <![CDATA[
                   15997: function updateFilters(caller) {
                   15998:     if (typeof(caller) != "undefined") {
                   15999:         document.filterpicker.updater.value = caller.name;
                   16000:     }
                   16001:     document.filterpicker.submit();
                   16002: }
                   16003: 
                   16004: function hideSearching() {
                   16005:     if (document.getElementById('searching')) {
                   16006:         document.getElementById('searching').style.display = 'none';
                   16007:     }
                   16008:     return;
                   16009: }
                   16010: 
                   16011: // ]]>
                   16012: </script>
                   16013: 
                   16014: ENDJS
                   16015: }
                   16016: 
                   16017: =pod
                   16018: 
                   16019: =item * &search_courses()
                   16020: 
                   16021: Process selected filters form course search form and pass to lonnet::courseiddump
                   16022: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16023: 
                   16024: Inputs:
                   16025: 
                   16026: dom - domain being searched
                   16027: 
                   16028: type - course type ('Course' or 'Community' or '.' if any).
                   16029: 
                   16030: filter - anonymous hash of criteria and their values
                   16031: 
                   16032: numtitles - for institutional codes - number of categories
                   16033: 
                   16034: cloneruname - optional username of new course owner
                   16035: 
                   16036: clonerudom - optional domain of new course owner
                   16037: 
1.1075.2.95  raeburn  16038: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  16039:             (used when DC is using course creation form)
                   16040: 
                   16041: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16042: 
1.1075.2.95  raeburn  16043: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16044:            (and so can clone automatically)
                   16045: 
                   16046: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16047: 
                   16048: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   16049:               courses to clone
1.1075.2.69  raeburn  16050: 
                   16051: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16052: 
                   16053: 
                   16054: Side Effects: None
                   16055: 
                   16056: =cut
                   16057: 
                   16058: 
                   16059: sub search_courses {
1.1075.2.95  raeburn  16060:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   16061:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  16062:     my (%courses,%showcourses,$cloner);
                   16063:     if (($filter->{'ownerfilter'} ne '') ||
                   16064:         ($filter->{'ownerdomfilter'} ne '')) {
                   16065:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   16066:                                        $filter->{'ownerdomfilter'};
                   16067:     }
                   16068:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   16069:         if (!$filter->{$item}) {
                   16070:             $filter->{$item}='.';
                   16071:         }
                   16072:     }
                   16073:     my $now = time;
                   16074:     my $timefilter =
                   16075:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   16076:     my ($createdbefore,$createdafter);
                   16077:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   16078:         $createdbefore = $now;
                   16079:         $createdafter = $now-$filter->{'createdfilter'};
                   16080:     }
                   16081:     my ($instcodefilter,$regexpok);
                   16082:     if ($numtitles) {
                   16083:         if ($env{'form.official'} eq 'on') {
                   16084:             $instcodefilter =
                   16085:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16086:             $regexpok = 1;
                   16087:         } elsif ($env{'form.official'} eq 'off') {
                   16088:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16089:             unless ($instcodefilter eq '') {
                   16090:                 $regexpok = -1;
                   16091:             }
                   16092:         }
                   16093:     } else {
                   16094:         $instcodefilter = $filter->{'instcodefilter'};
                   16095:     }
                   16096:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   16097:     if ($type eq '') { $type = '.'; }
                   16098: 
                   16099:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   16100:         $cloner = $cloneruname.':'.$clonerudom;
                   16101:     }
                   16102:     %courses = &Apache::lonnet::courseiddump($dom,
                   16103:                                              $filter->{'descriptfilter'},
                   16104:                                              $timefilter,
                   16105:                                              $instcodefilter,
                   16106:                                              $filter->{'combownerfilter'},
                   16107:                                              $filter->{'coursefilter'},
                   16108:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  16109:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  16110:                                              $filter->{'cloneableonly'},
                   16111:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  16112:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  16113:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   16114:         my $ccrole;
                   16115:         if ($type eq 'Community') {
                   16116:             $ccrole = 'co';
                   16117:         } else {
                   16118:             $ccrole = 'cc';
                   16119:         }
                   16120:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   16121:                                                      $filter->{'persondomfilter'},
                   16122:                                                      'userroles',undef,
                   16123:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   16124:                                                      $dom);
                   16125:         foreach my $role (keys(%rolehash)) {
                   16126:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   16127:             my $cid = $cdom.'_'.$cnum;
                   16128:             if (exists($courses{$cid})) {
                   16129:                 if (ref($courses{$cid}) eq 'HASH') {
                   16130:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   16131:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1075.2.119  raeburn  16132:                             push(@{$courses{$cid}{roles}},$courserole);
1.1075.2.69  raeburn  16133:                         }
                   16134:                     } else {
                   16135:                         $courses{$cid}{roles} = [$courserole];
                   16136:                     }
                   16137:                     $showcourses{$cid} = $courses{$cid};
                   16138:                 }
                   16139:             }
                   16140:         }
                   16141:         %courses = %showcourses;
                   16142:     }
                   16143:     return %courses;
                   16144: }
                   16145: 
                   16146: =pod
                   16147: 
                   16148: =back
                   16149: 
1.1075.2.88  raeburn  16150: =head1 Routines for version requirements for current course.
                   16151: 
                   16152: =over 4
                   16153: 
                   16154: =item * &check_release_required()
                   16155: 
                   16156: Compares required LON-CAPA version with version on server, and
                   16157: if required version is newer looks for a server with the required version.
                   16158: 
                   16159: Looks first at servers in user's owen domain; if none suitable, looks at
                   16160: servers in course's domain are permitted to host sessions for user's domain.
                   16161: 
                   16162: Inputs:
                   16163: 
                   16164: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16165: 
                   16166: $courseid - Course ID of current course
                   16167: 
                   16168: $rolecode - User's current role in course (for switchserver query string).
                   16169: 
                   16170: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16171: 
                   16172: 
                   16173: Returns:
                   16174: 
                   16175: $switchserver - query string tp append to /adm/switchserver call (if
                   16176:                 current server's LON-CAPA version is too old.
                   16177: 
                   16178: $warning - Message is displayed if no suitable server could be found.
                   16179: 
                   16180: =cut
                   16181: 
                   16182: sub check_release_required {
                   16183:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16184:     my ($switchserver,$warning);
                   16185:     if ($required ne '') {
                   16186:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16187:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16188:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16189:             my $otherserver;
                   16190:             if (($major eq '' && $minor eq '') ||
                   16191:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16192:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16193:                 my $switchlcrev =
                   16194:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16195:                                                            $userdomserver);
                   16196:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16197:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16198:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16199:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16200:                     if ($cdom ne $env{'user.domain'}) {
                   16201:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16202:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16203:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16204:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16205:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16206:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16207:                         my $canhost =
                   16208:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16209:                                                               $coursedomserver,
                   16210:                                                               $remoterev,
                   16211:                                                               $udomdefaults{'remotesessions'},
                   16212:                                                               $defdomdefaults{'hostedsessions'});
                   16213: 
                   16214:                         if ($canhost) {
                   16215:                             $otherserver = $coursedomserver;
                   16216:                         } else {
                   16217:                             $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.");
                   16218:                         }
                   16219:                     } else {
                   16220:                         $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).");
                   16221:                     }
                   16222:                 } else {
                   16223:                     $otherserver = $userdomserver;
                   16224:                 }
                   16225:             }
                   16226:             if ($otherserver ne '') {
                   16227:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16228:             }
                   16229:         }
                   16230:     }
                   16231:     return ($switchserver,$warning);
                   16232: }
                   16233: 
                   16234: =pod
                   16235: 
                   16236: =item * &check_release_result()
                   16237: 
                   16238: Inputs:
                   16239: 
                   16240: $switchwarning - Warning message if no suitable server found to host session.
                   16241: 
                   16242: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16243:                 and current role.
                   16244: 
                   16245: Returns: HTML to display with information about requirement to switch server.
                   16246:          Either displaying warning with link to Roles/Courses screen or
                   16247:          display link to switchserver.
                   16248: 
1.1075.2.69  raeburn  16249: =cut
                   16250: 
1.1075.2.88  raeburn  16251: sub check_release_result {
                   16252:     my ($switchwarning,$switchserver) = @_;
                   16253:     my $output = &start_page('Selected course unavailable on this server').
                   16254:                  '<p class="LC_warning">';
                   16255:     if ($switchwarning) {
                   16256:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16257:         if (&show_course()) {
                   16258:             $output .= &mt('Display courses');
                   16259:         } else {
                   16260:             $output .= &mt('Display roles');
                   16261:         }
                   16262:         $output .= '</a>';
                   16263:     } elsif ($switchserver) {
                   16264:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16265:                    '<br />'.
                   16266:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16267:                    &mt('Switch Server').
                   16268:                    '</a>';
                   16269:     }
                   16270:     $output .= '</p>'.&end_page();
                   16271:     return $output;
                   16272: }
                   16273: 
                   16274: =pod
                   16275: 
                   16276: =item * &needs_coursereinit()
                   16277: 
                   16278: Determine if course contents stored for user's session needs to be
                   16279: refreshed, because content has changed since "Big Hash" last tied.
                   16280: 
                   16281: Check for change is made if time last checked is more than 10 minutes ago
                   16282: (by default).
                   16283: 
                   16284: Inputs:
                   16285: 
                   16286: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16287: 
                   16288: $interval (optional) - Time which may elapse (in s) between last check for content
                   16289:                        change in current course. (default: 600 s).
                   16290: 
                   16291: Returns: an array; first element is:
                   16292: 
                   16293: =over 4
                   16294: 
                   16295: 'switch' - if content updates mean user's session
                   16296:            needs to be switched to a server running a newer LON-CAPA version
                   16297: 
                   16298: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16299:            on current server hosting user's session
                   16300: 
                   16301: ''       - if no action required.
                   16302: 
                   16303: =back
                   16304: 
                   16305: If first item element is 'switch':
                   16306: 
                   16307: second item is $switchwarning - Warning message if no suitable server found to host session.
                   16308: 
                   16309: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16310:                               and current role.
                   16311: 
                   16312: otherwise: no other elements returned.
                   16313: 
                   16314: =back
                   16315: 
                   16316: =cut
                   16317: 
                   16318: sub needs_coursereinit {
                   16319:     my ($loncaparev,$interval) = @_;
                   16320:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16321:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16322:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16323:     my $now = time;
                   16324:     if ($interval eq '') {
                   16325:         $interval = 600;
                   16326:     }
                   16327:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16328:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16329:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   16330:         if ($lastchange > $env{'request.course.tied'}) {
                   16331:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16332:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16333:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16334:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16335:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16336:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16337:                     my ($switchserver,$switchwarning) =
                   16338:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   16339:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   16340:                     if ($switchwarning ne '' || $switchserver ne '') {
                   16341:                         return ('switch',$switchwarning,$switchserver);
                   16342:                     }
                   16343:                 }
                   16344:             }
                   16345:             return ('update');
                   16346:         }
                   16347:     }
                   16348:     return ();
                   16349: }
1.1075.2.69  raeburn  16350: 
1.1075.2.11  raeburn  16351: sub update_content_constraints {
                   16352:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16353:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16354:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   16355:     my %checkresponsetypes;
                   16356:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   16357:         my ($item,$name,$value) = split(/:/,$key);
                   16358:         if ($item eq 'resourcetag') {
                   16359:             if ($name eq 'responsetype') {
                   16360:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   16361:             }
                   16362:         }
                   16363:     }
                   16364:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16365:     if (defined($navmap)) {
                   16366:         my %allresponses;
                   16367:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   16368:             my %responses = $res->responseTypes();
                   16369:             foreach my $key (keys(%responses)) {
                   16370:                 next unless(exists($checkresponsetypes{$key}));
                   16371:                 $allresponses{$key} += $responses{$key};
                   16372:             }
                   16373:         }
                   16374:         foreach my $key (keys(%allresponses)) {
                   16375:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   16376:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   16377:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   16378:             }
                   16379:         }
                   16380:         undef($navmap);
                   16381:     }
                   16382:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   16383:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   16384:     }
                   16385:     return;
                   16386: }
                   16387: 
1.1075.2.27  raeburn  16388: sub allmaps_incourse {
                   16389:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16390:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   16391:         $cid = $env{'request.course.id'};
                   16392:         $cdom = $env{'course.'.$cid.'.domain'};
                   16393:         $cnum = $env{'course.'.$cid.'.num'};
                   16394:         $chome = $env{'course.'.$cid.'.home'};
                   16395:     }
                   16396:     my %allmaps = ();
                   16397:     my $lastchange =
                   16398:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16399:     if ($lastchange > $env{'request.course.tied'}) {
                   16400:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   16401:         unless ($ferr) {
                   16402:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   16403:         }
                   16404:     }
                   16405:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16406:     if (defined($navmap)) {
                   16407:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   16408:             $allmaps{$res->src()} = 1;
                   16409:         }
                   16410:     }
                   16411:     return \%allmaps;
                   16412: }
                   16413: 
1.1075.2.11  raeburn  16414: sub parse_supplemental_title {
                   16415:     my ($title) = @_;
                   16416: 
                   16417:     my ($foldertitle,$renametitle);
                   16418:     if ($title =~ /&amp;&amp;&amp;/) {
                   16419:         $title = &HTML::Entites::decode($title);
                   16420:     }
                   16421:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   16422:         $renametitle=$4;
                   16423:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16424:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16425:         my $name =  &plainname($uname,$udom);
                   16426:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16427:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16428:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16429:             $name.': <br />'.$foldertitle;
                   16430:     }
                   16431:     if (wantarray) {
                   16432:         return ($title,$foldertitle,$renametitle);
                   16433:     }
                   16434:     return $title;
                   16435: }
                   16436: 
1.1075.2.43  raeburn  16437: sub recurse_supplemental {
                   16438:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16439:     if ($suppmap) {
                   16440:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16441:         if ($fatal) {
                   16442:             $errors ++;
                   16443:         } else {
                   16444:             if ($#LONCAPA::map::resources > 0) {
                   16445:                 foreach my $res (@LONCAPA::map::resources) {
                   16446:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16447:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  16448:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16449:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  16450:                         } else {
                   16451:                             $numfiles ++;
                   16452:                         }
                   16453:                     }
                   16454:                 }
                   16455:             }
                   16456:         }
                   16457:     }
                   16458:     return ($numfiles,$errors);
                   16459: }
                   16460: 
1.1075.2.18  raeburn  16461: sub symb_to_docspath {
1.1075.2.119  raeburn  16462:     my ($symb,$navmapref) = @_;
                   16463:     return unless ($symb && ref($navmapref));
1.1075.2.18  raeburn  16464:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16465:     if ($resurl=~/\.(sequence|page)$/) {
                   16466:         $mapurl=$resurl;
                   16467:     } elsif ($resurl eq 'adm/navmaps') {
                   16468:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16469:     }
                   16470:     my $mapresobj;
1.1075.2.119  raeburn  16471:     unless (ref($$navmapref)) {
                   16472:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   16473:     }
                   16474:     if (ref($$navmapref)) {
                   16475:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1075.2.18  raeburn  16476:     }
                   16477:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16478:     my $type=$2;
                   16479:     my $path;
                   16480:     if (ref($mapresobj)) {
                   16481:         my $pcslist = $mapresobj->map_hierarchy();
                   16482:         if ($pcslist ne '') {
                   16483:             foreach my $pc (split(/,/,$pcslist)) {
                   16484:                 next if ($pc <= 1);
1.1075.2.119  raeburn  16485:                 my $res = $$navmapref->getByMapPc($pc);
1.1075.2.18  raeburn  16486:                 if (ref($res)) {
                   16487:                     my $thisurl = $res->src();
                   16488:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16489:                     my $thistitle = $res->title();
                   16490:                     $path .= '&'.
                   16491:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  16492:                              &escape($thistitle).
1.1075.2.18  raeburn  16493:                              ':'.$res->randompick().
                   16494:                              ':'.$res->randomout().
                   16495:                              ':'.$res->encrypted().
                   16496:                              ':'.$res->randomorder().
                   16497:                              ':'.$res->is_page();
                   16498:                 }
                   16499:             }
                   16500:         }
                   16501:         $path =~ s/^\&//;
                   16502:         my $maptitle = $mapresobj->title();
                   16503:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16504:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16505:         }
                   16506:         $path .= (($path ne '')? '&' : '').
                   16507:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16508:                  &escape($maptitle).
1.1075.2.18  raeburn  16509:                  ':'.$mapresobj->randompick().
                   16510:                  ':'.$mapresobj->randomout().
                   16511:                  ':'.$mapresobj->encrypted().
                   16512:                  ':'.$mapresobj->randomorder().
                   16513:                  ':'.$mapresobj->is_page();
                   16514:     } else {
                   16515:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   16516:         my $ispage = (($type eq 'page')? 1 : '');
                   16517:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16518:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16519:         }
                   16520:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16521:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  16522:     }
                   16523:     unless ($mapurl eq 'default') {
                   16524:         $path = 'default&'.
1.1075.2.46  raeburn  16525:                 &escape('Main Content').
1.1075.2.18  raeburn  16526:                 ':::::&'.$path;
                   16527:     }
                   16528:     return $path;
                   16529: }
                   16530: 
1.1075.2.14  raeburn  16531: sub captcha_display {
                   16532:     my ($context,$lonhost) = @_;
                   16533:     my ($output,$error);
1.1075.2.107  raeburn  16534:     my ($captcha,$pubkey,$privkey,$version) =
                   16535:         &get_captcha_config($context,$lonhost);
1.1075.2.14  raeburn  16536:     if ($captcha eq 'original') {
                   16537:         $output = &create_captcha();
                   16538:         unless ($output) {
                   16539:             $error = 'captcha';
                   16540:         }
                   16541:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  16542:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  16543:         unless ($output) {
                   16544:             $error = 'recaptcha';
                   16545:         }
                   16546:     }
1.1075.2.107  raeburn  16547:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  16548: }
                   16549: 
                   16550: sub captcha_response {
                   16551:     my ($context,$lonhost) = @_;
                   16552:     my ($captcha_chk,$captcha_error);
1.1075.2.109  raeburn  16553:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
1.1075.2.14  raeburn  16554:     if ($captcha eq 'original') {
                   16555:         ($captcha_chk,$captcha_error) = &check_captcha();
                   16556:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  16557:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  16558:     } else {
                   16559:         $captcha_chk = 1;
                   16560:     }
                   16561:     return ($captcha_chk,$captcha_error);
                   16562: }
                   16563: 
                   16564: sub get_captcha_config {
                   16565:     my ($context,$lonhost) = @_;
1.1075.2.107  raeburn  16566:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  16567:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   16568:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   16569:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16570:     if ($context eq 'usercreation') {
                   16571:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   16572:         if (ref($domconfig{$context}) eq 'HASH') {
                   16573:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   16574:             if (ref($hashtocheck) eq 'HASH') {
                   16575:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   16576:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   16577:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   16578:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   16579:                     }
                   16580:                     if ($privkey && $pubkey) {
                   16581:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  16582:                         $version = $hashtocheck->{'recaptchaversion'};
                   16583:                         if ($version ne '2') {
                   16584:                             $version = 1;
                   16585:                         }
1.1075.2.14  raeburn  16586:                     } else {
                   16587:                         $captcha = 'original';
                   16588:                     }
                   16589:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   16590:                     $captcha = 'original';
                   16591:                 }
                   16592:             }
                   16593:         } else {
                   16594:             $captcha = 'captcha';
                   16595:         }
                   16596:     } elsif ($context eq 'login') {
                   16597:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   16598:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   16599:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   16600:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   16601:             if ($privkey && $pubkey) {
                   16602:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  16603:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   16604:                 if ($version ne '2') {
                   16605:                     $version = 1;
                   16606:                 }
1.1075.2.14  raeburn  16607:             } else {
                   16608:                 $captcha = 'original';
                   16609:             }
                   16610:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   16611:             $captcha = 'original';
                   16612:         }
                   16613:     }
1.1075.2.107  raeburn  16614:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  16615: }
                   16616: 
                   16617: sub create_captcha {
                   16618:     my %captcha_params = &captcha_settings();
                   16619:     my ($output,$maxtries,$tries) = ('',10,0);
                   16620:     while ($tries < $maxtries) {
                   16621:         $tries ++;
                   16622:         my $captcha = Authen::Captcha->new (
                   16623:                                            output_folder => $captcha_params{'output_dir'},
                   16624:                                            data_folder   => $captcha_params{'db_dir'},
                   16625:                                           );
                   16626:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   16627: 
                   16628:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   16629:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   16630:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.66  raeburn  16631:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   16632:                       '<br />'.
                   16633:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  16634:             last;
                   16635:         }
                   16636:     }
                   16637:     return $output;
                   16638: }
                   16639: 
                   16640: sub captcha_settings {
                   16641:     my %captcha_params = (
                   16642:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   16643:                            www_output_dir => "/captchaspool",
                   16644:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   16645:                            numchars       => '5',
                   16646:                          );
                   16647:     return %captcha_params;
                   16648: }
                   16649: 
                   16650: sub check_captcha {
                   16651:     my ($captcha_chk,$captcha_error);
                   16652:     my $code = $env{'form.code'};
                   16653:     my $md5sum = $env{'form.crypt'};
                   16654:     my %captcha_params = &captcha_settings();
                   16655:     my $captcha = Authen::Captcha->new(
                   16656:                       output_folder => $captcha_params{'output_dir'},
                   16657:                       data_folder   => $captcha_params{'db_dir'},
                   16658:                   );
1.1075.2.26  raeburn  16659:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  16660:     my %captcha_hash = (
                   16661:                         0       => 'Code not checked (file error)',
                   16662:                        -1      => 'Failed: code expired',
                   16663:                        -2      => 'Failed: invalid code (not in database)',
                   16664:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   16665:     );
                   16666:     if ($captcha_chk != 1) {
                   16667:         $captcha_error = $captcha_hash{$captcha_chk}
                   16668:     }
                   16669:     return ($captcha_chk,$captcha_error);
                   16670: }
                   16671: 
                   16672: sub create_recaptcha {
1.1075.2.107  raeburn  16673:     my ($pubkey,$version) = @_;
                   16674:     if ($version >= 2) {
                   16675:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   16676:     } else {
                   16677:         my $use_ssl;
                   16678:         if ($ENV{'SERVER_PORT'} == 443) {
                   16679:             $use_ssl = 1;
                   16680:         }
                   16681:         my $captcha = Captcha::reCAPTCHA->new;
                   16682:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   16683:                $captcha->get_html($pubkey,undef,$use_ssl).
                   16684:                &mt('If the text is hard to read, [_1] will replace them.',
                   16685:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   16686:                '<br /><br />';
                   16687:      }
1.1075.2.14  raeburn  16688: }
                   16689: 
                   16690: sub check_recaptcha {
1.1075.2.107  raeburn  16691:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  16692:     my $captcha_chk;
1.1075.2.107  raeburn  16693:     if ($version >= 2) {
                   16694:         my $ua = LWP::UserAgent->new;
                   16695:         $ua->timeout(10);
                   16696:         my %info = (
                   16697:                      secret   => $privkey,
                   16698:                      response => $env{'form.g-recaptcha-response'},
                   16699:                      remoteip => $ENV{'REMOTE_ADDR'},
                   16700:                    );
                   16701:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   16702:         if ($response->is_success)  {
                   16703:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   16704:             if (ref($data) eq 'HASH') {
                   16705:                 if ($data->{'success'}) {
                   16706:                     $captcha_chk = 1;
                   16707:                 }
                   16708:             }
                   16709:         }
                   16710:     } else {
                   16711:         my $captcha = Captcha::reCAPTCHA->new;
                   16712:         my $captcha_result =
                   16713:             $captcha->check_answer(
                   16714:                                     $privkey,
                   16715:                                     $ENV{'REMOTE_ADDR'},
                   16716:                                     $env{'form.recaptcha_challenge_field'},
                   16717:                                     $env{'form.recaptcha_response_field'},
                   16718:                                   );
                   16719:         if ($captcha_result->{is_valid}) {
                   16720:             $captcha_chk = 1;
                   16721:         }
1.1075.2.14  raeburn  16722:     }
                   16723:     return $captcha_chk;
                   16724: }
                   16725: 
1.1075.2.64  raeburn  16726: sub emailusername_info {
1.1075.2.103  raeburn  16727:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  16728:     my %titles = &Apache::lonlocal::texthash (
                   16729:                      lastname      => 'Last Name',
                   16730:                      firstname     => 'First Name',
                   16731:                      institution   => 'School/college/university',
                   16732:                      location      => "School's city, state/province, country",
                   16733:                      web           => "School's web address",
                   16734:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  16735:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  16736:                  );
                   16737:     return (\@fields,\%titles);
                   16738: }
                   16739: 
1.1075.2.56  raeburn  16740: sub cleanup_html {
                   16741:     my ($incoming) = @_;
                   16742:     my $outgoing;
                   16743:     if ($incoming ne '') {
                   16744:         $outgoing = $incoming;
                   16745:         $outgoing =~ s/;/&#059;/g;
                   16746:         $outgoing =~ s/\#/&#035;/g;
                   16747:         $outgoing =~ s/\&/&#038;/g;
                   16748:         $outgoing =~ s/</&#060;/g;
                   16749:         $outgoing =~ s/>/&#062;/g;
                   16750:         $outgoing =~ s/\(/&#040/g;
                   16751:         $outgoing =~ s/\)/&#041;/g;
                   16752:         $outgoing =~ s/"/&#034;/g;
                   16753:         $outgoing =~ s/'/&#039;/g;
                   16754:         $outgoing =~ s/\$/&#036;/g;
                   16755:         $outgoing =~ s{/}{&#047;}g;
                   16756:         $outgoing =~ s/=/&#061;/g;
                   16757:         $outgoing =~ s/\\/&#092;/g
                   16758:     }
                   16759:     return $outgoing;
                   16760: }
                   16761: 
1.1075.2.74  raeburn  16762: # Checks for critical messages and returns a redirect url if one exists.
                   16763: # $interval indicates how often to check for messages.
                   16764: sub critical_redirect {
                   16765:     my ($interval) = @_;
                   16766:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   16767:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   16768:                                         $env{'user.name'});
                   16769:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   16770:         my $redirecturl;
                   16771:         if ($what[0]) {
                   16772:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   16773:                 $redirecturl='/adm/email?critical=display';
                   16774:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   16775:                 return (1, $url);
                   16776:             }
                   16777:         }
                   16778:     }
                   16779:     return ();
                   16780: }
                   16781: 
1.1075.2.64  raeburn  16782: # Use:
                   16783: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   16784: #
                   16785: ##################################################
                   16786: #          password associated functions         #
                   16787: ##################################################
                   16788: sub des_keys {
                   16789:     # Make a new key for DES encryption.
                   16790:     # Each key has two parts which are returned separately.
                   16791:     # Please note:  Each key must be passed through the &hex function
                   16792:     # before it is output to the web browser.  The hex versions cannot
                   16793:     # be used to decrypt.
                   16794:     my @hexstr=('0','1','2','3','4','5','6','7',
                   16795:                 '8','9','a','b','c','d','e','f');
                   16796:     my $lkey='';
                   16797:     for (0..7) {
                   16798:         $lkey.=$hexstr[rand(15)];
                   16799:     }
                   16800:     my $ukey='';
                   16801:     for (0..7) {
                   16802:         $ukey.=$hexstr[rand(15)];
                   16803:     }
                   16804:     return ($lkey,$ukey);
                   16805: }
                   16806: 
                   16807: sub des_decrypt {
                   16808:     my ($key,$cyphertext) = @_;
                   16809:     my $keybin=pack("H16",$key);
                   16810:     my $cypher;
                   16811:     if ($Crypt::DES::VERSION>=2.03) {
                   16812:         $cypher=new Crypt::DES $keybin;
                   16813:     } else {
                   16814:         $cypher=new DES $keybin;
                   16815:     }
1.1075.2.106  raeburn  16816:     my $plaintext='';
                   16817:     my $cypherlength = length($cyphertext);
                   16818:     my $numchunks = int($cypherlength/32);
                   16819:     for (my $j=0; $j<$numchunks; $j++) {
                   16820:         my $start = $j*32;
                   16821:         my $cypherblock = substr($cyphertext,$start,32);
                   16822:         my $chunk =
                   16823:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   16824:         $chunk .=
                   16825:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   16826:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   16827:         $plaintext .= $chunk;
                   16828:     }
1.1075.2.64  raeburn  16829:     return $plaintext;
                   16830: }
                   16831: 
1.112     bowersj2 16832: 1;
                   16833: __END__;
1.41      ng       16834: 

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