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

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.118! raeburn     4: # $Id: loncommon.pm,v 1.1075.2.117 2016/11/13 14:38:30 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1075.2.25  raeburn    70: use Apache::lonuserutils();
1.1075.2.27  raeburn    71: use Apache::lonuserstate();
1.1075.2.69  raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    74: use DateTime::TimeZone;
1.1075.2.102  raeburn    75: use DateTime::Locale;
1.1075.2.94  raeburn    76: use Encode();
1.1075.2.14  raeburn    77: use Authen::Captcha;
                     78: use Captcha::reCAPTCHA;
1.1075.2.107  raeburn    79: use JSON::DWIW;
                     80: use LWP::UserAgent;
1.1075.2.64  raeburn    81: use Crypt::DES;
                     82: use DynaLoader; # for Crypt::DES version
1.117     www        83: 
1.517     raeburn    84: # ---------------------------------------------- Designs
                     85: use vars qw(%defaultdesign);
                     86: 
1.22      www        87: my $readit;
                     88: 
1.517     raeburn    89: 
1.157     matthew    90: ##
                     91: ## Global Variables
                     92: ##
1.46      matthew    93: 
1.643     foxr       94: 
                     95: # ----------------------------------------------- SSI with retries:
                     96: #
                     97: 
                     98: =pod
                     99: 
1.648     raeburn   100: =head1 Server Side include with retries:
1.643     foxr      101: 
                    102: =over 4
                    103: 
1.648     raeburn   104: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      105: 
                    106: Performs an ssi with some number of retries.  Retries continue either
                    107: until the result is ok or until the retry count supplied by the
                    108: caller is exhausted.  
                    109: 
                    110: Inputs:
1.648     raeburn   111: 
                    112: =over 4
                    113: 
1.643     foxr      114: resource   - Identifies the resource to insert.
1.648     raeburn   115: 
1.643     foxr      116: retries    - Count of the number of retries allowed.
1.648     raeburn   117: 
1.643     foxr      118: form       - Hash that identifies the rendering options.
                    119: 
1.648     raeburn   120: =back
                    121: 
                    122: Returns:
                    123: 
                    124: =over 4
                    125: 
1.643     foxr      126: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   127: 
1.643     foxr      128: response   - The response from the last attempt (which may or may not have been successful.
                    129: 
1.648     raeburn   130: =back
                    131: 
                    132: =back
                    133: 
1.643     foxr      134: =cut
                    135: 
                    136: sub ssi_with_retries {
                    137:     my ($resource, $retries, %form) = @_;
                    138: 
                    139: 
                    140:     my $ok = 0;			# True if we got a good response.
                    141:     my $content;
                    142:     my $response;
                    143: 
                    144:     # Try to get the ssi done. within the retries count:
                    145: 
                    146:     do {
                    147: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    148: 	$ok      = $response->is_success;
1.650     www       149:         if (!$ok) {
                    150:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    151:         }
1.643     foxr      152: 	$retries--;
                    153:     } while (!$ok && ($retries > 0));
                    154: 
                    155:     if (!$ok) {
                    156: 	$content = '';		# On error return an empty content.
                    157:     }
                    158:     return ($content, $response);
                    159: 
                    160: }
                    161: 
                    162: 
                    163: 
1.20      www       164: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  165: my %language;
1.124     www       166: my %supported_language;
1.1048    foxr      167: my %latex_language;		# For choosing hyphenation in <transl..>
                    168: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  169: my %cprtag;
1.192     taceyjo1  170: my %scprtag;
1.351     www       171: my %fe; my %fd; my %fm;
1.41      ng        172: my %category_extensions;
1.12      harris41  173: 
1.46      matthew   174: # ---------------------------------------------- Thesaurus variables
1.144     matthew   175: #
                    176: # %Keywords:
                    177: #      A hash used by &keyword to determine if a word is considered a keyword.
                    178: # $thesaurus_db_file 
                    179: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   180: 
                    181: my %Keywords;
                    182: my $thesaurus_db_file;
                    183: 
1.144     matthew   184: #
                    185: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    186: # thesaurus.tab, and filecategories.tab.
                    187: #
1.18      www       188: BEGIN {
1.46      matthew   189:     # Variable initialization
                    190:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    191:     #
1.22      www       192:     unless ($readit) {
1.12      harris41  193: # ------------------------------------------------------------------- languages
                    194:     {
1.158     raeburn   195:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    196:                                    '/language.tab';
                    197:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  198:             while (my $line = <$fh>) {
                    199:                 next if ($line=~/^\#/);
                    200:                 chomp($line);
1.1048    foxr      201:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   202:                 $language{$key}=$val.' - '.$enc;
                    203:                 if ($sup) {
                    204:                     $supported_language{$key}=$sup;
                    205:                 }
1.1048    foxr      206: 		if ($latex) {
                    207: 		    $latex_language_bykey{$key} = $latex;
                    208: 		    $latex_language{$two} = $latex;
                    209: 		}
1.158     raeburn   210:             }
                    211:             close($fh);
                    212:         }
1.12      harris41  213:     }
                    214: # ------------------------------------------------------------------ copyrights
                    215:     {
1.158     raeburn   216:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    217:                                   '/copyright.tab';
                    218:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  219:             while (my $line = <$fh>) {
                    220:                 next if ($line=~/^\#/);
                    221:                 chomp($line);
                    222:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   223:                 $cprtag{$key}=$val;
                    224:             }
                    225:             close($fh);
                    226:         }
1.12      harris41  227:     }
1.351     www       228: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  229:     {
                    230:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    231:                                   '/source_copyright.tab';
                    232:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  233:             while (my $line = <$fh>) {
                    234:                 next if ($line =~ /^\#/);
                    235:                 chomp($line);
                    236:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  237:                 $scprtag{$key}=$val;
                    238:             }
                    239:             close($fh);
                    240:         }
                    241:     }
1.63      www       242: 
1.517     raeburn   243: # -------------------------------------------------------------- default domain designs
1.63      www       244:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   245:     my $designfile = $designdir.'/default.tab';
                    246:     if ( open (my $fh,"<$designfile") ) {
                    247:         while (my $line = <$fh>) {
                    248:             next if ($line =~ /^\#/);
                    249:             chomp($line);
                    250:             my ($key,$val)=(split(/\=/,$line));
                    251:             if ($val) { $defaultdesign{$key}=$val; }
                    252:         }
                    253:         close($fh);
1.63      www       254:     }
                    255: 
1.15      harris41  256: # ------------------------------------------------------------- file categories
                    257:     {
1.158     raeburn   258:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    259:                                   '/filecategories.tab';
                    260:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  261: 	    while (my $line = <$fh>) {
                    262: 		next if ($line =~ /^\#/);
                    263: 		chomp($line);
                    264:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.158     raeburn   265:                 push @{$category_extensions{lc($category)}},$extension;
                    266:             }
                    267:             close($fh);
                    268:         }
                    269: 
1.15      harris41  270:     }
1.12      harris41  271: # ------------------------------------------------------------------ file types
                    272:     {
1.158     raeburn   273:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    274:                '/filetypes.tab';
                    275:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  276:             while (my $line = <$fh>) {
                    277: 		next if ($line =~ /^\#/);
                    278: 		chomp($line);
                    279:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   280:                 if ($descr ne '') {
                    281:                     $fe{$ending}=lc($emb);
                    282:                     $fd{$ending}=$descr;
1.351     www       283:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   284:                 }
                    285:             }
                    286:             close($fh);
                    287:         }
1.12      harris41  288:     }
1.22      www       289:     &Apache::lonnet::logthis(
1.705     tempelho  290:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       291:     $readit=1;
1.46      matthew   292:     }  # end of unless($readit) 
1.32      matthew   293:     
                    294: }
1.112     bowersj2  295: 
1.42      matthew   296: ###############################################################
                    297: ##           HTML and Javascript Helper Functions            ##
                    298: ###############################################################
                    299: 
                    300: =pod 
                    301: 
1.112     bowersj2  302: =head1 HTML and Javascript Functions
1.42      matthew   303: 
1.112     bowersj2  304: =over 4
                    305: 
1.648     raeburn   306: =item * &browser_and_searcher_javascript()
1.112     bowersj2  307: 
                    308: X<browsing, javascript>X<searching, javascript>Returns a string
                    309: containing javascript with two functions, C<openbrowser> and
                    310: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    311: tags.
1.42      matthew   312: 
1.648     raeburn   313: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   314: 
                    315: inputs: formname, elementname, only, omit
                    316: 
                    317: formname and elementname indicate the name of the html form and name of
                    318: the element that the results of the browsing selection are to be placed in. 
                    319: 
                    320: Specifying 'only' will restrict the browser to displaying only files
1.185     www       321: with the given extension.  Can be a comma separated list.
1.42      matthew   322: 
                    323: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       324: with the given extension.  Can be a comma separated list.
1.42      matthew   325: 
1.648     raeburn   326: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   327: 
                    328: Inputs: formname, elementname
                    329: 
                    330: formname and elementname specify the name of the html form and the name
                    331: of the element the selection from the search results will be placed in.
1.542     raeburn   332: 
1.42      matthew   333: =cut
                    334: 
                    335: sub browser_and_searcher_javascript {
1.199     albertel  336:     my ($mode)=@_;
                    337:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  338:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   339:     return <<END;
1.219     albertel  340: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   341:     var editbrowser = null;
1.135     albertel  342:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       343:         var url = '$resurl/?';
1.42      matthew   344:         if (editbrowser == null) {
                    345:             url += 'launch=1&';
                    346:         }
                    347:         url += 'catalogmode=interactive&';
1.199     albertel  348:         url += 'mode=$mode&';
1.611     albertel  349:         url += 'inhibitmenu=yes&';
1.42      matthew   350:         url += 'form=' + formname + '&';
                    351:         if (only != null) {
                    352:             url += 'only=' + only + '&';
1.217     albertel  353:         } else {
                    354:             url += 'only=&';
                    355: 	}
1.42      matthew   356:         if (omit != null) {
                    357:             url += 'omit=' + omit + '&';
1.217     albertel  358:         } else {
                    359:             url += 'omit=&';
                    360: 	}
1.135     albertel  361:         if (titleelement != null) {
                    362:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  363:         } else {
                    364: 	    url += 'titleelement=&';
                    365: 	}
1.42      matthew   366:         url += 'element=' + elementname + '';
                    367:         var title = 'Browser';
1.435     albertel  368:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   369:         options += ',width=700,height=600';
                    370:         editbrowser = open(url,title,options,'1');
                    371:         editbrowser.focus();
                    372:     }
                    373:     var editsearcher;
1.135     albertel  374:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   375:         var url = '/adm/searchcat?';
                    376:         if (editsearcher == null) {
                    377:             url += 'launch=1&';
                    378:         }
                    379:         url += 'catalogmode=interactive&';
1.199     albertel  380:         url += 'mode=$mode&';
1.42      matthew   381:         url += 'form=' + formname + '&';
1.135     albertel  382:         if (titleelement != null) {
                    383:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  384:         } else {
                    385: 	    url += 'titleelement=&';
                    386: 	}
1.42      matthew   387:         url += 'element=' + elementname + '';
                    388:         var title = 'Search';
1.435     albertel  389:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   390:         options += ',width=700,height=600';
                    391:         editsearcher = open(url,title,options,'1');
                    392:         editsearcher.focus();
                    393:     }
1.219     albertel  394: // END LON-CAPA Internal -->
1.42      matthew   395: END
1.170     www       396: }
                    397: 
                    398: sub lastresurl {
1.258     albertel  399:     if ($env{'environment.lastresurl'}) {
                    400: 	return $env{'environment.lastresurl'}
1.170     www       401:     } else {
                    402: 	return '/res';
                    403:     }
                    404: }
                    405: 
                    406: sub storeresurl {
                    407:     my $resurl=&Apache::lonnet::clutter(shift);
                    408:     unless ($resurl=~/^\/res/) { return 0; }
                    409:     $resurl=~s/\/$//;
                    410:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   411:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       412:     return 1;
1.42      matthew   413: }
                    414: 
1.74      www       415: sub studentbrowser_javascript {
1.111     www       416:    unless (
1.258     albertel  417:             (($env{'request.course.id'}) && 
1.302     albertel  418:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    419: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    420: 					  '/'.$env{'request.course.sec'})
                    421: 	      ))
1.258     albertel  422:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       423:           ) { return ''; }  
1.74      www       424:    return (<<'ENDSTDBRW');
1.776     bisitz    425: <script type="text/javascript" language="Javascript">
1.824     bisitz    426: // <![CDATA[
1.74      www       427:     var stdeditbrowser;
1.999     www       428:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       429:         var url = '/adm/pickstudent?';
                    430:         var filter;
1.558     albertel  431: 	if (!ignorefilter) {
                    432: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    433: 	}
1.74      www       434:         if (filter != null) {
                    435:            if (filter != '') {
                    436:                url += 'filter='+filter+'&';
                    437: 	   }
                    438:         }
                    439:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       440:                                     '&udomelement='+udom+
                    441:                                     '&clicker='+clicker;
1.111     www       442: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   443:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       444:         var title = 'Student_Browser';
1.74      www       445:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    446:         options += ',width=700,height=600';
                    447:         stdeditbrowser = open(url,title,options,'1');
                    448:         stdeditbrowser.focus();
                    449:     }
1.824     bisitz    450: // ]]>
1.74      www       451: </script>
                    452: ENDSTDBRW
                    453: }
1.42      matthew   454: 
1.1003    www       455: sub resourcebrowser_javascript {
                    456:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       457:    return (<<'ENDRESBRW');
1.1003    www       458: <script type="text/javascript" language="Javascript">
                    459: // <![CDATA[
                    460:     var reseditbrowser;
1.1004    www       461:     function openresbrowser(formname,reslink) {
1.1005    www       462:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       463:         var title = 'Resource_Browser';
                    464:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       465:         options += ',width=700,height=500';
1.1004    www       466:         reseditbrowser = open(url,title,options,'1');
                    467:         reseditbrowser.focus();
1.1003    www       468:     }
                    469: // ]]>
                    470: </script>
1.1004    www       471: ENDRESBRW
1.1003    www       472: }
                    473: 
1.74      www       474: sub selectstudent_link {
1.999     www       475:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    476:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    477:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    478:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  479:    if ($env{'request.course.id'}) {  
1.302     albertel  480:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    481: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    482: 					'/'.$env{'request.course.sec'})) {
1.111     www       483: 	   return '';
                    484:        }
1.999     www       485:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   486:        if ($courseadvonly)  {
                    487:            $callargs .= ",'',1,1";
                    488:        }
                    489:        return '<span class="LC_nobreak">'.
                    490:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    491:               &mt('Select User').'</a></span>';
1.74      www       492:    }
1.258     albertel  493:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       494:        $callargs .= ",'',1"; 
1.793     raeburn   495:        return '<span class="LC_nobreak">'.
                    496:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    497:               &mt('Select User').'</a></span>';
1.111     www       498:    }
                    499:    return '';
1.91      www       500: }
                    501: 
1.1004    www       502: sub selectresource_link {
                    503:    my ($form,$reslink,$arg)=@_;
                    504:    
                    505:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    506:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    507:    unless ($env{'request.course.id'}) { return $arg; }
                    508:    return '<span class="LC_nobreak">'.
                    509:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    510:               $arg.'</a></span>';
                    511: }
                    512: 
                    513: 
                    514: 
1.653     raeburn   515: sub authorbrowser_javascript {
                    516:     return <<"ENDAUTHORBRW";
1.776     bisitz    517: <script type="text/javascript" language="JavaScript">
1.824     bisitz    518: // <![CDATA[
1.653     raeburn   519: var stdeditbrowser;
                    520: 
                    521: function openauthorbrowser(formname,udom) {
                    522:     var url = '/adm/pickauthor?';
                    523:     url += 'form='+formname+'&roledom='+udom;
                    524:     var title = 'Author_Browser';
                    525:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    526:     options += ',width=700,height=600';
                    527:     stdeditbrowser = open(url,title,options,'1');
                    528:     stdeditbrowser.focus();
                    529: }
                    530: 
1.824     bisitz    531: // ]]>
1.653     raeburn   532: </script>
                    533: ENDAUTHORBRW
                    534: }
                    535: 
1.91      www       536: sub coursebrowser_javascript {
1.1075.2.31  raeburn   537:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1075.2.95  raeburn   538:         $credits_element,$instcode) = @_;
1.932     raeburn   539:     my $wintitle = 'Course_Browser';
1.931     raeburn   540:     if ($crstype eq 'Community') {
1.932     raeburn   541:         $wintitle = 'Community_Browser';
1.909     raeburn   542:     }
1.876     raeburn   543:     my $id_functions = &javascript_index_functions();
                    544:     my $output = '
1.776     bisitz    545: <script type="text/javascript" language="JavaScript">
1.824     bisitz    546: // <![CDATA[
1.468     raeburn   547:     var stdeditbrowser;'."\n";
1.876     raeburn   548: 
                    549:     $output .= <<"ENDSTDBRW";
1.909     raeburn   550:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       551:         var url = '/adm/pickcourse?';
1.895     raeburn   552:         var formid = getFormIdByName(formname);
1.876     raeburn   553:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  554:         if (domainfilter != null) {
                    555:            if (domainfilter != '') {
                    556:                url += 'domainfilter='+domainfilter+'&';
                    557: 	   }
                    558:         }
1.91      www       559:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  560: 	                            '&cdomelement='+udom+
                    561:                                     '&cnameelement='+desc;
1.468     raeburn   562:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   563:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   564:                 url += '&roleelement='+extra_element;
                    565:                 if (domainfilter == null || domainfilter == '') {
                    566:                     url += '&domainfilter='+extra_element;
                    567:                 }
1.234     raeburn   568:             }
1.468     raeburn   569:             else {
                    570:                 if (formname == 'portform') {
                    571:                     url += '&setroles='+extra_element;
1.800     raeburn   572:                 } else {
                    573:                     if (formname == 'rules') {
                    574:                         url += '&fixeddom='+extra_element; 
                    575:                     }
1.468     raeburn   576:                 }
                    577:             }     
1.230     raeburn   578:         }
1.909     raeburn   579:         if (type != null && type != '') {
                    580:             url += '&type='+type;
                    581:         }
                    582:         if (type_elem != null && type_elem != '') {
                    583:             url += '&typeelement='+type_elem;
                    584:         }
1.872     raeburn   585:         if (formname == 'ccrs') {
                    586:             var ownername = document.forms[formid].ccuname.value;
                    587:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1075.2.101  raeburn   588:             url += '&cloner='+ownername+':'+ownerdom;
                    589:             if (type == 'Course') {
                    590:                 url += '&crscode='+document.forms[formid].crscode.value;
                    591:             }
1.1075.2.95  raeburn   592:         }
                    593:         if (formname == 'requestcrs') {
                    594:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   595:         }
1.293     raeburn   596:         if (multflag !=null && multflag != '') {
                    597:             url += '&multiple='+multflag;
                    598:         }
1.909     raeburn   599:         var title = '$wintitle';
1.91      www       600:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    601:         options += ',width=700,height=600';
                    602:         stdeditbrowser = open(url,title,options,'1');
                    603:         stdeditbrowser.focus();
                    604:     }
1.876     raeburn   605: $id_functions
                    606: ENDSTDBRW
1.1075.2.31  raeburn   607:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    608:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    609:                                       $credits_element);
1.876     raeburn   610:     }
                    611:     $output .= '
                    612: // ]]>
                    613: </script>';
                    614:     return $output;
                    615: }
                    616: 
                    617: sub javascript_index_functions {
                    618:     return <<"ENDJS";
                    619: 
                    620: function getFormIdByName(formname) {
                    621:     for (var i=0;i<document.forms.length;i++) {
                    622:         if (document.forms[i].name == formname) {
                    623:             return i;
                    624:         }
                    625:     }
                    626:     return -1;
                    627: }
                    628: 
                    629: function getIndexByName(formid,item) {
                    630:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    631:         if (document.forms[formid].elements[i].name == item) {
                    632:             return i;
                    633:         }
                    634:     }
                    635:     return -1;
                    636: }
1.468     raeburn   637: 
1.876     raeburn   638: function getDomainFromSelectbox(formname,udom) {
                    639:     var userdom;
                    640:     var formid = getFormIdByName(formname);
                    641:     if (formid > -1) {
                    642:         var domid = getIndexByName(formid,udom);
                    643:         if (domid > -1) {
                    644:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    645:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    646:             }
                    647:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    648:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   649:             }
                    650:         }
                    651:     }
1.876     raeburn   652:     return userdom;
                    653: }
                    654: 
                    655: ENDJS
1.468     raeburn   656: 
1.876     raeburn   657: }
                    658: 
1.1017    raeburn   659: sub javascript_array_indexof {
1.1018    raeburn   660:     return <<ENDJS;
1.1017    raeburn   661: <script type="text/javascript" language="JavaScript">
                    662: // <![CDATA[
                    663: 
                    664: if (!Array.prototype.indexOf) {
                    665:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    666:         "use strict";
                    667:         if (this === void 0 || this === null) {
                    668:             throw new TypeError();
                    669:         }
                    670:         var t = Object(this);
                    671:         var len = t.length >>> 0;
                    672:         if (len === 0) {
                    673:             return -1;
                    674:         }
                    675:         var n = 0;
                    676:         if (arguments.length > 0) {
                    677:             n = Number(arguments[1]);
                    678:             if (n !== n) { // shortcut for verifying if it's NaN
                    679:                 n = 0;
                    680:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    681:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    682:             }
                    683:         }
                    684:         if (n >= len) {
                    685:             return -1;
                    686:         }
                    687:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    688:         for (; k < len; k++) {
                    689:             if (k in t && t[k] === searchElement) {
                    690:                 return k;
                    691:             }
                    692:         }
                    693:         return -1;
                    694:     }
                    695: }
                    696: 
                    697: // ]]>
                    698: </script>
                    699: 
                    700: ENDJS
                    701: 
                    702: }
                    703: 
1.876     raeburn   704: sub userbrowser_javascript {
                    705:     my $id_functions = &javascript_index_functions();
                    706:     return <<"ENDUSERBRW";
                    707: 
1.888     raeburn   708: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   709:     var url = '/adm/pickuser?';
                    710:     var userdom = getDomainFromSelectbox(formname,udom);
                    711:     if (userdom != null) {
                    712:        if (userdom != '') {
                    713:            url += 'srchdom='+userdom+'&';
                    714:        }
                    715:     }
                    716:     url += 'form=' + formname + '&unameelement='+uname+
                    717:                                 '&udomelement='+udom+
                    718:                                 '&ulastelement='+ulast+
                    719:                                 '&ufirstelement='+ufirst+
                    720:                                 '&uemailelement='+uemail+
1.881     raeburn   721:                                 '&hideudomelement='+hideudom+
                    722:                                 '&coursedom='+crsdom;
1.888     raeburn   723:     if ((caller != null) && (caller != undefined)) {
                    724:         url += '&caller='+caller;
                    725:     }
1.876     raeburn   726:     var title = 'User_Browser';
                    727:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    728:     options += ',width=700,height=600';
                    729:     var stdeditbrowser = open(url,title,options,'1');
                    730:     stdeditbrowser.focus();
                    731: }
                    732: 
1.888     raeburn   733: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   734:     var formid = getFormIdByName(formname);
                    735:     if (formid > -1) {
1.888     raeburn   736:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   737:         var domid = getIndexByName(formid,udom);
                    738:         var hidedomid = getIndexByName(formid,origdom);
                    739:         if (hidedomid > -1) {
                    740:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   741:             var unameval = document.forms[formid].elements[unameid].value;
                    742:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    743:                 if (domid > -1) {
                    744:                     var slct = document.forms[formid].elements[domid];
                    745:                     if (slct.type == 'select-one') {
                    746:                         var i;
                    747:                         for (i=0;i<slct.length;i++) {
                    748:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    749:                         }
                    750:                     }
                    751:                     if (slct.type == 'hidden') {
                    752:                         slct.value = fixeddom;
1.876     raeburn   753:                     }
                    754:                 }
1.468     raeburn   755:             }
                    756:         }
                    757:     }
1.876     raeburn   758:     return;
                    759: }
                    760: 
                    761: $id_functions
                    762: ENDUSERBRW
1.468     raeburn   763: }
                    764: 
                    765: sub setsec_javascript {
1.1075.2.31  raeburn   766:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   767:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    768:         $communityrolestr);
                    769:     if ($role_element ne '') {
                    770:         my @allroles = ('st','ta','ep','in','ad');
                    771:         foreach my $crstype ('Course','Community') {
                    772:             if ($crstype eq 'Community') {
                    773:                 foreach my $role (@allroles) {
                    774:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    775:                 }
                    776:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    777:             } else {
                    778:                 foreach my $role (@allroles) {
                    779:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    780:                 }
                    781:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    782:             }
                    783:         }
                    784:         $rolestr = '"'.join('","',@allroles).'"';
                    785:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    786:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    787:     }
1.468     raeburn   788:     my $setsections = qq|
                    789: function setSect(sectionlist) {
1.629     raeburn   790:     var sectionsArray = new Array();
                    791:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    792:         sectionsArray = sectionlist.split(",");
                    793:     }
1.468     raeburn   794:     var numSections = sectionsArray.length;
                    795:     document.$formname.$sec_element.length = 0;
                    796:     if (numSections == 0) {
                    797:         document.$formname.$sec_element.multiple=false;
                    798:         document.$formname.$sec_element.size=1;
                    799:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    800:     } else {
                    801:         if (numSections == 1) {
                    802:             document.$formname.$sec_element.multiple=false;
                    803:             document.$formname.$sec_element.size=1;
                    804:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    805:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    806:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    807:         } else {
                    808:             for (var i=0; i<numSections; i++) {
                    809:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    810:             }
                    811:             document.$formname.$sec_element.multiple=true
                    812:             if (numSections < 3) {
                    813:                 document.$formname.$sec_element.size=numSections;
                    814:             } else {
                    815:                 document.$formname.$sec_element.size=3;
                    816:             }
                    817:             document.$formname.$sec_element.options[0].selected = false
                    818:         }
                    819:     }
1.91      www       820: }
1.905     raeburn   821: 
                    822: function setRole(crstype) {
1.468     raeburn   823: |;
1.905     raeburn   824:     if ($role_element eq '') {
                    825:         $setsections .= '    return;
                    826: }
                    827: ';
                    828:     } else {
                    829:         $setsections .= qq|
                    830:     var elementLength = document.$formname.$role_element.length;
                    831:     var allroles = Array($rolestr);
                    832:     var courserolenames = Array($courserolestr);
                    833:     var communityrolenames = Array($communityrolestr);
                    834:     if (elementLength != undefined) {
                    835:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    836:             if (crstype == 'Course') {
                    837:                 return;
                    838:             } else {
                    839:                 allroles[5] = 'co';
                    840:                 for (var i=0; i<6; i++) {
                    841:                     document.$formname.$role_element.options[i].value = allroles[i];
                    842:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    843:                 }
                    844:             }
                    845:         } else {
                    846:             if (crstype == 'Community') {
                    847:                 return;
                    848:             } else {
                    849:                 allroles[5] = 'cc';
                    850:                 for (var i=0; i<6; i++) {
                    851:                     document.$formname.$role_element.options[i].value = allroles[i];
                    852:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    853:                 }
                    854:             }
                    855:         }
                    856:     }
                    857:     return;
                    858: }
                    859: |;
                    860:     }
1.1075.2.31  raeburn   861:     if ($credits_element) {
                    862:         $setsections .= qq|
                    863: function setCredits(defaultcredits) {
                    864:     document.$formname.$credits_element.value = defaultcredits;
                    865:     return;
                    866: }
                    867: |;
                    868:     }
1.468     raeburn   869:     return $setsections;
                    870: }
                    871: 
1.91      www       872: sub selectcourse_link {
1.909     raeburn   873:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    874:        $typeelement) = @_;
                    875:    my $type = $selecttype;
1.871     raeburn   876:    my $linktext = &mt('Select Course');
                    877:    if ($selecttype eq 'Community') {
1.909     raeburn   878:        $linktext = &mt('Select Community');
1.906     raeburn   879:    } elsif ($selecttype eq 'Course/Community') {
                    880:        $linktext = &mt('Select Course/Community');
1.909     raeburn   881:        $type = '';
1.1019    raeburn   882:    } elsif ($selecttype eq 'Select') {
                    883:        $linktext = &mt('Select');
                    884:        $type = '';
1.871     raeburn   885:    }
1.787     bisitz    886:    return '<span class="LC_nobreak">'
                    887:          ."<a href='"
                    888:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    889:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   890:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   891:          ."'>".$linktext.'</a>'
1.787     bisitz    892:          .'</span>';
1.74      www       893: }
1.42      matthew   894: 
1.653     raeburn   895: sub selectauthor_link {
                    896:    my ($form,$udom)=@_;
                    897:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    898:           &mt('Select Author').'</a>';
                    899: }
                    900: 
1.876     raeburn   901: sub selectuser_link {
1.881     raeburn   902:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   903:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   904:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   905:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   906:            ');">'.$linktext.'</a>';
1.876     raeburn   907: }
                    908: 
1.273     raeburn   909: sub check_uncheck_jscript {
                    910:     my $jscript = <<"ENDSCRT";
                    911: function checkAll(field) {
                    912:     if (field.length > 0) {
                    913:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   914:             if (!field[i].disabled) {
                    915:                 field[i].checked = true;
                    916:             }
1.273     raeburn   917:         }
                    918:     } else {
1.1075.2.14  raeburn   919:         if (!field.disabled) {
                    920:             field.checked = true;
                    921:         }
1.273     raeburn   922:     }
                    923: }
                    924:  
                    925: function uncheckAll(field) {
                    926:     if (field.length > 0) {
                    927:         for (i = 0; i < field.length; i++) {
                    928:             field[i].checked = false ;
1.543     albertel  929:         }
                    930:     } else {
1.273     raeburn   931:         field.checked = false ;
                    932:     }
                    933: }
                    934: ENDSCRT
                    935:     return $jscript;
                    936: }
                    937: 
1.656     www       938: sub select_timezone {
1.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) {
                   1141:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                   1142:         }
                   1143:         $result.="\"@s2texts\");\n";
                   1144:     }
                   1145:     $"=' ';
                   1146:     $result.= <<"END";
                   1147: 
                   1148: function select1_changed() {
                   1149:     // Determine new choice
                   1150:     var newvalue = "d_" + $first.value;
                   1151:     // update select2
                   1152:     var values     = select2data[newvalue].values;
                   1153:     var texts      = select2data[newvalue].texts;
                   1154:     var select2def = select2data[newvalue].def;
                   1155:     var i;
                   1156:     // out with the old
                   1157:     for (i = 0; i < $second.options.length; i++) {
                   1158:         $second.options[i] = null;
                   1159:     }
                   1160:     // in with the nuclear
                   1161:     for (i=0;i<values.length; i++) {
                   1162:         $second.options[i] = new Option(values[i]);
1.143     matthew  1163:         $second.options[i].value = values[i];
1.36      matthew  1164:         $second.options[i].text = texts[i];
                   1165:         if (values[i] == select2def) {
                   1166:             $second.options[i].selected = true;
                   1167:         }
                   1168:     }
                   1169: }
1.824     bisitz   1170: // ]]>
1.36      matthew  1171: </script>
                   1172: END
                   1173:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1174:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1175:     my @order = sort(keys(%{$hashref}));
                   1176:     if (ref($menuorder) eq 'ARRAY') {
                   1177:         @order = @{$menuorder};
                   1178:     }
                   1179:     foreach my $value (@order) {
1.36      matthew  1180:         $result.="    <option value=\"$value\" ";
1.253     albertel 1181:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1182:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1183:     }
                   1184:     $result .= "</select>\n";
                   1185:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1186:     $result .= $middletext;
1.1075.2.31  raeburn  1187:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1188:     if ($onchangesecond) {
                   1189:         $result .= ' onchange="'.$onchangesecond.'"';
                   1190:     }
                   1191:     $result .= ">\n";
1.36      matthew  1192:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1193:     
                   1194:     my @secondorder = sort(keys(%select2));
                   1195:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1196:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1197:     }
                   1198:     foreach my $value (@secondorder) {
1.36      matthew  1199:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1200:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1201:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1202:     }
                   1203:     $result .= "</select>\n";
                   1204:     #    return $debug;
                   1205:     return $result;
                   1206: }   #  end of sub linked_select_forms {
                   1207: 
1.45      matthew  1208: =pod
1.44      bowersj2 1209: 
1.973     raeburn  1210: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1211: 
1.112     bowersj2 1212: Returns a string corresponding to an HTML link to the given help
                   1213: $topic, where $topic corresponds to the name of a .tex file in
                   1214: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1215: spaces. 
                   1216: 
                   1217: $text will optionally be linked to the same topic, allowing you to
                   1218: link text in addition to the graphic. If you do not want to link
                   1219: text, but wish to specify one of the later parameters, pass an
                   1220: empty string. 
                   1221: 
                   1222: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1223: the link will not open a new window. If false, the link will open
                   1224: a new window using Javascript. (Default is false.) 
                   1225: 
                   1226: $width and $height are optional numerical parameters that will
                   1227: override the width and height of the popped up window, which may
1.973     raeburn  1228: be useful for certain help topics with big pictures included.
                   1229: 
                   1230: $imgid is the id of the img tag used for the help icon. This may be
                   1231: used in a javascript call to switch the image src.  See 
                   1232: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1233: 
                   1234: =cut
                   1235: 
                   1236: sub help_open_topic {
1.973     raeburn  1237:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1238:     $text = "" if (not defined $text);
1.44      bowersj2 1239:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1240:     $width = 500 if (not defined $width);
1.44      bowersj2 1241:     $height = 400 if (not defined $height);
                   1242:     my $filename = $topic;
                   1243:     $filename =~ s/ /_/g;
                   1244: 
1.48      bowersj2 1245:     my $template = "";
                   1246:     my $link;
1.572     banghart 1247:     
1.159     www      1248:     $topic=~s/\W/\_/g;
1.44      bowersj2 1249: 
1.572     banghart 1250:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1251:         if ($env{'browser.mobile'}) {
                   1252: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1253:         } else {
                   1254:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1255:         }
1.1037    www      1256:     } elsif ($stayOnPage eq 'popup') {
                   1257:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1.572     banghart 1258:     } else {
1.48      bowersj2 1259: 	$link = "/adm/help/${filename}.hlp";
                   1260:     }
                   1261: 
                   1262:     # Add the text
1.755     neumanie 1263:     if ($text ne "") {	
1.763     bisitz   1264: 	$template.='<span class="LC_help_open_topic">'
                   1265:                   .'<a target="_top" href="'.$link.'">'
                   1266:                   .$text.'</a>';
1.48      bowersj2 1267:     }
                   1268: 
1.763     bisitz   1269:     # (Always) Add the graphic
1.179     matthew  1270:     my $title = &mt('Online Help');
1.667     raeburn  1271:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1272:     if ($imgid ne '') {
                   1273:         $imgid = ' id="'.$imgid.'"';
                   1274:     }
1.763     bisitz   1275:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1276:               .'<img src="'.$helpicon.'" border="0"'
                   1277:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1278:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1279:               .' /></a>';
                   1280:     if ($text ne "") {	
                   1281:         $template.='</span>';
                   1282:     }
1.44      bowersj2 1283:     return $template;
                   1284: 
1.106     bowersj2 1285: }
                   1286: 
                   1287: # This is a quicky function for Latex cheatsheet editing, since it 
                   1288: # appears in at least four places
                   1289: sub helpLatexCheatsheet {
1.1037    www      1290:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1291:     my $out;
1.106     bowersj2 1292:     my $addOther = '';
1.732     raeburn  1293:     if ($topic) {
1.1037    www      1294: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1295:     }
                   1296:     $out = '<span>' # Start cheatsheet
                   1297: 	  .$addOther
                   1298:           .'<span>'
1.1037    www      1299: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1300: 	  .'</span> <span>'
1.1037    www      1301: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1302: 	  .'</span>';
1.732     raeburn  1303:     unless ($not_author) {
1.763     bisitz   1304:         $out .= ' <span>'
1.1037    www      1305: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1306: 	       .'</span> <span>'
1.1075.2.78  raeburn  1307:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1308:                .'</span>';
1.732     raeburn  1309:     }
1.763     bisitz   1310:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1311:     return $out;
1.172     www      1312: }
                   1313: 
1.430     albertel 1314: sub general_help {
                   1315:     my $helptopic='Student_Intro';
                   1316:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1317: 	$helptopic='Authoring_Intro';
1.907     raeburn  1318:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1319: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1320:     } elsif ($env{'request.role'}=~/^dc/) {
                   1321:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1322:     }
                   1323:     return $helptopic;
                   1324: }
                   1325: 
                   1326: sub update_help_link {
                   1327:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1328:     my $origurl = $ENV{'REQUEST_URI'};
                   1329:     $origurl=~s|^/~|/priv/|;
                   1330:     my $timestamp = time;
                   1331:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1332:         $$datum = &escape($$datum);
                   1333:     }
                   1334: 
                   1335:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
                   1336:     my $output .= <<"ENDOUTPUT";
                   1337: <script type="text/javascript">
1.824     bisitz   1338: // <![CDATA[
1.430     albertel 1339: banner_link = '$banner_link';
1.824     bisitz   1340: // ]]>
1.430     albertel 1341: </script>
                   1342: ENDOUTPUT
                   1343:     return $output;
                   1344: }
                   1345: 
                   1346: # now just updates the help link and generates a blue icon
1.193     raeburn  1347: sub help_open_menu {
1.430     albertel 1348:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1349: 	= @_;    
1.949     droeschl 1350:     $stayOnPage = 1;
1.430     albertel 1351:     my $output;
                   1352:     if ($component_help) {
                   1353: 	if (!$text) {
                   1354: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1355: 				       $width,$height);
                   1356: 	} else {
                   1357: 	    my $help_text;
                   1358: 	    $help_text=&unescape($topic);
                   1359: 	    $output='<table><tr><td>'.
                   1360: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1361: 				 $width,$height).'</td></tr></table>';
                   1362: 	}
                   1363:     }
                   1364:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1365:     return $output.$banner_link;
                   1366: }
                   1367: 
                   1368: sub top_nav_help {
                   1369:     my ($text) = @_;
1.436     albertel 1370:     $text = &mt($text);
1.1075.2.60  raeburn  1371:     my $stay_on_page;
                   1372:     unless ($env{'environment.remote'} eq 'on') {
                   1373:         $stay_on_page = 1;
                   1374:     }
1.1075.2.61  raeburn  1375:     my ($link,$banner_link);
                   1376:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1377:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1378: 	                         : "javascript:helpMenu('open')";
                   1379:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1380:     }
1.201     raeburn  1381:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1382:     if ($link) {
                   1383:         return <<"END";
1.436     albertel 1384: $banner_link
1.1075.2.56  raeburn  1385: <a href="$link" title="$title">$text</a>
1.436     albertel 1386: END
1.1075.2.61  raeburn  1387:     } else {
                   1388:         return '&nbsp;'.$text.'&nbsp;';
                   1389:     }
1.436     albertel 1390: }
                   1391: 
                   1392: sub help_menu_js {
1.1075.2.52  raeburn  1393:     my ($httphost) = @_;
1.949     droeschl 1394:     my $stayOnPage = 1;
1.436     albertel 1395:     my $width = 620;
                   1396:     my $height = 600;
1.430     albertel 1397:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1398:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1399:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1400:     my $start_page =
                   1401:         &Apache::loncommon::start_page('Help Menu', undef,
                   1402: 				       {'frameset'    => 1,
                   1403: 					'js_ready'    => 1,
1.1075.2.52  raeburn  1404:                                         'use_absolute' => $httphost, 
1.331     albertel 1405: 					'add_entries' => {
                   1406: 					    'border' => '0',
1.579     raeburn  1407: 					    'rows'   => "110,*",},});
1.331     albertel 1408:     my $end_page =
                   1409:         &Apache::loncommon::end_page({'frameset' => 1,
                   1410: 				      'js_ready' => 1,});
                   1411: 
1.436     albertel 1412:     my $template .= <<"ENDTEMPLATE";
                   1413: <script type="text/javascript">
1.877     bisitz   1414: // <![CDATA[
1.253     albertel 1415: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1416: var banner_link = '';
1.243     raeburn  1417: function helpMenu(target) {
                   1418:     var caller = this;
                   1419:     if (target == 'open') {
                   1420:         var newWindow = null;
                   1421:         try {
1.262     albertel 1422:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1423:         }
                   1424:         catch(error) {
                   1425:             writeHelp(caller);
                   1426:             return;
                   1427:         }
                   1428:         if (newWindow) {
                   1429:             caller = newWindow;
                   1430:         }
1.193     raeburn  1431:     }
1.243     raeburn  1432:     writeHelp(caller);
                   1433:     return;
                   1434: }
                   1435: function writeHelp(caller) {
1.1075.2.61  raeburn  1436:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1437:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1438:     caller.document.close();
                   1439:     caller.focus();
1.193     raeburn  1440: }
1.877     bisitz   1441: // END LON-CAPA Internal -->
1.253     albertel 1442: // ]]>
1.436     albertel 1443: </script>
1.193     raeburn  1444: ENDTEMPLATE
                   1445:     return $template;
                   1446: }
                   1447: 
1.172     www      1448: sub help_open_bug {
                   1449:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1450:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1451:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1452:     $text = "" if (not defined $text);
                   1453: 	$stayOnPage=1;
1.184     albertel 1454:     $width = 600 if (not defined $width);
                   1455:     $height = 600 if (not defined $height);
1.172     www      1456: 
                   1457:     $topic=~s/\W+/\+/g;
                   1458:     my $link='';
                   1459:     my $template='';
1.379     albertel 1460:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1461: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1462:     if (!$stayOnPage)
                   1463:     {
                   1464: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1465:     }
                   1466:     else
                   1467:     {
                   1468: 	$link = $url;
                   1469:     }
                   1470:     # Add the text
                   1471:     if ($text ne "")
                   1472:     {
                   1473: 	$template .= 
                   1474:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1475:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1476:     }
                   1477: 
                   1478:     # Add the graphic
1.179     matthew  1479:     my $title = &mt('Report a Bug');
1.215     albertel 1480:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1481:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1482:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1483: ENDTEMPLATE
                   1484:     if ($text ne '') { $template.='</td></tr></table>' };
                   1485:     return $template;
                   1486: 
                   1487: }
                   1488: 
                   1489: sub help_open_faq {
                   1490:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1491:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1492:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1493:     $text = "" if (not defined $text);
                   1494: 	$stayOnPage=1;
                   1495:     $width = 350 if (not defined $width);
                   1496:     $height = 400 if (not defined $height);
                   1497: 
                   1498:     $topic=~s/\W+/\+/g;
                   1499:     my $link='';
                   1500:     my $template='';
                   1501:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1502:     if (!$stayOnPage)
                   1503:     {
                   1504: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1505:     }
                   1506:     else
                   1507:     {
                   1508: 	$link = $url;
                   1509:     }
                   1510: 
                   1511:     # Add the text
                   1512:     if ($text ne "")
                   1513:     {
                   1514: 	$template .= 
1.173     www      1515:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1516:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1517:     }
                   1518: 
                   1519:     # Add the graphic
1.179     matthew  1520:     my $title = &mt('View the FAQ');
1.215     albertel 1521:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1522:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1523:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1524: ENDTEMPLATE
                   1525:     if ($text ne '') { $template.='</td></tr></table>' };
                   1526:     return $template;
                   1527: 
1.44      bowersj2 1528: }
1.37      matthew  1529: 
1.180     matthew  1530: ###############################################################
                   1531: ###############################################################
                   1532: 
1.45      matthew  1533: =pod
                   1534: 
1.648     raeburn  1535: =item * &change_content_javascript():
1.256     matthew  1536: 
                   1537: This and the next function allow you to create small sections of an
                   1538: otherwise static HTML page that you can update on the fly with
                   1539: Javascript, even in Netscape 4.
                   1540: 
                   1541: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1542: must be written to the HTML page once. It will prove the Javascript
                   1543: function "change(name, content)". Calling the change function with the
                   1544: name of the section 
                   1545: you want to update, matching the name passed to C<changable_area>, and
                   1546: the new content you want to put in there, will put the content into
                   1547: that area.
                   1548: 
                   1549: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1550: to contain room for the original contents. You need to "make space"
                   1551: for whatever changes you wish to make, and be B<sure> to check your
                   1552: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1553: it's adequate for updating a one-line status display, but little more.
                   1554: This script will set the space to 100% width, so you only need to
                   1555: worry about height in Netscape 4.
                   1556: 
                   1557: Modern browsers are much less limiting, and if you can commit to the
                   1558: user not using Netscape 4, this feature may be used freely with
                   1559: pretty much any HTML.
                   1560: 
                   1561: =cut
                   1562: 
                   1563: sub change_content_javascript {
                   1564:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1565:     if ($env{'browser.type'} eq 'netscape' &&
                   1566: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1567: 	return (<<NETSCAPE4);
                   1568: 	function change(name, content) {
                   1569: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1570: 	    doc.open();
                   1571: 	    doc.write(content);
                   1572: 	    doc.close();
                   1573: 	}
                   1574: NETSCAPE4
                   1575:     } else {
                   1576: 	# Otherwise, we need to use semi-standards-compliant code
                   1577: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1578: 	# is really scary, and every useful browser supports it
                   1579: 	return (<<DOMBASED);
                   1580: 	function change(name, content) {
                   1581: 	    element = document.getElementById(name);
                   1582: 	    element.innerHTML = content;
                   1583: 	}
                   1584: DOMBASED
                   1585:     }
                   1586: }
                   1587: 
                   1588: =pod
                   1589: 
1.648     raeburn  1590: =item * &changable_area($name,$origContent):
1.256     matthew  1591: 
                   1592: This provides a "changable area" that can be modified on the fly via
                   1593: the Javascript code provided in C<change_content_javascript>. $name is
                   1594: the name you will use to reference the area later; do not repeat the
                   1595: same name on a given HTML page more then once. $origContent is what
                   1596: the area will originally contain, which can be left blank.
                   1597: 
                   1598: =cut
                   1599: 
                   1600: sub changable_area {
                   1601:     my ($name, $origContent) = @_;
                   1602: 
1.258     albertel 1603:     if ($env{'browser.type'} eq 'netscape' &&
                   1604: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1605: 	# If this is netscape 4, we need to use the Layer tag
                   1606: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1607:     } else {
                   1608: 	return "<span id='$name'>$origContent</span>";
                   1609:     }
                   1610: }
                   1611: 
                   1612: =pod
                   1613: 
1.648     raeburn  1614: =item * &viewport_geometry_js 
1.590     raeburn  1615: 
                   1616: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1617: 
                   1618: =cut
                   1619: 
                   1620: 
                   1621: sub viewport_geometry_js { 
                   1622:     return <<"GEOMETRY";
                   1623: var Geometry = {};
                   1624: function init_geometry() {
                   1625:     if (Geometry.init) { return };
                   1626:     Geometry.init=1;
                   1627:     if (window.innerHeight) {
                   1628:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1629:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1630:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1631:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1632:     }
                   1633:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1634:         Geometry.getViewportHeight =
                   1635:             function() { return document.documentElement.clientHeight; };
                   1636:         Geometry.getViewportWidth =
                   1637:             function() { return document.documentElement.clientWidth; };
                   1638: 
                   1639:         Geometry.getHorizontalScroll =
                   1640:             function() { return document.documentElement.scrollLeft; };
                   1641:         Geometry.getVerticalScroll =
                   1642:             function() { return document.documentElement.scrollTop; };
                   1643:     }
                   1644:     else if (document.body.clientHeight) {
                   1645:         Geometry.getViewportHeight =
                   1646:             function() { return document.body.clientHeight; };
                   1647:         Geometry.getViewportWidth =
                   1648:             function() { return document.body.clientWidth; };
                   1649:         Geometry.getHorizontalScroll =
                   1650:             function() { return document.body.scrollLeft; };
                   1651:         Geometry.getVerticalScroll =
                   1652:             function() { return document.body.scrollTop; };
                   1653:     }
                   1654: }
                   1655: 
                   1656: GEOMETRY
                   1657: }
                   1658: 
                   1659: =pod
                   1660: 
1.648     raeburn  1661: =item * &viewport_size_js()
1.590     raeburn  1662: 
                   1663: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
                   1664: 
                   1665: =cut
                   1666: 
                   1667: sub viewport_size_js {
                   1668:     my $geometry = &viewport_geometry_js();
                   1669:     return <<"DIMS";
                   1670: 
                   1671: $geometry
                   1672: 
                   1673: function getViewportDims(width,height) {
                   1674:     init_geometry();
                   1675:     width.value = Geometry.getViewportWidth();
                   1676:     height.value = Geometry.getViewportHeight();
                   1677:     return;
                   1678: }
                   1679: 
                   1680: DIMS
                   1681: }
                   1682: 
                   1683: =pod
                   1684: 
1.648     raeburn  1685: =item * &resize_textarea_js()
1.565     albertel 1686: 
                   1687: emits the needed javascript to resize a textarea to be as big as possible
                   1688: 
                   1689: creates a function resize_textrea that takes two IDs first should be
                   1690: the id of the element to resize, second should be the id of a div that
                   1691: surrounds everything that comes after the textarea, this routine needs
                   1692: to be attached to the <body> for the onload and onresize events.
                   1693: 
1.648     raeburn  1694: =back
1.565     albertel 1695: 
                   1696: =cut
                   1697: 
                   1698: sub resize_textarea_js {
1.590     raeburn  1699:     my $geometry = &viewport_geometry_js();
1.565     albertel 1700:     return <<"RESIZE";
                   1701:     <script type="text/javascript">
1.824     bisitz   1702: // <![CDATA[
1.590     raeburn  1703: $geometry
1.565     albertel 1704: 
1.588     albertel 1705: function getX(element) {
                   1706:     var x = 0;
                   1707:     while (element) {
                   1708: 	x += element.offsetLeft;
                   1709: 	element = element.offsetParent;
                   1710:     }
                   1711:     return x;
                   1712: }
                   1713: function getY(element) {
                   1714:     var y = 0;
                   1715:     while (element) {
                   1716: 	y += element.offsetTop;
                   1717: 	element = element.offsetParent;
                   1718:     }
                   1719:     return y;
                   1720: }
                   1721: 
                   1722: 
1.565     albertel 1723: function resize_textarea(textarea_id,bottom_id) {
                   1724:     init_geometry();
                   1725:     var textarea        = document.getElementById(textarea_id);
                   1726:     //alert(textarea);
                   1727: 
1.588     albertel 1728:     var textarea_top    = getY(textarea);
1.565     albertel 1729:     var textarea_height = textarea.offsetHeight;
                   1730:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1731:     var bottom_top      = getY(bottom);
1.565     albertel 1732:     var bottom_height   = bottom.offsetHeight;
                   1733:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1734:     var fudge           = 23;
1.565     albertel 1735:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1736:     if (new_height < 300) {
                   1737: 	new_height = 300;
                   1738:     }
                   1739:     textarea.style.height=new_height+'px';
                   1740: }
1.824     bisitz   1741: // ]]>
1.565     albertel 1742: </script>
                   1743: RESIZE
                   1744: 
                   1745: }
                   1746: 
1.1075.2.112  raeburn  1747: sub colorfuleditor_js {
                   1748:     return <<"COLORFULEDIT"
                   1749: <script type="text/javascript">
                   1750: // <![CDATA[>
                   1751:     function fold_box(curDepth, lastresource){
                   1752: 
                   1753:     // we need a list because there can be several blocks you need to fold in one tag
                   1754:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1755:     // but there is only one folding button per tag
                   1756:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1757: 
                   1758:         if(block.item(0).style.display == 'none'){
                   1759: 
                   1760:             foldbutton.value = '@{[&mt("Hide")]}';
                   1761:             for (i = 0; i < block.length; i++){
                   1762:                 block.item(i).style.display = '';
                   1763:             }
                   1764:         }else{
                   1765: 
                   1766:             foldbutton.value = '@{[&mt("Show")]}';
                   1767:             for (i = 0; i < block.length; i++){
                   1768:                 // block.item(i).style.visibility = 'collapse';
                   1769:                 block.item(i).style.display = 'none';
                   1770:             }
                   1771:         };
                   1772:         saveState(lastresource);
                   1773:     }
                   1774: 
                   1775:     function saveState (lastresource) {
                   1776: 
                   1777:         var tag_list = getTagList();
                   1778:         if(tag_list != null){
                   1779:             var timestamp = new Date().getTime();
                   1780:             var key = lastresource;
                   1781: 
                   1782:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1783:             // starting with timestamp
                   1784:             var value = timestamp+';';
                   1785: 
                   1786:             // building the list of key-value pairs
                   1787:             for(var i = 0; i < tag_list.length; i++){
                   1788:                 value += tag_list[i]+',';
                   1789:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1790:             }
                   1791: 
                   1792:             // only iterate whole storage if nothing to override
                   1793:             if(localStorage.getItem(key) == null){
                   1794: 
                   1795:                 // prevent storage from growing large
                   1796:                 if(localStorage.length > 50){
                   1797:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1798:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1799:                     var oldest_key;
                   1800: 
                   1801:                     for(var i = 1; i < localStorage.length; i++){
                   1802:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1803:                             oldest_key = localStorage.key(i);
                   1804:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1805:                         }
                   1806:                     }
                   1807:                     localStorage.removeItem(oldest_key);
                   1808:                 }
                   1809:             }
                   1810:             localStorage.setItem(key,value);
                   1811:         }
                   1812:     }
                   1813: 
                   1814:     // restore folding status of blocks (on page load)
                   1815:     function restoreState (lastresource) {
                   1816:         if(localStorage.getItem(lastresource) != null){
                   1817:             var key = lastresource;
                   1818:             var value = localStorage.getItem(key);
                   1819:             var regex_delTimestamp = /^\d+;/;
                   1820: 
                   1821:             value.replace(regex_delTimestamp, '');
                   1822: 
                   1823:             var valueArr = value.split(';');
                   1824:             var pairs;
                   1825:             var elements;
                   1826:             for (var i = 0; i < valueArr.length; i++){
                   1827:                 pairs = valueArr[i].split(',');
                   1828:                 elements = document.getElementsByName(pairs[0]);
                   1829: 
                   1830:                 for (var j = 0; j < elements.length; j++){
                   1831:                     elements[j].style.display = pairs[1];
                   1832:                     if (pairs[1] == "none"){
                   1833:                         var regex_id = /([_\\d]+)\$/;
                   1834:                         regex_id.exec(pairs[0]);
                   1835:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1836:                     }
                   1837:                 }
                   1838:             }
                   1839:         }
                   1840:     }
                   1841: 
                   1842:     function getTagList () {
                   1843: 
                   1844:         var stringToSearch = document.lonhomework.innerHTML;
                   1845: 
                   1846:         var ret = new Array();
                   1847:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1848:         var tag_list = stringToSearch.match(regex_findBlock);
                   1849: 
                   1850:         if(tag_list != null){
                   1851:             for(var i = 0; i < tag_list.length; i++){
                   1852:                 ret.push(tag_list[i].replace(/"/, ''));
                   1853:             }
                   1854:         }
                   1855:         return ret;
                   1856:     }
                   1857: 
                   1858:     function saveScrollPosition (resource) {
                   1859:         var tag_list = getTagList();
                   1860: 
                   1861:         // we dont always want to jump to the first block
                   1862:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1863:         if(\$(window).scrollTop() > 170){
                   1864:             if(tag_list != null){
                   1865:                 var result;
                   1866:                 for(var i = 0; i < tag_list.length; i++){
                   1867:                     if(isElementInViewport(tag_list[i])){
                   1868:                         result += tag_list[i]+';';
                   1869:                     }
                   1870:                 }
                   1871:                 sessionStorage.setItem('anchor_'+resource, result);
                   1872:             }
                   1873:         } else {
                   1874:             // we dont need to save zero, just delete the item to leave everything tidy
                   1875:             sessionStorage.removeItem('anchor_'+resource);
                   1876:         }
                   1877:     }
                   1878: 
                   1879:     function restoreScrollPosition(resource){
                   1880: 
                   1881:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1882:         if(elem != null){
                   1883:             var tag_list = elem.split(';');
                   1884:             var elem_list;
                   1885: 
                   1886:             for(var i = 0; i < tag_list.length; i++){
                   1887:                 elem_list = document.getElementsByName(tag_list[i]);
                   1888: 
                   1889:                 if(elem_list.length > 0){
                   1890:                     elem = elem_list[0];
                   1891:                     break;
                   1892:                 }
                   1893:             }
                   1894:             elem.scrollIntoView();
                   1895:         }
                   1896:     }
                   1897: 
                   1898:     function isElementInViewport(el) {
                   1899: 
                   1900:         // change to last element instead of first
                   1901:         var elem = document.getElementsByName(el);
                   1902:         var rect = elem[0].getBoundingClientRect();
                   1903: 
                   1904:         return (
                   1905:             rect.top >= 0 &&
                   1906:             rect.left >= 0 &&
                   1907:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1908:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1909:         );
                   1910:     }
                   1911: 
                   1912:     function autosize(depth){
                   1913:         var cmInst = window['cm'+depth];
                   1914:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1915: 
                   1916:         // is fixed size, switching to dynamic
                   1917:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1918:             cmInst.setSize("","auto");
                   1919:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1920:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1921: 
                   1922:         // is dynamic size, switching to fixed
                   1923:         } else {
                   1924:             cmInst.setSize("","300px");
                   1925:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1926:             sessionStorage.removeItem("autosized_"+depth);
                   1927:         }
                   1928:     }
                   1929: 
                   1930: 
                   1931: 
                   1932: // ]]>
                   1933: </script>
                   1934: COLORFULEDIT
                   1935: }
                   1936: 
                   1937: sub xmleditor_js {
                   1938:     return <<XMLEDIT
                   1939: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1940: <script type="text/javascript">
                   1941: // <![CDATA[>
                   1942: 
                   1943:     function saveScrollPosition (resource) {
                   1944: 
                   1945:         var scrollPos = \$(window).scrollTop();
                   1946:         sessionStorage.setItem(resource,scrollPos);
                   1947:     }
                   1948: 
                   1949:     function restoreScrollPosition(resource){
                   1950: 
                   1951:         var scrollPos = sessionStorage.getItem(resource);
                   1952:         \$(window).scrollTop(scrollPos);
                   1953:     }
                   1954: 
                   1955:     // unless internet explorer
                   1956:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1957: 
                   1958:         \$(document).ready(function() {
                   1959:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1960:         });
                   1961:     }
                   1962: 
                   1963:     // inserts text at cursor position into codemirror (xml editor only)
                   1964:     function insertText(text){
                   1965:         cm.focus();
                   1966:         var curPos = cm.getCursor();
                   1967:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   1968:     }
                   1969: // ]]>
                   1970: </script>
                   1971: XMLEDIT
                   1972: }
                   1973: 
                   1974: sub insert_folding_button {
                   1975:     my $curDepth = $Apache::lonxml::curdepth;
                   1976:     my $lastresource = $env{'request.ambiguous'};
                   1977: 
                   1978:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
                   1979:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   1980: }
                   1981: 
                   1982: 
1.565     albertel 1983: =pod
                   1984: 
1.256     matthew  1985: =head1 Excel and CSV file utility routines
                   1986: 
                   1987: =cut
                   1988: 
                   1989: ###############################################################
                   1990: ###############################################################
                   1991: 
                   1992: =pod
                   1993: 
1.1075.2.56  raeburn  1994: =over 4
                   1995: 
1.648     raeburn  1996: =item * &csv_translate($text) 
1.37      matthew  1997: 
1.185     www      1998: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  1999: format.
                   2000: 
                   2001: =cut
                   2002: 
1.180     matthew  2003: ###############################################################
                   2004: ###############################################################
1.37      matthew  2005: sub csv_translate {
                   2006:     my $text = shift;
                   2007:     $text =~ s/\"/\"\"/g;
1.209     albertel 2008:     $text =~ s/\n/ /g;
1.37      matthew  2009:     return $text;
                   2010: }
1.180     matthew  2011: 
                   2012: ###############################################################
                   2013: ###############################################################
                   2014: 
                   2015: =pod
                   2016: 
1.648     raeburn  2017: =item * &define_excel_formats()
1.180     matthew  2018: 
                   2019: Define some commonly used Excel cell formats.
                   2020: 
                   2021: Currently supported formats:
                   2022: 
                   2023: =over 4
                   2024: 
                   2025: =item header
                   2026: 
                   2027: =item bold
                   2028: 
                   2029: =item h1
                   2030: 
                   2031: =item h2
                   2032: 
                   2033: =item h3
                   2034: 
1.256     matthew  2035: =item h4
                   2036: 
                   2037: =item i
                   2038: 
1.180     matthew  2039: =item date
                   2040: 
                   2041: =back
                   2042: 
                   2043: Inputs: $workbook
                   2044: 
                   2045: Returns: $format, a hash reference.
                   2046: 
1.1057    foxr     2047: 
1.180     matthew  2048: =cut
                   2049: 
                   2050: ###############################################################
                   2051: ###############################################################
                   2052: sub define_excel_formats {
                   2053:     my ($workbook) = @_;
                   2054:     my $format;
                   2055:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2056:                                                 bottom    => 1,
                   2057:                                                 align     => 'center');
                   2058:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2059:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2060:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2061:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2062:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2063:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2064:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2065:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2066:     return $format;
                   2067: }
                   2068: 
                   2069: ###############################################################
                   2070: ###############################################################
1.113     bowersj2 2071: 
                   2072: =pod
                   2073: 
1.648     raeburn  2074: =item * &create_workbook()
1.255     matthew  2075: 
                   2076: Create an Excel worksheet.  If it fails, output message on the
                   2077: request object and return undefs.
                   2078: 
                   2079: Inputs: Apache request object
                   2080: 
                   2081: Returns (undef) on failure, 
                   2082:     Excel worksheet object, scalar with filename, and formats 
                   2083:     from &Apache::loncommon::define_excel_formats on success
                   2084: 
                   2085: =cut
                   2086: 
                   2087: ###############################################################
                   2088: ###############################################################
                   2089: sub create_workbook {
                   2090:     my ($r) = @_;
                   2091:         #
                   2092:     # Create the excel spreadsheet
                   2093:     my $filename = '/prtspool/'.
1.258     albertel 2094:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2095:         time.'_'.rand(1000000000).'.xls';
                   2096:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2097:     if (! defined($workbook)) {
                   2098:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2099:         $r->print(
                   2100:             '<p class="LC_error">'
                   2101:            .&mt('Problems occurred in creating the new Excel file.')
                   2102:            .' '.&mt('This error has been logged.')
                   2103:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2104:            .'</p>'
                   2105:         );
1.255     matthew  2106:         return (undef);
                   2107:     }
                   2108:     #
1.1014    foxr     2109:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2110:     #
                   2111:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2112:     return ($workbook,$filename,$format);
                   2113: }
                   2114: 
                   2115: ###############################################################
                   2116: ###############################################################
                   2117: 
                   2118: =pod
                   2119: 
1.648     raeburn  2120: =item * &create_text_file()
1.113     bowersj2 2121: 
1.542     raeburn  2122: Create a file to write to and eventually make available to the user.
1.256     matthew  2123: If file creation fails, outputs an error message on the request object and 
                   2124: return undefs.
1.113     bowersj2 2125: 
1.256     matthew  2126: Inputs: Apache request object, and file suffix
1.113     bowersj2 2127: 
1.256     matthew  2128: Returns (undef) on failure, 
                   2129:     Filehandle and filename on success.
1.113     bowersj2 2130: 
                   2131: =cut
                   2132: 
1.256     matthew  2133: ###############################################################
                   2134: ###############################################################
                   2135: sub create_text_file {
                   2136:     my ($r,$suffix) = @_;
                   2137:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2138:     my $fh;
                   2139:     my $filename = '/prtspool/'.
1.258     albertel 2140:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2141:         time.'_'.rand(1000000000).'.'.$suffix;
                   2142:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2143:     if (! defined($fh)) {
                   2144:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2145:         $r->print(
                   2146:             '<p class="LC_error">'
                   2147:            .&mt('Problems occurred in creating the output file.')
                   2148:            .' '.&mt('This error has been logged.')
                   2149:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2150:            .'</p>'
                   2151:         );
1.113     bowersj2 2152:     }
1.256     matthew  2153:     return ($fh,$filename)
1.113     bowersj2 2154: }
                   2155: 
                   2156: 
1.256     matthew  2157: =pod 
1.113     bowersj2 2158: 
                   2159: =back
                   2160: 
                   2161: =cut
1.37      matthew  2162: 
                   2163: ###############################################################
1.33      matthew  2164: ##        Home server <option> list generating code          ##
                   2165: ###############################################################
1.35      matthew  2166: 
1.169     www      2167: # ------------------------------------------
                   2168: 
                   2169: sub domain_select {
                   2170:     my ($name,$value,$multiple)=@_;
                   2171:     my %domains=map { 
1.514     albertel 2172: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2173:     } &Apache::lonnet::all_domains();
1.169     www      2174:     if ($multiple) {
                   2175: 	$domains{''}=&mt('Any domain');
1.550     albertel 2176: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2177: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2178:     } else {
1.550     albertel 2179: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2180: 	return &select_form($name,$value,\%domains);
1.169     www      2181:     }
                   2182: }
                   2183: 
1.282     albertel 2184: #-------------------------------------------
                   2185: 
                   2186: =pod
                   2187: 
1.519     raeburn  2188: =head1 Routines for form select boxes
                   2189: 
                   2190: =over 4
                   2191: 
1.648     raeburn  2192: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2193: 
                   2194: Returns a string containing a <select> element int multiple mode
                   2195: 
                   2196: 
                   2197: Args:
                   2198:   $name - name of the <select> element
1.506     raeburn  2199:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2200:   $size - number of rows long the select element is
1.283     albertel 2201:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2202:           (shown text should already have been &mt())
1.506     raeburn  2203:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2204: 
1.282     albertel 2205: =cut
                   2206: 
                   2207: #-------------------------------------------
1.169     www      2208: sub multiple_select_form {
1.284     albertel 2209:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2210:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2211:     my $output='';
1.191     matthew  2212:     if (! defined($size)) {
                   2213:         $size = 4;
1.283     albertel 2214:         if (scalar(keys(%$hash))<4) {
                   2215:             $size = scalar(keys(%$hash));
1.191     matthew  2216:         }
                   2217:     }
1.734     bisitz   2218:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2219:     my @order;
1.506     raeburn  2220:     if (ref($order) eq 'ARRAY')  {
                   2221:         @order = @{$order};
                   2222:     } else {
                   2223:         @order = sort(keys(%$hash));
1.501     banghart 2224:     }
                   2225:     if (exists($$hash{'select_form_order'})) {
                   2226:         @order = @{$$hash{'select_form_order'}};
                   2227:     }
                   2228:         
1.284     albertel 2229:     foreach my $key (@order) {
1.356     albertel 2230:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2231:         $output.='selected="selected" ' if ($selected{$key});
                   2232:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2233:     }
                   2234:     $output.="</select>\n";
                   2235:     return $output;
                   2236: }
                   2237: 
1.88      www      2238: #-------------------------------------------
                   2239: 
                   2240: =pod
                   2241: 
1.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:                     }
                   4699:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
                   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:     }
                   4949:     my $allowed=0;
1.1075.2.111  raeburn  4950:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
1.682     raeburn  4951: 
                   4952:     my $name;
                   4953:     foreach my $pattern (split(',',$acc)) {
                   4954:         $pattern =~ s/^\s*//;
                   4955:         $pattern =~ s/\s*$//;
                   4956:         if ($pattern =~ /\*$/) {
                   4957:             #35.8.*
                   4958:             $pattern=~s/\*//;
                   4959:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4960:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   4961:             #35.8.3.[34-56]
                   4962:             my $low=$2;
                   4963:             my $high=$3;
                   4964:             $pattern=$1;
                   4965:             if ($ip =~ /^\Q$pattern\E/) {
                   4966:                 my $last=(split(/\./,$ip))[3];
                   4967:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   4968:             }
                   4969:         } elsif ($pattern =~ /^\*/) {
                   4970:             #*.msu.edu
                   4971:             $pattern=~s/\*//;
                   4972:             if (!defined($name)) {
                   4973:                 use Socket;
                   4974:                 my $netaddr=inet_aton($ip);
                   4975:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4976:             }
                   4977:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4978:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   4979:             #127.0.0.1
                   4980:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4981:         } else {
                   4982:             #some.name.com
                   4983:             if (!defined($name)) {
                   4984:                 use Socket;
                   4985:                 my $netaddr=inet_aton($ip);
                   4986:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4987:             }
                   4988:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4989:         }
                   4990:         if ($allowed) { last; }
                   4991:     }
                   4992:     return $allowed;
                   4993: }
                   4994: 
                   4995: ###############################################
                   4996: 
1.60      matthew  4997: =pod
                   4998: 
1.112     bowersj2 4999: =head1 Domain Template Functions
                   5000: 
                   5001: =over 4
                   5002: 
                   5003: =item * &determinedomain()
1.60      matthew  5004: 
                   5005: Inputs: $domain (usually will be undef)
                   5006: 
1.63      www      5007: Returns: Determines which domain should be used for designs
1.60      matthew  5008: 
                   5009: =cut
1.54      www      5010: 
1.60      matthew  5011: ###############################################
1.63      www      5012: sub determinedomain {
                   5013:     my $domain=shift;
1.531     albertel 5014:     if (! $domain) {
1.60      matthew  5015:         # Determine domain if we have not been given one
1.893     raeburn  5016:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5017:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5018:         if ($env{'request.role.domain'}) { 
                   5019:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5020:         }
                   5021:     }
1.63      www      5022:     return $domain;
                   5023: }
                   5024: ###############################################
1.517     raeburn  5025: 
1.518     albertel 5026: sub devalidate_domconfig_cache {
                   5027:     my ($udom)=@_;
                   5028:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5029: }
                   5030: 
                   5031: # ---------------------- Get domain configuration for a domain
                   5032: sub get_domainconf {
                   5033:     my ($udom) = @_;
                   5034:     my $cachetime=1800;
                   5035:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5036:     if (defined($cached)) { return %{$result}; }
                   5037: 
                   5038:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5039: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5040:     my (%designhash,%legacy);
1.518     albertel 5041:     if (keys(%domconfig) > 0) {
                   5042:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5043:             if (keys(%{$domconfig{'login'}})) {
                   5044:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5045:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  5046:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5047:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5048:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5049:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5050:                                         if ($key eq 'loginvia') {
                   5051:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5052:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5053:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5054:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5055:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5056:                                                 } else {
                   5057:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5058:                                                 }
1.948     raeburn  5059:                                             }
1.1075.2.87  raeburn  5060:                                         } elsif ($key eq 'headtag') {
                   5061:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5062:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5063:                                             }
1.946     raeburn  5064:                                         }
1.1075.2.87  raeburn  5065:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5066:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5067:                                         }
1.946     raeburn  5068:                                     }
                   5069:                                 }
                   5070:                             }
                   5071:                         } else {
                   5072:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5073:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5074:                                     $domconfig{'login'}{$key}{$img};
                   5075:                             }
1.699     raeburn  5076:                         }
                   5077:                     } else {
                   5078:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5079:                     }
1.632     raeburn  5080:                 }
                   5081:             } else {
                   5082:                 $legacy{'login'} = 1;
1.518     albertel 5083:             }
1.632     raeburn  5084:         } else {
                   5085:             $legacy{'login'} = 1;
1.518     albertel 5086:         }
                   5087:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5088:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5089:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5090:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5091:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5092:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5093:                         }
1.518     albertel 5094:                     }
                   5095:                 }
1.632     raeburn  5096:             } else {
                   5097:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5098:             }
1.632     raeburn  5099:         } else {
                   5100:             $legacy{'rolecolors'} = 1;
1.518     albertel 5101:         }
1.948     raeburn  5102:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5103:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5104:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5105:             }
                   5106:         }
1.632     raeburn  5107:         if (keys(%legacy) > 0) {
                   5108:             my %legacyhash = &get_legacy_domconf($udom);
                   5109:             foreach my $item (keys(%legacyhash)) {
                   5110:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5111:                     if ($legacy{'login'}) { 
                   5112:                         $designhash{$item} = $legacyhash{$item};
                   5113:                     }
                   5114:                 } else {
                   5115:                     if ($legacy{'rolecolors'}) {
                   5116:                         $designhash{$item} = $legacyhash{$item};
                   5117:                     }
1.518     albertel 5118:                 }
                   5119:             }
                   5120:         }
1.632     raeburn  5121:     } else {
                   5122:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5123:     }
                   5124:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5125: 				  $cachetime);
                   5126:     return %designhash;
                   5127: }
                   5128: 
1.632     raeburn  5129: sub get_legacy_domconf {
                   5130:     my ($udom) = @_;
                   5131:     my %legacyhash;
                   5132:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5133:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5134:     if (-e $designfile) {
                   5135:         if ( open (my $fh,"<$designfile") ) {
                   5136:             while (my $line = <$fh>) {
                   5137:                 next if ($line =~ /^\#/);
                   5138:                 chomp($line);
                   5139:                 my ($key,$val)=(split(/\=/,$line));
                   5140:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5141:             }
                   5142:             close($fh);
                   5143:         }
                   5144:     }
1.1026    raeburn  5145:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5146:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5147:     }
                   5148:     return %legacyhash;
                   5149: }
                   5150: 
1.63      www      5151: =pod
                   5152: 
1.112     bowersj2 5153: =item * &domainlogo()
1.63      www      5154: 
                   5155: Inputs: $domain (usually will be undef)
                   5156: 
                   5157: Returns: A link to a domain logo, if the domain logo exists.
                   5158: If the domain logo does not exist, a description of the domain.
                   5159: 
                   5160: =cut
1.112     bowersj2 5161: 
1.63      www      5162: ###############################################
                   5163: sub domainlogo {
1.517     raeburn  5164:     my $domain = &determinedomain(shift);
1.518     albertel 5165:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5166:     # See if there is a logo
                   5167:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5168:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5169:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5170: 	    if ($imgsrc =~ m{^/res/}) {
                   5171: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5172: 		&Apache::lonnet::repcopy($local_name);
                   5173: 	    }
                   5174: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5175:         } 
                   5176:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5177:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5178:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5179:     } else {
1.60      matthew  5180:         return '';
1.59      www      5181:     }
                   5182: }
1.63      www      5183: ##############################################
                   5184: 
                   5185: =pod
                   5186: 
1.112     bowersj2 5187: =item * &designparm()
1.63      www      5188: 
                   5189: Inputs: $which parameter; $domain (usually will be undef)
                   5190: 
                   5191: Returns: value of designparamter $which
                   5192: 
                   5193: =cut
1.112     bowersj2 5194: 
1.397     albertel 5195: 
1.400     albertel 5196: ##############################################
1.397     albertel 5197: sub designparm {
                   5198:     my ($which,$domain)=@_;
                   5199:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5200:         return $env{'environment.color.'.$which};
1.96      www      5201:     }
1.63      www      5202:     $domain=&determinedomain($domain);
1.1016    raeburn  5203:     my %domdesign;
                   5204:     unless ($domain eq 'public') {
                   5205:         %domdesign = &get_domainconf($domain);
                   5206:     }
1.520     raeburn  5207:     my $output;
1.517     raeburn  5208:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5209:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5210:     } else {
1.520     raeburn  5211:         $output = $defaultdesign{$which};
                   5212:     }
                   5213:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5214:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5215:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5216:             if ($output =~ m{^/res/}) {
                   5217:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5218:                 &Apache::lonnet::repcopy($local_name);
                   5219:             }
1.520     raeburn  5220:             $output = &lonhttpdurl($output);
                   5221:         }
1.63      www      5222:     }
1.520     raeburn  5223:     return $output;
1.63      www      5224: }
1.59      www      5225: 
1.822     bisitz   5226: ##############################################
                   5227: =pod
                   5228: 
1.832     bisitz   5229: =item * &authorspace()
                   5230: 
1.1028    raeburn  5231: Inputs: $url (usually will be undef).
1.832     bisitz   5232: 
1.1075.2.40  raeburn  5233: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5234:          directory being viewed (or for which action is being taken). 
                   5235:          If $url is provided, and begins /priv/<domain>/<uname>
                   5236:          the path will be that portion of the $context argument.
                   5237:          Otherwise the path will be for the author space of the current
                   5238:          user when the current role is author, or for that of the 
                   5239:          co-author/assistant co-author space when the current role 
                   5240:          is co-author or assistant co-author.
1.832     bisitz   5241: 
                   5242: =cut
                   5243: 
                   5244: sub authorspace {
1.1028    raeburn  5245:     my ($url) = @_;
                   5246:     if ($url ne '') {
                   5247:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5248:            return $1;
                   5249:         }
                   5250:     }
1.832     bisitz   5251:     my $caname = '';
1.1024    www      5252:     my $cadom = '';
1.1028    raeburn  5253:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5254:         ($cadom,$caname) =
1.832     bisitz   5255:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5256:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5257:         $caname = $env{'user.name'};
1.1024    www      5258:         $cadom = $env{'user.domain'};
1.832     bisitz   5259:     }
1.1028    raeburn  5260:     if (($caname ne '') && ($cadom ne '')) {
                   5261:         return "/priv/$cadom/$caname/";
                   5262:     }
                   5263:     return;
1.832     bisitz   5264: }
                   5265: 
                   5266: ##############################################
                   5267: =pod
                   5268: 
1.822     bisitz   5269: =item * &head_subbox()
                   5270: 
                   5271: Inputs: $content (contains HTML code with page functions, etc.)
                   5272: 
                   5273: Returns: HTML div with $content
                   5274:          To be included in page header
                   5275: 
                   5276: =cut
                   5277: 
                   5278: sub head_subbox {
                   5279:     my ($content)=@_;
                   5280:     my $output =
1.993     raeburn  5281:         '<div class="LC_head_subbox">'
1.822     bisitz   5282:        .$content
                   5283:        .'</div>'
                   5284: }
                   5285: 
                   5286: ##############################################
                   5287: =pod
                   5288: 
                   5289: =item * &CSTR_pageheader()
                   5290: 
1.1026    raeburn  5291: Input: (optional) filename from which breadcrumb trail is built.
                   5292:        In most cases no input as needed, as $env{'request.filename'}
                   5293:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5294: 
                   5295: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5296:          To be included on Authoring Space pages
1.822     bisitz   5297: 
                   5298: =cut
                   5299: 
                   5300: sub CSTR_pageheader {
1.1026    raeburn  5301:     my ($trailfile) = @_;
                   5302:     if ($trailfile eq '') {
                   5303:         $trailfile = $env{'request.filename'};
                   5304:     }
                   5305: 
                   5306: # this is for resources; directories have customtitle, and crumbs
                   5307: # and select recent are created in lonpubdir.pm
                   5308: 
                   5309:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5310:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5311:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5312:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5313:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5314: 
                   5315:     my $parentpath = '';
                   5316:     my $lastitem = '';
                   5317:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5318:         $parentpath = $1;
                   5319:         $lastitem = $2;
                   5320:     } else {
                   5321:         $lastitem = $thisdisfn;
                   5322:     }
1.921     bisitz   5323: 
                   5324:     my $output =
1.822     bisitz   5325:          '<div>'
                   5326:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  5327:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5328:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5329:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5330:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5331: 
                   5332:     if ($lastitem) {
                   5333:         $output .=
                   5334:              '<span class="LC_filename">'
                   5335:             .$lastitem
                   5336:             .'</span>';
                   5337:     }
                   5338:     $output .=
                   5339:          '<br />'
1.822     bisitz   5340:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5341:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5342:         .'</form>'
                   5343:         .&Apache::lonmenu::constspaceform()
                   5344:         .'</div>';
1.921     bisitz   5345: 
                   5346:     return $output;
1.822     bisitz   5347: }
                   5348: 
1.60      matthew  5349: ###############################################
                   5350: ###############################################
                   5351: 
                   5352: =pod
                   5353: 
1.112     bowersj2 5354: =back
                   5355: 
1.549     albertel 5356: =head1 HTML Helpers
1.112     bowersj2 5357: 
                   5358: =over 4
                   5359: 
                   5360: =item * &bodytag()
1.60      matthew  5361: 
                   5362: Returns a uniform header for LON-CAPA web pages.
                   5363: 
                   5364: Inputs: 
                   5365: 
1.112     bowersj2 5366: =over 4
                   5367: 
                   5368: =item * $title, A title to be displayed on the page.
                   5369: 
                   5370: =item * $function, the current role (can be undef).
                   5371: 
                   5372: =item * $addentries, extra parameters for the <body> tag.
                   5373: 
                   5374: =item * $bodyonly, if defined, only return the <body> tag.
                   5375: 
                   5376: =item * $domain, if defined, force a given domain.
                   5377: 
                   5378: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5379:             text interface only)
1.60      matthew  5380: 
1.814     bisitz   5381: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5382:                      navigational links
1.317     albertel 5383: 
1.338     albertel 5384: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5385: 
1.1075.2.12  raeburn  5386: =item * $no_inline_link, if true and in remote mode, don't show the
                   5387:          'Switch To Inline Menu' link
                   5388: 
1.460     albertel 5389: =item * $args, optional argument valid values are
                   5390:             no_auto_mt_title -> prevents &mt()ing the title arg
                   5391: 
1.1075.2.15  raeburn  5392: =item * $advtoolsref, optional argument, ref to an array containing
                   5393:             inlineremote items to be added in "Functions" menu below
                   5394:             breadcrumbs.
                   5395: 
1.112     bowersj2 5396: =back
                   5397: 
1.60      matthew  5398: Returns: A uniform header for LON-CAPA web pages.  
                   5399: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5400: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5401: other decorations will be returned.
                   5402: 
                   5403: =cut
                   5404: 
1.54      www      5405: sub bodytag {
1.831     bisitz   5406:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.15  raeburn  5407:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
1.339     albertel 5408: 
1.954     raeburn  5409:     my $public;
                   5410:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5411:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5412:         $public = 1;
                   5413:     }
1.460     albertel 5414:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5415:     my $httphost = $args->{'use_absolute'};
1.339     albertel 5416: 
1.183     matthew  5417:     $function = &get_users_function() if (!$function);
1.339     albertel 5418:     my $img =    &designparm($function.'.img',$domain);
                   5419:     my $font =   &designparm($function.'.font',$domain);
                   5420:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5421: 
1.803     bisitz   5422:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5423: 		   'bgcolor' => $pgbg,
1.339     albertel 5424: 		   'text'    => $font,
                   5425:                    'alink'   => &designparm($function.'.alink',$domain),
                   5426: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5427: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5428:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5429: 
1.63      www      5430:  # role and realm
1.1075.2.68  raeburn  5431:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5432:     if ($realm) {
                   5433:         $realm = '/'.$realm;
                   5434:     }
1.378     raeburn  5435:     if ($role  eq 'ca') {
1.479     albertel 5436:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5437:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5438:     } 
1.55      www      5439: # realm
1.258     albertel 5440:     if ($env{'request.course.id'}) {
1.378     raeburn  5441:         if ($env{'request.role'} !~ /^cr/) {
                   5442:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1075.2.115  raeburn  5443:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
                   5444:             $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   5445:         } else {
                   5446:             $role = (split(/\//,$role,4))[-1];
1.378     raeburn  5447:         }
1.898     raeburn  5448:         if ($env{'request.course.sec'}) {
                   5449:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5450:         }   
1.359     albertel 5451: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5452:     } else {
                   5453:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5454:     }
1.433     albertel 5455: 
1.359     albertel 5456:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5457: 
1.438     albertel 5458:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5459: 
1.101     www      5460: # construct main body tag
1.359     albertel 5461:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  5462: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5463: 
1.1075.2.38  raeburn  5464:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5465: 
                   5466:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5467:         return $bodytag;
1.1075.2.38  raeburn  5468:     }
1.359     albertel 5469: 
1.954     raeburn  5470:     if ($public) {
1.433     albertel 5471: 	undef($role);
                   5472:     }
1.359     albertel 5473:     
1.762     bisitz   5474:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5475:     #
                   5476:     # Extra info if you are the DC
                   5477:     my $dc_info = '';
                   5478:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5479:                         $env{'course.'.$env{'request.course.id'}.
                   5480:                                  '.domain'}.'/'})) {
                   5481:         my $cid = $env{'request.course.id'};
1.917     raeburn  5482:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5483:         $dc_info =~ s/\s+$//;
1.359     albertel 5484:     }
                   5485: 
1.1075.2.108  raeburn  5486:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 5487: 
1.1075.2.13  raeburn  5488:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5489: 
1.1075.2.38  raeburn  5490: 
                   5491: 
1.1075.2.21  raeburn  5492:     my $funclist;
                   5493:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  5494:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  5495:                     Apache::lonmenu::serverform();
                   5496:         my $forbodytag;
                   5497:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5498:                                             $forcereg,$args->{'group'},
                   5499:                                             $args->{'bread_crumbs'},
                   5500:                                             $advtoolsref,'',\$forbodytag);
                   5501:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5502:             $funclist = $forbodytag;
                   5503:         }
                   5504:     } else {
1.903     droeschl 5505: 
                   5506:         #    if ($env{'request.state'} eq 'construct') {
                   5507:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5508:         #    }
                   5509: 
1.1075.2.38  raeburn  5510:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5511:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5512: 
1.1075.2.38  raeburn  5513:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.1075.2.2  raeburn  5514: 
1.916     droeschl 5515:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.1075.2.22  raeburn  5516:             if ($dc_info) {
                   5517:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
1.1075.2.1  raeburn  5518:             }
1.1075.2.38  raeburn  5519:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.1075.2.22  raeburn  5520:                            <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5521:             return $bodytag;
                   5522:         }
1.894     droeschl 5523: 
1.927     raeburn  5524:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1075.2.38  raeburn  5525:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5526:         }
1.916     droeschl 5527: 
1.1075.2.38  raeburn  5528:         $bodytag .= $right;
1.852     droeschl 5529: 
1.917     raeburn  5530:         if ($dc_info) {
                   5531:             $dc_info = &dc_courseid_toggle($dc_info);
                   5532:         }
                   5533:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5534: 
1.1075.2.61  raeburn  5535:         #if directed to not display the secondary menu, don't.
                   5536:         if ($args->{'no_secondary_menu'}) {
                   5537:             return $bodytag;
                   5538:         }
1.903     droeschl 5539:         #don't show menus for public users
1.954     raeburn  5540:         if (!$public){
1.1075.2.52  raeburn  5541:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5542:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5543:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5544:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5545:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5546:                                 $args->{'bread_crumbs'});
1.1075.2.116  raeburn  5547:             } elsif ($forcereg) {
1.1075.2.22  raeburn  5548:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1075.2.116  raeburn  5549:                                                             $args->{'group'},
                   5550:                                                             $args->{'hide_buttons'});
1.1075.2.15  raeburn  5551:             } else {
1.1075.2.21  raeburn  5552:                 my $forbodytag;
                   5553:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5554:                                                     $forcereg,$args->{'group'},
                   5555:                                                     $args->{'bread_crumbs'},
                   5556:                                                     $advtoolsref,'',\$forbodytag);
                   5557:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5558:                     $bodytag .= $forbodytag;
                   5559:                 }
1.920     raeburn  5560:             }
1.903     droeschl 5561:         }else{
                   5562:             # this is to seperate menu from content when there's no secondary
                   5563:             # menu. Especially needed for public accessible ressources.
                   5564:             $bodytag .= '<hr style="clear:both" />';
                   5565:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5566:         }
1.903     droeschl 5567: 
1.235     raeburn  5568:         return $bodytag;
1.1075.2.12  raeburn  5569:     }
                   5570: 
                   5571: #
                   5572: # Top frame rendering, Remote is up
                   5573: #
                   5574: 
                   5575:     my $imgsrc = $img;
                   5576:     if ($img =~ /^\/adm/) {
                   5577:         $imgsrc = &lonhttpdurl($img);
                   5578:     }
                   5579:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5580: 
1.1075.2.60  raeburn  5581:     my $help=($no_inline_link?''
                   5582:               :&Apache::loncommon::top_nav_help('Help'));
                   5583: 
1.1075.2.12  raeburn  5584:     # Explicit link to get inline menu
                   5585:     my $menu= ($no_inline_link?''
                   5586:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5587: 
                   5588:     if ($dc_info) {
                   5589:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5590:     }
                   5591: 
1.1075.2.38  raeburn  5592:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   5593:     unless ($public) {
                   5594:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5595:                                 undef,'LC_menubuttons_link');
                   5596:     }
                   5597: 
1.1075.2.12  raeburn  5598:     unless ($env{'form.inhibitmenu'}) {
                   5599:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  5600:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  5601:                        <li>$help</li>
1.1075.2.12  raeburn  5602:                        <li>$menu</li>
                   5603:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5604:     }
1.1075.2.13  raeburn  5605:     if ($env{'request.state'} eq 'construct') {
                   5606:         if (!$public){
                   5607:             if ($env{'request.state'} eq 'construct') {
                   5608:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5609:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  5610:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5611:                             &Apache::lonmenu::innerregister($forcereg,
                   5612:                                                             $args->{'bread_crumbs'});
                   5613:             }
                   5614:         }
                   5615:     }
1.1075.2.21  raeburn  5616:     return $bodytag."\n".$funclist;
1.182     matthew  5617: }
                   5618: 
1.917     raeburn  5619: sub dc_courseid_toggle {
                   5620:     my ($dc_info) = @_;
1.980     raeburn  5621:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5622:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5623:            &mt('(More ...)').'</a></span>'.
                   5624:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5625: }
                   5626: 
1.330     albertel 5627: sub make_attr_string {
                   5628:     my ($register,$attr_ref) = @_;
                   5629: 
                   5630:     if ($attr_ref && !ref($attr_ref)) {
                   5631: 	die("addentries Must be a hash ref ".
                   5632: 	    join(':',caller(1))." ".
                   5633: 	    join(':',caller(0))." ");
                   5634:     }
                   5635: 
                   5636:     if ($register) {
1.339     albertel 5637: 	my ($on_load,$on_unload);
                   5638: 	foreach my $key (keys(%{$attr_ref})) {
                   5639: 	    if      (lc($key) eq 'onload') {
                   5640: 		$on_load.=$attr_ref->{$key}.';';
                   5641: 		delete($attr_ref->{$key});
                   5642: 
                   5643: 	    } elsif (lc($key) eq 'onunload') {
                   5644: 		$on_unload.=$attr_ref->{$key}.';';
                   5645: 		delete($attr_ref->{$key});
                   5646: 	    }
                   5647: 	}
1.1075.2.12  raeburn  5648:         if ($env{'environment.remote'} eq 'on') {
                   5649:             $attr_ref->{'onload'}  =
                   5650:                 &Apache::lonmenu::loadevents().  $on_load;
                   5651:             $attr_ref->{'onunload'}=
                   5652:                 &Apache::lonmenu::unloadevents().$on_unload;
                   5653:         } else {  
                   5654: 	    $attr_ref->{'onload'}  = $on_load;
                   5655: 	    $attr_ref->{'onunload'}= $on_unload;
                   5656:         }
1.330     albertel 5657:     }
1.339     albertel 5658: 
1.330     albertel 5659:     my $attr_string;
1.1075.2.56  raeburn  5660:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5661: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5662:     }
                   5663:     return $attr_string;
                   5664: }
                   5665: 
                   5666: 
1.182     matthew  5667: ###############################################
1.251     albertel 5668: ###############################################
                   5669: 
                   5670: =pod
                   5671: 
                   5672: =item * &endbodytag()
                   5673: 
                   5674: Returns a uniform footer for LON-CAPA web pages.
                   5675: 
1.635     raeburn  5676: Inputs: 1 - optional reference to an args hash
                   5677: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5678: a 'Continue' link is not displayed if the page contains an
                   5679: internal redirect in the <head></head> section,
                   5680: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5681: 
                   5682: =cut
                   5683: 
                   5684: sub endbodytag {
1.635     raeburn  5685:     my ($args) = @_;
1.1075.2.6  raeburn  5686:     my $endbodytag;
                   5687:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5688:         $endbodytag='</body>';
                   5689:     }
1.315     albertel 5690:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5691:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5692: 	    $endbodytag=
                   5693: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5694: 	        &mt('Continue').'</a>'.
                   5695: 	        $endbodytag;
                   5696:         }
1.315     albertel 5697:     }
1.251     albertel 5698:     return $endbodytag;
                   5699: }
                   5700: 
1.352     albertel 5701: =pod
                   5702: 
                   5703: =item * &standard_css()
                   5704: 
                   5705: Returns a style sheet
                   5706: 
                   5707: Inputs: (all optional)
                   5708:             domain         -> force to color decorate a page for a specific
                   5709:                                domain
                   5710:             function       -> force usage of a specific rolish color scheme
                   5711:             bgcolor        -> override the default page bgcolor
                   5712: 
                   5713: =cut
                   5714: 
1.343     albertel 5715: sub standard_css {
1.345     albertel 5716:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5717:     $function  = &get_users_function() if (!$function);
                   5718:     my $img    = &designparm($function.'.img',   $domain);
                   5719:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5720:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5721:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5722: #second colour for later usage
1.345     albertel 5723:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5724:     my $pgbg_or_bgcolor =
                   5725: 	         $bgcolor ||
1.352     albertel 5726: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5727:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5728:     my $alink  = &designparm($function.'.alink', $domain);
                   5729:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5730:     my $link   = &designparm($function.'.link',  $domain);
                   5731: 
1.602     albertel 5732:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5733:     my $mono                 = 'monospace';
1.850     bisitz   5734:     my $data_table_head      = $sidebg;
                   5735:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5736:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5737:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5738:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5739:     my $mail_new             = '#FFBB77';
                   5740:     my $mail_new_hover       = '#DD9955';
                   5741:     my $mail_read            = '#BBBB77';
                   5742:     my $mail_read_hover      = '#999944';
                   5743:     my $mail_replied         = '#AAAA88';
                   5744:     my $mail_replied_hover   = '#888855';
                   5745:     my $mail_other           = '#99BBBB';
                   5746:     my $mail_other_hover     = '#669999';
1.391     albertel 5747:     my $table_header         = '#DDDDDD';
1.489     raeburn  5748:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5749:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5750:     my $button_hover         = '#BF2317';
1.392     albertel 5751: 
1.608     albertel 5752:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5753:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5754:                                              : '0 3px 0 4px';
1.448     albertel 5755: 
1.523     albertel 5756: 
1.343     albertel 5757:     return <<END;
1.947     droeschl 5758: 
                   5759: /* needed for iframe to allow 100% height in FF */
                   5760: body, html { 
                   5761:     margin: 0;
                   5762:     padding: 0 0.5%;
                   5763:     height: 99%; /* to avoid scrollbars */
                   5764: }
                   5765: 
1.795     www      5766: body {
1.911     bisitz   5767:   font-family: $sans;
                   5768:   line-height:130%;
                   5769:   font-size:0.83em;
                   5770:   color:$font;
1.795     www      5771: }
                   5772: 
1.959     onken    5773: a:focus,
                   5774: a:focus img {
1.795     www      5775:   color: red;
                   5776: }
1.698     harmsja  5777: 
1.911     bisitz   5778: form, .inline {
                   5779:   display: inline;
1.795     www      5780: }
1.721     harmsja  5781: 
1.795     www      5782: .LC_right {
1.911     bisitz   5783:   text-align:right;
1.795     www      5784: }
                   5785: 
                   5786: .LC_middle {
1.911     bisitz   5787:   vertical-align:middle;
1.795     www      5788: }
1.721     harmsja  5789: 
1.1075.2.38  raeburn  5790: .LC_floatleft {
                   5791:   float: left;
                   5792: }
                   5793: 
                   5794: .LC_floatright {
                   5795:   float: right;
                   5796: }
                   5797: 
1.911     bisitz   5798: .LC_400Box {
                   5799:   width:400px;
                   5800: }
1.721     harmsja  5801: 
1.947     droeschl 5802: .LC_iframecontainer {
                   5803:     width: 98%;
                   5804:     margin: 0;
                   5805:     position: fixed;
                   5806:     top: 8.5em;
                   5807:     bottom: 0;
                   5808: }
                   5809: 
                   5810: .LC_iframecontainer iframe{
                   5811:     border: none;
                   5812:     width: 100%;
                   5813:     height: 100%;
                   5814: }
                   5815: 
1.778     bisitz   5816: .LC_filename {
                   5817:   font-family: $mono;
                   5818:   white-space:pre;
1.921     bisitz   5819:   font-size: 120%;
1.778     bisitz   5820: }
                   5821: 
                   5822: .LC_fileicon {
                   5823:   border: none;
                   5824:   height: 1.3em;
                   5825:   vertical-align: text-bottom;
                   5826:   margin-right: 0.3em;
                   5827:   text-decoration:none;
                   5828: }
                   5829: 
1.1008    www      5830: .LC_setting {
                   5831:   text-decoration:underline;
                   5832: }
                   5833: 
1.350     albertel 5834: .LC_error {
                   5835:   color: red;
                   5836: }
1.795     www      5837: 
1.1075.2.15  raeburn  5838: .LC_warning {
                   5839:   color: darkorange;
                   5840: }
                   5841: 
1.457     albertel 5842: .LC_diff_removed {
1.733     bisitz   5843:   color: red;
1.394     albertel 5844: }
1.532     albertel 5845: 
                   5846: .LC_info,
1.457     albertel 5847: .LC_success,
                   5848: .LC_diff_added {
1.350     albertel 5849:   color: green;
                   5850: }
1.795     www      5851: 
1.802     bisitz   5852: div.LC_confirm_box {
                   5853:   background-color: #FAFAFA;
                   5854:   border: 1px solid $lg_border_color;
                   5855:   margin-right: 0;
                   5856:   padding: 5px;
                   5857: }
                   5858: 
                   5859: div.LC_confirm_box .LC_error img,
                   5860: div.LC_confirm_box .LC_success img {
                   5861:   vertical-align: middle;
                   5862: }
                   5863: 
1.1075.2.108  raeburn  5864: .LC_maxwidth {
                   5865:   max-width: 100%;
                   5866:   height: auto;
                   5867: }
                   5868: 
                   5869: .LC_textsize_mobile {
                   5870:   \@media only screen and (max-device-width: 480px) {
                   5871:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   5872:   }
                   5873: }
                   5874: 
1.440     albertel 5875: .LC_icon {
1.771     droeschl 5876:   border: none;
1.790     droeschl 5877:   vertical-align: middle;
1.771     droeschl 5878: }
                   5879: 
1.543     albertel 5880: .LC_docs_spacer {
                   5881:   width: 25px;
                   5882:   height: 1px;
1.771     droeschl 5883:   border: none;
1.543     albertel 5884: }
1.346     albertel 5885: 
1.532     albertel 5886: .LC_internal_info {
1.735     bisitz   5887:   color: #999999;
1.532     albertel 5888: }
                   5889: 
1.794     www      5890: .LC_discussion {
1.1050    www      5891:   background: $data_table_dark;
1.911     bisitz   5892:   border: 1px solid black;
                   5893:   margin: 2px;
1.794     www      5894: }
                   5895: 
                   5896: .LC_disc_action_left {
1.1050    www      5897:   background: $sidebg;
1.911     bisitz   5898:   text-align: left;
1.1050    www      5899:   padding: 4px;
                   5900:   margin: 2px;
1.794     www      5901: }
                   5902: 
                   5903: .LC_disc_action_right {
1.1050    www      5904:   background: $sidebg;
1.911     bisitz   5905:   text-align: right;
1.1050    www      5906:   padding: 4px;
                   5907:   margin: 2px;
1.794     www      5908: }
                   5909: 
                   5910: .LC_disc_new_item {
1.911     bisitz   5911:   background: white;
                   5912:   border: 2px solid red;
1.1050    www      5913:   margin: 4px;
                   5914:   padding: 4px;
1.794     www      5915: }
                   5916: 
                   5917: .LC_disc_old_item {
1.911     bisitz   5918:   background: white;
1.1050    www      5919:   margin: 4px;
                   5920:   padding: 4px;
1.794     www      5921: }
                   5922: 
1.458     albertel 5923: table.LC_pastsubmission {
                   5924:   border: 1px solid black;
                   5925:   margin: 2px;
                   5926: }
                   5927: 
1.924     bisitz   5928: table#LC_menubuttons {
1.345     albertel 5929:   width: 100%;
                   5930:   background: $pgbg;
1.392     albertel 5931:   border: 2px;
1.402     albertel 5932:   border-collapse: separate;
1.803     bisitz   5933:   padding: 0;
1.345     albertel 5934: }
1.392     albertel 5935: 
1.801     tempelho 5936: table#LC_title_bar a {
                   5937:   color: $fontmenu;
                   5938: }
1.836     bisitz   5939: 
1.807     droeschl 5940: table#LC_title_bar {
1.819     tempelho 5941:   clear: both;
1.836     bisitz   5942:   display: none;
1.807     droeschl 5943: }
                   5944: 
1.795     www      5945: table#LC_title_bar,
1.933     droeschl 5946: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5947: table#LC_title_bar.LC_with_remote {
1.359     albertel 5948:   width: 100%;
1.392     albertel 5949:   border-color: $pgbg;
                   5950:   border-style: solid;
                   5951:   border-width: $border;
1.379     albertel 5952:   background: $pgbg;
1.801     tempelho 5953:   color: $fontmenu;
1.392     albertel 5954:   border-collapse: collapse;
1.803     bisitz   5955:   padding: 0;
1.819     tempelho 5956:   margin: 0;
1.359     albertel 5957: }
1.795     www      5958: 
1.933     droeschl 5959: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5960:     margin: 0;
                   5961:     padding: 0;
1.933     droeschl 5962:     position: relative;
                   5963:     list-style: none;
1.913     droeschl 5964: }
1.933     droeschl 5965: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5966:     display: inline;
                   5967: }
1.933     droeschl 5968: 
                   5969: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5970:     padding: 0;
1.933     droeschl 5971:     margin: 0;
                   5972:     float: left;
1.913     droeschl 5973: }
1.933     droeschl 5974: .LC_breadcrumb_tools_tools {
                   5975:     padding: 0;
                   5976:     margin: 0;
1.913     droeschl 5977:     float: right;
                   5978: }
                   5979: 
1.359     albertel 5980: table#LC_title_bar td {
                   5981:   background: $tabbg;
                   5982: }
1.795     www      5983: 
1.911     bisitz   5984: table#LC_menubuttons img {
1.803     bisitz   5985:   border: none;
1.346     albertel 5986: }
1.795     www      5987: 
1.842     droeschl 5988: .LC_breadcrumbs_component {
1.911     bisitz   5989:   float: right;
                   5990:   margin: 0 1em;
1.357     albertel 5991: }
1.842     droeschl 5992: .LC_breadcrumbs_component img {
1.911     bisitz   5993:   vertical-align: middle;
1.777     tempelho 5994: }
1.795     www      5995: 
1.1075.2.108  raeburn  5996: .LC_breadcrumbs_hoverable {
                   5997:   background: $sidebg;
                   5998: }
                   5999: 
1.383     albertel 6000: td.LC_table_cell_checkbox {
                   6001:   text-align: center;
                   6002: }
1.795     www      6003: 
                   6004: .LC_fontsize_small {
1.911     bisitz   6005:   font-size: 70%;
1.705     tempelho 6006: }
                   6007: 
1.844     bisitz   6008: #LC_breadcrumbs {
1.911     bisitz   6009:   clear:both;
                   6010:   background: $sidebg;
                   6011:   border-bottom: 1px solid $lg_border_color;
                   6012:   line-height: 2.5em;
1.933     droeschl 6013:   overflow: hidden;
1.911     bisitz   6014:   margin: 0;
                   6015:   padding: 0;
1.995     raeburn  6016:   text-align: left;
1.819     tempelho 6017: }
1.862     bisitz   6018: 
1.1075.2.16  raeburn  6019: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6020:   clear:both;
                   6021:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6022:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  6023:   margin: 0 0 10px 0;
1.966     bisitz   6024:   padding: 3px;
1.995     raeburn  6025:   text-align: left;
1.822     bisitz   6026: }
                   6027: 
1.795     www      6028: .LC_fontsize_medium {
1.911     bisitz   6029:   font-size: 85%;
1.705     tempelho 6030: }
                   6031: 
1.795     www      6032: .LC_fontsize_large {
1.911     bisitz   6033:   font-size: 120%;
1.705     tempelho 6034: }
                   6035: 
1.346     albertel 6036: .LC_menubuttons_inline_text {
                   6037:   color: $font;
1.698     harmsja  6038:   font-size: 90%;
1.701     harmsja  6039:   padding-left:3px;
1.346     albertel 6040: }
                   6041: 
1.934     droeschl 6042: .LC_menubuttons_inline_text img{
                   6043:   vertical-align: middle;
                   6044: }
                   6045: 
1.1051    www      6046: li.LC_menubuttons_inline_text img {
1.951     onken    6047:   cursor:pointer;
1.1002    droeschl 6048:   text-decoration: none;
1.951     onken    6049: }
                   6050: 
1.526     www      6051: .LC_menubuttons_link {
                   6052:   text-decoration: none;
                   6053: }
1.795     www      6054: 
1.522     albertel 6055: .LC_menubuttons_category {
1.521     www      6056:   color: $font;
1.526     www      6057:   background: $pgbg;
1.521     www      6058:   font-size: larger;
                   6059:   font-weight: bold;
                   6060: }
                   6061: 
1.346     albertel 6062: td.LC_menubuttons_text {
1.911     bisitz   6063:   color: $font;
1.346     albertel 6064: }
1.706     harmsja  6065: 
1.346     albertel 6066: .LC_current_location {
                   6067:   background: $tabbg;
                   6068: }
1.795     www      6069: 
1.938     bisitz   6070: table.LC_data_table {
1.347     albertel 6071:   border: 1px solid #000000;
1.402     albertel 6072:   border-collapse: separate;
1.426     albertel 6073:   border-spacing: 1px;
1.610     albertel 6074:   background: $pgbg;
1.347     albertel 6075: }
1.795     www      6076: 
1.422     albertel 6077: .LC_data_table_dense {
                   6078:   font-size: small;
                   6079: }
1.795     www      6080: 
1.507     raeburn  6081: table.LC_nested_outer {
                   6082:   border: 1px solid #000000;
1.589     raeburn  6083:   border-collapse: collapse;
1.803     bisitz   6084:   border-spacing: 0;
1.507     raeburn  6085:   width: 100%;
                   6086: }
1.795     www      6087: 
1.879     raeburn  6088: table.LC_innerpickbox,
1.507     raeburn  6089: table.LC_nested {
1.803     bisitz   6090:   border: none;
1.589     raeburn  6091:   border-collapse: collapse;
1.803     bisitz   6092:   border-spacing: 0;
1.507     raeburn  6093:   width: 100%;
                   6094: }
1.795     www      6095: 
1.911     bisitz   6096: table.LC_data_table tr th,
                   6097: table.LC_calendar tr th,
1.879     raeburn  6098: table.LC_prior_tries tr th,
                   6099: table.LC_innerpickbox tr th {
1.349     albertel 6100:   font-weight: bold;
                   6101:   background-color: $data_table_head;
1.801     tempelho 6102:   color:$fontmenu;
1.701     harmsja  6103:   font-size:90%;
1.347     albertel 6104: }
1.795     www      6105: 
1.879     raeburn  6106: table.LC_innerpickbox tr th,
                   6107: table.LC_innerpickbox tr td {
                   6108:   vertical-align: top;
                   6109: }
                   6110: 
1.711     raeburn  6111: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6112:   background-color: #CCCCCC;
1.711     raeburn  6113:   font-weight: bold;
                   6114:   text-align: left;
                   6115: }
1.795     www      6116: 
1.912     bisitz   6117: table.LC_data_table tr.LC_odd_row > td {
                   6118:   background-color: $data_table_light;
                   6119:   padding: 2px;
                   6120:   vertical-align: top;
                   6121: }
                   6122: 
1.809     bisitz   6123: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6124:   background-color: $data_table_light;
1.912     bisitz   6125:   vertical-align: top;
                   6126: }
                   6127: 
                   6128: table.LC_data_table tr.LC_even_row > td {
                   6129:   background-color: $data_table_dark;
1.425     albertel 6130:   padding: 2px;
1.900     bisitz   6131:   vertical-align: top;
1.347     albertel 6132: }
1.795     www      6133: 
1.809     bisitz   6134: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6135:   background-color: $data_table_dark;
1.900     bisitz   6136:   vertical-align: top;
1.347     albertel 6137: }
1.795     www      6138: 
1.425     albertel 6139: table.LC_data_table tr.LC_data_table_highlight td {
                   6140:   background-color: $data_table_darker;
                   6141: }
1.795     www      6142: 
1.639     raeburn  6143: table.LC_data_table tr td.LC_leftcol_header {
                   6144:   background-color: $data_table_head;
                   6145:   font-weight: bold;
                   6146: }
1.795     www      6147: 
1.451     albertel 6148: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6149: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6150:   font-weight: bold;
                   6151:   font-style: italic;
                   6152:   text-align: center;
                   6153:   padding: 8px;
1.347     albertel 6154: }
1.795     www      6155: 
1.1075.2.30  raeburn  6156: table.LC_data_table tr.LC_empty_row td,
                   6157: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6158:   background-color: $sidebg;
                   6159: }
                   6160: 
                   6161: table.LC_nested tr.LC_empty_row td {
                   6162:   background-color: #FFFFFF;
                   6163: }
                   6164: 
1.890     droeschl 6165: table.LC_caption {
                   6166: }
                   6167: 
1.507     raeburn  6168: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6169:   padding: 4ex
                   6170: }
1.795     www      6171: 
1.507     raeburn  6172: table.LC_nested_outer tr th {
                   6173:   font-weight: bold;
1.801     tempelho 6174:   color:$fontmenu;
1.507     raeburn  6175:   background-color: $data_table_head;
1.701     harmsja  6176:   font-size: small;
1.507     raeburn  6177:   border-bottom: 1px solid #000000;
                   6178: }
1.795     www      6179: 
1.507     raeburn  6180: table.LC_nested_outer tr td.LC_subheader {
                   6181:   background-color: $data_table_head;
                   6182:   font-weight: bold;
                   6183:   font-size: small;
                   6184:   border-bottom: 1px solid #000000;
                   6185:   text-align: right;
1.451     albertel 6186: }
1.795     www      6187: 
1.507     raeburn  6188: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6189:   background-color: #CCCCCC;
1.451     albertel 6190:   font-weight: bold;
                   6191:   font-size: small;
1.507     raeburn  6192:   text-align: center;
                   6193: }
1.795     www      6194: 
1.589     raeburn  6195: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6196: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6197:   text-align: left;
1.451     albertel 6198: }
1.795     www      6199: 
1.507     raeburn  6200: table.LC_nested td {
1.735     bisitz   6201:   background-color: #FFFFFF;
1.451     albertel 6202:   font-size: small;
1.507     raeburn  6203: }
1.795     www      6204: 
1.507     raeburn  6205: table.LC_nested_outer tr th.LC_right_item,
                   6206: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6207: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6208: table.LC_nested tr td.LC_right_item {
1.451     albertel 6209:   text-align: right;
                   6210: }
                   6211: 
1.507     raeburn  6212: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6213:   background-color: #EEEEEE;
1.451     albertel 6214: }
                   6215: 
1.473     raeburn  6216: table.LC_createuser {
                   6217: }
                   6218: 
                   6219: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6220:   font-size: small;
1.473     raeburn  6221: }
                   6222: 
                   6223: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6224:   background-color: #CCCCCC;
1.473     raeburn  6225:   font-weight: bold;
                   6226:   text-align: center;
                   6227: }
                   6228: 
1.349     albertel 6229: table.LC_calendar {
                   6230:   border: 1px solid #000000;
                   6231:   border-collapse: collapse;
1.917     raeburn  6232:   width: 98%;
1.349     albertel 6233: }
1.795     www      6234: 
1.349     albertel 6235: table.LC_calendar_pickdate {
                   6236:   font-size: xx-small;
                   6237: }
1.795     www      6238: 
1.349     albertel 6239: table.LC_calendar tr td {
                   6240:   border: 1px solid #000000;
                   6241:   vertical-align: top;
1.917     raeburn  6242:   width: 14%;
1.349     albertel 6243: }
1.795     www      6244: 
1.349     albertel 6245: table.LC_calendar tr td.LC_calendar_day_empty {
                   6246:   background-color: $data_table_dark;
                   6247: }
1.795     www      6248: 
1.779     bisitz   6249: table.LC_calendar tr td.LC_calendar_day_current {
                   6250:   background-color: $data_table_highlight;
1.777     tempelho 6251: }
1.795     www      6252: 
1.938     bisitz   6253: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6254:   background-color: $mail_new;
                   6255: }
1.795     www      6256: 
1.938     bisitz   6257: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6258:   background-color: $mail_new_hover;
                   6259: }
1.795     www      6260: 
1.938     bisitz   6261: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6262:   background-color: $mail_read;
                   6263: }
1.795     www      6264: 
1.938     bisitz   6265: /*
                   6266: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6267:   background-color: $mail_read_hover;
                   6268: }
1.938     bisitz   6269: */
1.795     www      6270: 
1.938     bisitz   6271: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6272:   background-color: $mail_replied;
                   6273: }
1.795     www      6274: 
1.938     bisitz   6275: /*
                   6276: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6277:   background-color: $mail_replied_hover;
                   6278: }
1.938     bisitz   6279: */
1.795     www      6280: 
1.938     bisitz   6281: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6282:   background-color: $mail_other;
                   6283: }
1.795     www      6284: 
1.938     bisitz   6285: /*
                   6286: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6287:   background-color: $mail_other_hover;
                   6288: }
1.938     bisitz   6289: */
1.494     raeburn  6290: 
1.777     tempelho 6291: table.LC_data_table tr > td.LC_browser_file,
                   6292: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6293:   background: #AAEE77;
1.389     albertel 6294: }
1.795     www      6295: 
1.777     tempelho 6296: table.LC_data_table tr > td.LC_browser_file_locked,
                   6297: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6298:   background: #FFAA99;
1.387     albertel 6299: }
1.795     www      6300: 
1.777     tempelho 6301: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6302:   background: #888888;
1.779     bisitz   6303: }
1.795     www      6304: 
1.777     tempelho 6305: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6306: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6307:   background: #F8F866;
1.777     tempelho 6308: }
1.795     www      6309: 
1.696     bisitz   6310: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6311:   background: #E0E8FF;
1.387     albertel 6312: }
1.696     bisitz   6313: 
1.707     bisitz   6314: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6315:   /* background: #77FF77; */
1.707     bisitz   6316: }
1.795     www      6317: 
1.707     bisitz   6318: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6319:   border-right: 8px solid #FFFF77;
1.707     bisitz   6320: }
1.795     www      6321: 
1.707     bisitz   6322: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6323:   border-right: 8px solid #FFAA77;
1.707     bisitz   6324: }
1.795     www      6325: 
1.707     bisitz   6326: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6327:   border-right: 8px solid #FF7777;
1.707     bisitz   6328: }
1.795     www      6329: 
1.707     bisitz   6330: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6331:   border-right: 8px solid #AAFF77;
1.707     bisitz   6332: }
1.795     www      6333: 
1.707     bisitz   6334: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6335:   border-right: 8px solid #11CC55;
1.707     bisitz   6336: }
                   6337: 
1.388     albertel 6338: span.LC_current_location {
1.701     harmsja  6339:   font-size:larger;
1.388     albertel 6340:   background: $pgbg;
                   6341: }
1.387     albertel 6342: 
1.1029    www      6343: span.LC_current_nav_location {
                   6344:   font-weight:bold;
                   6345:   background: $sidebg;
                   6346: }
                   6347: 
1.395     albertel 6348: span.LC_parm_menu_item {
                   6349:   font-size: larger;
                   6350: }
1.795     www      6351: 
1.395     albertel 6352: span.LC_parm_scope_all {
                   6353:   color: red;
                   6354: }
1.795     www      6355: 
1.395     albertel 6356: span.LC_parm_scope_folder {
                   6357:   color: green;
                   6358: }
1.795     www      6359: 
1.395     albertel 6360: span.LC_parm_scope_resource {
                   6361:   color: orange;
                   6362: }
1.795     www      6363: 
1.395     albertel 6364: span.LC_parm_part {
                   6365:   color: blue;
                   6366: }
1.795     www      6367: 
1.911     bisitz   6368: span.LC_parm_folder,
                   6369: span.LC_parm_symb {
1.395     albertel 6370:   font-size: x-small;
                   6371:   font-family: $mono;
                   6372:   color: #AAAAAA;
                   6373: }
                   6374: 
1.977     bisitz   6375: ul.LC_parm_parmlist li {
                   6376:   display: inline-block;
                   6377:   padding: 0.3em 0.8em;
                   6378:   vertical-align: top;
                   6379:   width: 150px;
                   6380:   border-top:1px solid $lg_border_color;
                   6381: }
                   6382: 
1.795     www      6383: td.LC_parm_overview_level_menu,
                   6384: td.LC_parm_overview_map_menu,
                   6385: td.LC_parm_overview_parm_selectors,
                   6386: td.LC_parm_overview_restrictions  {
1.396     albertel 6387:   border: 1px solid black;
                   6388:   border-collapse: collapse;
                   6389: }
1.795     www      6390: 
1.396     albertel 6391: table.LC_parm_overview_restrictions td {
                   6392:   border-width: 1px 4px 1px 4px;
                   6393:   border-style: solid;
                   6394:   border-color: $pgbg;
                   6395:   text-align: center;
                   6396: }
1.795     www      6397: 
1.396     albertel 6398: table.LC_parm_overview_restrictions th {
                   6399:   background: $tabbg;
                   6400:   border-width: 1px 4px 1px 4px;
                   6401:   border-style: solid;
                   6402:   border-color: $pgbg;
                   6403: }
1.795     www      6404: 
1.398     albertel 6405: table#LC_helpmenu {
1.803     bisitz   6406:   border: none;
1.398     albertel 6407:   height: 55px;
1.803     bisitz   6408:   border-spacing: 0;
1.398     albertel 6409: }
                   6410: 
                   6411: table#LC_helpmenu fieldset legend {
                   6412:   font-size: larger;
                   6413: }
1.795     www      6414: 
1.397     albertel 6415: table#LC_helpmenu_links {
                   6416:   width: 100%;
                   6417:   border: 1px solid black;
                   6418:   background: $pgbg;
1.803     bisitz   6419:   padding: 0;
1.397     albertel 6420:   border-spacing: 1px;
                   6421: }
1.795     www      6422: 
1.397     albertel 6423: table#LC_helpmenu_links tr td {
                   6424:   padding: 1px;
                   6425:   background: $tabbg;
1.399     albertel 6426:   text-align: center;
                   6427:   font-weight: bold;
1.397     albertel 6428: }
1.396     albertel 6429: 
1.795     www      6430: table#LC_helpmenu_links a:link,
                   6431: table#LC_helpmenu_links a:visited,
1.397     albertel 6432: table#LC_helpmenu_links a:active {
                   6433:   text-decoration: none;
                   6434:   color: $font;
                   6435: }
1.795     www      6436: 
1.397     albertel 6437: table#LC_helpmenu_links a:hover {
                   6438:   text-decoration: underline;
                   6439:   color: $vlink;
                   6440: }
1.396     albertel 6441: 
1.417     albertel 6442: .LC_chrt_popup_exists {
                   6443:   border: 1px solid #339933;
                   6444:   margin: -1px;
                   6445: }
1.795     www      6446: 
1.417     albertel 6447: .LC_chrt_popup_up {
                   6448:   border: 1px solid yellow;
                   6449:   margin: -1px;
                   6450: }
1.795     www      6451: 
1.417     albertel 6452: .LC_chrt_popup {
                   6453:   border: 1px solid #8888FF;
                   6454:   background: #CCCCFF;
                   6455: }
1.795     www      6456: 
1.421     albertel 6457: table.LC_pick_box {
                   6458:   border-collapse: separate;
                   6459:   background: white;
                   6460:   border: 1px solid black;
                   6461:   border-spacing: 1px;
                   6462: }
1.795     www      6463: 
1.421     albertel 6464: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6465:   background: $sidebg;
1.421     albertel 6466:   font-weight: bold;
1.900     bisitz   6467:   text-align: left;
1.740     bisitz   6468:   vertical-align: top;
1.421     albertel 6469:   width: 184px;
                   6470:   padding: 8px;
                   6471: }
1.795     www      6472: 
1.579     raeburn  6473: table.LC_pick_box td.LC_pick_box_value {
                   6474:   text-align: left;
                   6475:   padding: 8px;
                   6476: }
1.795     www      6477: 
1.579     raeburn  6478: table.LC_pick_box td.LC_pick_box_select {
                   6479:   text-align: left;
                   6480:   padding: 8px;
                   6481: }
1.795     www      6482: 
1.424     albertel 6483: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6484:   padding: 0;
1.421     albertel 6485:   height: 1px;
                   6486:   background: black;
                   6487: }
1.795     www      6488: 
1.421     albertel 6489: table.LC_pick_box td.LC_pick_box_submit {
                   6490:   text-align: right;
                   6491: }
1.795     www      6492: 
1.579     raeburn  6493: table.LC_pick_box td.LC_evenrow_value {
                   6494:   text-align: left;
                   6495:   padding: 8px;
                   6496:   background-color: $data_table_light;
                   6497: }
1.795     www      6498: 
1.579     raeburn  6499: table.LC_pick_box td.LC_oddrow_value {
                   6500:   text-align: left;
                   6501:   padding: 8px;
                   6502:   background-color: $data_table_light;
                   6503: }
1.795     www      6504: 
1.579     raeburn  6505: span.LC_helpform_receipt_cat {
                   6506:   font-weight: bold;
                   6507: }
1.795     www      6508: 
1.424     albertel 6509: table.LC_group_priv_box {
                   6510:   background: white;
                   6511:   border: 1px solid black;
                   6512:   border-spacing: 1px;
                   6513: }
1.795     www      6514: 
1.424     albertel 6515: table.LC_group_priv_box td.LC_pick_box_title {
                   6516:   background: $tabbg;
                   6517:   font-weight: bold;
                   6518:   text-align: right;
                   6519:   width: 184px;
                   6520: }
1.795     www      6521: 
1.424     albertel 6522: table.LC_group_priv_box td.LC_groups_fixed {
                   6523:   background: $data_table_light;
                   6524:   text-align: center;
                   6525: }
1.795     www      6526: 
1.424     albertel 6527: table.LC_group_priv_box td.LC_groups_optional {
                   6528:   background: $data_table_dark;
                   6529:   text-align: center;
                   6530: }
1.795     www      6531: 
1.424     albertel 6532: table.LC_group_priv_box td.LC_groups_functionality {
                   6533:   background: $data_table_darker;
                   6534:   text-align: center;
                   6535:   font-weight: bold;
                   6536: }
1.795     www      6537: 
1.424     albertel 6538: table.LC_group_priv td {
                   6539:   text-align: left;
1.803     bisitz   6540:   padding: 0;
1.424     albertel 6541: }
                   6542: 
                   6543: .LC_navbuttons {
                   6544:   margin: 2ex 0ex 2ex 0ex;
                   6545: }
1.795     www      6546: 
1.423     albertel 6547: .LC_topic_bar {
                   6548:   font-weight: bold;
                   6549:   background: $tabbg;
1.918     wenzelju 6550:   margin: 1em 0em 1em 2em;
1.805     bisitz   6551:   padding: 3px;
1.918     wenzelju 6552:   font-size: 1.2em;
1.423     albertel 6553: }
1.795     www      6554: 
1.423     albertel 6555: .LC_topic_bar span {
1.918     wenzelju 6556:   left: 0.5em;
                   6557:   position: absolute;
1.423     albertel 6558:   vertical-align: middle;
1.918     wenzelju 6559:   font-size: 1.2em;
1.423     albertel 6560: }
1.795     www      6561: 
1.423     albertel 6562: table.LC_course_group_status {
                   6563:   margin: 20px;
                   6564: }
1.795     www      6565: 
1.423     albertel 6566: table.LC_status_selector td {
                   6567:   vertical-align: top;
                   6568:   text-align: center;
1.424     albertel 6569:   padding: 4px;
                   6570: }
1.795     www      6571: 
1.599     albertel 6572: div.LC_feedback_link {
1.616     albertel 6573:   clear: both;
1.829     kalberla 6574:   background: $sidebg;
1.779     bisitz   6575:   width: 100%;
1.829     kalberla 6576:   padding-bottom: 10px;
                   6577:   border: 1px $tabbg solid;
1.833     kalberla 6578:   height: 22px;
                   6579:   line-height: 22px;
                   6580:   padding-top: 5px;
                   6581: }
                   6582: 
                   6583: div.LC_feedback_link img {
                   6584:   height: 22px;
1.867     kalberla 6585:   vertical-align:middle;
1.829     kalberla 6586: }
                   6587: 
1.911     bisitz   6588: div.LC_feedback_link a {
1.829     kalberla 6589:   text-decoration: none;
1.489     raeburn  6590: }
1.795     www      6591: 
1.867     kalberla 6592: div.LC_comblock {
1.911     bisitz   6593:   display:inline;
1.867     kalberla 6594:   color:$font;
                   6595:   font-size:90%;
                   6596: }
                   6597: 
                   6598: div.LC_feedback_link div.LC_comblock {
                   6599:   padding-left:5px;
                   6600: }
                   6601: 
                   6602: div.LC_feedback_link div.LC_comblock a {
                   6603:   color:$font;
                   6604: }
                   6605: 
1.489     raeburn  6606: span.LC_feedback_link {
1.858     bisitz   6607:   /* background: $feedback_link_bg; */
1.599     albertel 6608:   font-size: larger;
                   6609: }
1.795     www      6610: 
1.599     albertel 6611: span.LC_message_link {
1.858     bisitz   6612:   /* background: $feedback_link_bg; */
1.599     albertel 6613:   font-size: larger;
                   6614:   position: absolute;
                   6615:   right: 1em;
1.489     raeburn  6616: }
1.421     albertel 6617: 
1.515     albertel 6618: table.LC_prior_tries {
1.524     albertel 6619:   border: 1px solid #000000;
                   6620:   border-collapse: separate;
                   6621:   border-spacing: 1px;
1.515     albertel 6622: }
1.523     albertel 6623: 
1.515     albertel 6624: table.LC_prior_tries td {
1.524     albertel 6625:   padding: 2px;
1.515     albertel 6626: }
1.523     albertel 6627: 
                   6628: .LC_answer_correct {
1.795     www      6629:   background: lightgreen;
                   6630:   color: darkgreen;
                   6631:   padding: 6px;
1.523     albertel 6632: }
1.795     www      6633: 
1.523     albertel 6634: .LC_answer_charged_try {
1.797     www      6635:   background: #FFAAAA;
1.795     www      6636:   color: darkred;
                   6637:   padding: 6px;
1.523     albertel 6638: }
1.795     www      6639: 
1.779     bisitz   6640: .LC_answer_not_charged_try,
1.523     albertel 6641: .LC_answer_no_grade,
                   6642: .LC_answer_late {
1.795     www      6643:   background: lightyellow;
1.523     albertel 6644:   color: black;
1.795     www      6645:   padding: 6px;
1.523     albertel 6646: }
1.795     www      6647: 
1.523     albertel 6648: .LC_answer_previous {
1.795     www      6649:   background: lightblue;
                   6650:   color: darkblue;
                   6651:   padding: 6px;
1.523     albertel 6652: }
1.795     www      6653: 
1.779     bisitz   6654: .LC_answer_no_message {
1.777     tempelho 6655:   background: #FFFFFF;
                   6656:   color: black;
1.795     www      6657:   padding: 6px;
1.779     bisitz   6658: }
1.795     www      6659: 
1.779     bisitz   6660: .LC_answer_unknown {
                   6661:   background: orange;
                   6662:   color: black;
1.795     www      6663:   padding: 6px;
1.777     tempelho 6664: }
1.795     www      6665: 
1.529     albertel 6666: span.LC_prior_numerical,
                   6667: span.LC_prior_string,
                   6668: span.LC_prior_custom,
                   6669: span.LC_prior_reaction,
                   6670: span.LC_prior_math {
1.925     bisitz   6671:   font-family: $mono;
1.523     albertel 6672:   white-space: pre;
                   6673: }
                   6674: 
1.525     albertel 6675: span.LC_prior_string {
1.925     bisitz   6676:   font-family: $mono;
1.525     albertel 6677:   white-space: pre;
                   6678: }
                   6679: 
1.523     albertel 6680: table.LC_prior_option {
                   6681:   width: 100%;
                   6682:   border-collapse: collapse;
                   6683: }
1.795     www      6684: 
1.911     bisitz   6685: table.LC_prior_rank,
1.795     www      6686: table.LC_prior_match {
1.528     albertel 6687:   border-collapse: collapse;
                   6688: }
1.795     www      6689: 
1.528     albertel 6690: table.LC_prior_option tr td,
                   6691: table.LC_prior_rank tr td,
                   6692: table.LC_prior_match tr td {
1.524     albertel 6693:   border: 1px solid #000000;
1.515     albertel 6694: }
                   6695: 
1.855     bisitz   6696: .LC_nobreak {
1.544     albertel 6697:   white-space: nowrap;
1.519     raeburn  6698: }
                   6699: 
1.576     raeburn  6700: span.LC_cusr_emph {
                   6701:   font-style: italic;
                   6702: }
                   6703: 
1.633     raeburn  6704: span.LC_cusr_subheading {
                   6705:   font-weight: normal;
                   6706:   font-size: 85%;
                   6707: }
                   6708: 
1.861     bisitz   6709: div.LC_docs_entry_move {
1.859     bisitz   6710:   border: 1px solid #BBBBBB;
1.545     albertel 6711:   background: #DDDDDD;
1.861     bisitz   6712:   width: 22px;
1.859     bisitz   6713:   padding: 1px;
                   6714:   margin: 0;
1.545     albertel 6715: }
                   6716: 
1.861     bisitz   6717: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6718: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6719:   font-size: x-small;
                   6720: }
1.795     www      6721: 
1.861     bisitz   6722: .LC_docs_entry_parameter {
                   6723:   white-space: nowrap;
                   6724: }
                   6725: 
1.544     albertel 6726: .LC_docs_copy {
1.545     albertel 6727:   color: #000099;
1.544     albertel 6728: }
1.795     www      6729: 
1.544     albertel 6730: .LC_docs_cut {
1.545     albertel 6731:   color: #550044;
1.544     albertel 6732: }
1.795     www      6733: 
1.544     albertel 6734: .LC_docs_rename {
1.545     albertel 6735:   color: #009900;
1.544     albertel 6736: }
1.795     www      6737: 
1.544     albertel 6738: .LC_docs_remove {
1.545     albertel 6739:   color: #990000;
                   6740: }
                   6741: 
1.547     albertel 6742: .LC_docs_reinit_warn,
                   6743: .LC_docs_ext_edit {
                   6744:   font-size: x-small;
                   6745: }
                   6746: 
1.545     albertel 6747: table.LC_docs_adddocs td,
                   6748: table.LC_docs_adddocs th {
                   6749:   border: 1px solid #BBBBBB;
                   6750:   padding: 4px;
                   6751:   background: #DDDDDD;
1.543     albertel 6752: }
                   6753: 
1.584     albertel 6754: table.LC_sty_begin {
                   6755:   background: #BBFFBB;
                   6756: }
1.795     www      6757: 
1.584     albertel 6758: table.LC_sty_end {
                   6759:   background: #FFBBBB;
                   6760: }
                   6761: 
1.589     raeburn  6762: table.LC_double_column {
1.803     bisitz   6763:   border-width: 0;
1.589     raeburn  6764:   border-collapse: collapse;
                   6765:   width: 100%;
                   6766:   padding: 2px;
                   6767: }
                   6768: 
                   6769: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6770:   top: 2px;
1.589     raeburn  6771:   left: 2px;
                   6772:   width: 47%;
                   6773:   vertical-align: top;
                   6774: }
                   6775: 
                   6776: table.LC_double_column tr td.LC_right_col {
                   6777:   top: 2px;
1.779     bisitz   6778:   right: 2px;
1.589     raeburn  6779:   width: 47%;
                   6780:   vertical-align: top;
                   6781: }
                   6782: 
1.591     raeburn  6783: div.LC_left_float {
                   6784:   float: left;
                   6785:   padding-right: 5%;
1.597     albertel 6786:   padding-bottom: 4px;
1.591     raeburn  6787: }
                   6788: 
                   6789: div.LC_clear_float_header {
1.597     albertel 6790:   padding-bottom: 2px;
1.591     raeburn  6791: }
                   6792: 
                   6793: div.LC_clear_float_footer {
1.597     albertel 6794:   padding-top: 10px;
1.591     raeburn  6795:   clear: both;
                   6796: }
                   6797: 
1.597     albertel 6798: div.LC_grade_show_user {
1.941     bisitz   6799: /*  border-left: 5px solid $sidebg; */
                   6800:   border-top: 5px solid #000000;
                   6801:   margin: 50px 0 0 0;
1.936     bisitz   6802:   padding: 15px 0 5px 10px;
1.597     albertel 6803: }
1.795     www      6804: 
1.936     bisitz   6805: div.LC_grade_show_user_odd_row {
1.941     bisitz   6806: /*  border-left: 5px solid #000000; */
                   6807: }
                   6808: 
                   6809: div.LC_grade_show_user div.LC_Box {
                   6810:   margin-right: 50px;
1.597     albertel 6811: }
                   6812: 
                   6813: div.LC_grade_submissions,
                   6814: div.LC_grade_message_center,
1.936     bisitz   6815: div.LC_grade_info_links {
1.597     albertel 6816:   margin: 5px;
                   6817:   width: 99%;
                   6818:   background: #FFFFFF;
                   6819: }
1.795     www      6820: 
1.597     albertel 6821: div.LC_grade_submissions_header,
1.936     bisitz   6822: div.LC_grade_message_center_header {
1.705     tempelho 6823:   font-weight: bold;
                   6824:   font-size: large;
1.597     albertel 6825: }
1.795     www      6826: 
1.597     albertel 6827: div.LC_grade_submissions_body,
1.936     bisitz   6828: div.LC_grade_message_center_body {
1.597     albertel 6829:   border: 1px solid black;
                   6830:   width: 99%;
                   6831:   background: #FFFFFF;
                   6832: }
1.795     www      6833: 
1.613     albertel 6834: table.LC_scantron_action {
                   6835:   width: 100%;
                   6836: }
1.795     www      6837: 
1.613     albertel 6838: table.LC_scantron_action tr th {
1.698     harmsja  6839:   font-weight:bold;
                   6840:   font-style:normal;
1.613     albertel 6841: }
1.795     www      6842: 
1.779     bisitz   6843: .LC_edit_problem_header,
1.614     albertel 6844: div.LC_edit_problem_footer {
1.705     tempelho 6845:   font-weight: normal;
                   6846:   font-size:  medium;
1.602     albertel 6847:   margin: 2px;
1.1060    bisitz   6848:   background-color: $sidebg;
1.600     albertel 6849: }
1.795     www      6850: 
1.600     albertel 6851: div.LC_edit_problem_header,
1.602     albertel 6852: div.LC_edit_problem_header div,
1.614     albertel 6853: div.LC_edit_problem_footer,
                   6854: div.LC_edit_problem_footer div,
1.602     albertel 6855: div.LC_edit_problem_editxml_header,
                   6856: div.LC_edit_problem_editxml_header div {
1.1075.2.112  raeburn  6857:   z-index: 100;
1.600     albertel 6858: }
1.795     www      6859: 
1.600     albertel 6860: div.LC_edit_problem_header_title {
1.705     tempelho 6861:   font-weight: bold;
                   6862:   font-size: larger;
1.602     albertel 6863:   background: $tabbg;
                   6864:   padding: 3px;
1.1060    bisitz   6865:   margin: 0 0 5px 0;
1.602     albertel 6866: }
1.795     www      6867: 
1.602     albertel 6868: table.LC_edit_problem_header_title {
                   6869:   width: 100%;
1.600     albertel 6870:   background: $tabbg;
1.602     albertel 6871: }
                   6872: 
1.1075.2.112  raeburn  6873: div.LC_edit_actionbar {
                   6874:     background-color: $sidebg;
                   6875:     margin: 0;
                   6876:     padding: 0;
                   6877:     line-height: 200%;
1.602     albertel 6878: }
1.795     www      6879: 
1.1075.2.112  raeburn  6880: div.LC_edit_actionbar div{
                   6881:     padding: 0;
                   6882:     margin: 0;
                   6883:     display: inline-block;
1.600     albertel 6884: }
1.795     www      6885: 
1.1075.2.34  raeburn  6886: .LC_edit_opt {
                   6887:   padding-left: 1em;
                   6888:   white-space: nowrap;
                   6889: }
                   6890: 
1.1075.2.57  raeburn  6891: .LC_edit_problem_latexhelper{
                   6892:     text-align: right;
                   6893: }
                   6894: 
                   6895: #LC_edit_problem_colorful div{
                   6896:     margin-left: 40px;
                   6897: }
                   6898: 
1.1075.2.112  raeburn  6899: #LC_edit_problem_codemirror div{
                   6900:     margin-left: 0px;
                   6901: }
                   6902: 
1.911     bisitz   6903: img.stift {
1.803     bisitz   6904:   border-width: 0;
                   6905:   vertical-align: middle;
1.677     riegler  6906: }
1.680     riegler  6907: 
1.923     bisitz   6908: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6909:   vertical-align: top;
1.777     tempelho 6910: }
1.795     www      6911: 
1.716     raeburn  6912: div.LC_createcourse {
1.911     bisitz   6913:   margin: 10px 10px 10px 10px;
1.716     raeburn  6914: }
                   6915: 
1.917     raeburn  6916: .LC_dccid {
1.1075.2.38  raeburn  6917:   float: right;
1.917     raeburn  6918:   margin: 0.2em 0 0 0;
                   6919:   padding: 0;
                   6920:   font-size: 90%;
                   6921:   display:none;
                   6922: }
                   6923: 
1.897     wenzelju 6924: ol.LC_primary_menu a:hover,
1.721     harmsja  6925: ol#LC_MenuBreadcrumbs a:hover,
                   6926: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6927: ul#LC_secondary_menu a:hover,
1.721     harmsja  6928: .LC_FormSectionClearButton input:hover
1.795     www      6929: ul.LC_TabContent   li:hover a {
1.952     onken    6930:   color:$button_hover;
1.911     bisitz   6931:   text-decoration:none;
1.693     droeschl 6932: }
                   6933: 
1.779     bisitz   6934: h1 {
1.911     bisitz   6935:   padding: 0;
                   6936:   line-height:130%;
1.693     droeschl 6937: }
1.698     harmsja  6938: 
1.911     bisitz   6939: h2,
                   6940: h3,
                   6941: h4,
                   6942: h5,
                   6943: h6 {
                   6944:   margin: 5px 0 5px 0;
                   6945:   padding: 0;
                   6946:   line-height:130%;
1.693     droeschl 6947: }
1.795     www      6948: 
                   6949: .LC_hcell {
1.911     bisitz   6950:   padding:3px 15px 3px 15px;
                   6951:   margin: 0;
                   6952:   background-color:$tabbg;
                   6953:   color:$fontmenu;
                   6954:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6955: }
1.795     www      6956: 
1.840     bisitz   6957: .LC_Box > .LC_hcell {
1.911     bisitz   6958:   margin: 0 -10px 10px -10px;
1.835     bisitz   6959: }
                   6960: 
1.721     harmsja  6961: .LC_noBorder {
1.911     bisitz   6962:   border: 0;
1.698     harmsja  6963: }
1.693     droeschl 6964: 
1.721     harmsja  6965: .LC_FormSectionClearButton input {
1.911     bisitz   6966:   background-color:transparent;
                   6967:   border: none;
                   6968:   cursor:pointer;
                   6969:   text-decoration:underline;
1.693     droeschl 6970: }
1.763     bisitz   6971: 
                   6972: .LC_help_open_topic {
1.911     bisitz   6973:   color: #FFFFFF;
                   6974:   background-color: #EEEEFF;
                   6975:   margin: 1px;
                   6976:   padding: 4px;
                   6977:   border: 1px solid #000033;
                   6978:   white-space: nowrap;
                   6979:   /* vertical-align: middle; */
1.759     neumanie 6980: }
1.693     droeschl 6981: 
1.911     bisitz   6982: dl,
                   6983: ul,
                   6984: div,
                   6985: fieldset {
                   6986:   margin: 10px 10px 10px 0;
                   6987:   /* overflow: hidden; */
1.693     droeschl 6988: }
1.795     www      6989: 
1.1075.2.90  raeburn  6990: article.geogebraweb div {
                   6991:     margin: 0;
                   6992: }
                   6993: 
1.838     bisitz   6994: fieldset > legend {
1.911     bisitz   6995:   font-weight: bold;
                   6996:   padding: 0 5px 0 5px;
1.838     bisitz   6997: }
                   6998: 
1.813     bisitz   6999: #LC_nav_bar {
1.911     bisitz   7000:   float: left;
1.995     raeburn  7001:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7002:   margin: 0 0 2px 0;
1.807     droeschl 7003: }
                   7004: 
1.916     droeschl 7005: #LC_realm {
                   7006:   margin: 0.2em 0 0 0;
                   7007:   padding: 0;
                   7008:   font-weight: bold;
                   7009:   text-align: center;
1.995     raeburn  7010:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7011: }
                   7012: 
1.911     bisitz   7013: #LC_nav_bar em {
                   7014:   font-weight: bold;
                   7015:   font-style: normal;
1.807     droeschl 7016: }
                   7017: 
1.897     wenzelju 7018: ol.LC_primary_menu {
1.934     droeschl 7019:   margin: 0;
1.1075.2.2  raeburn  7020:   padding: 0;
1.807     droeschl 7021: }
                   7022: 
1.852     droeschl 7023: ol#LC_PathBreadcrumbs {
1.911     bisitz   7024:   margin: 0;
1.693     droeschl 7025: }
                   7026: 
1.897     wenzelju 7027: ol.LC_primary_menu li {
1.1075.2.2  raeburn  7028:   color: RGB(80, 80, 80);
                   7029:   vertical-align: middle;
                   7030:   text-align: left;
                   7031:   list-style: none;
1.1075.2.112  raeburn  7032:   position: relative;
1.1075.2.2  raeburn  7033:   float: left;
1.1075.2.112  raeburn  7034:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7035:   line-height: 1.5em;
1.1075.2.2  raeburn  7036: }
                   7037: 
1.1075.2.113  raeburn  7038: ol.LC_primary_menu li a, 
1.1075.2.112  raeburn  7039: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  7040:   display: block;
                   7041:   margin: 0;
                   7042:   padding: 0 5px 0 10px;
                   7043:   text-decoration: none;
                   7044: }
                   7045: 
1.1075.2.112  raeburn  7046: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7047:   display: inline-block;
                   7048:   width: 95%;
                   7049:   text-align: left;
                   7050: }
                   7051: 
                   7052: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7053:   display: inline-block;
                   7054:   width: 5%;
                   7055:   float: right;
                   7056:   text-align: right;
                   7057:   font-size: 70%;
                   7058: }
                   7059: 
                   7060: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  7061:   display: none;
1.1075.2.112  raeburn  7062:   width: 15em;
1.1075.2.2  raeburn  7063:   background-color: $data_table_light;
1.1075.2.112  raeburn  7064:   position: absolute;
                   7065:   top: 100%;
                   7066: }
                   7067: 
                   7068: ol.LC_primary_menu ul ul {
                   7069:   left: 100%;
                   7070:   top: 0;
1.1075.2.2  raeburn  7071: }
                   7072: 
1.1075.2.112  raeburn  7073: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  7074:   display: block;
                   7075:   position: absolute;
                   7076:   margin: 0;
                   7077:   padding: 0;
1.1075.2.5  raeburn  7078:   z-index: 2;
1.1075.2.2  raeburn  7079: }
                   7080: 
                   7081: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112  raeburn  7082: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  7083:   font-size: 90%;
1.911     bisitz   7084:   vertical-align: top;
1.1075.2.2  raeburn  7085:   float: none;
1.1075.2.5  raeburn  7086:   border-left: 1px solid black;
                   7087:   border-right: 1px solid black;
1.1075.2.112  raeburn  7088: /* A dark bottom border to visualize different menu options;
                   7089: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7090:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  7091: }
                   7092: 
1.1075.2.112  raeburn  7093: ol.LC_primary_menu li li p:hover {
                   7094:   color:$button_hover;
                   7095:   text-decoration:none;
                   7096:   background-color:$data_table_dark;
1.1075.2.2  raeburn  7097: }
                   7098: 
                   7099: ol.LC_primary_menu li li a:hover {
                   7100:    color:$button_hover;
                   7101:    background-color:$data_table_dark;
1.693     droeschl 7102: }
                   7103: 
1.1075.2.112  raeburn  7104: /* Font-size equal to the size of the predecessors*/
                   7105: ol.LC_primary_menu li:hover li li {
                   7106:   font-size: 100%;
                   7107: }
                   7108: 
1.897     wenzelju 7109: ol.LC_primary_menu li img {
1.911     bisitz   7110:   vertical-align: bottom;
1.934     droeschl 7111:   height: 1.1em;
1.1075.2.3  raeburn  7112:   margin: 0.2em 0 0 0;
1.693     droeschl 7113: }
                   7114: 
1.897     wenzelju 7115: ol.LC_primary_menu a {
1.911     bisitz   7116:   color: RGB(80, 80, 80);
                   7117:   text-decoration: none;
1.693     droeschl 7118: }
1.795     www      7119: 
1.949     droeschl 7120: ol.LC_primary_menu a.LC_new_message {
                   7121:   font-weight:bold;
                   7122:   color: darkred;
                   7123: }
                   7124: 
1.975     raeburn  7125: ol.LC_docs_parameters {
                   7126:   margin-left: 0;
                   7127:   padding: 0;
                   7128:   list-style: none;
                   7129: }
                   7130: 
                   7131: ol.LC_docs_parameters li {
                   7132:   margin: 0;
                   7133:   padding-right: 20px;
                   7134:   display: inline;
                   7135: }
                   7136: 
1.976     raeburn  7137: ol.LC_docs_parameters li:before {
                   7138:   content: "\\002022 \\0020";
                   7139: }
                   7140: 
                   7141: li.LC_docs_parameters_title {
                   7142:   font-weight: bold;
                   7143: }
                   7144: 
                   7145: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7146:   content: "";
                   7147: }
                   7148: 
1.897     wenzelju 7149: ul#LC_secondary_menu {
1.1075.2.23  raeburn  7150:   clear: right;
1.911     bisitz   7151:   color: $fontmenu;
                   7152:   background: $tabbg;
                   7153:   list-style: none;
                   7154:   padding: 0;
                   7155:   margin: 0;
                   7156:   width: 100%;
1.995     raeburn  7157:   text-align: left;
1.1075.2.4  raeburn  7158:   float: left;
1.808     droeschl 7159: }
                   7160: 
1.897     wenzelju 7161: ul#LC_secondary_menu li {
1.911     bisitz   7162:   font-weight: bold;
                   7163:   line-height: 1.8em;
                   7164:   border-right: 1px solid black;
1.1075.2.4  raeburn  7165:   float: left;
                   7166: }
                   7167: 
                   7168: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7169:   background-color: $data_table_light;
                   7170: }
                   7171: 
                   7172: ul#LC_secondary_menu li a {
                   7173:   padding: 0 0.8em;
                   7174: }
                   7175: 
                   7176: ul#LC_secondary_menu li ul {
                   7177:   display: none;
                   7178: }
                   7179: 
                   7180: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7181:   display: block;
                   7182:   position: absolute;
                   7183:   margin: 0;
                   7184:   padding: 0;
                   7185:   list-style:none;
                   7186:   float: none;
                   7187:   background-color: $data_table_light;
1.1075.2.5  raeburn  7188:   z-index: 2;
1.1075.2.10  raeburn  7189:   margin-left: -1px;
1.1075.2.4  raeburn  7190: }
                   7191: 
                   7192: ul#LC_secondary_menu li ul li {
                   7193:   font-size: 90%;
                   7194:   vertical-align: top;
                   7195:   border-left: 1px solid black;
                   7196:   border-right: 1px solid black;
1.1075.2.33  raeburn  7197:   background-color: $data_table_light;
1.1075.2.4  raeburn  7198:   list-style:none;
                   7199:   float: none;
                   7200: }
                   7201: 
                   7202: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7203:   background-color: $data_table_dark;
1.807     droeschl 7204: }
                   7205: 
1.847     tempelho 7206: ul.LC_TabContent {
1.911     bisitz   7207:   display:block;
                   7208:   background: $sidebg;
                   7209:   border-bottom: solid 1px $lg_border_color;
                   7210:   list-style:none;
1.1020    raeburn  7211:   margin: -1px -10px 0 -10px;
1.911     bisitz   7212:   padding: 0;
1.693     droeschl 7213: }
                   7214: 
1.795     www      7215: ul.LC_TabContent li,
                   7216: ul.LC_TabContentBigger li {
1.911     bisitz   7217:   float:left;
1.741     harmsja  7218: }
1.795     www      7219: 
1.897     wenzelju 7220: ul#LC_secondary_menu li a {
1.911     bisitz   7221:   color: $fontmenu;
                   7222:   text-decoration: none;
1.693     droeschl 7223: }
1.795     www      7224: 
1.721     harmsja  7225: ul.LC_TabContent {
1.952     onken    7226:   min-height:20px;
1.721     harmsja  7227: }
1.795     www      7228: 
                   7229: ul.LC_TabContent li {
1.911     bisitz   7230:   vertical-align:middle;
1.959     onken    7231:   padding: 0 16px 0 10px;
1.911     bisitz   7232:   background-color:$tabbg;
                   7233:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7234:   border-left: solid 1px $font;
1.721     harmsja  7235: }
1.795     www      7236: 
1.847     tempelho 7237: ul.LC_TabContent .right {
1.911     bisitz   7238:   float:right;
1.847     tempelho 7239: }
                   7240: 
1.911     bisitz   7241: ul.LC_TabContent li a,
                   7242: ul.LC_TabContent li {
                   7243:   color:rgb(47,47,47);
                   7244:   text-decoration:none;
                   7245:   font-size:95%;
                   7246:   font-weight:bold;
1.952     onken    7247:   min-height:20px;
                   7248: }
                   7249: 
1.959     onken    7250: ul.LC_TabContent li a:hover,
                   7251: ul.LC_TabContent li a:focus {
1.952     onken    7252:   color: $button_hover;
1.959     onken    7253:   background:none;
                   7254:   outline:none;
1.952     onken    7255: }
                   7256: 
                   7257: ul.LC_TabContent li:hover {
                   7258:   color: $button_hover;
                   7259:   cursor:pointer;
1.721     harmsja  7260: }
1.795     www      7261: 
1.911     bisitz   7262: ul.LC_TabContent li.active {
1.952     onken    7263:   color: $font;
1.911     bisitz   7264:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7265:   border-bottom:solid 1px #FFFFFF;
                   7266:   cursor: default;
1.744     ehlerst  7267: }
1.795     www      7268: 
1.959     onken    7269: ul.LC_TabContent li.active a {
                   7270:   color:$font;
                   7271:   background:#FFFFFF;
                   7272:   outline: none;
                   7273: }
1.1047    raeburn  7274: 
                   7275: ul.LC_TabContent li.goback {
                   7276:   float: left;
                   7277:   border-left: none;
                   7278: }
                   7279: 
1.870     tempelho 7280: #maincoursedoc {
1.911     bisitz   7281:   clear:both;
1.870     tempelho 7282: }
                   7283: 
                   7284: ul.LC_TabContentBigger {
1.911     bisitz   7285:   display:block;
                   7286:   list-style:none;
                   7287:   padding: 0;
1.870     tempelho 7288: }
                   7289: 
1.795     www      7290: ul.LC_TabContentBigger li {
1.911     bisitz   7291:   vertical-align:bottom;
                   7292:   height: 30px;
                   7293:   font-size:110%;
                   7294:   font-weight:bold;
                   7295:   color: #737373;
1.841     tempelho 7296: }
                   7297: 
1.957     onken    7298: ul.LC_TabContentBigger li.active {
                   7299:   position: relative;
                   7300:   top: 1px;
                   7301: }
                   7302: 
1.870     tempelho 7303: ul.LC_TabContentBigger li a {
1.911     bisitz   7304:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7305:   height: 30px;
                   7306:   line-height: 30px;
                   7307:   text-align: center;
                   7308:   display: block;
                   7309:   text-decoration: none;
1.958     onken    7310:   outline: none;  
1.741     harmsja  7311: }
1.795     www      7312: 
1.870     tempelho 7313: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7314:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7315:   color:$font;
1.744     ehlerst  7316: }
1.795     www      7317: 
1.870     tempelho 7318: ul.LC_TabContentBigger li b {
1.911     bisitz   7319:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7320:   display: block;
                   7321:   float: left;
                   7322:   padding: 0 30px;
1.957     onken    7323:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7324: }
                   7325: 
1.956     onken    7326: ul.LC_TabContentBigger li:hover b {
                   7327:   color:$button_hover;
                   7328: }
                   7329: 
1.870     tempelho 7330: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7331:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7332:   color:$font;
1.957     onken    7333:   border: 0;
1.741     harmsja  7334: }
1.693     droeschl 7335: 
1.870     tempelho 7336: 
1.862     bisitz   7337: ul.LC_CourseBreadcrumbs {
                   7338:   background: $sidebg;
1.1020    raeburn  7339:   height: 2em;
1.862     bisitz   7340:   padding-left: 10px;
1.1020    raeburn  7341:   margin: 0;
1.862     bisitz   7342:   list-style-position: inside;
                   7343: }
                   7344: 
1.911     bisitz   7345: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7346: ol#LC_PathBreadcrumbs {
1.911     bisitz   7347:   padding-left: 10px;
                   7348:   margin: 0;
1.933     droeschl 7349:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7350: }
                   7351: 
1.911     bisitz   7352: ol#LC_MenuBreadcrumbs li,
                   7353: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7354: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7355:   display: inline;
1.933     droeschl 7356:   white-space: normal;  
1.693     droeschl 7357: }
                   7358: 
1.823     bisitz   7359: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7360: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7361:   text-decoration: none;
                   7362:   font-size:90%;
1.693     droeschl 7363: }
1.795     www      7364: 
1.969     droeschl 7365: ol#LC_MenuBreadcrumbs h1 {
                   7366:   display: inline;
                   7367:   font-size: 90%;
                   7368:   line-height: 2.5em;
                   7369:   margin: 0;
                   7370:   padding: 0;
                   7371: }
                   7372: 
1.795     www      7373: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7374:   text-decoration:none;
                   7375:   font-size:100%;
                   7376:   font-weight:bold;
1.693     droeschl 7377: }
1.795     www      7378: 
1.840     bisitz   7379: .LC_Box {
1.911     bisitz   7380:   border: solid 1px $lg_border_color;
                   7381:   padding: 0 10px 10px 10px;
1.746     neumanie 7382: }
1.795     www      7383: 
1.1020    raeburn  7384: .LC_DocsBox {
                   7385:   border: solid 1px $lg_border_color;
                   7386:   padding: 0 0 10px 10px;
                   7387: }
                   7388: 
1.795     www      7389: .LC_AboutMe_Image {
1.911     bisitz   7390:   float:left;
                   7391:   margin-right:10px;
1.747     neumanie 7392: }
1.795     www      7393: 
                   7394: .LC_Clear_AboutMe_Image {
1.911     bisitz   7395:   clear:left;
1.747     neumanie 7396: }
1.795     www      7397: 
1.721     harmsja  7398: dl.LC_ListStyleClean dt {
1.911     bisitz   7399:   padding-right: 5px;
                   7400:   display: table-header-group;
1.693     droeschl 7401: }
                   7402: 
1.721     harmsja  7403: dl.LC_ListStyleClean dd {
1.911     bisitz   7404:   display: table-row;
1.693     droeschl 7405: }
                   7406: 
1.721     harmsja  7407: .LC_ListStyleClean,
                   7408: .LC_ListStyleSimple,
                   7409: .LC_ListStyleNormal,
1.795     www      7410: .LC_ListStyleSpecial {
1.911     bisitz   7411:   /* display:block; */
                   7412:   list-style-position: inside;
                   7413:   list-style-type: none;
                   7414:   overflow: hidden;
                   7415:   padding: 0;
1.693     droeschl 7416: }
                   7417: 
1.721     harmsja  7418: .LC_ListStyleSimple li,
                   7419: .LC_ListStyleSimple dd,
                   7420: .LC_ListStyleNormal li,
                   7421: .LC_ListStyleNormal dd,
                   7422: .LC_ListStyleSpecial li,
1.795     www      7423: .LC_ListStyleSpecial dd {
1.911     bisitz   7424:   margin: 0;
                   7425:   padding: 5px 5px 5px 10px;
                   7426:   clear: both;
1.693     droeschl 7427: }
                   7428: 
1.721     harmsja  7429: .LC_ListStyleClean li,
                   7430: .LC_ListStyleClean dd {
1.911     bisitz   7431:   padding-top: 0;
                   7432:   padding-bottom: 0;
1.693     droeschl 7433: }
                   7434: 
1.721     harmsja  7435: .LC_ListStyleSimple dd,
1.795     www      7436: .LC_ListStyleSimple li {
1.911     bisitz   7437:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7438: }
                   7439: 
1.721     harmsja  7440: .LC_ListStyleSpecial li,
                   7441: .LC_ListStyleSpecial dd {
1.911     bisitz   7442:   list-style-type: none;
                   7443:   background-color: RGB(220, 220, 220);
                   7444:   margin-bottom: 4px;
1.693     droeschl 7445: }
                   7446: 
1.721     harmsja  7447: table.LC_SimpleTable {
1.911     bisitz   7448:   margin:5px;
                   7449:   border:solid 1px $lg_border_color;
1.795     www      7450: }
1.693     droeschl 7451: 
1.721     harmsja  7452: table.LC_SimpleTable tr {
1.911     bisitz   7453:   padding: 0;
                   7454:   border:solid 1px $lg_border_color;
1.693     droeschl 7455: }
1.795     www      7456: 
                   7457: table.LC_SimpleTable thead {
1.911     bisitz   7458:   background:rgb(220,220,220);
1.693     droeschl 7459: }
                   7460: 
1.721     harmsja  7461: div.LC_columnSection {
1.911     bisitz   7462:   display: block;
                   7463:   clear: both;
                   7464:   overflow: hidden;
                   7465:   margin: 0;
1.693     droeschl 7466: }
                   7467: 
1.721     harmsja  7468: div.LC_columnSection>* {
1.911     bisitz   7469:   float: left;
                   7470:   margin: 10px 20px 10px 0;
                   7471:   overflow:hidden;
1.693     droeschl 7472: }
1.721     harmsja  7473: 
1.795     www      7474: table em {
1.911     bisitz   7475:   font-weight: bold;
                   7476:   font-style: normal;
1.748     schulted 7477: }
1.795     www      7478: 
1.779     bisitz   7479: table.LC_tableBrowseRes,
1.795     www      7480: table.LC_tableOfContent {
1.911     bisitz   7481:   border:none;
                   7482:   border-spacing: 1px;
                   7483:   padding: 3px;
                   7484:   background-color: #FFFFFF;
                   7485:   font-size: 90%;
1.753     droeschl 7486: }
1.789     droeschl 7487: 
1.911     bisitz   7488: table.LC_tableOfContent {
                   7489:   border-collapse: collapse;
1.789     droeschl 7490: }
                   7491: 
1.771     droeschl 7492: table.LC_tableBrowseRes a,
1.768     schulted 7493: table.LC_tableOfContent a {
1.911     bisitz   7494:   background-color: transparent;
                   7495:   text-decoration: none;
1.753     droeschl 7496: }
                   7497: 
1.795     www      7498: table.LC_tableOfContent img {
1.911     bisitz   7499:   border: none;
                   7500:   height: 1.3em;
                   7501:   vertical-align: text-bottom;
                   7502:   margin-right: 0.3em;
1.753     droeschl 7503: }
1.757     schulted 7504: 
1.795     www      7505: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7506:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7507: }
                   7508: 
1.795     www      7509: a#LC_content_toolbar_everything {
1.911     bisitz   7510:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7511: }
                   7512: 
1.795     www      7513: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7514:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7515: }
                   7516: 
1.795     www      7517: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7518:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7519: }
                   7520: 
1.795     www      7521: a#LC_content_toolbar_changefolder {
1.911     bisitz   7522:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7523: }
                   7524: 
1.795     www      7525: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7526:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7527: }
                   7528: 
1.1043    raeburn  7529: a#LC_content_toolbar_edittoplevel {
                   7530:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7531: }
                   7532: 
1.795     www      7533: ul#LC_toolbar li a:hover {
1.911     bisitz   7534:   background-position: bottom center;
1.757     schulted 7535: }
                   7536: 
1.795     www      7537: ul#LC_toolbar {
1.911     bisitz   7538:   padding: 0;
                   7539:   margin: 2px;
                   7540:   list-style:none;
                   7541:   position:relative;
                   7542:   background-color:white;
1.1075.2.9  raeburn  7543:   overflow: auto;
1.757     schulted 7544: }
                   7545: 
1.795     www      7546: ul#LC_toolbar li {
1.911     bisitz   7547:   border:1px solid white;
                   7548:   padding: 0;
                   7549:   margin: 0;
                   7550:   float: left;
                   7551:   display:inline;
                   7552:   vertical-align:middle;
1.1075.2.9  raeburn  7553:   white-space: nowrap;
1.911     bisitz   7554: }
1.757     schulted 7555: 
1.783     amueller 7556: 
1.795     www      7557: a.LC_toolbarItem {
1.911     bisitz   7558:   display:block;
                   7559:   padding: 0;
                   7560:   margin: 0;
                   7561:   height: 32px;
                   7562:   width: 32px;
                   7563:   color:white;
                   7564:   border: none;
                   7565:   background-repeat:no-repeat;
                   7566:   background-color:transparent;
1.757     schulted 7567: }
                   7568: 
1.915     droeschl 7569: ul.LC_funclist {
                   7570:     margin: 0;
                   7571:     padding: 0.5em 1em 0.5em 0;
                   7572: }
                   7573: 
1.933     droeschl 7574: ul.LC_funclist > li:first-child {
                   7575:     font-weight:bold; 
                   7576:     margin-left:0.8em;
                   7577: }
                   7578: 
1.915     droeschl 7579: ul.LC_funclist + ul.LC_funclist {
                   7580:     /* 
                   7581:        left border as a seperator if we have more than
                   7582:        one list 
                   7583:     */
                   7584:     border-left: 1px solid $sidebg;
                   7585:     /* 
                   7586:        this hides the left border behind the border of the 
                   7587:        outer box if element is wrapped to the next 'line' 
                   7588:     */
                   7589:     margin-left: -1px;
                   7590: }
                   7591: 
1.843     bisitz   7592: ul.LC_funclist li {
1.915     droeschl 7593:   display: inline;
1.782     bisitz   7594:   white-space: nowrap;
1.915     droeschl 7595:   margin: 0 0 0 25px;
                   7596:   line-height: 150%;
1.782     bisitz   7597: }
                   7598: 
1.974     wenzelju 7599: .LC_hidden {
                   7600:   display: none;
                   7601: }
                   7602: 
1.1030    www      7603: .LCmodal-overlay {
                   7604: 		position:fixed;
                   7605: 		top:0;
                   7606: 		right:0;
                   7607: 		bottom:0;
                   7608: 		left:0;
                   7609: 		height:100%;
                   7610: 		width:100%;
                   7611: 		margin:0;
                   7612: 		padding:0;
                   7613: 		background:#999;
                   7614: 		opacity:.75;
                   7615: 		filter: alpha(opacity=75);
                   7616: 		-moz-opacity: 0.75;
                   7617: 		z-index:101;
                   7618: }
                   7619: 
                   7620: * html .LCmodal-overlay {   
                   7621: 		position: absolute;
                   7622: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7623: }
                   7624: 
                   7625: .LCmodal-window {
                   7626: 		position:fixed;
                   7627: 		top:50%;
                   7628: 		left:50%;
                   7629: 		margin:0;
                   7630: 		padding:0;
                   7631: 		z-index:102;
                   7632: 	}
                   7633: 
                   7634: * html .LCmodal-window {
                   7635: 		position:absolute;
                   7636: }
                   7637: 
                   7638: .LCclose-window {
                   7639: 		position:absolute;
                   7640: 		width:32px;
                   7641: 		height:32px;
                   7642: 		right:8px;
                   7643: 		top:8px;
                   7644: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7645: 		text-indent:-99999px;
                   7646: 		overflow:hidden;
                   7647: 		cursor:pointer;
                   7648: }
                   7649: 
1.1075.2.17  raeburn  7650: /*
                   7651:   styles used by TTH when "Default set of options to pass to tth/m
                   7652:   when converting TeX" in course settings has been set
                   7653: 
                   7654:   option passed: -t
                   7655: 
                   7656: */
                   7657: 
                   7658: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7659: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7660: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7661: td div.norm {line-height:normal;}
                   7662: 
                   7663: /*
                   7664:   option passed -y3
                   7665: */
                   7666: 
                   7667: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7668: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7669: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7670: 
1.343     albertel 7671: END
                   7672: }
                   7673: 
1.306     albertel 7674: =pod
                   7675: 
                   7676: =item * &headtag()
                   7677: 
                   7678: Returns a uniform footer for LON-CAPA web pages.
                   7679: 
1.307     albertel 7680: Inputs: $title - optional title for the head
                   7681:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7682:         $args - optional arguments
1.319     albertel 7683:             force_register - if is true call registerurl so the remote is 
                   7684:                              informed
1.415     albertel 7685:             redirect       -> array ref of
                   7686:                                    1- seconds before redirect occurs
                   7687:                                    2- url to redirect to
                   7688:                                    3- whether the side effect should occur
1.315     albertel 7689:                            (side effect of setting 
                   7690:                                $env{'internal.head.redirect'} to the url 
                   7691:                                redirected too)
1.352     albertel 7692:             domain         -> force to color decorate a page for a specific
                   7693:                                domain
                   7694:             function       -> force usage of a specific rolish color scheme
                   7695:             bgcolor        -> override the default page bgcolor
1.460     albertel 7696:             no_auto_mt_title
                   7697:                            -> prevent &mt()ing the title arg
1.464     albertel 7698: 
1.306     albertel 7699: =cut
                   7700: 
                   7701: sub headtag {
1.313     albertel 7702:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7703:     
1.363     albertel 7704:     my $function = $args->{'function'} || &get_users_function();
                   7705:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7706:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  7707:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7708:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7709: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7710: 		   #time(),
1.418     albertel 7711: 		   $env{'environment.color.timestamp'},
1.363     albertel 7712: 		   $function,$domain,$bgcolor);
                   7713: 
1.369     www      7714:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7715: 
1.308     albertel 7716:     my $result =
                   7717: 	'<head>'.
1.1075.2.56  raeburn  7718: 	&font_settings($args);
1.319     albertel 7719: 
1.1075.2.72  raeburn  7720:     my $inhibitprint;
                   7721:     if ($args->{'print_suppress'}) {
                   7722:         $inhibitprint = &print_suppression();
                   7723:     }
1.1064    raeburn  7724: 
1.461     albertel 7725:     if (!$args->{'frameset'}) {
                   7726: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7727:     }
1.1075.2.12  raeburn  7728:     if ($args->{'force_register'}) {
                   7729:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 7730:     }
1.436     albertel 7731:     if (!$args->{'no_nav_bar'} 
                   7732: 	&& !$args->{'only_body'}
                   7733: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  7734: 	$result .= &help_menu_js($httphost);
1.1032    www      7735:         $result.=&modal_window();
1.1038    www      7736:         $result.=&togglebox_script();
1.1034    www      7737:         $result.=&wishlist_window();
1.1041    www      7738:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7739:     } else {
                   7740:         if ($args->{'add_modal'}) {
                   7741:            $result.=&modal_window();
                   7742:         }
                   7743:         if ($args->{'add_wishlist'}) {
                   7744:            $result.=&wishlist_window();
                   7745:         }
1.1038    www      7746:         if ($args->{'add_togglebox'}) {
                   7747:            $result.=&togglebox_script();
                   7748:         }
1.1041    www      7749:         if ($args->{'add_progressbar'}) {
                   7750:            $result.=&LCprogressbarUpdate_script();
                   7751:         }
1.436     albertel 7752:     }
1.314     albertel 7753:     if (ref($args->{'redirect'})) {
1.414     albertel 7754: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7755: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7756: 	if (!$inhibit_continue) {
                   7757: 	    $env{'internal.head.redirect'} = $url;
                   7758: 	}
1.313     albertel 7759: 	$result.=<<ADDMETA
                   7760: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7761: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7762: ADDMETA
1.1075.2.89  raeburn  7763:     } else {
                   7764:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7765:             my $requrl = $env{'request.uri'};
                   7766:             if ($requrl eq '') {
                   7767:                 $requrl = $ENV{'REQUEST_URI'};
                   7768:                 $requrl =~ s/\?.+$//;
                   7769:             }
                   7770:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7771:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7772:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7773:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7774:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7775:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   7776:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7777:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7778:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   7779:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   7780:                             if (($newserver) && ($newserver ne $lonhost)) {
                   7781:                                 my $numsec = 5;
                   7782:                                 my $timeout = $numsec * 1000;
                   7783:                                 my ($newurl,$locknum,%locks,$msg);
                   7784:                                 if ($env{'request.role.adv'}) {
                   7785:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   7786:                                 }
                   7787:                                 my $disable_submit = 0;
                   7788:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   7789:                                     $disable_submit = 1;
                   7790:                                 }
                   7791:                                 if ($locknum) {
                   7792:                                     my @lockinfo = sort(values(%locks));
                   7793:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   7794:                                            join(", ",sort(values(%locks)))."\\n".
                   7795:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   7796:                                 } else {
                   7797:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   7798:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   7799:                                     }
                   7800:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   7801:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   7802:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   7803:                                         $newurl .= '&role='.$env{'request.role'};
                   7804:                                     }
                   7805:                                     if ($env{'request.symb'}) {
                   7806:                                         $newurl .= '&symb='.$env{'request.symb'};
                   7807:                                     } else {
                   7808:                                         $newurl .= '&origurl='.$requrl;
                   7809:                                     }
                   7810:                                 }
1.1075.2.98  raeburn  7811:                                 &js_escape(\$msg);
1.1075.2.89  raeburn  7812:                                 $result.=<<OFFLOAD
                   7813: <meta http-equiv="pragma" content="no-cache" />
                   7814: <script type="text/javascript">
1.1075.2.92  raeburn  7815: // <![CDATA[
1.1075.2.89  raeburn  7816: function LC_Offload_Now() {
                   7817:     var dest = "$newurl";
                   7818:     if (dest != '') {
                   7819:         window.location.href="$newurl";
                   7820:     }
                   7821: }
1.1075.2.92  raeburn  7822: \$(document).ready(function () {
                   7823:     window.alert('$msg');
                   7824:     if ($disable_submit) {
1.1075.2.89  raeburn  7825:         \$(".LC_hwk_submit").prop("disabled", true);
                   7826:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  7827:     }
                   7828:     setTimeout('LC_Offload_Now()', $timeout);
                   7829: });
                   7830: // ]]>
1.1075.2.89  raeburn  7831: </script>
                   7832: OFFLOAD
                   7833:                             }
                   7834:                         }
                   7835:                     }
                   7836:                 }
                   7837:             }
                   7838:         }
1.313     albertel 7839:     }
1.306     albertel 7840:     if (!defined($title)) {
                   7841: 	$title = 'The LearningOnline Network with CAPA';
                   7842:     }
1.460     albertel 7843:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7844:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  7845: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   7846:     if (!$args->{'frameset'}) {
                   7847:         $result .= ' /';
                   7848:     }
                   7849:     $result .= '>'
1.1064    raeburn  7850:         .$inhibitprint
1.414     albertel 7851: 	.$head_extra;
1.1075.2.108  raeburn  7852:     my $clientmobile;
                   7853:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   7854:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   7855:     } else {
                   7856:         $clientmobile = $env{'browser.mobile'};
                   7857:     }
                   7858:     if ($clientmobile) {
1.1075.2.42  raeburn  7859:         $result .= '
                   7860: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   7861: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   7862:     }
1.962     droeschl 7863:     return $result.'</head>';
1.306     albertel 7864: }
                   7865: 
                   7866: =pod
                   7867: 
1.340     albertel 7868: =item * &font_settings()
                   7869: 
                   7870: Returns neccessary <meta> to set the proper encoding
                   7871: 
1.1075.2.56  raeburn  7872: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 7873: 
                   7874: =cut
                   7875: 
                   7876: sub font_settings {
1.1075.2.56  raeburn  7877:     my ($args) = @_;
1.340     albertel 7878:     my $headerstring='';
1.1075.2.56  raeburn  7879:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   7880:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 7881: 	$headerstring.=
1.1075.2.61  raeburn  7882: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   7883:         if (!$args->{'frameset'}) {
                   7884:             $headerstring.= ' /';
                   7885:         }
                   7886:         $headerstring .= '>'."\n";
1.340     albertel 7887:     }
                   7888:     return $headerstring;
                   7889: }
                   7890: 
1.341     albertel 7891: =pod
                   7892: 
1.1064    raeburn  7893: =item * &print_suppression()
                   7894: 
                   7895: In course context returns css which causes the body to be blank when media="print",
                   7896: if printout generation is unavailable for the current resource.
                   7897: 
                   7898: This could be because:
                   7899: 
                   7900: (a) printstartdate is in the future
                   7901: 
                   7902: (b) printenddate is in the past
                   7903: 
                   7904: (c) there is an active exam block with "printout"
                   7905: functionality blocked
                   7906: 
                   7907: Users with pav, pfo or evb privileges are exempt.
                   7908: 
                   7909: Inputs: none
                   7910: 
                   7911: =cut
                   7912: 
                   7913: 
                   7914: sub print_suppression {
                   7915:     my $noprint;
                   7916:     if ($env{'request.course.id'}) {
                   7917:         my $scope = $env{'request.course.id'};
                   7918:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7919:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7920:             return;
                   7921:         }
                   7922:         if ($env{'request.course.sec'} ne '') {
                   7923:             $scope .= "/$env{'request.course.sec'}";
                   7924:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7925:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7926:                 return;
1.1064    raeburn  7927:             }
                   7928:         }
                   7929:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7930:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.73  raeburn  7931:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  7932:         if ($blocked) {
                   7933:             my $checkrole = "cm./$cdom/$cnum";
                   7934:             if ($env{'request.course.sec'} ne '') {
                   7935:                 $checkrole .= "/$env{'request.course.sec'}";
                   7936:             }
                   7937:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7938:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7939:                 $noprint = 1;
                   7940:             }
                   7941:         }
                   7942:         unless ($noprint) {
                   7943:             my $symb = &Apache::lonnet::symbread();
                   7944:             if ($symb ne '') {
                   7945:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7946:                 if (ref($navmap)) {
                   7947:                     my $res = $navmap->getBySymb($symb);
                   7948:                     if (ref($res)) {
                   7949:                         if (!$res->resprintable()) {
                   7950:                             $noprint = 1;
                   7951:                         }
                   7952:                     }
                   7953:                 }
                   7954:             }
                   7955:         }
                   7956:         if ($noprint) {
                   7957:             return <<"ENDSTYLE";
                   7958: <style type="text/css" media="print">
                   7959:     body { display:none }
                   7960: </style>
                   7961: ENDSTYLE
                   7962:         }
                   7963:     }
                   7964:     return;
                   7965: }
                   7966: 
                   7967: =pod
                   7968: 
1.341     albertel 7969: =item * &xml_begin()
                   7970: 
                   7971: Returns the needed doctype and <html>
                   7972: 
                   7973: Inputs: none
                   7974: 
                   7975: =cut
                   7976: 
                   7977: sub xml_begin {
1.1075.2.61  raeburn  7978:     my ($is_frameset) = @_;
1.341     albertel 7979:     my $output='';
                   7980: 
                   7981:     if ($env{'browser.mathml'}) {
                   7982: 	$output='<?xml version="1.0"?>'
                   7983:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   7984: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   7985:             
                   7986: #	    .'<!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">] >'
                   7987: 	    .'<!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">'
                   7988:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   7989: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  7990:     } elsif ($is_frameset) {
                   7991:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   7992:                 '<html>'."\n";
1.341     albertel 7993:     } else {
1.1075.2.61  raeburn  7994: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   7995:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 7996:     }
                   7997:     return $output;
                   7998: }
1.340     albertel 7999: 
                   8000: =pod
                   8001: 
1.306     albertel 8002: =item * &start_page()
                   8003: 
                   8004: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8005: 
1.648     raeburn  8006: Inputs:
                   8007: 
                   8008: =over 4
                   8009: 
                   8010: $title - optional title for the page
                   8011: 
                   8012: $head_extra - optional extra HTML to incude inside the <head>
                   8013: 
                   8014: $args - additional optional args supported are:
                   8015: 
                   8016: =over 8
                   8017: 
                   8018:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8019:                                     arg on
1.814     bisitz   8020:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8021:              add_entries    -> additional attributes to add to the  <body>
                   8022:              domain         -> force to color decorate a page for a 
1.317     albertel 8023:                                     specific domain
1.648     raeburn  8024:              function       -> force usage of a specific rolish color
1.317     albertel 8025:                                     scheme
1.648     raeburn  8026:              redirect       -> see &headtag()
                   8027:              bgcolor        -> override the default page bg color
                   8028:              js_ready       -> return a string ready for being used in 
1.317     albertel 8029:                                     a javascript writeln
1.648     raeburn  8030:              html_encode    -> return a string ready for being used in 
1.320     albertel 8031:                                     a html attribute
1.648     raeburn  8032:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8033:                                     $forcereg arg
1.648     raeburn  8034:              frameset       -> if true will start with a <frameset>
1.330     albertel 8035:                                     rather than <body>
1.648     raeburn  8036:              skip_phases    -> hash ref of 
1.338     albertel 8037:                                     head -> skip the <html><head> generation
                   8038:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  8039:              no_inline_link -> if true and in remote mode, don't show the
                   8040:                                     'Switch To Inline Menu' link
1.648     raeburn  8041:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8042:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8043:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.15  raeburn  8044:              group          -> includes the current group, if page is for a
                   8045:                                specific group
1.361     albertel 8046: 
1.648     raeburn  8047: =back
1.460     albertel 8048: 
1.648     raeburn  8049: =back
1.562     albertel 8050: 
1.306     albertel 8051: =cut
                   8052: 
                   8053: sub start_page {
1.309     albertel 8054:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8055:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8056: 
1.315     albertel 8057:     $env{'internal.start_page'}++;
1.1075.2.15  raeburn  8058:     my ($result,@advtools);
1.964     droeschl 8059: 
1.338     albertel 8060:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  8061:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8062:     }
                   8063:     
                   8064:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8065: 	if ($args->{'frameset'}) {
                   8066: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8067: 						$args->{'add_entries'});
                   8068: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8069:         } else {
                   8070:             $result .=
                   8071:                 &bodytag($title, 
                   8072:                          $args->{'function'},       $args->{'add_entries'},
                   8073:                          $args->{'only_body'},      $args->{'domain'},
                   8074:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  8075:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.15  raeburn  8076:                          $args,                     \@advtools);
1.831     bisitz   8077:         }
1.330     albertel 8078:     }
1.338     albertel 8079: 
1.315     albertel 8080:     if ($args->{'js_ready'}) {
1.713     kaisler  8081: 		$result = &js_ready($result);
1.315     albertel 8082:     }
1.320     albertel 8083:     if ($args->{'html_encode'}) {
1.713     kaisler  8084: 		$result = &html_encode($result);
                   8085:     }
                   8086: 
1.813     bisitz   8087:     # Preparation for new and consistent functionlist at top of screen
                   8088:     # if ($args->{'functionlist'}) {
                   8089:     #            $result .= &build_functionlist();
                   8090:     #}
                   8091: 
1.964     droeschl 8092:     # Don't add anything more if only_body wanted or in const space
                   8093:     return $result if    $args->{'only_body'} 
                   8094:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8095: 
                   8096:     #Breadcrumbs
1.758     kaisler  8097:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8098: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8099: 		#if any br links exists, add them to the breadcrumbs
                   8100: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8101: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8102: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8103: 			}
                   8104: 		}
1.1075.2.19  raeburn  8105:                 # if @advtools array contains items add then to the breadcrumbs
                   8106:                 if (@advtools > 0) {
                   8107:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8108:                 }
1.758     kaisler  8109: 
                   8110: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8111: 		if(exists($args->{'bread_crumbs_component'})){
                   8112: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   8113: 		}else{
                   8114: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   8115: 		}
1.1075.2.24  raeburn  8116:     } elsif (($env{'environment.remote'} eq 'on') &&
                   8117:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   8118:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   8119:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  8120:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 8121:     }
1.315     albertel 8122:     return $result;
1.306     albertel 8123: }
                   8124: 
                   8125: sub end_page {
1.315     albertel 8126:     my ($args) = @_;
                   8127:     $env{'internal.end_page'}++;
1.330     albertel 8128:     my $result;
1.335     albertel 8129:     if ($args->{'discussion'}) {
                   8130: 	my ($target,$parser);
                   8131: 	if (ref($args->{'discussion'})) {
                   8132: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8133: 				$args->{'discussion'}{'parser'});
                   8134: 	}
                   8135: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8136:     }
1.330     albertel 8137:     if ($args->{'frameset'}) {
                   8138: 	$result .= '</frameset>';
                   8139:     } else {
1.635     raeburn  8140: 	$result .= &endbodytag($args);
1.330     albertel 8141:     }
1.1075.2.6  raeburn  8142:     unless ($args->{'notbody'}) {
                   8143:         $result .= "\n</html>";
                   8144:     }
1.330     albertel 8145: 
1.315     albertel 8146:     if ($args->{'js_ready'}) {
1.317     albertel 8147: 	$result = &js_ready($result);
1.315     albertel 8148:     }
1.335     albertel 8149: 
1.320     albertel 8150:     if ($args->{'html_encode'}) {
                   8151: 	$result = &html_encode($result);
                   8152:     }
1.335     albertel 8153: 
1.315     albertel 8154:     return $result;
                   8155: }
                   8156: 
1.1034    www      8157: sub wishlist_window {
                   8158:     return(<<'ENDWISHLIST');
1.1046    raeburn  8159: <script type="text/javascript">
1.1034    www      8160: // <![CDATA[
                   8161: // <!-- BEGIN LON-CAPA Internal
                   8162: function set_wishlistlink(title, path) {
                   8163:     if (!title) {
                   8164:         title = document.title;
                   8165:         title = title.replace(/^LON-CAPA /,'');
                   8166:     }
1.1075.2.65  raeburn  8167:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  8168:     title = title.replace("'","\\\'");
1.1034    www      8169:     if (!path) {
                   8170:         path = location.pathname;
                   8171:     }
1.1075.2.65  raeburn  8172:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  8173:     path = path.replace("'","\\\'");
1.1034    www      8174:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8175:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8176: }
                   8177: // END LON-CAPA Internal -->
                   8178: // ]]>
                   8179: </script>
                   8180: ENDWISHLIST
                   8181: }
                   8182: 
1.1030    www      8183: sub modal_window {
                   8184:     return(<<'ENDMODAL');
1.1046    raeburn  8185: <script type="text/javascript">
1.1030    www      8186: // <![CDATA[
                   8187: // <!-- BEGIN LON-CAPA Internal
                   8188: var modalWindow = {
                   8189: 	parent:"body",
                   8190: 	windowId:null,
                   8191: 	content:null,
                   8192: 	width:null,
                   8193: 	height:null,
                   8194: 	close:function()
                   8195: 	{
                   8196: 	        $(".LCmodal-window").remove();
                   8197: 	        $(".LCmodal-overlay").remove();
                   8198: 	},
                   8199: 	open:function()
                   8200: 	{
                   8201: 		var modal = "";
                   8202: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8203: 		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;\">";
                   8204: 		modal += this.content;
                   8205: 		modal += "</div>";	
                   8206: 
                   8207: 		$(this.parent).append(modal);
                   8208: 
                   8209: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8210: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8211: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8212: 	}
                   8213: };
1.1075.2.42  raeburn  8214: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8215: 	{
1.1075.2.83  raeburn  8216:                 source = source.replace("'","&#39;");
1.1030    www      8217: 		modalWindow.windowId = "myModal";
                   8218: 		modalWindow.width = width;
                   8219: 		modalWindow.height = height;
1.1075.2.80  raeburn  8220: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8221: 		modalWindow.open();
1.1075.2.87  raeburn  8222: 	};
1.1030    www      8223: // END LON-CAPA Internal -->
                   8224: // ]]>
                   8225: </script>
                   8226: ENDMODAL
                   8227: }
                   8228: 
                   8229: sub modal_link {
1.1075.2.42  raeburn  8230:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8231:     unless ($width) { $width=480; }
                   8232:     unless ($height) { $height=400; }
1.1031    www      8233:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  8234:     unless ($transparency) { $transparency='true'; }
                   8235: 
1.1074    raeburn  8236:     my $target_attr;
                   8237:     if (defined($target)) {
                   8238:         $target_attr = 'target="'.$target.'"';
                   8239:     }
                   8240:     return <<"ENDLINK";
1.1075.2.42  raeburn  8241: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8242:            $linktext</a>
                   8243: ENDLINK
1.1030    www      8244: }
                   8245: 
1.1032    www      8246: sub modal_adhoc_script {
                   8247:     my ($funcname,$width,$height,$content)=@_;
                   8248:     return (<<ENDADHOC);
1.1046    raeburn  8249: <script type="text/javascript">
1.1032    www      8250: // <![CDATA[
                   8251:         var $funcname = function()
                   8252:         {
                   8253:                 modalWindow.windowId = "myModal";
                   8254:                 modalWindow.width = $width;
                   8255:                 modalWindow.height = $height;
                   8256:                 modalWindow.content = '$content';
                   8257:                 modalWindow.open();
                   8258:         };  
                   8259: // ]]>
                   8260: </script>
                   8261: ENDADHOC
                   8262: }
                   8263: 
1.1041    www      8264: sub modal_adhoc_inner {
                   8265:     my ($funcname,$width,$height,$content)=@_;
                   8266:     my $innerwidth=$width-20;
                   8267:     $content=&js_ready(
1.1042    www      8268:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  8269:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8270:                  $content.
1.1041    www      8271:                  &end_scrollbox().
1.1075.2.42  raeburn  8272:                  &end_page()
1.1041    www      8273:              );
                   8274:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8275: }
                   8276: 
                   8277: sub modal_adhoc_window {
                   8278:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8279:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8280:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8281: }
                   8282: 
                   8283: sub modal_adhoc_launch {
                   8284:     my ($funcname,$width,$height,$content)=@_;
                   8285:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8286: <script type="text/javascript">
                   8287: // <![CDATA[
                   8288: $funcname();
                   8289: // ]]>
                   8290: </script>
                   8291: ENDLAUNCH
                   8292: }
                   8293: 
                   8294: sub modal_adhoc_close {
                   8295:     return (<<ENDCLOSE);
                   8296: <script type="text/javascript">
                   8297: // <![CDATA[
                   8298: modalWindow.close();
                   8299: // ]]>
                   8300: </script>
                   8301: ENDCLOSE
                   8302: }
                   8303: 
1.1038    www      8304: sub togglebox_script {
                   8305:    return(<<ENDTOGGLE);
                   8306: <script type="text/javascript"> 
                   8307: // <![CDATA[
                   8308: function LCtoggleDisplay(id,hidetext,showtext) {
                   8309:    link = document.getElementById(id + "link").childNodes[0];
                   8310:    with (document.getElementById(id).style) {
                   8311:       if (display == "none" ) {
                   8312:           display = "inline";
                   8313:           link.nodeValue = hidetext;
                   8314:         } else {
                   8315:           display = "none";
                   8316:           link.nodeValue = showtext;
                   8317:        }
                   8318:    }
                   8319: }
                   8320: // ]]>
                   8321: </script>
                   8322: ENDTOGGLE
                   8323: }
                   8324: 
1.1039    www      8325: sub start_togglebox {
                   8326:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8327:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8328:     unless ($showtext) { $showtext=&mt('show'); }
                   8329:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8330:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8331:     return &start_data_table().
                   8332:            &start_data_table_header_row().
                   8333:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8334:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8335:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8336:            &end_data_table_header_row().
                   8337:            '<tr id="'.$id.'" style="display:none""><td>';
                   8338: }
                   8339: 
                   8340: sub end_togglebox {
                   8341:     return '</td></tr>'.&end_data_table();
                   8342: }
                   8343: 
1.1041    www      8344: sub LCprogressbar_script {
1.1045    www      8345:    my ($id)=@_;
1.1041    www      8346:    return(<<ENDPROGRESS);
                   8347: <script type="text/javascript">
                   8348: // <![CDATA[
1.1045    www      8349: \$('#progressbar$id').progressbar({
1.1041    www      8350:   value: 0,
                   8351:   change: function(event, ui) {
                   8352:     var newVal = \$(this).progressbar('option', 'value');
                   8353:     \$('.pblabel', this).text(LCprogressTxt);
                   8354:   }
                   8355: });
                   8356: // ]]>
                   8357: </script>
                   8358: ENDPROGRESS
                   8359: }
                   8360: 
                   8361: sub LCprogressbarUpdate_script {
                   8362:    return(<<ENDPROGRESSUPDATE);
                   8363: <style type="text/css">
                   8364: .ui-progressbar { position:relative; }
                   8365: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8366: </style>
                   8367: <script type="text/javascript">
                   8368: // <![CDATA[
1.1045    www      8369: var LCprogressTxt='---';
                   8370: 
                   8371: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8372:    LCprogressTxt=progresstext;
1.1045    www      8373:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8374: }
                   8375: // ]]>
                   8376: </script>
                   8377: ENDPROGRESSUPDATE
                   8378: }
                   8379: 
1.1042    www      8380: my $LClastpercent;
1.1045    www      8381: my $LCidcnt;
                   8382: my $LCcurrentid;
1.1042    www      8383: 
1.1041    www      8384: sub LCprogressbar {
1.1042    www      8385:     my ($r)=(@_);
                   8386:     $LClastpercent=0;
1.1045    www      8387:     $LCidcnt++;
                   8388:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8389:     my $starting=&mt('Starting');
                   8390:     my $content=(<<ENDPROGBAR);
1.1045    www      8391:   <div id="progressbar$LCcurrentid">
1.1041    www      8392:     <span class="pblabel">$starting</span>
                   8393:   </div>
                   8394: ENDPROGBAR
1.1045    www      8395:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8396: }
                   8397: 
                   8398: sub LCprogressbarUpdate {
1.1042    www      8399:     my ($r,$val,$text)=@_;
                   8400:     unless ($val) { 
                   8401:        if ($LClastpercent) {
                   8402:            $val=$LClastpercent;
                   8403:        } else {
                   8404:            $val=0;
                   8405:        }
                   8406:     }
1.1041    www      8407:     if ($val<0) { $val=0; }
                   8408:     if ($val>100) { $val=0; }
1.1042    www      8409:     $LClastpercent=$val;
1.1041    www      8410:     unless ($text) { $text=$val.'%'; }
                   8411:     $text=&js_ready($text);
1.1044    www      8412:     &r_print($r,<<ENDUPDATE);
1.1041    www      8413: <script type="text/javascript">
                   8414: // <![CDATA[
1.1045    www      8415: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8416: // ]]>
                   8417: </script>
                   8418: ENDUPDATE
1.1035    www      8419: }
                   8420: 
1.1042    www      8421: sub LCprogressbarClose {
                   8422:     my ($r)=@_;
                   8423:     $LClastpercent=0;
1.1044    www      8424:     &r_print($r,<<ENDCLOSE);
1.1042    www      8425: <script type="text/javascript">
                   8426: // <![CDATA[
1.1045    www      8427: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8428: // ]]>
                   8429: </script>
                   8430: ENDCLOSE
1.1044    www      8431: }
                   8432: 
                   8433: sub r_print {
                   8434:     my ($r,$to_print)=@_;
                   8435:     if ($r) {
                   8436:       $r->print($to_print);
                   8437:       $r->rflush();
                   8438:     } else {
                   8439:       print($to_print);
                   8440:     }
1.1042    www      8441: }
                   8442: 
1.320     albertel 8443: sub html_encode {
                   8444:     my ($result) = @_;
                   8445: 
1.322     albertel 8446:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8447:     
                   8448:     return $result;
                   8449: }
1.1044    www      8450: 
1.317     albertel 8451: sub js_ready {
                   8452:     my ($result) = @_;
                   8453: 
1.323     albertel 8454:     $result =~ s/[\n\r]/ /xmsg;
                   8455:     $result =~ s/\\/\\\\/xmsg;
                   8456:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8457:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8458:     
                   8459:     return $result;
                   8460: }
                   8461: 
1.315     albertel 8462: sub validate_page {
                   8463:     if (  exists($env{'internal.start_page'})
1.316     albertel 8464: 	  &&     $env{'internal.start_page'} > 1) {
                   8465: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8466: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8467: 				 $ENV{'request.filename'});
1.315     albertel 8468:     }
                   8469:     if (  exists($env{'internal.end_page'})
1.316     albertel 8470: 	  &&     $env{'internal.end_page'} > 1) {
                   8471: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8472: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8473: 				 $env{'request.filename'});
1.315     albertel 8474:     }
                   8475:     if (     exists($env{'internal.start_page'})
                   8476: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8477: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8478: 				 $env{'request.filename'});
1.315     albertel 8479:     }
                   8480:     if (   ! exists($env{'internal.start_page'})
                   8481: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8482: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8483: 				 $env{'request.filename'});
1.315     albertel 8484:     }
1.306     albertel 8485: }
1.315     albertel 8486: 
1.996     www      8487: 
                   8488: sub start_scrollbox {
1.1075.2.56  raeburn  8489:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8490:     unless ($outerwidth) { $outerwidth='520px'; }
                   8491:     unless ($width) { $width='500px'; }
                   8492:     unless ($height) { $height='200px'; }
1.1075    raeburn  8493:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8494:     if ($id ne '') {
1.1075.2.42  raeburn  8495:         $table_id = ' id="table_'.$id.'"';
                   8496:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8497:     }
1.1075    raeburn  8498:     if ($bgcolor ne '') {
                   8499:         $tdcol = "background-color: $bgcolor;";
                   8500:     }
1.1075.2.42  raeburn  8501:     my $nicescroll_js;
                   8502:     if ($env{'browser.mobile'}) {
                   8503:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8504:     }
1.1075    raeburn  8505:     return <<"END";
1.1075.2.42  raeburn  8506: $nicescroll_js
                   8507: 
                   8508: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  8509: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  8510: END
1.996     www      8511: }
                   8512: 
                   8513: sub end_scrollbox {
1.1036    www      8514:     return '</div></td></tr></table>';
1.996     www      8515: }
                   8516: 
1.1075.2.42  raeburn  8517: sub nicescroll_javascript {
                   8518:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8519:     my %options;
                   8520:     if (ref($cursor) eq 'HASH') {
                   8521:         %options = %{$cursor};
                   8522:     }
                   8523:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8524:         $options{'railalign'} = 'left';
                   8525:     }
                   8526:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8527:         my $function  = &get_users_function();
                   8528:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   8529:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8530:             $options{'cursorcolor'} = '#00F';
                   8531:         }
                   8532:     }
                   8533:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8534:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   8535:             $options{'cursoropacity'}='1.0';
                   8536:         }
                   8537:     } else {
                   8538:         $options{'cursoropacity'}='1.0';
                   8539:     }
                   8540:     if ($options{'cursorfixedheight'} eq 'none') {
                   8541:         delete($options{'cursorfixedheight'});
                   8542:     } else {
                   8543:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8544:     }
                   8545:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8546:         delete($options{'railoffset'});
                   8547:     }
                   8548:     my @niceoptions;
                   8549:     while (my($key,$value) = each(%options)) {
                   8550:         if ($value =~ /^\{.+\}$/) {
                   8551:             push(@niceoptions,$key.':'.$value);
                   8552:         } else {
                   8553:             push(@niceoptions,$key.':"'.$value.'"');
                   8554:         }
                   8555:     }
                   8556:     my $nicescroll_js = '
                   8557: $(document).ready(
                   8558:       function() {
                   8559:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8560:       }
                   8561: );
                   8562: ';
                   8563:     if ($framecheck) {
                   8564:         $nicescroll_js .= '
                   8565: function expand_div(caller) {
                   8566:     if (top === self) {
                   8567:         document.getElementById("'.$id.'").style.width = "auto";
                   8568:         document.getElementById("'.$id.'").style.height = "auto";
                   8569:     } else {
                   8570:         try {
                   8571:             if (parent.frames) {
                   8572:                 if (parent.frames.length > 1) {
                   8573:                     var framesrc = parent.frames[1].location.href;
                   8574:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8575:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8576:                         document.getElementById("'.$id.'").style.width = "auto";
                   8577:                         document.getElementById("'.$id.'").style.height = "auto";
                   8578:                     }
                   8579:                 }
                   8580:             }
                   8581:         } catch (e) {
                   8582:             return;
                   8583:         }
                   8584:     }
                   8585:     return;
                   8586: }
                   8587: ';
                   8588:     }
                   8589:     if ($needjsready) {
                   8590:         $nicescroll_js = '
                   8591: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8592:     } else {
                   8593:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8594:     }
                   8595:     return $nicescroll_js;
                   8596: }
                   8597: 
1.318     albertel 8598: sub simple_error_page {
1.1075.2.49  raeburn  8599:     my ($r,$title,$msg,$args) = @_;
                   8600:     if (ref($args) eq 'HASH') {
                   8601:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8602:     } else {
                   8603:         $msg = &mt($msg);
                   8604:     }
                   8605: 
1.318     albertel 8606:     my $page =
                   8607: 	&Apache::loncommon::start_page($title).
1.1075.2.49  raeburn  8608: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8609: 	&Apache::loncommon::end_page();
                   8610:     if (ref($r)) {
                   8611: 	$r->print($page);
1.327     albertel 8612: 	return;
1.318     albertel 8613:     }
                   8614:     return $page;
                   8615: }
1.347     albertel 8616: 
                   8617: {
1.610     albertel 8618:     my @row_count;
1.961     onken    8619: 
                   8620:     sub start_data_table_count {
                   8621:         unshift(@row_count, 0);
                   8622:         return;
                   8623:     }
                   8624: 
                   8625:     sub end_data_table_count {
                   8626:         shift(@row_count);
                   8627:         return;
                   8628:     }
                   8629: 
1.347     albertel 8630:     sub start_data_table {
1.1018    raeburn  8631: 	my ($add_class,$id) = @_;
1.422     albertel 8632: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8633:         my $table_id;
                   8634:         if (defined($id)) {
                   8635:             $table_id = ' id="'.$id.'"';
                   8636:         }
1.961     onken    8637: 	&start_data_table_count();
1.1018    raeburn  8638: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8639:     }
                   8640: 
                   8641:     sub end_data_table {
1.961     onken    8642: 	&end_data_table_count();
1.389     albertel 8643: 	return '</table>'."\n";;
1.347     albertel 8644:     }
                   8645: 
                   8646:     sub start_data_table_row {
1.974     wenzelju 8647: 	my ($add_class, $id) = @_;
1.610     albertel 8648: 	$row_count[0]++;
                   8649: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8650: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8651:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8652:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8653:     }
1.471     banghart 8654:     
                   8655:     sub continue_data_table_row {
1.974     wenzelju 8656: 	my ($add_class, $id) = @_;
1.610     albertel 8657: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8658: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8659:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8660:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8661:     }
1.347     albertel 8662: 
                   8663:     sub end_data_table_row {
1.389     albertel 8664: 	return '</tr>'."\n";;
1.347     albertel 8665:     }
1.367     www      8666: 
1.421     albertel 8667:     sub start_data_table_empty_row {
1.707     bisitz   8668: #	$row_count[0]++;
1.421     albertel 8669: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8670:     }
                   8671: 
                   8672:     sub end_data_table_empty_row {
                   8673: 	return '</tr>'."\n";;
                   8674:     }
                   8675: 
1.367     www      8676:     sub start_data_table_header_row {
1.389     albertel 8677: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8678:     }
                   8679: 
                   8680:     sub end_data_table_header_row {
1.389     albertel 8681: 	return '</tr>'."\n";;
1.367     www      8682:     }
1.890     droeschl 8683: 
                   8684:     sub data_table_caption {
                   8685:         my $caption = shift;
                   8686:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8687:     }
1.347     albertel 8688: }
                   8689: 
1.548     albertel 8690: =pod
                   8691: 
                   8692: =item * &inhibit_menu_check($arg)
                   8693: 
                   8694: Checks for a inhibitmenu state and generates output to preserve it
                   8695: 
                   8696: Inputs:         $arg - can be any of
                   8697:                      - undef - in which case the return value is a string 
                   8698:                                to add  into arguments list of a uri
                   8699:                      - 'input' - in which case the return value is a HTML
                   8700:                                  <form> <input> field of type hidden to
                   8701:                                  preserve the value
                   8702:                      - a url - in which case the return value is the url with
                   8703:                                the neccesary cgi args added to preserve the
                   8704:                                inhibitmenu state
                   8705:                      - a ref to a url - no return value, but the string is
                   8706:                                         updated to include the neccessary cgi
                   8707:                                         args to preserve the inhibitmenu state
                   8708: 
                   8709: =cut
                   8710: 
                   8711: sub inhibit_menu_check {
                   8712:     my ($arg) = @_;
                   8713:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8714:     if ($arg eq 'input') {
                   8715: 	if ($env{'form.inhibitmenu'}) {
                   8716: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8717: 	} else {
                   8718: 	    return
                   8719: 	}
                   8720:     }
                   8721:     if ($env{'form.inhibitmenu'}) {
                   8722: 	if (ref($arg)) {
                   8723: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8724: 	} elsif ($arg eq '') {
                   8725: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8726: 	} else {
                   8727: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8728: 	}
                   8729:     }
                   8730:     if (!ref($arg)) {
                   8731: 	return $arg;
                   8732:     }
                   8733: }
                   8734: 
1.251     albertel 8735: ###############################################
1.182     matthew  8736: 
                   8737: =pod
                   8738: 
1.549     albertel 8739: =back
                   8740: 
                   8741: =head1 User Information Routines
                   8742: 
                   8743: =over 4
                   8744: 
1.405     albertel 8745: =item * &get_users_function()
1.182     matthew  8746: 
                   8747: Used by &bodytag to determine the current users primary role.
                   8748: Returns either 'student','coordinator','admin', or 'author'.
                   8749: 
                   8750: =cut
                   8751: 
                   8752: ###############################################
                   8753: sub get_users_function {
1.815     tempelho 8754:     my $function = 'norole';
1.818     tempelho 8755:     if ($env{'request.role'}=~/^(st)/) {
                   8756:         $function='student';
                   8757:     }
1.907     raeburn  8758:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8759:         $function='coordinator';
                   8760:     }
1.258     albertel 8761:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8762:         $function='admin';
                   8763:     }
1.826     bisitz   8764:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8765:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8766:         $function='author';
                   8767:     }
                   8768:     return $function;
1.54      www      8769: }
1.99      www      8770: 
                   8771: ###############################################
                   8772: 
1.233     raeburn  8773: =pod
                   8774: 
1.821     raeburn  8775: =item * &show_course()
                   8776: 
                   8777: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8778: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8779: 
                   8780: Inputs:
                   8781: None
                   8782: 
                   8783: Outputs:
                   8784: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8785: 
                   8786: =cut
                   8787: 
                   8788: ###############################################
                   8789: sub show_course {
                   8790:     my $course = !$env{'user.adv'};
                   8791:     if (!$env{'user.adv'}) {
                   8792:         foreach my $env (keys(%env)) {
                   8793:             next if ($env !~ m/^user\.priv\./);
                   8794:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8795:                 $course = 0;
                   8796:                 last;
                   8797:             }
                   8798:         }
                   8799:     }
                   8800:     return $course;
                   8801: }
                   8802: 
                   8803: ###############################################
                   8804: 
                   8805: =pod
                   8806: 
1.542     raeburn  8807: =item * &check_user_status()
1.274     raeburn  8808: 
                   8809: Determines current status of supplied role for a
                   8810: specific user. Roles can be active, previous or future.
                   8811: 
                   8812: Inputs: 
                   8813: user's domain, user's username, course's domain,
1.375     raeburn  8814: course's number, optional section ID.
1.274     raeburn  8815: 
                   8816: Outputs:
                   8817: role status: active, previous or future. 
                   8818: 
                   8819: =cut
                   8820: 
                   8821: sub check_user_status {
1.412     raeburn  8822:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8823:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  8824:     my @uroles = keys(%userinfo);
1.274     raeburn  8825:     my $srchstr;
                   8826:     my $active_chk = 'none';
1.412     raeburn  8827:     my $now = time;
1.274     raeburn  8828:     if (@uroles > 0) {
1.908     raeburn  8829:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8830:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8831:         } else {
1.412     raeburn  8832:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8833:         }
                   8834:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8835:             my $role_end = 0;
                   8836:             my $role_start = 0;
                   8837:             $active_chk = 'active';
1.412     raeburn  8838:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8839:                 $role_end = $1;
                   8840:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8841:                     $role_start = $1;
1.274     raeburn  8842:                 }
                   8843:             }
                   8844:             if ($role_start > 0) {
1.412     raeburn  8845:                 if ($now < $role_start) {
1.274     raeburn  8846:                     $active_chk = 'future';
                   8847:                 }
                   8848:             }
                   8849:             if ($role_end > 0) {
1.412     raeburn  8850:                 if ($now > $role_end) {
1.274     raeburn  8851:                     $active_chk = 'previous';
                   8852:                 }
                   8853:             }
                   8854:         }
                   8855:     }
                   8856:     return $active_chk;
                   8857: }
                   8858: 
                   8859: ###############################################
                   8860: 
                   8861: =pod
                   8862: 
1.405     albertel 8863: =item * &get_sections()
1.233     raeburn  8864: 
                   8865: Determines all the sections for a course including
                   8866: sections with students and sections containing other roles.
1.419     raeburn  8867: Incoming parameters: 
                   8868: 
                   8869: 1. domain
                   8870: 2. course number 
                   8871: 3. reference to array containing roles for which sections should 
                   8872: be gathered (optional).
                   8873: 4. reference to array containing status types for which sections 
                   8874: should be gathered (optional).
                   8875: 
                   8876: If the third argument is undefined, sections are gathered for any role. 
                   8877: If the fourth argument is undefined, sections are gathered for any status.
                   8878: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8879:  
1.374     raeburn  8880: Returns section hash (keys are section IDs, values are
                   8881: number of users in each section), subject to the
1.419     raeburn  8882: optional roles filter, optional status filter 
1.233     raeburn  8883: 
                   8884: =cut
                   8885: 
                   8886: ###############################################
                   8887: sub get_sections {
1.419     raeburn  8888:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8889:     if (!defined($cdom) || !defined($cnum)) {
                   8890:         my $cid =  $env{'request.course.id'};
                   8891: 
                   8892: 	return if (!defined($cid));
                   8893: 
                   8894:         $cdom = $env{'course.'.$cid.'.domain'};
                   8895:         $cnum = $env{'course.'.$cid.'.num'};
                   8896:     }
                   8897: 
                   8898:     my %sectioncount;
1.419     raeburn  8899:     my $now = time;
1.240     albertel 8900: 
1.1075.2.33  raeburn  8901:     my $check_students = 1;
                   8902:     my $only_students = 0;
                   8903:     if (ref($possible_roles) eq 'ARRAY') {
                   8904:         if (grep(/^st$/,@{$possible_roles})) {
                   8905:             if (@{$possible_roles} == 1) {
                   8906:                 $only_students = 1;
                   8907:             }
                   8908:         } else {
                   8909:             $check_students = 0;
                   8910:         }
                   8911:     }
                   8912: 
                   8913:     if ($check_students) {
1.276     albertel 8914: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8915: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8916: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8917:         my $start_index = &Apache::loncoursedata::CL_START();
                   8918:         my $end_index = &Apache::loncoursedata::CL_END();
                   8919:         my $status;
1.366     albertel 8920: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8921: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8922: 				                     $data->[$status_index],
                   8923:                                                      $data->[$start_index],
                   8924:                                                      $data->[$end_index]);
                   8925:             if ($stu_status eq 'Active') {
                   8926:                 $status = 'active';
                   8927:             } elsif ($end < $now) {
                   8928:                 $status = 'previous';
                   8929:             } elsif ($start > $now) {
                   8930:                 $status = 'future';
                   8931:             } 
                   8932: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8933:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8934:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8935: 		    $sectioncount{$section}++;
                   8936:                 }
1.240     albertel 8937: 	    }
                   8938: 	}
                   8939:     }
1.1075.2.33  raeburn  8940:     if ($only_students) {
                   8941:         return %sectioncount;
                   8942:     }
1.240     albertel 8943:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8944:     foreach my $user (sort(keys(%courseroles))) {
                   8945: 	if ($user !~ /^(\w{2})/) { next; }
                   8946: 	my ($role) = ($user =~ /^(\w{2})/);
                   8947: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  8948: 	my ($section,$status);
1.240     albertel 8949: 	if ($role eq 'cr' &&
                   8950: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   8951: 	    $section=$1;
                   8952: 	}
                   8953: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   8954: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  8955:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   8956:         if ($end == -1 && $start == -1) {
                   8957:             next; #deleted role
                   8958:         }
                   8959:         if (!defined($possible_status)) { 
                   8960:             $sectioncount{$section}++;
                   8961:         } else {
                   8962:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   8963:                 $status = 'active';
                   8964:             } elsif ($end < $now) {
                   8965:                 $status = 'future';
                   8966:             } elsif ($start > $now) {
                   8967:                 $status = 'previous';
                   8968:             }
                   8969:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   8970:                 $sectioncount{$section}++;
                   8971:             }
                   8972:         }
1.233     raeburn  8973:     }
1.366     albertel 8974:     return %sectioncount;
1.233     raeburn  8975: }
                   8976: 
1.274     raeburn  8977: ###############################################
1.294     raeburn  8978: 
                   8979: =pod
1.405     albertel 8980: 
                   8981: =item * &get_course_users()
                   8982: 
1.275     raeburn  8983: Retrieves usernames:domains for users in the specified course
                   8984: with specific role(s), and access status. 
                   8985: 
                   8986: Incoming parameters:
1.277     albertel 8987: 1. course domain
                   8988: 2. course number
                   8989: 3. access status: users must have - either active, 
1.275     raeburn  8990: previous, future, or all.
1.277     albertel 8991: 4. reference to array of permissible roles
1.288     raeburn  8992: 5. reference to array of section restrictions (optional)
                   8993: 6. reference to results object (hash of hashes).
                   8994: 7. reference to optional userdata hash
1.609     raeburn  8995: 8. reference to optional statushash
1.630     raeburn  8996: 9. flag if privileged users (except those set to unhide in
                   8997:    course settings) should be excluded    
1.609     raeburn  8998: Keys of top level results hash are roles.
1.275     raeburn  8999: Keys of inner hashes are username:domain, with 
                   9000: values set to access type.
1.288     raeburn  9001: Optional userdata hash returns an array with arguments in the 
                   9002: same order as loncoursedata::get_classlist() for student data.
                   9003: 
1.609     raeburn  9004: Optional statushash returns
                   9005: 
1.288     raeburn  9006: Entries for end, start, section and status are blank because
                   9007: of the possibility of multiple values for non-student roles.
                   9008: 
1.275     raeburn  9009: =cut
1.405     albertel 9010: 
1.275     raeburn  9011: ###############################################
1.405     albertel 9012: 
1.275     raeburn  9013: sub get_course_users {
1.630     raeburn  9014:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9015:     my %idx = ();
1.419     raeburn  9016:     my %seclists;
1.288     raeburn  9017: 
                   9018:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9019:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9020:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9021:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9022:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9023:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9024:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9025:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9026: 
1.290     albertel 9027:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9028:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9029:         my $now = time;
1.277     albertel 9030:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9031:             my $match = 0;
1.412     raeburn  9032:             my $secmatch = 0;
1.419     raeburn  9033:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9034:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9035:             if ($section eq '') {
                   9036:                 $section = 'none';
                   9037:             }
1.291     albertel 9038:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9039:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9040:                     $secmatch = 1;
                   9041:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9042:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9043:                         $secmatch = 1;
                   9044:                     }
                   9045:                 } else {  
1.419     raeburn  9046: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9047: 		        $secmatch = 1;
                   9048:                     }
1.290     albertel 9049: 		}
1.412     raeburn  9050:                 if (!$secmatch) {
                   9051:                     next;
                   9052:                 }
1.419     raeburn  9053:             }
1.275     raeburn  9054:             if (defined($$types{'active'})) {
1.288     raeburn  9055:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9056:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9057:                     $match = 1;
1.275     raeburn  9058:                 }
                   9059:             }
                   9060:             if (defined($$types{'previous'})) {
1.609     raeburn  9061:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9062:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9063:                     $match = 1;
1.275     raeburn  9064:                 }
                   9065:             }
                   9066:             if (defined($$types{'future'})) {
1.609     raeburn  9067:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9068:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9069:                     $match = 1;
1.275     raeburn  9070:                 }
                   9071:             }
1.609     raeburn  9072:             if ($match) {
                   9073:                 push(@{$seclists{$student}},$section);
                   9074:                 if (ref($userdata) eq 'HASH') {
                   9075:                     $$userdata{$student} = $$classlist{$student};
                   9076:                 }
                   9077:                 if (ref($statushash) eq 'HASH') {
                   9078:                     $statushash->{$student}{'st'}{$section} = $status;
                   9079:                 }
1.288     raeburn  9080:             }
1.275     raeburn  9081:         }
                   9082:     }
1.412     raeburn  9083:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9084:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9085:         my $now = time;
1.609     raeburn  9086:         my %displaystatus = ( previous => 'Expired',
                   9087:                               active   => 'Active',
                   9088:                               future   => 'Future',
                   9089:                             );
1.1075.2.36  raeburn  9090:         my (%nothide,@possdoms);
1.630     raeburn  9091:         if ($hidepriv) {
                   9092:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9093:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9094:                 if ($user !~ /:/) {
                   9095:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9096:                 } else {
                   9097:                     $nothide{$user} = 1;
                   9098:                 }
                   9099:             }
1.1075.2.36  raeburn  9100:             my @possdoms = ($cdom);
                   9101:             if ($coursehash{'checkforpriv'}) {
                   9102:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9103:             }
1.630     raeburn  9104:         }
1.439     raeburn  9105:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9106:             my $match = 0;
1.412     raeburn  9107:             my $secmatch = 0;
1.439     raeburn  9108:             my $status;
1.412     raeburn  9109:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9110:             $user =~ s/:$//;
1.439     raeburn  9111:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9112:             if ($end == -1 || $start == -1) {
                   9113:                 next;
                   9114:             }
                   9115:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9116:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9117:                 my ($uname,$udom) = split(/:/,$user);
                   9118:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9119:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9120:                         $secmatch = 1;
                   9121:                     } elsif ($usec eq '') {
1.420     albertel 9122:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9123:                             $secmatch = 1;
                   9124:                         }
                   9125:                     } else {
                   9126:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9127:                             $secmatch = 1;
                   9128:                         }
                   9129:                     }
                   9130:                     if (!$secmatch) {
                   9131:                         next;
                   9132:                     }
1.288     raeburn  9133:                 }
1.419     raeburn  9134:                 if ($usec eq '') {
                   9135:                     $usec = 'none';
                   9136:                 }
1.275     raeburn  9137:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9138:                     if ($hidepriv) {
1.1075.2.36  raeburn  9139:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9140:                             (!$nothide{$uname.':'.$udom})) {
                   9141:                             next;
                   9142:                         }
                   9143:                     }
1.503     raeburn  9144:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9145:                         $status = 'previous';
                   9146:                     } elsif ($start > $now) {
                   9147:                         $status = 'future';
                   9148:                     } else {
                   9149:                         $status = 'active';
                   9150:                     }
1.277     albertel 9151:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9152:                         if ($status eq $type) {
1.420     albertel 9153:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9154:                                 push(@{$$users{$role}{$user}},$type);
                   9155:                             }
1.288     raeburn  9156:                             $match = 1;
                   9157:                         }
                   9158:                     }
1.419     raeburn  9159:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9160:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9161: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9162:                         }
1.420     albertel 9163:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9164:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9165:                         }
1.609     raeburn  9166:                         if (ref($statushash) eq 'HASH') {
                   9167:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9168:                         }
1.275     raeburn  9169:                     }
                   9170:                 }
                   9171:             }
                   9172:         }
1.290     albertel 9173:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9174:             if ((defined($cdom)) && (defined($cnum))) {
                   9175:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9176:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9177:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9178:                     next if ($owner eq '');
                   9179:                     my ($ownername,$ownerdom);
                   9180:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9181:                         $ownername = $1;
                   9182:                         $ownerdom = $2;
                   9183:                     } else {
                   9184:                         $ownername = $owner;
                   9185:                         $ownerdom = $cdom;
                   9186:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9187:                     }
                   9188:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9189:                     if (defined($userdata) && 
1.609     raeburn  9190: 			!exists($$userdata{$owner})) {
                   9191: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9192:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9193:                             push(@{$seclists{$owner}},'none');
                   9194:                         }
                   9195:                         if (ref($statushash) eq 'HASH') {
                   9196:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9197:                         }
1.290     albertel 9198: 		    }
1.279     raeburn  9199:                 }
                   9200:             }
                   9201:         }
1.419     raeburn  9202:         foreach my $user (keys(%seclists)) {
                   9203:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9204:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9205:         }
1.275     raeburn  9206:     }
                   9207:     return;
                   9208: }
                   9209: 
1.288     raeburn  9210: sub get_user_info {
                   9211:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9212:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9213: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9214:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9215:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9216:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9217:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9218:     return;
                   9219: }
1.275     raeburn  9220: 
1.472     raeburn  9221: ###############################################
                   9222: 
                   9223: =pod
                   9224: 
                   9225: =item * &get_user_quota()
                   9226: 
1.1075.2.41  raeburn  9227: Retrieves quota assigned for storage of user files.
                   9228: Default is to report quota for portfolio files.
1.472     raeburn  9229: 
                   9230: Incoming parameters:
                   9231: 1. user's username
                   9232: 2. user's domain
1.1075.2.41  raeburn  9233: 3. quota name - portfolio, author, or course
                   9234:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  9235: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  9236:    course
1.472     raeburn  9237: 
                   9238: Returns:
1.1075.2.58  raeburn  9239: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9240: 2. (Optional) Type of setting: custom or default
                   9241:    (individually assigned or default for user's 
                   9242:    institutional status).
                   9243: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9244:    or student - types as defined in localenroll::inst_usertypes 
                   9245:    for user's domain, which determines default quota for user.
                   9246: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9247: 
                   9248: If a value has been stored in the user's environment, 
1.536     raeburn  9249: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  9250: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9251: 
                   9252: =cut
                   9253: 
                   9254: ###############################################
                   9255: 
                   9256: 
                   9257: sub get_user_quota {
1.1075.2.42  raeburn  9258:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9259:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9260:     if (!defined($udom)) {
                   9261:         $udom = $env{'user.domain'};
                   9262:     }
                   9263:     if (!defined($uname)) {
                   9264:         $uname = $env{'user.name'};
                   9265:     }
                   9266:     if (($udom eq '' || $uname eq '') ||
                   9267:         ($udom eq 'public') && ($uname eq 'public')) {
                   9268:         $quota = 0;
1.536     raeburn  9269:         $quotatype = 'default';
                   9270:         $defquota = 0; 
1.472     raeburn  9271:     } else {
1.536     raeburn  9272:         my $inststatus;
1.1075.2.41  raeburn  9273:         if ($quotaname eq 'course') {
                   9274:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9275:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9276:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9277:             } else {
                   9278:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9279:                 $quota = $cenv{'internal.uploadquota'};
                   9280:             }
1.536     raeburn  9281:         } else {
1.1075.2.41  raeburn  9282:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9283:                 if ($quotaname eq 'author') {
                   9284:                     $quota = $env{'environment.authorquota'};
                   9285:                 } else {
                   9286:                     $quota = $env{'environment.portfolioquota'};
                   9287:                 }
                   9288:                 $inststatus = $env{'environment.inststatus'};
                   9289:             } else {
                   9290:                 my %userenv = 
                   9291:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9292:                                          'authorquota','inststatus'],$udom,$uname);
                   9293:                 my ($tmp) = keys(%userenv);
                   9294:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9295:                     if ($quotaname eq 'author') {
                   9296:                         $quota = $userenv{'authorquota'};
                   9297:                     } else {
                   9298:                         $quota = $userenv{'portfolioquota'};
                   9299:                     }
                   9300:                     $inststatus = $userenv{'inststatus'};
                   9301:                 } else {
                   9302:                     undef(%userenv);
                   9303:                 }
                   9304:             }
                   9305:         }
                   9306:         if ($quota eq '' || wantarray) {
                   9307:             if ($quotaname eq 'course') {
                   9308:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  9309:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   9310:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  9311:                     $defquota = $domdefs{$crstype.'quota'};
                   9312:                 }
                   9313:                 if ($defquota eq '') {
                   9314:                     $defquota = 500;
                   9315:                 }
1.1075.2.41  raeburn  9316:             } else {
                   9317:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9318:             }
                   9319:             if ($quota eq '') {
                   9320:                 $quota = $defquota;
                   9321:                 $quotatype = 'default';
                   9322:             } else {
                   9323:                 $quotatype = 'custom';
                   9324:             }
1.472     raeburn  9325:         }
                   9326:     }
1.536     raeburn  9327:     if (wantarray) {
                   9328:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9329:     } else {
                   9330:         return $quota;
                   9331:     }
1.472     raeburn  9332: }
                   9333: 
                   9334: ###############################################
                   9335: 
                   9336: =pod
                   9337: 
                   9338: =item * &default_quota()
                   9339: 
1.536     raeburn  9340: Retrieves default quota assigned for storage of user portfolio files,
                   9341: given an (optional) user's institutional status.
1.472     raeburn  9342: 
                   9343: Incoming parameters:
1.1075.2.42  raeburn  9344: 
1.472     raeburn  9345: 1. domain
1.536     raeburn  9346: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9347:    status types (e.g., faculty, staff, student etc.)
                   9348:    which apply to the user for whom the default is being retrieved.
                   9349:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  9350:    default quota will be returned.
                   9351: 3.  quota name - portfolio, author, or course
                   9352:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9353: 
                   9354: Returns:
1.1075.2.42  raeburn  9355: 
1.1075.2.58  raeburn  9356: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9357: 2. (Optional) institutional type which determined the value of the
                   9358:    default quota.
1.472     raeburn  9359: 
                   9360: If a value has been stored in the domain's configuration db,
                   9361: it will return that, otherwise it returns 20 (for backwards 
                   9362: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  9363: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9364: 
1.536     raeburn  9365: If the user's status includes multiple types (e.g., staff and student),
                   9366: the largest default quota which applies to the user determines the
                   9367: default quota returned.
                   9368: 
1.472     raeburn  9369: =cut
                   9370: 
                   9371: ###############################################
                   9372: 
                   9373: 
                   9374: sub default_quota {
1.1075.2.41  raeburn  9375:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9376:     my ($defquota,$settingstatus);
                   9377:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9378:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  9379:     my $key = 'defaultquota';
                   9380:     if ($quotaname eq 'author') {
                   9381:         $key = 'authorquota';
                   9382:     }
1.622     raeburn  9383:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9384:         if ($inststatus ne '') {
1.765     raeburn  9385:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9386:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  9387:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9388:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9389:                         if ($defquota eq '') {
1.1075.2.41  raeburn  9390:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9391:                             $settingstatus = $item;
1.1075.2.41  raeburn  9392:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9393:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9394:                             $settingstatus = $item;
                   9395:                         }
                   9396:                     }
1.1075.2.41  raeburn  9397:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9398:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9399:                         if ($defquota eq '') {
                   9400:                             $defquota = $quotahash{'quotas'}{$item};
                   9401:                             $settingstatus = $item;
                   9402:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9403:                             $defquota = $quotahash{'quotas'}{$item};
                   9404:                             $settingstatus = $item;
                   9405:                         }
1.536     raeburn  9406:                     }
                   9407:                 }
                   9408:             }
                   9409:         }
                   9410:         if ($defquota eq '') {
1.1075.2.41  raeburn  9411:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9412:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9413:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9414:                 $defquota = $quotahash{'quotas'}{'default'};
                   9415:             }
1.536     raeburn  9416:             $settingstatus = 'default';
1.1075.2.42  raeburn  9417:             if ($defquota eq '') {
                   9418:                 if ($quotaname eq 'author') {
                   9419:                     $defquota = 500;
                   9420:                 }
                   9421:             }
1.536     raeburn  9422:         }
                   9423:     } else {
                   9424:         $settingstatus = 'default';
1.1075.2.41  raeburn  9425:         if ($quotaname eq 'author') {
                   9426:             $defquota = 500;
                   9427:         } else {
                   9428:             $defquota = 20;
                   9429:         }
1.536     raeburn  9430:     }
                   9431:     if (wantarray) {
                   9432:         return ($defquota,$settingstatus);
1.472     raeburn  9433:     } else {
1.536     raeburn  9434:         return $defquota;
1.472     raeburn  9435:     }
                   9436: }
                   9437: 
1.1075.2.41  raeburn  9438: ###############################################
                   9439: 
                   9440: =pod
                   9441: 
1.1075.2.42  raeburn  9442: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  9443: 
                   9444: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  9445: of existing file within authoring space will cause quota for the authoring
                   9446: space to be exceeded.
                   9447: 
                   9448: Same, if upload of a file directly to a course/community via Course Editor
                   9449: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  9450: 
1.1075.2.61  raeburn  9451: Inputs: 7 
1.1075.2.42  raeburn  9452: 1. username or coursenum
1.1075.2.41  raeburn  9453: 2. domain
1.1075.2.42  raeburn  9454: 3. context ('author' or 'course')
1.1075.2.41  raeburn  9455: 4. filename of file for which action is being requested
                   9456: 5. filesize (kB) of file
                   9457: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  9458: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  9459: 
                   9460: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   9461:          otherwise return null.
                   9462: 
1.1075.2.42  raeburn  9463: =back
                   9464: 
1.1075.2.41  raeburn  9465: =cut
                   9466: 
1.1075.2.42  raeburn  9467: sub excess_filesize_warning {
1.1075.2.59  raeburn  9468:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  9469:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  9470:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  9471:     if ($context eq 'author') {
                   9472:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9473:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9474:     } else {
                   9475:         foreach my $subdir ('docs','supplemental') {
                   9476:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9477:         }
                   9478:     }
1.1075.2.41  raeburn  9479:     $disk_quota = int($disk_quota * 1000);
                   9480:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  9481:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  9482:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  9483:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9484:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  9485:                             $disk_quota,$current_disk_usage).
                   9486:                '</p>';
                   9487:     }
                   9488:     return;
                   9489: }
                   9490: 
                   9491: ###############################################
                   9492: 
                   9493: 
1.384     raeburn  9494: sub get_secgrprole_info {
                   9495:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9496:     my %sections_count = &get_sections($cdom,$cnum);
                   9497:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9498:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9499:     my @groups = sort(keys(%curr_groups));
                   9500:     my $allroles = [];
                   9501:     my $rolehash;
                   9502:     my $accesshash = {
                   9503:                      active => 'Currently has access',
                   9504:                      future => 'Will have future access',
                   9505:                      previous => 'Previously had access',
                   9506:                   };
                   9507:     if ($needroles) {
                   9508:         $rolehash = {'all' => 'all'};
1.385     albertel 9509:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9510: 	if (&Apache::lonnet::error(%user_roles)) {
                   9511: 	    undef(%user_roles);
                   9512: 	}
                   9513:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9514:             my ($role)=split(/\:/,$item,2);
                   9515:             if ($role eq 'cr') { next; }
                   9516:             if ($role =~ /^cr/) {
                   9517:                 $$rolehash{$role} = (split('/',$role))[3];
                   9518:             } else {
                   9519:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9520:             }
                   9521:         }
                   9522:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9523:             push(@{$allroles},$key);
                   9524:         }
                   9525:         push (@{$allroles},'st');
                   9526:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9527:     }
                   9528:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9529: }
                   9530: 
1.555     raeburn  9531: sub user_picker {
1.1075.2.115  raeburn  9532:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom) = @_;
1.555     raeburn  9533:     my $currdom = $dom;
1.1075.2.114  raeburn  9534:     my @alldoms = &Apache::lonnet::all_domains();
                   9535:     if (@alldoms == 1) {
                   9536:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   9537:                                                ['directorysrch'],$alldoms[0]);
                   9538:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   9539:         my $showdom = $domdesc;
                   9540:         if ($showdom eq '') {
                   9541:             $showdom = $dom;
                   9542:         }
                   9543:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   9544:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   9545:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   9546:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   9547:             }
                   9548:         }
                   9549:     }
1.555     raeburn  9550:     my %curr_selected = (
                   9551:                         srchin => 'dom',
1.580     raeburn  9552:                         srchby => 'lastname',
1.555     raeburn  9553:                       );
                   9554:     my $srchterm;
1.625     raeburn  9555:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9556:         if ($srch->{'srchby'} ne '') {
                   9557:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9558:         }
                   9559:         if ($srch->{'srchin'} ne '') {
                   9560:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9561:         }
                   9562:         if ($srch->{'srchtype'} ne '') {
                   9563:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9564:         }
                   9565:         if ($srch->{'srchdomain'} ne '') {
                   9566:             $currdom = $srch->{'srchdomain'};
                   9567:         }
                   9568:         $srchterm = $srch->{'srchterm'};
                   9569:     }
1.1075.2.98  raeburn  9570:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  9571:                     'usr'       => 'Search criteria',
1.563     raeburn  9572:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9573:                     'uname'     => 'username',
                   9574:                     'lastname'  => 'last name',
1.555     raeburn  9575:                     'lastfirst' => 'last name, first name',
1.558     albertel 9576:                     'crs'       => 'in this course',
1.576     raeburn  9577:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9578:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9579:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9580:                     'exact'     => 'is',
                   9581:                     'contains'  => 'contains',
1.569     raeburn  9582:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  9583:                                        );
                   9584:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  9585:                     'youm'      => "You must include some text to search for.",
                   9586:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9587:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9588:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9589:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9590:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9591:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9592:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9593:                                        );
1.1075.2.98  raeburn  9594:     &html_escape(\%html_lt);
                   9595:     &js_escape(\%js_lt);
1.1075.2.115  raeburn  9596:     my $domform;
                   9597:     if ($fixeddom) {
                   9598:         $domform = &select_dom_form($currdom,'srchdomain',1,1,undef,[$currdom]);
                   9599:     } else {
                   9600:         $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   9601:     }
1.563     raeburn  9602:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9603: 
                   9604:     my @srchins = ('crs','dom','alc','instd');
                   9605: 
                   9606:     foreach my $option (@srchins) {
                   9607:         # FIXME 'alc' option unavailable until 
                   9608:         #       loncreateuser::print_user_query_page()
                   9609:         #       has been completed.
                   9610:         next if ($option eq 'alc');
1.880     raeburn  9611:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9612:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  9613:         if ($curr_selected{'srchin'} eq $option) {
                   9614:             $srchinsel .= ' 
1.1075.2.98  raeburn  9615:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  9616:         } else {
                   9617:             $srchinsel .= '
1.1075.2.98  raeburn  9618:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  9619:         }
1.555     raeburn  9620:     }
1.563     raeburn  9621:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9622: 
                   9623:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9624:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9625:         if ($curr_selected{'srchby'} eq $option) {
                   9626:             $srchbysel .= '
1.1075.2.98  raeburn  9627:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9628:         } else {
                   9629:             $srchbysel .= '
1.1075.2.98  raeburn  9630:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9631:          }
                   9632:     }
                   9633:     $srchbysel .= "\n  </select>\n";
                   9634: 
                   9635:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9636:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9637:         if ($curr_selected{'srchtype'} eq $option) {
                   9638:             $srchtypesel .= '
1.1075.2.98  raeburn  9639:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9640:         } else {
                   9641:             $srchtypesel .= '
1.1075.2.98  raeburn  9642:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9643:         }
                   9644:     }
                   9645:     $srchtypesel .= "\n  </select>\n";
                   9646: 
1.558     albertel 9647:     my ($newuserscript,$new_user_create);
1.994     raeburn  9648:     my $context_dom = $env{'request.role.domain'};
                   9649:     if ($context eq 'requestcrs') {
                   9650:         if ($env{'form.coursedom'} ne '') { 
                   9651:             $context_dom = $env{'form.coursedom'};
                   9652:         }
                   9653:     }
1.556     raeburn  9654:     if ($forcenewuser) {
1.576     raeburn  9655:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9656:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9657:                 if ($cancreate) {
                   9658:                     $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>';
                   9659:                 } else {
1.799     bisitz   9660:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9661:                     my %usertypetext = (
                   9662:                         official   => 'institutional',
                   9663:                         unofficial => 'non-institutional',
                   9664:                     );
1.799     bisitz   9665:                     $new_user_create = '<p class="LC_warning">'
                   9666:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9667:                                       .' '
                   9668:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9669:                                           ,'<a href="'.$helplink.'">','</a>')
                   9670:                                       .'</p><br />';
1.627     raeburn  9671:                 }
1.576     raeburn  9672:             }
                   9673:         }
                   9674: 
1.556     raeburn  9675:         $newuserscript = <<"ENDSCRIPT";
                   9676: 
1.570     raeburn  9677: function setSearch(createnew,callingForm) {
1.556     raeburn  9678:     if (createnew == 1) {
1.570     raeburn  9679:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9680:             if (callingForm.srchby.options[i].value == 'uname') {
                   9681:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9682:             }
                   9683:         }
1.570     raeburn  9684:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9685:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9686: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9687:             }
                   9688:         }
1.570     raeburn  9689:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9690:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9691:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9692:             }
                   9693:         }
1.570     raeburn  9694:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9695:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9696:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9697:             }
                   9698:         }
                   9699:     }
                   9700: }
                   9701: ENDSCRIPT
1.558     albertel 9702: 
1.556     raeburn  9703:     }
                   9704: 
1.555     raeburn  9705:     my $output = <<"END_BLOCK";
1.556     raeburn  9706: <script type="text/javascript">
1.824     bisitz   9707: // <![CDATA[
1.570     raeburn  9708: function validateEntry(callingForm) {
1.558     albertel 9709: 
1.556     raeburn  9710:     var checkok = 1;
1.558     albertel 9711:     var srchin;
1.570     raeburn  9712:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9713: 	if ( callingForm.srchin[i].checked ) {
                   9714: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9715: 	}
                   9716:     }
                   9717: 
1.570     raeburn  9718:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9719:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9720:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9721:     var srchterm =  callingForm.srchterm.value;
                   9722:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9723:     var msg = "";
                   9724: 
                   9725:     if (srchterm == "") {
                   9726:         checkok = 0;
1.1075.2.98  raeburn  9727:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  9728:     }
                   9729: 
1.569     raeburn  9730:     if (srchtype== 'begins') {
                   9731:         if (srchterm.length < 2) {
                   9732:             checkok = 0;
1.1075.2.98  raeburn  9733:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  9734:         }
                   9735:     }
                   9736: 
1.556     raeburn  9737:     if (srchtype== 'contains') {
                   9738:         if (srchterm.length < 3) {
                   9739:             checkok = 0;
1.1075.2.98  raeburn  9740:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  9741:         }
                   9742:     }
                   9743:     if (srchin == 'instd') {
                   9744:         if (srchdomain == '') {
                   9745:             checkok = 0;
1.1075.2.98  raeburn  9746:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  9747:         }
                   9748:     }
                   9749:     if (srchin == 'dom') {
                   9750:         if (srchdomain == '') {
                   9751:             checkok = 0;
1.1075.2.98  raeburn  9752:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  9753:         }
                   9754:     }
                   9755:     if (srchby == 'lastfirst') {
                   9756:         if (srchterm.indexOf(",") == -1) {
                   9757:             checkok = 0;
1.1075.2.98  raeburn  9758:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  9759:         }
                   9760:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9761:             checkok = 0;
1.1075.2.98  raeburn  9762:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  9763:         }
                   9764:     }
                   9765:     if (checkok == 0) {
1.1075.2.98  raeburn  9766:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  9767:         return;
                   9768:     }
                   9769:     if (checkok == 1) {
1.570     raeburn  9770:         callingForm.submit();
1.556     raeburn  9771:     }
                   9772: }
                   9773: 
                   9774: $newuserscript
                   9775: 
1.824     bisitz   9776: // ]]>
1.556     raeburn  9777: </script>
1.558     albertel 9778: 
                   9779: $new_user_create
                   9780: 
1.555     raeburn  9781: END_BLOCK
1.558     albertel 9782: 
1.876     raeburn  9783:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  9784:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  9785:                $domform.
                   9786:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  9787:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  9788:                $srchbysel.
                   9789:                $srchtypesel. 
                   9790:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9791:                $srchinsel.
                   9792:                &Apache::lonhtmlcommon::row_closure(1). 
                   9793:                &Apache::lonhtmlcommon::end_pick_box().
                   9794:                '<br />';
1.1075.2.114  raeburn  9795:     return ($output,1);
1.555     raeburn  9796: }
                   9797: 
1.612     raeburn  9798: sub user_rule_check {
1.615     raeburn  9799:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  9800:     my ($response,%inst_response);
1.612     raeburn  9801:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  9802:         if (keys(%{$usershash}) > 1) {
                   9803:             my (%by_username,%by_id,%userdoms);
                   9804:             my $checkid;
1.612     raeburn  9805:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  9806:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   9807:                     $checkid = 1;
                   9808:                 }
                   9809:             }
                   9810:             foreach my $user (keys(%{$usershash})) {
                   9811:                 my ($uname,$udom) = split(/:/,$user);
                   9812:                 if ($checkid) {
                   9813:                     if (ref($usershash->{$user}) eq 'HASH') {
                   9814:                         if ($usershash->{$user}->{'id'} ne '') {
                   9815:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   9816:                             $userdoms{$udom} = 1;
                   9817:                             if (ref($inst_results) eq 'HASH') {
                   9818:                                 $inst_results->{$uname.':'.$udom} = {};
                   9819:                             }
                   9820:                         }
                   9821:                     }
                   9822:                 } else {
                   9823:                     $by_username{$udom}{$uname} = 1;
                   9824:                     $userdoms{$udom} = 1;
                   9825:                     if (ref($inst_results) eq 'HASH') {
                   9826:                         $inst_results->{$uname.':'.$udom} = {};
                   9827:                     }
                   9828:                 }
                   9829:             }
                   9830:             foreach my $udom (keys(%userdoms)) {
                   9831:                 if (!$got_rules->{$udom}) {
                   9832:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9833:                                                              ['usercreation'],$udom);
                   9834:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   9835:                         foreach my $item ('username','id') {
                   9836:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9837:                                 $$curr_rules{$udom}{$item} =
                   9838:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   9839:                             }
                   9840:                         }
                   9841:                     }
                   9842:                     $got_rules->{$udom} = 1;
                   9843:                 }
                   9844:             }
                   9845:             if ($checkid) {
                   9846:                 foreach my $udom (keys(%by_id)) {
                   9847:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   9848:                     if ($outcome eq 'ok') {
                   9849:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   9850:                             my $uname = $by_id{$udom}{$id};
                   9851:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9852:                         }
                   9853:                         if (ref($results) eq 'HASH') {
                   9854:                             foreach my $uname (keys(%{$results})) {
                   9855:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   9856:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   9857:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   9858:                                 }
                   9859:                             }
                   9860:                         }
                   9861:                     }
1.612     raeburn  9862:                 }
1.615     raeburn  9863:             } else {
1.1075.2.99  raeburn  9864:                 foreach my $udom (keys(%by_username)) {
                   9865:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   9866:                     if ($outcome eq 'ok') {
                   9867:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   9868:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9869:                         }
                   9870:                         if (ref($results) eq 'HASH') {
                   9871:                             foreach my $uname (keys(%{$results})) {
                   9872:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   9873:                             }
                   9874:                         }
                   9875:                     }
                   9876:                 }
1.612     raeburn  9877:             }
1.1075.2.99  raeburn  9878:         } elsif (keys(%{$usershash}) == 1) {
                   9879:             my $user = (keys(%{$usershash}))[0];
                   9880:             my ($uname,$udom) = split(/:/,$user);
                   9881:             if (($udom ne '') && ($uname ne '')) {
                   9882:                 if (ref($usershash->{$user}) eq 'HASH') {
                   9883:                     if (ref($checks) eq 'HASH') {
                   9884:                         if (defined($checks->{'username'})) {
                   9885:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   9886:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   9887:                         } elsif (defined($checks->{'id'})) {
                   9888:                             if ($usershash->{$user}->{'id'} ne '') {
                   9889:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   9890:                                     &Apache::lonnet::get_instuser($udom,undef,
                   9891:                                                                   $usershash->{$user}->{'id'});
                   9892:                             } else {
                   9893:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   9894:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   9895:                             }
                   9896:                         }
                   9897:                     } else {
                   9898:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   9899:                             &Apache::lonnet::get_instuser($udom,$uname);
                   9900:                        return;
                   9901:                     }
                   9902:                     if (!$got_rules->{$udom}) {
                   9903:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9904:                                                                  ['usercreation'],$udom);
                   9905:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   9906:                             foreach my $item ('username','id') {
                   9907:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9908:                                    $$curr_rules{$udom}{$item} =
                   9909:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   9910:                                 }
                   9911:                             }
1.585     raeburn  9912:                         }
1.1075.2.99  raeburn  9913:                         $got_rules->{$udom} = 1;
1.585     raeburn  9914:                     }
                   9915:                 }
1.1075.2.99  raeburn  9916:             } else {
                   9917:                 return;
                   9918:             }
                   9919:         } else {
                   9920:             return;
                   9921:         }
                   9922:         foreach my $user (keys(%{$usershash})) {
                   9923:             my ($uname,$udom) = split(/:/,$user);
                   9924:             next if (($udom eq '') || ($uname eq ''));
                   9925:             my $id;
                   9926:             if (ref($inst_results) eq 'HASH') {
                   9927:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   9928:                     $id = $inst_results->{$user}->{'id'};
                   9929:                 }
                   9930:             }
                   9931:             if ($id eq '') {
                   9932:                 if (ref($usershash->{$user})) {
                   9933:                     $id = $usershash->{$user}->{'id'};
                   9934:                 }
1.585     raeburn  9935:             }
1.612     raeburn  9936:             foreach my $item (keys(%{$checks})) {
                   9937:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   9938:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   9939:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  9940:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   9941:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  9942:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   9943:                                 if ($rule_check{$rule}) {
                   9944:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  9945:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  9946:                                         if (ref($inst_results) eq 'HASH') {
                   9947:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   9948:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   9949:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  9950:                                                 } elsif ($item eq 'id') {
                   9951:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   9952:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   9953:                                                     }
1.615     raeburn  9954:                                                 }
1.612     raeburn  9955:                                             }
                   9956:                                         }
1.615     raeburn  9957:                                     }
                   9958:                                     last;
1.585     raeburn  9959:                                 }
                   9960:                             }
                   9961:                         }
                   9962:                     }
                   9963:                 }
                   9964:             }
                   9965:         }
                   9966:     }
1.612     raeburn  9967:     return;
                   9968: }
                   9969: 
                   9970: sub user_rule_formats {
                   9971:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   9972:     my %text = ( 
                   9973:                  'username' => 'Usernames',
                   9974:                  'id'       => 'IDs',
                   9975:                );
                   9976:     my $output;
                   9977:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   9978:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   9979:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  9980:             $output = '<br />'.
                   9981:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   9982:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   9983:                       ' <ul>';
1.612     raeburn  9984:             foreach my $rule (@{$ruleorder}) {
                   9985:                 if (ref($curr_rules) eq 'ARRAY') {
                   9986:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   9987:                         if (ref($rules->{$rule}) eq 'HASH') {
                   9988:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   9989:                                         $rules->{$rule}{'desc'}.'</li>';
                   9990:                         }
                   9991:                     }
                   9992:                 }
                   9993:             }
                   9994:             $output .= '</ul>';
                   9995:         }
                   9996:     }
                   9997:     return $output;
                   9998: }
                   9999: 
                   10000: sub instrule_disallow_msg {
1.615     raeburn  10001:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10002:     my $response;
                   10003:     my %text = (
                   10004:                   item   => 'username',
                   10005:                   items  => 'usernames',
                   10006:                   match  => 'matches',
                   10007:                   do     => 'does',
                   10008:                   action => 'a username',
                   10009:                   one    => 'one',
                   10010:                );
                   10011:     if ($count > 1) {
                   10012:         $text{'item'} = 'usernames';
                   10013:         $text{'match'} ='match';
                   10014:         $text{'do'} = 'do';
                   10015:         $text{'action'} = 'usernames',
                   10016:         $text{'one'} = 'ones';
                   10017:     }
                   10018:     if ($checkitem eq 'id') {
                   10019:         $text{'items'} = 'IDs';
                   10020:         $text{'item'} = 'ID';
                   10021:         $text{'action'} = 'an ID';
1.615     raeburn  10022:         if ($count > 1) {
                   10023:             $text{'item'} = 'IDs';
                   10024:             $text{'action'} = 'IDs';
                   10025:         }
1.612     raeburn  10026:     }
1.674     bisitz   10027:     $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  10028:     if ($mode eq 'upload') {
                   10029:         if ($checkitem eq 'username') {
                   10030:             $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'}.");
                   10031:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10032:             $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  10033:         }
1.669     raeburn  10034:     } elsif ($mode eq 'selfcreate') {
                   10035:         if ($checkitem eq 'id') {
                   10036:             $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.");
                   10037:         }
1.615     raeburn  10038:     } else {
                   10039:         if ($checkitem eq 'username') {
                   10040:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10041:         } elsif ($checkitem eq 'id') {
                   10042:             $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.");
                   10043:         }
1.612     raeburn  10044:     }
                   10045:     return $response;
1.585     raeburn  10046: }
                   10047: 
1.624     raeburn  10048: sub personal_data_fieldtitles {
                   10049:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10050:                         id => 'Student/Employee ID',
                   10051:                         permanentemail => 'E-mail address',
                   10052:                         lastname => 'Last Name',
                   10053:                         firstname => 'First Name',
                   10054:                         middlename => 'Middle Name',
                   10055:                         generation => 'Generation',
                   10056:                         gen => 'Generation',
1.765     raeburn  10057:                         inststatus => 'Affiliation',
1.624     raeburn  10058:                    );
                   10059:     return %fieldtitles;
                   10060: }
                   10061: 
1.642     raeburn  10062: sub sorted_inst_types {
                   10063:     my ($dom) = @_;
1.1075.2.70  raeburn  10064:     my ($usertypes,$order);
                   10065:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10066:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10067:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10068:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10069:     } else {
                   10070:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10071:     }
1.642     raeburn  10072:     my $othertitle = &mt('All users');
                   10073:     if ($env{'request.course.id'}) {
1.668     raeburn  10074:         $othertitle  = &mt('Any users');
1.642     raeburn  10075:     }
                   10076:     my @types;
                   10077:     if (ref($order) eq 'ARRAY') {
                   10078:         @types = @{$order};
                   10079:     }
                   10080:     if (@types == 0) {
                   10081:         if (ref($usertypes) eq 'HASH') {
                   10082:             @types = sort(keys(%{$usertypes}));
                   10083:         }
                   10084:     }
                   10085:     if (keys(%{$usertypes}) > 0) {
                   10086:         $othertitle = &mt('Other users');
                   10087:     }
                   10088:     return ($othertitle,$usertypes,\@types);
                   10089: }
                   10090: 
1.645     raeburn  10091: sub get_institutional_codes {
                   10092:     my ($settings,$allcourses,$LC_code) = @_;
                   10093: # Get complete list of course sections to update
                   10094:     my @currsections = ();
                   10095:     my @currxlists = ();
                   10096:     my $coursecode = $$settings{'internal.coursecode'};
                   10097: 
                   10098:     if ($$settings{'internal.sectionnums'} ne '') {
                   10099:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10100:     }
                   10101: 
                   10102:     if ($$settings{'internal.crosslistings'} ne '') {
                   10103:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10104:     }
                   10105: 
                   10106:     if (@currxlists > 0) {
                   10107:         foreach (@currxlists) {
                   10108:             if (m/^([^:]+):(\w*)$/) {
                   10109:                 unless (grep/^$1$/,@{$allcourses}) {
                   10110:                     push @{$allcourses},$1;
                   10111:                     $$LC_code{$1} = $2;
                   10112:                 }
                   10113:             }
                   10114:         }
                   10115:     }
                   10116:  
                   10117:     if (@currsections > 0) {
                   10118:         foreach (@currsections) {
                   10119:             if (m/^(\w+):(\w*)$/) {
                   10120:                 my $sec = $coursecode.$1;
                   10121:                 my $lc_sec = $2;
                   10122:                 unless (grep/^$sec$/,@{$allcourses}) {
                   10123:                     push @{$allcourses},$sec;
                   10124:                     $$LC_code{$sec} = $lc_sec;
                   10125:                 }
                   10126:             }
                   10127:         }
                   10128:     }
                   10129:     return;
                   10130: }
                   10131: 
1.971     raeburn  10132: sub get_standard_codeitems {
                   10133:     return ('Year','Semester','Department','Number','Section');
                   10134: }
                   10135: 
1.112     bowersj2 10136: =pod
                   10137: 
1.780     raeburn  10138: =head1 Slot Helpers
                   10139: 
                   10140: =over 4
                   10141: 
                   10142: =item * sorted_slots()
                   10143: 
1.1040    raeburn  10144: Sorts an array of slot names in order of an optional sort key,
                   10145: default sort is by slot start time (earliest first). 
1.780     raeburn  10146: 
                   10147: Inputs:
                   10148: 
                   10149: =over 4
                   10150: 
                   10151: slotsarr  - Reference to array of unsorted slot names.
                   10152: 
                   10153: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10154: 
1.1040    raeburn  10155: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10156: 
1.549     albertel 10157: =back
                   10158: 
1.780     raeburn  10159: Returns:
                   10160: 
                   10161: =over 4
                   10162: 
1.1040    raeburn  10163: sorted   - An array of slot names sorted by a specified sort key 
                   10164:            (default sort key is start time of the slot).
1.780     raeburn  10165: 
                   10166: =back
                   10167: 
                   10168: =cut
                   10169: 
                   10170: 
                   10171: sub sorted_slots {
1.1040    raeburn  10172:     my ($slotsarr,$slots,$sortkey) = @_;
                   10173:     if ($sortkey eq '') {
                   10174:         $sortkey = 'starttime';
                   10175:     }
1.780     raeburn  10176:     my @sorted;
                   10177:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10178:         @sorted =
                   10179:             sort {
                   10180:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10181:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10182:                      }
                   10183:                      if (ref($slots->{$a})) { return -1;}
                   10184:                      if (ref($slots->{$b})) { return 1;}
                   10185:                      return 0;
                   10186:                  } @{$slotsarr};
                   10187:     }
                   10188:     return @sorted;
                   10189: }
                   10190: 
1.1040    raeburn  10191: =pod
                   10192: 
                   10193: =item * get_future_slots()
                   10194: 
                   10195: Inputs:
                   10196: 
                   10197: =over 4
                   10198: 
                   10199: cnum - course number
                   10200: 
                   10201: cdom - course domain
                   10202: 
                   10203: now - current UNIX time
                   10204: 
                   10205: symb - optional symb
                   10206: 
                   10207: =back
                   10208: 
                   10209: Returns:
                   10210: 
                   10211: =over 4
                   10212: 
                   10213: sorted_reservable - ref to array of student_schedulable slots currently 
                   10214:                     reservable, ordered by end date of reservation period.
                   10215: 
                   10216: reservable_now - ref to hash of student_schedulable slots currently
                   10217:                  reservable.
                   10218: 
                   10219:     Keys in inner hash are:
                   10220:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  10221:     (b) endreserve: end date of reservation period.
                   10222:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10223:         selected.
1.1040    raeburn  10224: 
                   10225: sorted_future - ref to array of student_schedulable slots reservable in
                   10226:                 the future, ordered by start date of reservation period.
                   10227: 
                   10228: future_reservable - ref to hash of student_schedulable slots reservable
                   10229:                     in the future.
                   10230: 
                   10231:     Keys in inner hash are:
                   10232:     (a) symb: either blank or symb to which slot use is restricted.
                   10233:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  10234:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10235:         selected.
1.1040    raeburn  10236: 
                   10237: =back
                   10238: 
                   10239: =cut
                   10240: 
                   10241: sub get_future_slots {
                   10242:     my ($cnum,$cdom,$now,$symb) = @_;
                   10243:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10244:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10245:     foreach my $slot (keys(%slots)) {
                   10246:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10247:         if ($symb) {
                   10248:             next if (($slots{$slot}->{'symb'} ne '') && 
                   10249:                      ($slots{$slot}->{'symb'} ne $symb));
                   10250:         }
                   10251:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10252:             ($slots{$slot}->{'endtime'} > $now)) {
                   10253:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10254:                 my $userallowed = 0;
                   10255:                 if ($slots{$slot}->{'allowedsections'}) {
                   10256:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10257:                     if (!defined($env{'request.role.sec'})
                   10258:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10259:                         $userallowed=1;
                   10260:                     } else {
                   10261:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10262:                             $userallowed=1;
                   10263:                         }
                   10264:                     }
                   10265:                     unless ($userallowed) {
                   10266:                         if (defined($env{'request.course.groups'})) {
                   10267:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10268:                             foreach my $group (@groups) {
                   10269:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10270:                                     $userallowed=1;
                   10271:                                     last;
                   10272:                                 }
                   10273:                             }
                   10274:                         }
                   10275:                     }
                   10276:                 }
                   10277:                 if ($slots{$slot}->{'allowedusers'}) {
                   10278:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10279:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10280:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10281:                         $userallowed = 1;
                   10282:                     }
                   10283:                 }
                   10284:                 next unless($userallowed);
                   10285:             }
                   10286:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10287:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10288:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  10289:             my $uniqueperiod;
                   10290:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10291:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10292:             }
1.1040    raeburn  10293:             if (($startreserve < $now) &&
                   10294:                 (!$endreserve || $endreserve > $now)) {
                   10295:                 my $lastres = $endreserve;
                   10296:                 if (!$lastres) {
                   10297:                     $lastres = $slots{$slot}->{'starttime'};
                   10298:                 }
                   10299:                 $reservable_now{$slot} = {
                   10300:                                            symb       => $symb,
1.1075.2.104  raeburn  10301:                                            endreserve => $lastres,
                   10302:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  10303:                                          };
                   10304:             } elsif (($startreserve > $now) &&
                   10305:                      (!$endreserve || $endreserve > $startreserve)) {
                   10306:                 $future_reservable{$slot} = {
                   10307:                                               symb         => $symb,
1.1075.2.104  raeburn  10308:                                               startreserve => $startreserve,
                   10309:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10310:                                             };
                   10311:             }
                   10312:         }
                   10313:     }
                   10314:     my @unsorted_reservable = keys(%reservable_now);
                   10315:     if (@unsorted_reservable > 0) {
                   10316:         @sorted_reservable = 
                   10317:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10318:     }
                   10319:     my @unsorted_future = keys(%future_reservable);
                   10320:     if (@unsorted_future > 0) {
                   10321:         @sorted_future =
                   10322:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10323:     }
                   10324:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10325: }
1.780     raeburn  10326: 
                   10327: =pod
                   10328: 
1.1057    foxr     10329: =back
                   10330: 
1.549     albertel 10331: =head1 HTTP Helpers
                   10332: 
                   10333: =over 4
                   10334: 
1.648     raeburn  10335: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10336: 
1.258     albertel 10337: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10338: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10339: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10340: 
                   10341: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10342: $possible_names is an ref to an array of form element names.  As an example:
                   10343: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10344: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10345: 
                   10346: =cut
1.1       albertel 10347: 
1.6       albertel 10348: sub get_unprocessed_cgi {
1.25      albertel 10349:   my ($query,$possible_names)= @_;
1.26      matthew  10350:   # $Apache::lonxml::debug=1;
1.356     albertel 10351:   foreach my $pair (split(/&/,$query)) {
                   10352:     my ($name, $value) = split(/=/,$pair);
1.369     www      10353:     $name = &unescape($name);
1.25      albertel 10354:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10355:       $value =~ tr/+/ /;
                   10356:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10357:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10358:     }
1.16      harris41 10359:   }
1.6       albertel 10360: }
                   10361: 
1.112     bowersj2 10362: =pod
                   10363: 
1.648     raeburn  10364: =item * &cacheheader() 
1.112     bowersj2 10365: 
                   10366: returns cache-controlling header code
                   10367: 
                   10368: =cut
                   10369: 
1.7       albertel 10370: sub cacheheader {
1.258     albertel 10371:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10372:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10373:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10374:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10375:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10376:     return $output;
1.7       albertel 10377: }
                   10378: 
1.112     bowersj2 10379: =pod
                   10380: 
1.648     raeburn  10381: =item * &no_cache($r) 
1.112     bowersj2 10382: 
                   10383: specifies header code to not have cache
                   10384: 
                   10385: =cut
                   10386: 
1.9       albertel 10387: sub no_cache {
1.216     albertel 10388:     my ($r) = @_;
                   10389:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10390: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10391:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10392:     $r->no_cache(1);
                   10393:     $r->header_out("Expires" => $date);
                   10394:     $r->header_out("Pragma" => "no-cache");
1.123     www      10395: }
                   10396: 
                   10397: sub content_type {
1.181     albertel 10398:     my ($r,$type,$charset) = @_;
1.299     foxr     10399:     if ($r) {
                   10400: 	#  Note that printout.pl calls this with undef for $r.
                   10401: 	&no_cache($r);
                   10402:     }
1.258     albertel 10403:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10404:     unless ($charset) {
                   10405: 	$charset=&Apache::lonlocal::current_encoding;
                   10406:     }
                   10407:     if ($charset) { $type.='; charset='.$charset; }
                   10408:     if ($r) {
                   10409: 	$r->content_type($type);
                   10410:     } else {
                   10411: 	print("Content-type: $type\n\n");
                   10412:     }
1.9       albertel 10413: }
1.25      albertel 10414: 
1.112     bowersj2 10415: =pod
                   10416: 
1.648     raeburn  10417: =item * &add_to_env($name,$value) 
1.112     bowersj2 10418: 
1.258     albertel 10419: adds $name to the %env hash with value
1.112     bowersj2 10420: $value, if $name already exists, the entry is converted to an array
                   10421: reference and $value is added to the array.
                   10422: 
                   10423: =cut
                   10424: 
1.25      albertel 10425: sub add_to_env {
                   10426:   my ($name,$value)=@_;
1.258     albertel 10427:   if (defined($env{$name})) {
                   10428:     if (ref($env{$name})) {
1.25      albertel 10429:       #already have multiple values
1.258     albertel 10430:       push(@{ $env{$name} },$value);
1.25      albertel 10431:     } else {
                   10432:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10433:       my $first=$env{$name};
                   10434:       undef($env{$name});
                   10435:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10436:     }
                   10437:   } else {
1.258     albertel 10438:     $env{$name}=$value;
1.25      albertel 10439:   }
1.31      albertel 10440: }
1.149     albertel 10441: 
                   10442: =pod
                   10443: 
1.648     raeburn  10444: =item * &get_env_multiple($name) 
1.149     albertel 10445: 
1.258     albertel 10446: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10447: values may be defined and end up as an array ref.
                   10448: 
                   10449: returns an array of values
                   10450: 
                   10451: =cut
                   10452: 
                   10453: sub get_env_multiple {
                   10454:     my ($name) = @_;
                   10455:     my @values;
1.258     albertel 10456:     if (defined($env{$name})) {
1.149     albertel 10457:         # exists is it an array
1.258     albertel 10458:         if (ref($env{$name})) {
                   10459:             @values=@{ $env{$name} };
1.149     albertel 10460:         } else {
1.258     albertel 10461:             $values[0]=$env{$name};
1.149     albertel 10462:         }
                   10463:     }
                   10464:     return(@values);
                   10465: }
                   10466: 
1.660     raeburn  10467: sub ask_for_embedded_content {
                   10468:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10469:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  10470:         %currsubfile,%unused,$rem);
1.1071    raeburn  10471:     my $counter = 0;
                   10472:     my $numnew = 0;
1.987     raeburn  10473:     my $numremref = 0;
                   10474:     my $numinvalid = 0;
                   10475:     my $numpathchg = 0;
                   10476:     my $numexisting = 0;
1.1071    raeburn  10477:     my $numunused = 0;
                   10478:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  10479:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10480:     my $heading = &mt('Upload embedded files');
                   10481:     my $buttontext = &mt('Upload');
                   10482: 
1.1075.2.11  raeburn  10483:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  10484:         if ($actionurl eq '/adm/dependencies') {
                   10485:             $navmap = Apache::lonnavmaps::navmap->new();
                   10486:         }
                   10487:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10488:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  10489:     }
1.1075.2.35  raeburn  10490:     if (($actionurl eq '/adm/portfolio') ||
                   10491:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10492:         my $current_path='/';
                   10493:         if ($env{'form.currentpath'}) {
                   10494:             $current_path = $env{'form.currentpath'};
                   10495:         }
                   10496:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  10497:             $udom = $cdom;
                   10498:             $uname = $cnum;
1.984     raeburn  10499:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10500:         } else {
                   10501:             $udom = $env{'user.domain'};
                   10502:             $uname = $env{'user.name'};
                   10503:             $url = '/userfiles/portfolio';
                   10504:         }
1.987     raeburn  10505:         $toplevel = $url.'/';
1.984     raeburn  10506:         $url .= $current_path;
                   10507:         $getpropath = 1;
1.987     raeburn  10508:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10509:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10510:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10511:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10512:         $toplevel = $url;
1.984     raeburn  10513:         if ($rest ne '') {
1.987     raeburn  10514:             $url .= $rest;
                   10515:         }
                   10516:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10517:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10518:             $url = $args->{'docs_url'};
                   10519:             $toplevel = $url;
1.1075.2.11  raeburn  10520:             if ($args->{'context'} eq 'paste') {
                   10521:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10522:                 ($path) =
                   10523:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10524:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10525:                 $fileloc =~ s{^/}{};
                   10526:             }
1.1071    raeburn  10527:         }
                   10528:     } elsif ($actionurl eq '/adm/dependencies') {
                   10529:         if ($env{'request.course.id'} ne '') {
                   10530:             if (ref($args) eq 'HASH') {
                   10531:                 $url = $args->{'docs_url'};
                   10532:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  10533:                 $toplevel = $url;
                   10534:                 unless ($toplevel =~ m{^/}) {
                   10535:                     $toplevel = "/$url";
                   10536:                 }
1.1075.2.11  raeburn  10537:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  10538:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10539:                     $path = $1;
                   10540:                 } else {
                   10541:                     ($path) =
                   10542:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10543:                 }
1.1075.2.79  raeburn  10544:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10545:                     $fileloc = $toplevel;
                   10546:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10547:                     my ($udom,$uname,$fname) =
                   10548:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10549:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10550:                 } else {
                   10551:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10552:                 }
1.1071    raeburn  10553:                 $fileloc =~ s{^/}{};
                   10554:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10555:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10556:             }
1.987     raeburn  10557:         }
1.1075.2.35  raeburn  10558:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10559:         $udom = $cdom;
                   10560:         $uname = $cnum;
                   10561:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10562:         $toplevel = $url;
                   10563:         $path = $url;
                   10564:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10565:         $fileloc =~ s{^/}{};
                   10566:     }
                   10567:     foreach my $file (keys(%{$allfiles})) {
                   10568:         my $embed_file;
                   10569:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10570:             $embed_file = $1;
                   10571:         } else {
                   10572:             $embed_file = $file;
                   10573:         }
1.1075.2.55  raeburn  10574:         my ($absolutepath,$cleaned_file);
                   10575:         if ($embed_file =~ m{^\w+://}) {
                   10576:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  10577:             $newfiles{$cleaned_file} = 1;
                   10578:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10579:         } else {
1.1075.2.55  raeburn  10580:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10581:             if ($embed_file =~ m{^/}) {
                   10582:                 $absolutepath = $embed_file;
                   10583:             }
1.1075.2.47  raeburn  10584:             if ($cleaned_file =~ m{/}) {
                   10585:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10586:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10587:                 my $item = $fname;
                   10588:                 if ($path ne '') {
                   10589:                     $item = $path.'/'.$fname;
                   10590:                     $subdependencies{$path}{$fname} = 1;
                   10591:                 } else {
                   10592:                     $dependencies{$item} = 1;
                   10593:                 }
                   10594:                 if ($absolutepath) {
                   10595:                     $mapping{$item} = $absolutepath;
                   10596:                 } else {
                   10597:                     $mapping{$item} = $embed_file;
                   10598:                 }
                   10599:             } else {
                   10600:                 $dependencies{$embed_file} = 1;
                   10601:                 if ($absolutepath) {
1.1075.2.47  raeburn  10602:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10603:                 } else {
1.1075.2.47  raeburn  10604:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10605:                 }
                   10606:             }
1.984     raeburn  10607:         }
                   10608:     }
1.1071    raeburn  10609:     my $dirptr = 16384;
1.984     raeburn  10610:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10611:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  10612:         if (($actionurl eq '/adm/portfolio') ||
                   10613:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  10614:             my ($sublistref,$listerror) =
                   10615:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10616:             if (ref($sublistref) eq 'ARRAY') {
                   10617:                 foreach my $line (@{$sublistref}) {
                   10618:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10619:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10620:                 }
1.984     raeburn  10621:             }
1.987     raeburn  10622:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10623:             if (opendir(my $dir,$url.'/'.$path)) {
                   10624:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10625:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10626:             }
1.1075.2.11  raeburn  10627:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10628:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10629:                   ($args->{'context'} eq 'paste')) ||
                   10630:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10631:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  10632:                 my $dir;
                   10633:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10634:                     $dir = $fileloc;
                   10635:                 } else {
                   10636:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10637:                 }
1.1071    raeburn  10638:                 if ($dir ne '') {
                   10639:                     my ($sublistref,$listerror) =
                   10640:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10641:                     if (ref($sublistref) eq 'ARRAY') {
                   10642:                         foreach my $line (@{$sublistref}) {
                   10643:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10644:                                 undef,$mtime)=split(/\&/,$line,12);
                   10645:                             unless (($testdir&$dirptr) ||
                   10646:                                     ($file_name =~ /^\.\.?$/)) {
                   10647:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10648:                             }
                   10649:                         }
                   10650:                     }
                   10651:                 }
1.984     raeburn  10652:             }
                   10653:         }
                   10654:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10655:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10656:                 my $item = $path.'/'.$file;
                   10657:                 unless ($mapping{$item} eq $item) {
                   10658:                     $pathchanges{$item} = 1;
                   10659:                 }
                   10660:                 $existing{$item} = 1;
                   10661:                 $numexisting ++;
                   10662:             } else {
                   10663:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10664:             }
                   10665:         }
1.1071    raeburn  10666:         if ($actionurl eq '/adm/dependencies') {
                   10667:             foreach my $path (keys(%currsubfile)) {
                   10668:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10669:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10670:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  10671:                              next if (($rem ne '') &&
                   10672:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10673:                                        (ref($navmap) &&
                   10674:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10675:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10676:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10677:                              $unused{$path.'/'.$file} = 1; 
                   10678:                          }
                   10679:                     }
                   10680:                 }
                   10681:             }
                   10682:         }
1.984     raeburn  10683:     }
1.987     raeburn  10684:     my %currfile;
1.1075.2.35  raeburn  10685:     if (($actionurl eq '/adm/portfolio') ||
                   10686:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10687:         my ($dirlistref,$listerror) =
                   10688:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10689:         if (ref($dirlistref) eq 'ARRAY') {
                   10690:             foreach my $line (@{$dirlistref}) {
                   10691:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10692:                 $currfile{$file_name} = 1;
                   10693:             }
1.984     raeburn  10694:         }
1.987     raeburn  10695:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10696:         if (opendir(my $dir,$url)) {
1.987     raeburn  10697:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10698:             map {$currfile{$_} = 1;} @dir_list;
                   10699:         }
1.1075.2.11  raeburn  10700:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10701:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10702:               ($args->{'context'} eq 'paste')) ||
                   10703:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10704:         if ($env{'request.course.id'} ne '') {
                   10705:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10706:             if ($dir ne '') {
                   10707:                 my ($dirlistref,$listerror) =
                   10708:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10709:                 if (ref($dirlistref) eq 'ARRAY') {
                   10710:                     foreach my $line (@{$dirlistref}) {
                   10711:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10712:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10713:                         unless (($testdir&$dirptr) ||
                   10714:                                 ($file_name =~ /^\.\.?$/)) {
                   10715:                             $currfile{$file_name} = [$size,$mtime];
                   10716:                         }
                   10717:                     }
                   10718:                 }
                   10719:             }
                   10720:         }
1.984     raeburn  10721:     }
                   10722:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10723:         if (exists($currfile{$file})) {
1.987     raeburn  10724:             unless ($mapping{$file} eq $file) {
                   10725:                 $pathchanges{$file} = 1;
                   10726:             }
                   10727:             $existing{$file} = 1;
                   10728:             $numexisting ++;
                   10729:         } else {
1.984     raeburn  10730:             $newfiles{$file} = 1;
                   10731:         }
                   10732:     }
1.1071    raeburn  10733:     foreach my $file (keys(%currfile)) {
                   10734:         unless (($file eq $filename) ||
                   10735:                 ($file eq $filename.'.bak') ||
                   10736:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  10737:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  10738:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10739:                     next if (($rem ne '') &&
                   10740:                              (($env{"httpref.$rem".$file} ne '') ||
                   10741:                               (ref($navmap) &&
                   10742:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10743:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10744:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10745:                 }
1.1075.2.11  raeburn  10746:             }
1.1071    raeburn  10747:             $unused{$file} = 1;
                   10748:         }
                   10749:     }
1.1075.2.11  raeburn  10750:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10751:         ($args->{'context'} eq 'paste')) {
                   10752:         $counter = scalar(keys(%existing));
                   10753:         $numpathchg = scalar(keys(%pathchanges));
                   10754:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  10755:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   10756:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10757:         $counter = scalar(keys(%existing));
                   10758:         $numpathchg = scalar(keys(%pathchanges));
                   10759:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  10760:     }
1.984     raeburn  10761:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10762:         if ($actionurl eq '/adm/dependencies') {
                   10763:             next if ($embed_file =~ m{^\w+://});
                   10764:         }
1.660     raeburn  10765:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10766:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  10767:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  10768:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  10769:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   10770:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  10771:         }
1.1075.2.35  raeburn  10772:         $upload_output .= '</td>';
1.1071    raeburn  10773:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  10774:             $upload_output.='<td align="right">'.
                   10775:                             '<span class="LC_info LC_fontsize_medium">'.
                   10776:                             &mt("URL points to web address").'</span>';
1.987     raeburn  10777:             $numremref++;
1.660     raeburn  10778:         } elsif ($args->{'error_on_invalid_names'}
                   10779:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  10780:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   10781:                             &mt('Invalid characters').'</span>';
1.987     raeburn  10782:             $numinvalid++;
1.660     raeburn  10783:         } else {
1.1075.2.35  raeburn  10784:             $upload_output .= '<td>'.
                   10785:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  10786:                                                      $embed_file,\%mapping,
1.1071    raeburn  10787:                                                      $allfiles,$codebase,'upload');
                   10788:             $counter ++;
                   10789:             $numnew ++;
1.987     raeburn  10790:         }
                   10791:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   10792:     }
                   10793:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  10794:         if ($actionurl eq '/adm/dependencies') {
                   10795:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   10796:             $modify_output .= &start_data_table_row().
                   10797:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   10798:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   10799:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   10800:                               '<td>'.$size.'</td>'.
                   10801:                               '<td>'.$mtime.'</td>'.
                   10802:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   10803:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   10804:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   10805:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   10806:                               &embedded_file_element('upload_embedded',$counter,
                   10807:                                                      $embed_file,\%mapping,
                   10808:                                                      $allfiles,$codebase,'modify').
                   10809:                               '</div></td>'.
                   10810:                               &end_data_table_row()."\n";
                   10811:             $counter ++;
                   10812:         } else {
                   10813:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10814:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   10815:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   10816:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  10817:                               &Apache::loncommon::end_data_table_row()."\n";
                   10818:         }
                   10819:     }
                   10820:     my $delidx = $counter;
                   10821:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   10822:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   10823:         $delete_output .= &start_data_table_row().
                   10824:                           '<td><img src="'.&icon($oldfile).'" />'.
                   10825:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   10826:                           '<td>'.$size.'</td>'.
                   10827:                           '<td>'.$mtime.'</td>'.
                   10828:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   10829:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   10830:                           &embedded_file_element('upload_embedded',$delidx,
                   10831:                                                  $oldfile,\%mapping,$allfiles,
                   10832:                                                  $codebase,'delete').'</td>'.
                   10833:                           &end_data_table_row()."\n"; 
                   10834:         $numunused ++;
                   10835:         $delidx ++;
1.987     raeburn  10836:     }
                   10837:     if ($upload_output) {
                   10838:         $upload_output = &start_data_table().
                   10839:                          $upload_output.
                   10840:                          &end_data_table()."\n";
                   10841:     }
1.1071    raeburn  10842:     if ($modify_output) {
                   10843:         $modify_output = &start_data_table().
                   10844:                          &start_data_table_header_row().
                   10845:                          '<th>'.&mt('File').'</th>'.
                   10846:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10847:                          '<th>'.&mt('Modified').'</th>'.
                   10848:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   10849:                          &end_data_table_header_row().
                   10850:                          $modify_output.
                   10851:                          &end_data_table()."\n";
                   10852:     }
                   10853:     if ($delete_output) {
                   10854:         $delete_output = &start_data_table().
                   10855:                          &start_data_table_header_row().
                   10856:                          '<th>'.&mt('File').'</th>'.
                   10857:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10858:                          '<th>'.&mt('Modified').'</th>'.
                   10859:                          '<th>'.&mt('Delete?').'</th>'.
                   10860:                          &end_data_table_header_row().
                   10861:                          $delete_output.
                   10862:                          &end_data_table()."\n";
                   10863:     }
1.987     raeburn  10864:     my $applies = 0;
                   10865:     if ($numremref) {
                   10866:         $applies ++;
                   10867:     }
                   10868:     if ($numinvalid) {
                   10869:         $applies ++;
                   10870:     }
                   10871:     if ($numexisting) {
                   10872:         $applies ++;
                   10873:     }
1.1071    raeburn  10874:     if ($counter || $numunused) {
1.987     raeburn  10875:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   10876:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  10877:                   $state.'<h3>'.$heading.'</h3>'; 
                   10878:         if ($actionurl eq '/adm/dependencies') {
                   10879:             if ($numnew) {
                   10880:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   10881:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   10882:                            $upload_output.'<br />'."\n";
                   10883:             }
                   10884:             if ($numexisting) {
                   10885:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   10886:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   10887:                            $modify_output.'<br />'."\n";
                   10888:                            $buttontext = &mt('Save changes');
                   10889:             }
                   10890:             if ($numunused) {
                   10891:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   10892:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   10893:                            $delete_output.'<br />'."\n";
                   10894:                            $buttontext = &mt('Save changes');
                   10895:             }
                   10896:         } else {
                   10897:             $output .= $upload_output.'<br />'."\n";
                   10898:         }
                   10899:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   10900:                    $counter.'" />'."\n";
                   10901:         if ($actionurl eq '/adm/dependencies') { 
                   10902:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   10903:                        $numnew.'" />'."\n";
                   10904:         } elsif ($actionurl eq '') {
1.987     raeburn  10905:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   10906:         }
                   10907:     } elsif ($applies) {
                   10908:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   10909:         if ($applies > 1) {
                   10910:             $output .=  
1.1075.2.35  raeburn  10911:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  10912:             if ($numremref) {
                   10913:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   10914:             }
                   10915:             if ($numinvalid) {
                   10916:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   10917:             }
                   10918:             if ($numexisting) {
                   10919:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   10920:             }
                   10921:             $output .= '</ul><br />';
                   10922:         } elsif ($numremref) {
                   10923:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   10924:         } elsif ($numinvalid) {
                   10925:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   10926:         } elsif ($numexisting) {
                   10927:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   10928:         }
                   10929:         $output .= $upload_output.'<br />';
                   10930:     }
                   10931:     my ($pathchange_output,$chgcount);
1.1071    raeburn  10932:     $chgcount = $counter;
1.987     raeburn  10933:     if (keys(%pathchanges) > 0) {
                   10934:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  10935:             if ($counter) {
1.987     raeburn  10936:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   10937:                                                   $embed_file,\%mapping,
1.1071    raeburn  10938:                                                   $allfiles,$codebase,'change');
1.987     raeburn  10939:             } else {
                   10940:                 $pathchange_output .= 
                   10941:                     &start_data_table_row().
                   10942:                     '<td><input type ="checkbox" name="namechange" value="'.
                   10943:                     $chgcount.'" checked="checked" /></td>'.
                   10944:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   10945:                     '<td>'.$embed_file.
                   10946:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  10947:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  10948:                     '</td>'.&end_data_table_row();
1.660     raeburn  10949:             }
1.987     raeburn  10950:             $numpathchg ++;
                   10951:             $chgcount ++;
1.660     raeburn  10952:         }
                   10953:     }
1.1075.2.35  raeburn  10954:     if (($counter) || ($numunused)) {
1.987     raeburn  10955:         if ($numpathchg) {
                   10956:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   10957:                        $numpathchg.'" />'."\n";
                   10958:         }
                   10959:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   10960:             ($actionurl eq '/adm/imsimport')) {
                   10961:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   10962:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   10963:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  10964:         } elsif ($actionurl eq '/adm/dependencies') {
                   10965:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  10966:         }
1.1075.2.35  raeburn  10967:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  10968:     } elsif ($numpathchg) {
                   10969:         my %pathchange = ();
                   10970:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   10971:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10972:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  10973:         }
1.987     raeburn  10974:     }
1.1071    raeburn  10975:     return ($output,$counter,$numpathchg);
1.987     raeburn  10976: }
                   10977: 
1.1075.2.47  raeburn  10978: =pod
                   10979: 
                   10980: =item * clean_path($name)
                   10981: 
                   10982: Performs clean-up of directories, subdirectories and filename in an
                   10983: embedded object, referenced in an HTML file which is being uploaded
                   10984: to a course or portfolio, where
                   10985: "Upload embedded images/multimedia files if HTML file" checkbox was
                   10986: checked.
                   10987: 
                   10988: Clean-up is similar to replacements in lonnet::clean_filename()
                   10989: except each / between sub-directory and next level is preserved.
                   10990: 
                   10991: =cut
                   10992: 
                   10993: sub clean_path {
                   10994:     my ($embed_file) = @_;
                   10995:     $embed_file =~s{^/+}{};
                   10996:     my @contents;
                   10997:     if ($embed_file =~ m{/}) {
                   10998:         @contents = split(/\//,$embed_file);
                   10999:     } else {
                   11000:         @contents = ($embed_file);
                   11001:     }
                   11002:     my $lastidx = scalar(@contents)-1;
                   11003:     for (my $i=0; $i<=$lastidx; $i++) {
                   11004:         $contents[$i]=~s{\\}{/}g;
                   11005:         $contents[$i]=~s/\s+/\_/g;
                   11006:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11007:         if ($i == $lastidx) {
                   11008:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11009:         }
                   11010:     }
                   11011:     if ($lastidx > 0) {
                   11012:         return join('/',@contents);
                   11013:     } else {
                   11014:         return $contents[0];
                   11015:     }
                   11016: }
                   11017: 
1.987     raeburn  11018: sub embedded_file_element {
1.1071    raeburn  11019:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11020:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11021:                    (ref($codebase) eq 'HASH'));
                   11022:     my $output;
1.1071    raeburn  11023:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11024:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11025:     }
                   11026:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11027:                &escape($embed_file).'" />';
                   11028:     unless (($context eq 'upload_embedded') && 
                   11029:             ($mapping->{$embed_file} eq $embed_file)) {
                   11030:         $output .='
                   11031:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11032:     }
                   11033:     my $attrib;
                   11034:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11035:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11036:     }
                   11037:     $output .=
                   11038:         "\n\t\t".
                   11039:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11040:         $attrib.'" />';
                   11041:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11042:         $output .=
                   11043:             "\n\t\t".
                   11044:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11045:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11046:     }
1.987     raeburn  11047:     return $output;
1.660     raeburn  11048: }
                   11049: 
1.1071    raeburn  11050: sub get_dependency_details {
                   11051:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11052:     my ($size,$mtime,$showsize,$showmtime);
                   11053:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11054:         if ($embed_file =~ m{/}) {
                   11055:             my ($path,$fname) = split(/\//,$embed_file);
                   11056:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11057:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11058:             }
                   11059:         } else {
                   11060:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11061:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11062:             }
                   11063:         }
                   11064:         $showsize = $size/1024.0;
                   11065:         $showsize = sprintf("%.1f",$showsize);
                   11066:         if ($mtime > 0) {
                   11067:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11068:         }
                   11069:     }
                   11070:     return ($showsize,$showmtime);
                   11071: }
                   11072: 
                   11073: sub ask_embedded_js {
                   11074:     return <<"END";
                   11075: <script type="text/javascript"">
                   11076: // <![CDATA[
                   11077: function toggleBrowse(counter) {
                   11078:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11079:     var fileid = document.getElementById('embedded_item_'+counter);
                   11080:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11081:     if (chkboxid.checked == true) {
                   11082:         uploaddivid.style.display='block';
                   11083:     } else {
                   11084:         uploaddivid.style.display='none';
                   11085:         fileid.value = '';
                   11086:     }
                   11087: }
                   11088: // ]]>
                   11089: </script>
                   11090: 
                   11091: END
                   11092: }
                   11093: 
1.661     raeburn  11094: sub upload_embedded {
                   11095:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11096:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11097:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11098:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11099:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11100:         my $orig_uploaded_filename =
                   11101:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11102:         foreach my $type ('orig','ref','attrib','codebase') {
                   11103:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11104:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11105:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11106:             }
                   11107:         }
1.661     raeburn  11108:         my ($path,$fname) =
                   11109:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11110:         # no path, whole string is fname
                   11111:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11112:         $fname = &Apache::lonnet::clean_filename($fname);
                   11113:         # See if there is anything left
                   11114:         next if ($fname eq '');
                   11115: 
                   11116:         # Check if file already exists as a file or directory.
                   11117:         my ($state,$msg);
                   11118:         if ($context eq 'portfolio') {
                   11119:             my $port_path = $dirpath;
                   11120:             if ($group ne '') {
                   11121:                 $port_path = "groups/$group/$port_path";
                   11122:             }
1.987     raeburn  11123:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11124:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11125:                                               $dir_root,$port_path,$disk_quota,
                   11126:                                               $current_disk_usage,$uname,$udom);
                   11127:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11128:                 || $state eq 'file_locked') {
1.661     raeburn  11129:                 $output .= $msg;
                   11130:                 next;
                   11131:             }
                   11132:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11133:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11134:             if ($state eq 'exists') {
                   11135:                 $output .= $msg;
                   11136:                 next;
                   11137:             }
                   11138:         }
                   11139:         # Check if extension is valid
                   11140:         if (($fname =~ /\.(\w+)$/) &&
                   11141:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  11142:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11143:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11144:             next;
                   11145:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11146:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11147:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11148:             next;
                   11149:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  11150:             $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  11151:             next;
                   11152:         }
                   11153:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  11154:         my $subdir = $path;
                   11155:         $subdir =~ s{/+$}{};
1.661     raeburn  11156:         if ($context eq 'portfolio') {
1.984     raeburn  11157:             my $result;
                   11158:             if ($state eq 'existingfile') {
                   11159:                 $result=
                   11160:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  11161:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11162:             } else {
1.984     raeburn  11163:                 $result=
                   11164:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11165:                                                     $dirpath.
1.1075.2.35  raeburn  11166:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11167:                 if ($result !~ m|^/uploaded/|) {
                   11168:                     $output .= '<span class="LC_error">'
                   11169:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11170:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11171:                                .'</span><br />';
                   11172:                     next;
                   11173:                 } else {
1.987     raeburn  11174:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11175:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11176:                 }
1.661     raeburn  11177:             }
1.1075.2.35  raeburn  11178:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   11179:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11180:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11181:             my $result =
1.1075.2.35  raeburn  11182:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11183:             if ($result !~ m|^/uploaded/|) {
                   11184:                 $output .= '<span class="LC_error">'
                   11185:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11186:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11187:                            .'</span><br />';
                   11188:                     next;
                   11189:             } else {
                   11190:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11191:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  11192:                 if ($context eq 'syllabus') {
                   11193:                     &Apache::lonnet::make_public_indefinitely($result);
                   11194:                 }
1.987     raeburn  11195:             }
1.661     raeburn  11196:         } else {
                   11197: # Save the file
                   11198:             my $target = $env{'form.embedded_item_'.$i};
                   11199:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11200:             my $dest = $fullpath.$fname;
                   11201:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11202:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11203:             my $count;
                   11204:             my $filepath = $dir_root;
1.1027    raeburn  11205:             foreach my $subdir (@parts) {
                   11206:                 $filepath .= "/$subdir";
                   11207:                 if (!-e $filepath) {
1.661     raeburn  11208:                     mkdir($filepath,0770);
                   11209:                 }
                   11210:             }
                   11211:             my $fh;
                   11212:             if (!open($fh,'>'.$dest)) {
                   11213:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11214:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11215:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11216:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11217:                            '</span><br />';
                   11218:             } else {
                   11219:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11220:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11221:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11222:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11223:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11224:                               '</span><br />';
                   11225:                 } else {
1.987     raeburn  11226:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11227:                                $url.'</span>').'<br />';
                   11228:                     unless ($context eq 'testbank') {
                   11229:                         $footer .= &mt('View embedded file: [_1]',
                   11230:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11231:                     }
                   11232:                 }
                   11233:                 close($fh);
                   11234:             }
                   11235:         }
                   11236:         if ($env{'form.embedded_ref_'.$i}) {
                   11237:             $pathchange{$i} = 1;
                   11238:         }
                   11239:     }
                   11240:     if ($output) {
                   11241:         $output = '<p>'.$output.'</p>';
                   11242:     }
                   11243:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11244:     $returnflag = 'ok';
1.1071    raeburn  11245:     my $numpathchgs = scalar(keys(%pathchange));
                   11246:     if ($numpathchgs > 0) {
1.987     raeburn  11247:         if ($context eq 'portfolio') {
                   11248:             $output .= '<p>'.&mt('or').'</p>';
                   11249:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11250:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11251:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11252:             $returnflag = 'modify_orightml';
                   11253:         }
                   11254:     }
1.1071    raeburn  11255:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11256: }
                   11257: 
                   11258: sub modify_html_form {
                   11259:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11260:     my $end = 0;
                   11261:     my $modifyform;
                   11262:     if ($context eq 'upload_embedded') {
                   11263:         return unless (ref($pathchange) eq 'HASH');
                   11264:         if ($env{'form.number_embedded_items'}) {
                   11265:             $end += $env{'form.number_embedded_items'};
                   11266:         }
                   11267:         if ($env{'form.number_pathchange_items'}) {
                   11268:             $end += $env{'form.number_pathchange_items'};
                   11269:         }
                   11270:         if ($end) {
                   11271:             for (my $i=0; $i<$end; $i++) {
                   11272:                 if ($i < $env{'form.number_embedded_items'}) {
                   11273:                     next unless($pathchange->{$i});
                   11274:                 }
                   11275:                 $modifyform .=
                   11276:                     &start_data_table_row().
                   11277:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11278:                     'checked="checked" /></td>'.
                   11279:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11280:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11281:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11282:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11283:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11284:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11285:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11286:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11287:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11288:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11289:                     &end_data_table_row();
1.1071    raeburn  11290:             }
1.987     raeburn  11291:         }
                   11292:     } else {
                   11293:         $modifyform = $pathchgtable;
                   11294:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11295:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11296:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11297:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11298:         }
                   11299:     }
                   11300:     if ($modifyform) {
1.1071    raeburn  11301:         if ($actionurl eq '/adm/dependencies') {
                   11302:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11303:         }
1.987     raeburn  11304:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11305:                '<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".
                   11306:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11307:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11308:                '</ol></p>'."\n".'<p>'.
                   11309:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11310:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11311:                &start_data_table()."\n".
                   11312:                &start_data_table_header_row().
                   11313:                '<th>'.&mt('Change?').'</th>'.
                   11314:                '<th>'.&mt('Current reference').'</th>'.
                   11315:                '<th>'.&mt('Required reference').'</th>'.
                   11316:                &end_data_table_header_row()."\n".
                   11317:                $modifyform.
                   11318:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11319:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11320:                '</form>'."\n";
                   11321:     }
                   11322:     return;
                   11323: }
                   11324: 
                   11325: sub modify_html_refs {
1.1075.2.35  raeburn  11326:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11327:     my $container;
                   11328:     if ($context eq 'portfolio') {
                   11329:         $container = $env{'form.container'};
                   11330:     } elsif ($context eq 'coursedoc') {
                   11331:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11332:     } elsif ($context eq 'manage_dependencies') {
                   11333:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11334:         $container = "/$container";
1.1075.2.35  raeburn  11335:     } elsif ($context eq 'syllabus') {
                   11336:         $container = $url;
1.987     raeburn  11337:     } else {
1.1027    raeburn  11338:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11339:     }
                   11340:     my (%allfiles,%codebase,$output,$content);
                   11341:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  11342:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  11343:         if (wantarray) {
                   11344:             return ('',0,0); 
                   11345:         } else {
                   11346:             return;
                   11347:         }
                   11348:     }
                   11349:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11350:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11351:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11352:             if (wantarray) {
                   11353:                 return ('',0,0);
                   11354:             } else {
                   11355:                 return;
                   11356:             }
                   11357:         } 
1.987     raeburn  11358:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11359:         if ($content eq '-1') {
                   11360:             if (wantarray) {
                   11361:                 return ('',0,0);
                   11362:             } else {
                   11363:                 return;
                   11364:             }
                   11365:         }
1.987     raeburn  11366:     } else {
1.1071    raeburn  11367:         unless ($container =~ /^\Q$dir_root\E/) {
                   11368:             if (wantarray) {
                   11369:                 return ('',0,0);
                   11370:             } else {
                   11371:                 return;
                   11372:             }
                   11373:         } 
1.987     raeburn  11374:         if (open(my $fh,"<$container")) {
                   11375:             $content = join('', <$fh>);
                   11376:             close($fh);
                   11377:         } else {
1.1071    raeburn  11378:             if (wantarray) {
                   11379:                 return ('',0,0);
                   11380:             } else {
                   11381:                 return;
                   11382:             }
1.987     raeburn  11383:         }
                   11384:     }
                   11385:     my ($count,$codebasecount) = (0,0);
                   11386:     my $mm = new File::MMagic;
                   11387:     my $mime_type = $mm->checktype_contents($content);
                   11388:     if ($mime_type eq 'text/html') {
                   11389:         my $parse_result = 
                   11390:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11391:                                                     \%codebase,\$content);
                   11392:         if ($parse_result eq 'ok') {
                   11393:             foreach my $i (@changes) {
                   11394:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11395:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11396:                 if ($allfiles{$ref}) {
                   11397:                     my $newname =  $orig;
                   11398:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11399:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11400:                     if ($attrib_regexp =~ /:/) {
                   11401:                         $attrib_regexp =~ s/\:/|/g;
                   11402:                     }
                   11403:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11404:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11405:                         $count += $numchg;
1.1075.2.35  raeburn  11406:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  11407:                         delete($allfiles{$ref});
1.987     raeburn  11408:                     }
                   11409:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11410:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11411:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11412:                         $codebasecount ++;
                   11413:                     }
                   11414:                 }
                   11415:             }
1.1075.2.35  raeburn  11416:             my $skiprewrites;
1.987     raeburn  11417:             if ($count || $codebasecount) {
                   11418:                 my $saveresult;
1.1071    raeburn  11419:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11420:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11421:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11422:                     if ($url eq $container) {
                   11423:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11424:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11425:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11426:                                             $fname.'</span>').'</p>';
1.987     raeburn  11427:                     } else {
                   11428:                          $output = '<p class="LC_error">'.
                   11429:                                    &mt('Error: update failed for: [_1].',
                   11430:                                    '<span class="LC_filename">'.
                   11431:                                    $container.'</span>').'</p>';
                   11432:                     }
1.1075.2.35  raeburn  11433:                     if ($context eq 'syllabus') {
                   11434:                         unless ($saveresult eq 'ok') {
                   11435:                             $skiprewrites = 1;
                   11436:                         }
                   11437:                     }
1.987     raeburn  11438:                 } else {
                   11439:                     if (open(my $fh,">$container")) {
                   11440:                         print $fh $content;
                   11441:                         close($fh);
                   11442:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11443:                                   $count,'<span class="LC_filename">'.
                   11444:                                   $container.'</span>').'</p>';
1.661     raeburn  11445:                     } else {
1.987     raeburn  11446:                          $output = '<p class="LC_error">'.
                   11447:                                    &mt('Error: could not update [_1].',
                   11448:                                    '<span class="LC_filename">'.
                   11449:                                    $container.'</span>').'</p>';
1.661     raeburn  11450:                     }
                   11451:                 }
                   11452:             }
1.1075.2.35  raeburn  11453:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11454:                 my ($actionurl,$state);
                   11455:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11456:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11457:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11458:                                               \%codebase,
                   11459:                                               {'context' => 'rewrites',
                   11460:                                                'ignore_remote_references' => 1,});
                   11461:                 if (ref($mapping) eq 'HASH') {
                   11462:                     my $rewrites = 0;
                   11463:                     foreach my $key (keys(%{$mapping})) {
                   11464:                         next if ($key =~ m{^https?://});
                   11465:                         my $ref = $mapping->{$key};
                   11466:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11467:                         my $attrib;
                   11468:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11469:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11470:                         }
                   11471:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11472:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11473:                             $rewrites += $numchg;
                   11474:                         }
                   11475:                     }
                   11476:                     if ($rewrites) {
                   11477:                         my $saveresult;
                   11478:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11479:                         if ($url eq $container) {
                   11480:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11481:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11482:                                             $count,'<span class="LC_filename">'.
                   11483:                                             $fname.'</span>').'</p>';
                   11484:                         } else {
                   11485:                             $output .= '<p class="LC_error">'.
                   11486:                                        &mt('Error: could not update links in [_1].',
                   11487:                                        '<span class="LC_filename">'.
                   11488:                                        $container.'</span>').'</p>';
                   11489: 
                   11490:                         }
                   11491:                     }
                   11492:                 }
                   11493:             }
1.987     raeburn  11494:         } else {
                   11495:             &logthis('Failed to parse '.$container.
                   11496:                      ' to modify references: '.$parse_result);
1.661     raeburn  11497:         }
                   11498:     }
1.1071    raeburn  11499:     if (wantarray) {
                   11500:         return ($output,$count,$codebasecount);
                   11501:     } else {
                   11502:         return $output;
                   11503:     }
1.661     raeburn  11504: }
                   11505: 
                   11506: sub check_for_existing {
                   11507:     my ($path,$fname,$element) = @_;
                   11508:     my ($state,$msg);
                   11509:     if (-d $path.'/'.$fname) {
                   11510:         $state = 'exists';
                   11511:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11512:     } elsif (-e $path.'/'.$fname) {
                   11513:         $state = 'exists';
                   11514:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11515:     }
                   11516:     if ($state eq 'exists') {
                   11517:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11518:     }
                   11519:     return ($state,$msg);
                   11520: }
                   11521: 
                   11522: sub check_for_upload {
                   11523:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11524:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11525:     my $filesize = length($env{'form.'.$element});
                   11526:     if (!$filesize) {
                   11527:         my $msg = '<span class="LC_error">'.
                   11528:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11529:                       '<span class="LC_filename">'.$fname.'</span>',
                   11530:                       $filesize).'<br />'.
1.1007    raeburn  11531:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11532:                   '</span>';
                   11533:         return ('zero_bytes',$msg);
                   11534:     }
                   11535:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11536:     my $getpropath = 1;
1.1021    raeburn  11537:     my ($dirlistref,$listerror) =
                   11538:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11539:     my $found_file = 0;
                   11540:     my $locked_file = 0;
1.991     raeburn  11541:     my @lockers;
                   11542:     my $navmap;
                   11543:     if ($env{'request.course.id'}) {
                   11544:         $navmap = Apache::lonnavmaps::navmap->new();
                   11545:     }
1.1021    raeburn  11546:     if (ref($dirlistref) eq 'ARRAY') {
                   11547:         foreach my $line (@{$dirlistref}) {
                   11548:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11549:             if ($file_name eq $fname){
                   11550:                 $file_name = $path.$file_name;
                   11551:                 if ($group ne '') {
                   11552:                     $file_name = $group.$file_name;
                   11553:                 }
                   11554:                 $found_file = 1;
                   11555:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11556:                     foreach my $lock (@lockers) {
                   11557:                         if (ref($lock) eq 'ARRAY') {
                   11558:                             my ($symb,$crsid) = @{$lock};
                   11559:                             if ($crsid eq $env{'request.course.id'}) {
                   11560:                                 if (ref($navmap)) {
                   11561:                                     my $res = $navmap->getBySymb($symb);
                   11562:                                     foreach my $part (@{$res->parts()}) { 
                   11563:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11564:                                         unless (($slot_status == $res->RESERVED) ||
                   11565:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11566:                                             $locked_file = 1;
                   11567:                                         }
1.991     raeburn  11568:                                     }
1.1021    raeburn  11569:                                 } else {
                   11570:                                     $locked_file = 1;
1.991     raeburn  11571:                                 }
                   11572:                             } else {
                   11573:                                 $locked_file = 1;
                   11574:                             }
                   11575:                         }
1.1021    raeburn  11576:                    }
                   11577:                 } else {
                   11578:                     my @info = split(/\&/,$rest);
                   11579:                     my $currsize = $info[6]/1000;
                   11580:                     if ($currsize < $filesize) {
                   11581:                         my $extra = $filesize - $currsize;
                   11582:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  11583:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11584:                                       &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  11585:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11586:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11587:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11588:                             return ('will_exceed_quota',$msg);
                   11589:                         }
1.984     raeburn  11590:                     }
                   11591:                 }
1.661     raeburn  11592:             }
                   11593:         }
                   11594:     }
                   11595:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  11596:         my $msg = '<p class="LC_warning">'.
                   11597:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   11598:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11599:         return ('will_exceed_quota',$msg);
                   11600:     } elsif ($found_file) {
                   11601:         if ($locked_file) {
1.1075.2.69  raeburn  11602:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11603:             $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  11604:             $msg .= '</p>';
1.661     raeburn  11605:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11606:             return ('file_locked',$msg);
                   11607:         } else {
1.1075.2.69  raeburn  11608:             my $msg = '<p class="LC_error">';
1.984     raeburn  11609:             $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  11610:             $msg .= '</p>';
1.984     raeburn  11611:             return ('existingfile',$msg);
1.661     raeburn  11612:         }
                   11613:     }
                   11614: }
                   11615: 
1.987     raeburn  11616: sub check_for_traversal {
                   11617:     my ($path,$url,$toplevel) = @_;
                   11618:     my @parts=split(/\//,$path);
                   11619:     my $cleanpath;
                   11620:     my $fullpath = $url;
                   11621:     for (my $i=0;$i<@parts;$i++) {
                   11622:         next if ($parts[$i] eq '.');
                   11623:         if ($parts[$i] eq '..') {
                   11624:             $fullpath =~ s{([^/]+/)$}{};
                   11625:         } else {
                   11626:             $fullpath .= $parts[$i].'/';
                   11627:         }
                   11628:     }
                   11629:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11630:         $cleanpath = $1;
                   11631:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11632:         my $curr_toprel = $1;
                   11633:         my @parts = split(/\//,$curr_toprel);
                   11634:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11635:         my @urlparts = split(/\//,$url_toprel);
                   11636:         my $doubledots;
                   11637:         my $startdiff = -1;
                   11638:         for (my $i=0; $i<@urlparts; $i++) {
                   11639:             if ($startdiff == -1) {
                   11640:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11641:                     $startdiff = $i;
                   11642:                     $doubledots .= '../';
                   11643:                 }
                   11644:             } else {
                   11645:                 $doubledots .= '../';
                   11646:             }
                   11647:         }
                   11648:         if ($startdiff > -1) {
                   11649:             $cleanpath = $doubledots;
                   11650:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11651:                 $cleanpath .= $parts[$i].'/';
                   11652:             }
                   11653:         }
                   11654:     }
                   11655:     $cleanpath =~ s{(/)$}{};
                   11656:     return $cleanpath;
                   11657: }
1.31      albertel 11658: 
1.1053    raeburn  11659: sub is_archive_file {
                   11660:     my ($mimetype) = @_;
                   11661:     if (($mimetype eq 'application/octet-stream') ||
                   11662:         ($mimetype eq 'application/x-stuffit') ||
                   11663:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11664:         return 1;
                   11665:     }
                   11666:     return;
                   11667: }
                   11668: 
                   11669: sub decompress_form {
1.1065    raeburn  11670:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11671:     my %lt = &Apache::lonlocal::texthash (
                   11672:         this => 'This file is an archive file.',
1.1067    raeburn  11673:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11674:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11675:         youm => 'You may wish to extract its contents.',
                   11676:         extr => 'Extract contents',
1.1067    raeburn  11677:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11678:         proa => 'Process automatically?',
1.1053    raeburn  11679:         yes  => 'Yes',
                   11680:         no   => 'No',
1.1067    raeburn  11681:         fold => 'Title for folder containing movie',
                   11682:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11683:     );
1.1065    raeburn  11684:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11685:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11686:     my $info = &list_archive_contents($fileloc,\@paths);
                   11687:     if (@paths) {
                   11688:         foreach my $path (@paths) {
                   11689:             $path =~ s{^/}{};
1.1067    raeburn  11690:             if ($path =~ m{^([^/]+)/$}) {
                   11691:                 $topdir = $1;
                   11692:             }
1.1065    raeburn  11693:             if ($path =~ m{^([^/]+)/}) {
                   11694:                 $toplevel{$1} = $path;
                   11695:             } else {
                   11696:                 $toplevel{$path} = $path;
                   11697:             }
                   11698:         }
                   11699:     }
1.1067    raeburn  11700:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  11701:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11702:                         "$topdir/media/",
                   11703:                         "$topdir/media/$topdir.mp4",
                   11704:                         "$topdir/media/FirstFrame.png",
                   11705:                         "$topdir/media/player.swf",
                   11706:                         "$topdir/media/swfobject.js",
                   11707:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  11708:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  11709:                          "$topdir/$topdir.mp4",
                   11710:                          "$topdir/$topdir\_config.xml",
                   11711:                          "$topdir/$topdir\_controller.swf",
                   11712:                          "$topdir/$topdir\_embed.css",
                   11713:                          "$topdir/$topdir\_First_Frame.png",
                   11714:                          "$topdir/$topdir\_player.html",
                   11715:                          "$topdir/$topdir\_Thumbnails.png",
                   11716:                          "$topdir/playerProductInstall.swf",
                   11717:                          "$topdir/scripts/",
                   11718:                          "$topdir/scripts/config_xml.js",
                   11719:                          "$topdir/scripts/handlebars.js",
                   11720:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11721:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11722:                          "$topdir/scripts/modernizr.js",
                   11723:                          "$topdir/scripts/player-min.js",
                   11724:                          "$topdir/scripts/swfobject.js",
                   11725:                          "$topdir/skins/",
                   11726:                          "$topdir/skins/configuration_express.xml",
                   11727:                          "$topdir/skins/express_show/",
                   11728:                          "$topdir/skins/express_show/player-min.css",
                   11729:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  11730:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   11731:                          "$topdir/$topdir.mp4",
                   11732:                          "$topdir/$topdir\_config.xml",
                   11733:                          "$topdir/$topdir\_controller.swf",
                   11734:                          "$topdir/$topdir\_embed.css",
                   11735:                          "$topdir/$topdir\_First_Frame.png",
                   11736:                          "$topdir/$topdir\_player.html",
                   11737:                          "$topdir/$topdir\_Thumbnails.png",
                   11738:                          "$topdir/playerProductInstall.swf",
                   11739:                          "$topdir/scripts/",
                   11740:                          "$topdir/scripts/config_xml.js",
                   11741:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   11742:                          "$topdir/skins/",
                   11743:                          "$topdir/skins/configuration_express.xml",
                   11744:                          "$topdir/skins/express_show/",
                   11745:                          "$topdir/skins/express_show/spritesheet.min.css",
                   11746:                          "$topdir/skins/express_show/spritesheet.png",
                   11747:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  11748:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11749:         if (@diffs == 0) {
1.1075.2.59  raeburn  11750:             $is_camtasia = 6;
                   11751:         } else {
1.1075.2.81  raeburn  11752:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  11753:             if (@diffs == 0) {
                   11754:                 $is_camtasia = 8;
1.1075.2.81  raeburn  11755:             } else {
                   11756:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   11757:                 if (@diffs == 0) {
                   11758:                     $is_camtasia = 8;
                   11759:                 }
1.1075.2.59  raeburn  11760:             }
1.1067    raeburn  11761:         }
                   11762:     }
                   11763:     my $output;
                   11764:     if ($is_camtasia) {
                   11765:         $output = <<"ENDCAM";
                   11766: <script type="text/javascript" language="Javascript">
                   11767: // <![CDATA[
                   11768: 
                   11769: function camtasiaToggle() {
                   11770:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   11771:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  11772:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  11773:                 document.getElementById('camtasia_titles').style.display='block';
                   11774:             } else {
                   11775:                 document.getElementById('camtasia_titles').style.display='none';
                   11776:             }
                   11777:         }
                   11778:     }
                   11779:     return;
                   11780: }
                   11781: 
                   11782: // ]]>
                   11783: </script>
                   11784: <p>$lt{'camt'}</p>
                   11785: ENDCAM
1.1065    raeburn  11786:     } else {
1.1067    raeburn  11787:         $output = '<p>'.$lt{'this'};
                   11788:         if ($info eq '') {
                   11789:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   11790:         } else {
                   11791:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   11792:                        '<div><pre>'.$info.'</pre></div>';
                   11793:         }
1.1065    raeburn  11794:     }
1.1067    raeburn  11795:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  11796:     my $duplicates;
                   11797:     my $num = 0;
                   11798:     if (ref($dirlist) eq 'ARRAY') {
                   11799:         foreach my $item (@{$dirlist}) {
                   11800:             if (ref($item) eq 'ARRAY') {
                   11801:                 if (exists($toplevel{$item->[0]})) {
                   11802:                     $duplicates .= 
                   11803:                         &start_data_table_row().
                   11804:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11805:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   11806:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11807:                         'value="1" />'.&mt('Yes').'</label>'.
                   11808:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   11809:                         '<td>'.$item->[0].'</td>';
                   11810:                     if ($item->[2]) {
                   11811:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   11812:                     } else {
                   11813:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   11814:                     }
                   11815:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   11816:                                    '<td>'.
                   11817:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   11818:                                    '</td>'.
                   11819:                                    &end_data_table_row();
                   11820:                     $num ++;
                   11821:                 }
                   11822:             }
                   11823:         }
                   11824:     }
                   11825:     my $itemcount;
                   11826:     if (@paths > 0) {
                   11827:         $itemcount = scalar(@paths);
                   11828:     } else {
                   11829:         $itemcount = 1;
                   11830:     }
1.1067    raeburn  11831:     if ($is_camtasia) {
                   11832:         $output .= $lt{'auto'}.'<br />'.
                   11833:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  11834:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  11835:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   11836:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   11837:                    $lt{'no'}.'</label></span><br />'.
                   11838:                    '<div id="camtasia_titles" style="display:block">'.
                   11839:                    &Apache::lonhtmlcommon::start_pick_box().
                   11840:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   11841:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   11842:                    &Apache::lonhtmlcommon::row_closure().
                   11843:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   11844:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   11845:                    &Apache::lonhtmlcommon::row_closure(1).
                   11846:                    &Apache::lonhtmlcommon::end_pick_box().
                   11847:                    '</div>';
                   11848:     }
1.1065    raeburn  11849:     $output .= 
                   11850:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  11851:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   11852:         "\n";
1.1065    raeburn  11853:     if ($duplicates ne '') {
                   11854:         $output .= '<p><span class="LC_warning">'.
                   11855:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   11856:                    &start_data_table().
                   11857:                    &start_data_table_header_row().
                   11858:                    '<th>'.&mt('Overwrite?').'</th>'.
                   11859:                    '<th>'.&mt('Name').'</th>'.
                   11860:                    '<th>'.&mt('Type').'</th>'.
                   11861:                    '<th>'.&mt('Size').'</th>'.
                   11862:                    '<th>'.&mt('Last modified').'</th>'.
                   11863:                    &end_data_table_header_row().
                   11864:                    $duplicates.
                   11865:                    &end_data_table().
                   11866:                    '</p>';
                   11867:     }
1.1067    raeburn  11868:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  11869:     if (ref($hiddenelements) eq 'HASH') {
                   11870:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   11871:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   11872:         }
                   11873:     }
                   11874:     $output .= <<"END";
1.1067    raeburn  11875: <br />
1.1053    raeburn  11876: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   11877: </form>
                   11878: $noextract
                   11879: END
                   11880:     return $output;
                   11881: }
                   11882: 
1.1065    raeburn  11883: sub decompression_utility {
                   11884:     my ($program) = @_;
                   11885:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   11886:     my $location;
                   11887:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   11888:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   11889:                          '/usr/sbin/') {
                   11890:             if (-x $dir.$program) {
                   11891:                 $location = $dir.$program;
                   11892:                 last;
                   11893:             }
                   11894:         }
                   11895:     }
                   11896:     return $location;
                   11897: }
                   11898: 
                   11899: sub list_archive_contents {
                   11900:     my ($file,$pathsref) = @_;
                   11901:     my (@cmd,$output);
                   11902:     my $needsregexp;
                   11903:     if ($file =~ /\.zip$/) {
                   11904:         @cmd = (&decompression_utility('unzip'),"-l");
                   11905:         $needsregexp = 1;
                   11906:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   11907:              ($file =~ /\.tgz$/)) {
                   11908:         @cmd = (&decompression_utility('tar'),"-ztf");
                   11909:     } elsif ($file =~ /\.tar\.bz2$/) {
                   11910:         @cmd = (&decompression_utility('tar'),"-jtf");
                   11911:     } elsif ($file =~ m|\.tar$|) {
                   11912:         @cmd = (&decompression_utility('tar'),"-tf");
                   11913:     }
                   11914:     if (@cmd) {
                   11915:         undef($!);
                   11916:         undef($@);
                   11917:         if (open(my $fh,"-|", @cmd, $file)) {
                   11918:             while (my $line = <$fh>) {
                   11919:                 $output .= $line;
                   11920:                 chomp($line);
                   11921:                 my $item;
                   11922:                 if ($needsregexp) {
                   11923:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   11924:                 } else {
                   11925:                     $item = $line;
                   11926:                 }
                   11927:                 if ($item ne '') {
                   11928:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   11929:                         push(@{$pathsref},$item);
                   11930:                     } 
                   11931:                 }
                   11932:             }
                   11933:             close($fh);
                   11934:         }
                   11935:     }
                   11936:     return $output;
                   11937: }
                   11938: 
1.1053    raeburn  11939: sub decompress_uploaded_file {
                   11940:     my ($file,$dir) = @_;
                   11941:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   11942:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   11943:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   11944:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   11945:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   11946:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   11947:     my $decompressed = $env{'cgi.decompressed'};
                   11948:     &Apache::lonnet::delenv('cgi.file');
                   11949:     &Apache::lonnet::delenv('cgi.dir');
                   11950:     &Apache::lonnet::delenv('cgi.decompressed');
                   11951:     return ($decompressed,$result);
                   11952: }
                   11953: 
1.1055    raeburn  11954: sub process_decompression {
                   11955:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   11956:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  11957:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  11958:         $error = &mt('Filename not a supported archive file type.').
                   11959:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  11960:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   11961:     } else {
                   11962:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11963:         if ($docuhome eq 'no_host') {
                   11964:             $error = &mt('Could not determine home server for course.');
                   11965:         } else {
                   11966:             my @ids=&Apache::lonnet::current_machine_ids();
                   11967:             my $currdir = "$dir_root/$destination";
                   11968:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11969:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   11970:                        "$dir_root/$destination";
                   11971:             } else {
                   11972:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   11973:                        "$dir_root/$docudom/$docuname/$destination";
                   11974:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   11975:                     $error = &mt('Archive file not found.');
                   11976:                 }
                   11977:             }
1.1065    raeburn  11978:             my (@to_overwrite,@to_skip);
                   11979:             if ($env{'form.archive_overwrite_total'} > 0) {
                   11980:                 my $total = $env{'form.archive_overwrite_total'};
                   11981:                 for (my $i=0; $i<$total; $i++) {
                   11982:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   11983:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   11984:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   11985:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   11986:                     }
                   11987:                 }
                   11988:             }
                   11989:             my $numskip = scalar(@to_skip);
                   11990:             if (($numskip > 0) && 
                   11991:                 ($numskip == $env{'form.archive_itemcount'})) {
                   11992:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   11993:             } elsif ($dir eq '') {
1.1055    raeburn  11994:                 $error = &mt('Directory containing archive file unavailable.');
                   11995:             } elsif (!$error) {
1.1065    raeburn  11996:                 my ($decompressed,$display);
                   11997:                 if ($numskip > 0) {
                   11998:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   11999:                     mkdir("$dir/$tempdir",0755);
                   12000:                     system("mv $dir/$file $dir/$tempdir/$file");
                   12001:                     ($decompressed,$display) = 
                   12002:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   12003:                     foreach my $item (@to_skip) {
                   12004:                         if (($item ne '') && ($item !~ /\.\./)) {
                   12005:                             if (-f "$dir/$tempdir/$item") { 
                   12006:                                 unlink("$dir/$tempdir/$item");
                   12007:                             } elsif (-d "$dir/$tempdir/$item") {
                   12008:                                 system("rm -rf $dir/$tempdir/$item");
                   12009:                             }
                   12010:                         }
                   12011:                     }
                   12012:                     system("mv $dir/$tempdir/* $dir");
                   12013:                     rmdir("$dir/$tempdir");   
                   12014:                 } else {
                   12015:                     ($decompressed,$display) = 
                   12016:                         &decompress_uploaded_file($file,$dir);
                   12017:                 }
1.1055    raeburn  12018:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12019:                     $output = '<p class="LC_info">'.
                   12020:                               &mt('Files extracted successfully from archive.').
                   12021:                               '</p>'."\n";
1.1055    raeburn  12022:                     my ($warning,$result,@contents);
                   12023:                     my ($newdirlistref,$newlisterror) =
                   12024:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12025:                                                  $docuname,1);
                   12026:                     my (%is_dir,%changes,@newitems);
                   12027:                     my $dirptr = 16384;
1.1065    raeburn  12028:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12029:                         foreach my $dir_line (@{$newdirlistref}) {
                   12030:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  12031:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   12032:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  12033:                                 push(@newitems,$item);
                   12034:                                 if ($dirptr&$testdir) {
                   12035:                                     $is_dir{$item} = 1;
                   12036:                                 }
                   12037:                                 $changes{$item} = 1;
                   12038:                             }
                   12039:                         }
                   12040:                     }
                   12041:                     if (keys(%changes) > 0) {
                   12042:                         foreach my $item (sort(@newitems)) {
                   12043:                             if ($changes{$item}) {
                   12044:                                 push(@contents,$item);
                   12045:                             }
                   12046:                         }
                   12047:                     }
                   12048:                     if (@contents > 0) {
1.1067    raeburn  12049:                         my $wantform;
                   12050:                         unless ($env{'form.autoextract_camtasia'}) {
                   12051:                             $wantform = 1;
                   12052:                         }
1.1056    raeburn  12053:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12054:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12055:                                                                 $currdir,\%is_dir,
                   12056:                                                                 \%children,\%parent,
1.1056    raeburn  12057:                                                                 \@contents,\%dirorder,
                   12058:                                                                 \%titles,$wantform);
1.1055    raeburn  12059:                         if ($datatable ne '') {
                   12060:                             $output .= &archive_options_form('decompressed',$datatable,
                   12061:                                                              $count,$hiddenelem);
1.1065    raeburn  12062:                             my $startcount = 6;
1.1055    raeburn  12063:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12064:                                                            \%titles,\%children);
1.1055    raeburn  12065:                         }
1.1067    raeburn  12066:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  12067:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12068:                             my %displayed;
                   12069:                             my $total = 1;
                   12070:                             $env{'form.archive_directory'} = [];
                   12071:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12072:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12073:                                 $path =~ s{/$}{};
                   12074:                                 my $item;
                   12075:                                 if ($path ne '') {
                   12076:                                     $item = "$path/$titles{$i}";
                   12077:                                 } else {
                   12078:                                     $item = $titles{$i};
                   12079:                                 }
                   12080:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12081:                                 if ($item eq $contents[0]) {
                   12082:                                     push(@{$env{'form.archive_directory'}},$i);
                   12083:                                     $env{'form.archive_'.$i} = 'display';
                   12084:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12085:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  12086:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12087:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  12088:                                     $env{'form.archive_'.$i} = 'display';
                   12089:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12090:                                     $displayed{'web'} = $i;
                   12091:                                 } else {
1.1075.2.59  raeburn  12092:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12093:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12094:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12095:                                         push(@{$env{'form.archive_directory'}},$i);
                   12096:                                     }
                   12097:                                     $env{'form.archive_'.$i} = 'dependency';
                   12098:                                 }
                   12099:                                 $total ++;
                   12100:                             }
                   12101:                             for (my $i=1; $i<$total; $i++) {
                   12102:                                 next if ($i == $displayed{'web'});
                   12103:                                 next if ($i == $displayed{'folder'});
                   12104:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12105:                             }
                   12106:                             $env{'form.phase'} = 'decompress_cleanup';
                   12107:                             $env{'form.archivedelete'} = 1;
                   12108:                             $env{'form.archive_count'} = $total-1;
                   12109:                             $output .=
                   12110:                                 &process_extracted_files('coursedocs',$docudom,
                   12111:                                                          $docuname,$destination,
                   12112:                                                          $dir_root,$hiddenelem);
                   12113:                         }
1.1055    raeburn  12114:                     } else {
                   12115:                         $warning = &mt('No new items extracted from archive file.');
                   12116:                     }
                   12117:                 } else {
                   12118:                     $output = $display;
                   12119:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12120:                 }
                   12121:             }
                   12122:         }
                   12123:     }
                   12124:     if ($error) {
                   12125:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12126:                    $error.'</p>'."\n";
                   12127:     }
                   12128:     if ($warning) {
                   12129:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12130:     }
                   12131:     return $output;
                   12132: }
                   12133: 
                   12134: sub get_extracted {
1.1056    raeburn  12135:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12136:         $titles,$wantform) = @_;
1.1055    raeburn  12137:     my $count = 0;
                   12138:     my $depth = 0;
                   12139:     my $datatable;
1.1056    raeburn  12140:     my @hierarchy;
1.1055    raeburn  12141:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12142:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12143:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12144:     foreach my $item (@{$contents}) {
                   12145:         $count ++;
1.1056    raeburn  12146:         @{$dirorder->{$count}} = @hierarchy;
                   12147:         $titles->{$count} = $item;
1.1055    raeburn  12148:         &archive_hierarchy($depth,$count,$parent,$children);
                   12149:         if ($wantform) {
                   12150:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12151:                                        $currdir,$depth,$count);
                   12152:         }
                   12153:         if ($is_dir->{$item}) {
                   12154:             $depth ++;
1.1056    raeburn  12155:             push(@hierarchy,$count);
                   12156:             $parent->{$depth} = $count;
1.1055    raeburn  12157:             $datatable .=
                   12158:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12159:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12160:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12161:             $depth --;
1.1056    raeburn  12162:             pop(@hierarchy);
1.1055    raeburn  12163:         }
                   12164:     }
                   12165:     return ($count,$datatable);
                   12166: }
                   12167: 
                   12168: sub recurse_extracted_archive {
1.1056    raeburn  12169:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12170:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12171:     my $result='';
1.1056    raeburn  12172:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12173:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12174:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12175:         return $result;
                   12176:     }
                   12177:     my $dirptr = 16384;
                   12178:     my ($newdirlistref,$newlisterror) =
                   12179:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12180:     if (ref($newdirlistref) eq 'ARRAY') {
                   12181:         foreach my $dir_line (@{$newdirlistref}) {
                   12182:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12183:             unless ($item =~ /^\.+$/) {
                   12184:                 $$count ++;
1.1056    raeburn  12185:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12186:                 $titles->{$$count} = $item;
1.1055    raeburn  12187:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12188: 
1.1055    raeburn  12189:                 my $is_dir;
                   12190:                 if ($dirptr&$testdir) {
                   12191:                     $is_dir = 1;
                   12192:                 }
                   12193:                 if ($wantform) {
                   12194:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12195:                 }
                   12196:                 if ($is_dir) {
                   12197:                     $$depth ++;
1.1056    raeburn  12198:                     push(@{$hierarchy},$$count);
                   12199:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12200:                     $result .=
                   12201:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12202:                                                    $docuname,$depth,$count,
1.1056    raeburn  12203:                                                    $hierarchy,$dirorder,$children,
                   12204:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12205:                     $$depth --;
1.1056    raeburn  12206:                     pop(@{$hierarchy});
1.1055    raeburn  12207:                 }
                   12208:             }
                   12209:         }
                   12210:     }
                   12211:     return $result;
                   12212: }
                   12213: 
                   12214: sub archive_hierarchy {
                   12215:     my ($depth,$count,$parent,$children) =@_;
                   12216:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12217:         if (exists($parent->{$depth})) {
                   12218:              $children->{$parent->{$depth}} .= $count.':';
                   12219:         }
                   12220:     }
                   12221:     return;
                   12222: }
                   12223: 
                   12224: sub archive_row {
                   12225:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12226:     my ($name) = ($item =~ m{([^/]+)$});
                   12227:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12228:                                        'display'    => 'Add as file',
1.1055    raeburn  12229:                                        'dependency' => 'Include as dependency',
                   12230:                                        'discard'    => 'Discard',
                   12231:                                       );
                   12232:     if ($is_dir) {
1.1059    raeburn  12233:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12234:     }
1.1056    raeburn  12235:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12236:     my $offset = 0;
1.1055    raeburn  12237:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12238:         $offset ++;
1.1065    raeburn  12239:         if ($action ne 'display') {
                   12240:             $offset ++;
                   12241:         }  
1.1055    raeburn  12242:         $output .= '<td><span class="LC_nobreak">'.
                   12243:                    '<label><input type="radio" name="archive_'.$count.
                   12244:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12245:         my $text = $choices{$action};
                   12246:         if ($is_dir) {
                   12247:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12248:             if ($action eq 'display') {
1.1059    raeburn  12249:                 $text = &mt('Add as folder');
1.1055    raeburn  12250:             }
1.1056    raeburn  12251:         } else {
                   12252:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12253: 
                   12254:         }
                   12255:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12256:         if ($action eq 'dependency') {
                   12257:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12258:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12259:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12260:                        '<option value=""></option>'."\n".
                   12261:                        '</select>'."\n".
                   12262:                        '</div>';
1.1059    raeburn  12263:         } elsif ($action eq 'display') {
                   12264:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12265:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12266:                        '</div>';
1.1055    raeburn  12267:         }
1.1056    raeburn  12268:         $output .= '</td>';
1.1055    raeburn  12269:     }
                   12270:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12271:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12272:     for (my $i=0; $i<$depth; $i++) {
                   12273:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12274:     }
                   12275:     if ($is_dir) {
                   12276:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12277:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12278:     } else {
                   12279:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12280:     }
                   12281:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12282:                &end_data_table_row();
                   12283:     return $output;
                   12284: }
                   12285: 
                   12286: sub archive_options_form {
1.1065    raeburn  12287:     my ($form,$display,$count,$hiddenelem) = @_;
                   12288:     my %lt = &Apache::lonlocal::texthash(
                   12289:                perm => 'Permanently remove archive file?',
                   12290:                hows => 'How should each extracted item be incorporated in the course?',
                   12291:                cont => 'Content actions for all',
                   12292:                addf => 'Add as folder/file',
                   12293:                incd => 'Include as dependency for a displayed file',
                   12294:                disc => 'Discard',
                   12295:                no   => 'No',
                   12296:                yes  => 'Yes',
                   12297:                save => 'Save',
                   12298:     );
                   12299:     my $output = <<"END";
                   12300: <form name="$form" method="post" action="">
                   12301: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12302: <label>
                   12303:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12304: </label>
                   12305: &nbsp;
                   12306: <label>
                   12307:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12308: </span>
                   12309: </p>
                   12310: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12311: <br />$lt{'hows'}
                   12312: <div class="LC_columnSection">
                   12313:   <fieldset>
                   12314:     <legend>$lt{'cont'}</legend>
                   12315:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12316:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12317:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12318:   </fieldset>
                   12319: </div>
                   12320: END
                   12321:     return $output.
1.1055    raeburn  12322:            &start_data_table()."\n".
1.1065    raeburn  12323:            $display."\n".
1.1055    raeburn  12324:            &end_data_table()."\n".
                   12325:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12326:            $hiddenelem.
1.1065    raeburn  12327:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12328:            '</form>';
                   12329: }
                   12330: 
                   12331: sub archive_javascript {
1.1056    raeburn  12332:     my ($startcount,$numitems,$titles,$children) = @_;
                   12333:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12334:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12335:     my $scripttag = <<START;
                   12336: <script type="text/javascript">
                   12337: // <![CDATA[
                   12338: 
                   12339: function checkAll(form,prefix) {
                   12340:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12341:     for (var i=0; i < form.elements.length; i++) {
                   12342:         var id = form.elements[i].id;
                   12343:         if ((id != '') && (id != undefined)) {
                   12344:             if (idstr.test(id)) {
                   12345:                 if (form.elements[i].type == 'radio') {
                   12346:                     form.elements[i].checked = true;
1.1056    raeburn  12347:                     var nostart = i-$startcount;
1.1059    raeburn  12348:                     var offset = nostart%7;
                   12349:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12350:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12351:                 }
                   12352:             }
                   12353:         }
                   12354:     }
                   12355: }
                   12356: 
                   12357: function propagateCheck(form,count) {
                   12358:     if (count > 0) {
1.1059    raeburn  12359:         var startelement = $startcount + ((count-1) * 7);
                   12360:         for (var j=1; j<6; j++) {
                   12361:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12362:                 var item = startelement + j; 
                   12363:                 if (form.elements[item].type == 'radio') {
                   12364:                     if (form.elements[item].checked) {
                   12365:                         containerCheck(form,count,j);
                   12366:                         break;
                   12367:                     }
1.1055    raeburn  12368:                 }
                   12369:             }
                   12370:         }
                   12371:     }
                   12372: }
                   12373: 
                   12374: numitems = $numitems
1.1056    raeburn  12375: var titles = new Array(numitems);
                   12376: var parents = new Array(numitems);
1.1055    raeburn  12377: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12378:     parents[i] = new Array;
1.1055    raeburn  12379: }
1.1059    raeburn  12380: var maintitle = '$maintitle';
1.1055    raeburn  12381: 
                   12382: START
                   12383: 
1.1056    raeburn  12384:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12385:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12386:         for (my $i=0; $i<@contents; $i ++) {
                   12387:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12388:         }
                   12389:     }
                   12390: 
1.1056    raeburn  12391:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12392:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12393:     }
                   12394: 
1.1055    raeburn  12395:     $scripttag .= <<END;
                   12396: 
                   12397: function containerCheck(form,count,offset) {
                   12398:     if (count > 0) {
1.1056    raeburn  12399:         dependencyCheck(form,count,offset);
1.1059    raeburn  12400:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12401:         form.elements[item].checked = true;
                   12402:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12403:             if (parents[count].length > 0) {
                   12404:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12405:                     containerCheck(form,parents[count][j],offset);
                   12406:                 }
                   12407:             }
                   12408:         }
                   12409:     }
                   12410: }
                   12411: 
                   12412: function dependencyCheck(form,count,offset) {
                   12413:     if (count > 0) {
1.1059    raeburn  12414:         var chosen = (offset+$startcount)+7*(count-1);
                   12415:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12416:         var currtype = form.elements[depitem].type;
                   12417:         if (form.elements[chosen].value == 'dependency') {
                   12418:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12419:             form.elements[depitem].options.length = 0;
                   12420:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  12421:             for (var i=1; i<=numitems; i++) {
                   12422:                 if (i == count) {
                   12423:                     continue;
                   12424:                 }
1.1059    raeburn  12425:                 var startelement = $startcount + (i-1) * 7;
                   12426:                 for (var j=1; j<6; j++) {
                   12427:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12428:                         var item = startelement + j;
                   12429:                         if (form.elements[item].type == 'radio') {
                   12430:                             if (form.elements[item].checked) {
                   12431:                                 if (form.elements[item].value == 'display') {
                   12432:                                     var n = form.elements[depitem].options.length;
                   12433:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12434:                                 }
                   12435:                             }
                   12436:                         }
                   12437:                     }
                   12438:                 }
                   12439:             }
                   12440:         } else {
                   12441:             document.getElementById('arc_depon_'+count).style.display='none';
                   12442:             form.elements[depitem].options.length = 0;
                   12443:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12444:         }
1.1059    raeburn  12445:         titleCheck(form,count,offset);
1.1056    raeburn  12446:     }
                   12447: }
                   12448: 
                   12449: function propagateSelect(form,count,offset) {
                   12450:     if (count > 0) {
1.1065    raeburn  12451:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12452:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12453:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12454:             if (parents[count].length > 0) {
                   12455:                 for (var j=0; j<parents[count].length; j++) {
                   12456:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12457:                 }
                   12458:             }
                   12459:         }
                   12460:     }
                   12461: }
1.1056    raeburn  12462: 
                   12463: function containerSelect(form,count,offset,picked) {
                   12464:     if (count > 0) {
1.1065    raeburn  12465:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12466:         if (form.elements[item].type == 'radio') {
                   12467:             if (form.elements[item].value == 'dependency') {
                   12468:                 if (form.elements[item+1].type == 'select-one') {
                   12469:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12470:                         if (form.elements[item+1].options[i].value == picked) {
                   12471:                             form.elements[item+1].selectedIndex = i;
                   12472:                             break;
                   12473:                         }
                   12474:                     }
                   12475:                 }
                   12476:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12477:                     if (parents[count].length > 0) {
                   12478:                         for (var j=0; j<parents[count].length; j++) {
                   12479:                             containerSelect(form,parents[count][j],offset,picked);
                   12480:                         }
                   12481:                     }
                   12482:                 }
                   12483:             }
                   12484:         }
                   12485:     }
                   12486: }
                   12487: 
1.1059    raeburn  12488: function titleCheck(form,count,offset) {
                   12489:     if (count > 0) {
                   12490:         var chosen = (offset+$startcount)+7*(count-1);
                   12491:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12492:         var currtype = form.elements[depitem].type;
                   12493:         if (form.elements[chosen].value == 'display') {
                   12494:             document.getElementById('arc_title_'+count).style.display='block';
                   12495:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12496:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12497:             }
                   12498:         } else {
                   12499:             document.getElementById('arc_title_'+count).style.display='none';
                   12500:             if (currtype == 'text') { 
                   12501:                 document.getElementById('archive_title_'+count).value='';
                   12502:             }
                   12503:         }
                   12504:     }
                   12505:     return;
                   12506: }
                   12507: 
1.1055    raeburn  12508: // ]]>
                   12509: </script>
                   12510: END
                   12511:     return $scripttag;
                   12512: }
                   12513: 
                   12514: sub process_extracted_files {
1.1067    raeburn  12515:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12516:     my $numitems = $env{'form.archive_count'};
                   12517:     return unless ($numitems);
                   12518:     my @ids=&Apache::lonnet::current_machine_ids();
                   12519:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12520:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12521:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12522:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12523:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12524:         $pathtocheck = "$dir_root/$destination";
                   12525:         $dir = $dir_root;
                   12526:         $ishome = 1;
                   12527:     } else {
                   12528:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12529:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   12530:         $dir = "$dir_root/$docudom/$docuname";    
                   12531:     }
                   12532:     my $currdir = "$dir_root/$destination";
                   12533:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12534:     if ($env{'form.folderpath'}) {
                   12535:         my @items = split('&',$env{'form.folderpath'});
                   12536:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  12537:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12538:             $containers{'0'}='page';
                   12539:         } else {
                   12540:             $containers{'0'}='sequence';
                   12541:         }
1.1055    raeburn  12542:     }
                   12543:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12544:     if ($numitems) {
                   12545:         for (my $i=1; $i<=$numitems; $i++) {
                   12546:             my $path = $env{'form.archive_content_'.$i};
                   12547:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12548:                 my $item = $1;
                   12549:                 $toplevelitems{$item} = $i;
                   12550:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12551:                     $is_dir{$item} = 1;
                   12552:                 }
                   12553:             }
                   12554:         }
                   12555:     }
1.1067    raeburn  12556:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12557:     if (keys(%toplevelitems) > 0) {
                   12558:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12559:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12560:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12561:     }
1.1066    raeburn  12562:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12563:     if ($numitems) {
                   12564:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  12565:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12566:             my $path = $env{'form.archive_content_'.$i};
                   12567:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12568:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12569:                     if ($prefix ne '' && $path ne '') {
                   12570:                         if (-e $prefix.$path) {
1.1066    raeburn  12571:                             if ((@archdirs > 0) && 
                   12572:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12573:                                 $todeletedir{$prefix.$path} = 1;
                   12574:                             } else {
                   12575:                                 $todelete{$prefix.$path} = 1;
                   12576:                             }
1.1055    raeburn  12577:                         }
                   12578:                     }
                   12579:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12580:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12581:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12582:                     $docstitle = $env{'form.archive_title_'.$i};
                   12583:                     if ($docstitle eq '') {
                   12584:                         $docstitle = $title;
                   12585:                     }
1.1055    raeburn  12586:                     $outer = 0;
1.1056    raeburn  12587:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12588:                         if (@{$dirorder{$i}} > 0) {
                   12589:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12590:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12591:                                     $outer = $item;
                   12592:                                     last;
                   12593:                                 }
                   12594:                             }
                   12595:                         }
                   12596:                     }
                   12597:                     my ($errtext,$fatal) = 
                   12598:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12599:                                                '/'.$folders{$outer}.'.'.
                   12600:                                                $containers{$outer});
                   12601:                     next if ($fatal);
                   12602:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12603:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12604:                             $mapinner{$i} = time;
1.1055    raeburn  12605:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12606:                             $containers{$i} = 'sequence';
                   12607:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12608:                                       $folders{$i}.'.'.$containers{$i};
                   12609:                             my $newidx = &LONCAPA::map::getresidx();
                   12610:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12611:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12612:                             push(@LONCAPA::map::order,$newidx);
                   12613:                             my ($outtext,$errtext) =
                   12614:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12615:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12616:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12617:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12618:                             unless ($errtext) {
                   12619:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   12620:                             }
1.1055    raeburn  12621:                         }
                   12622:                     } else {
                   12623:                         if ($context eq 'coursedocs') {
                   12624:                             my $newidx=&LONCAPA::map::getresidx();
                   12625:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12626:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12627:                                       $title;
                   12628:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12629:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   12630:                             }
                   12631:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12632:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12633:                             }
                   12634:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12635:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  12636:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  12637:                                 unless ($ishome) {
                   12638:                                     my $fetch = "$newdest{$i}/$title";
                   12639:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   12640:                                     $prompttofetch{$fetch} = 1;
                   12641:                                 }
1.1055    raeburn  12642:                             }
                   12643:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12644:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12645:                             push(@LONCAPA::map::order, $newidx);
                   12646:                             my ($outtext,$errtext)=
                   12647:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12648:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12649:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  12650:                             unless ($errtext) {
                   12651:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12652:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   12653:                                 }
                   12654:                             }
1.1055    raeburn  12655:                         }
                   12656:                     }
1.1075.2.11  raeburn  12657:                 }
                   12658:             } else {
                   12659:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
                   12660:             }
                   12661:         }
                   12662:         for (my $i=1; $i<=$numitems; $i++) {
                   12663:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12664:             my $path = $env{'form.archive_content_'.$i};
                   12665:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12666:                 my ($title) = ($path =~ m{/([^/]+)$});
                   12667:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   12668:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   12669:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12670:                         my ($itemidx,$fullpath,$relpath);
                   12671:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   12672:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  12673:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  12674:                                 if ($dirorder{$i}->[$j] eq $container) {
                   12675:                                     $itemidx = $j;
1.1056    raeburn  12676:                                 }
                   12677:                             }
1.1075.2.11  raeburn  12678:                         }
                   12679:                         if ($itemidx eq '') {
                   12680:                             $itemidx =  0;
                   12681:                         }
                   12682:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   12683:                             if ($mapinner{$referrer{$i}}) {
                   12684:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   12685:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12686:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12687:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12688:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12689:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12690:                                             if (!-e $fullpath) {
                   12691:                                                 mkdir($fullpath,0755);
1.1056    raeburn  12692:                                             }
                   12693:                                         }
1.1075.2.11  raeburn  12694:                                     } else {
                   12695:                                         last;
1.1056    raeburn  12696:                                     }
1.1075.2.11  raeburn  12697:                                 }
                   12698:                             }
                   12699:                         } elsif ($newdest{$referrer{$i}}) {
                   12700:                             $fullpath = $newdest{$referrer{$i}};
                   12701:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12702:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   12703:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   12704:                                     last;
                   12705:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12706:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12707:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12708:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12709:                                         if (!-e $fullpath) {
                   12710:                                             mkdir($fullpath,0755);
1.1056    raeburn  12711:                                         }
                   12712:                                     }
1.1075.2.11  raeburn  12713:                                 } else {
                   12714:                                     last;
1.1056    raeburn  12715:                                 }
1.1075.2.11  raeburn  12716:                             }
                   12717:                         }
                   12718:                         if ($fullpath ne '') {
                   12719:                             if (-e "$prefix$path") {
                   12720:                                 system("mv $prefix$path $fullpath/$title");
                   12721:                             }
                   12722:                             if (-e "$fullpath/$title") {
                   12723:                                 my $showpath;
                   12724:                                 if ($relpath ne '') {
                   12725:                                     $showpath = "$relpath/$title";
                   12726:                                 } else {
                   12727:                                     $showpath = "/$title";
1.1056    raeburn  12728:                                 }
1.1075.2.11  raeburn  12729:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   12730:                             }
                   12731:                             unless ($ishome) {
                   12732:                                 my $fetch = "$fullpath/$title";
                   12733:                                 $fetch =~ s/^\Q$prefix$dir\E//;
                   12734:                                 $prompttofetch{$fetch} = 1;
1.1055    raeburn  12735:                             }
                   12736:                         }
                   12737:                     }
1.1075.2.11  raeburn  12738:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   12739:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   12740:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  12741:                 }
                   12742:             } else {
1.1075.2.11  raeburn  12743:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
1.1055    raeburn  12744:             }
                   12745:         }
                   12746:         if (keys(%todelete)) {
                   12747:             foreach my $key (keys(%todelete)) {
                   12748:                 unlink($key);
1.1066    raeburn  12749:             }
                   12750:         }
                   12751:         if (keys(%todeletedir)) {
                   12752:             foreach my $key (keys(%todeletedir)) {
                   12753:                 rmdir($key);
                   12754:             }
                   12755:         }
                   12756:         foreach my $dir (sort(keys(%is_dir))) {
                   12757:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   12758:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  12759:             }
                   12760:         }
1.1067    raeburn  12761:         if ($result ne '') {
                   12762:             $output .= '<ul>'."\n".
                   12763:                        $result."\n".
                   12764:                        '</ul>';
                   12765:         }
                   12766:         unless ($ishome) {
                   12767:             my $replicationfail;
                   12768:             foreach my $item (keys(%prompttofetch)) {
                   12769:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   12770:                 unless ($fetchresult eq 'ok') {
                   12771:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   12772:                 }
                   12773:             }
                   12774:             if ($replicationfail) {
                   12775:                 $output .= '<p class="LC_error">'.
                   12776:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   12777:                            $replicationfail.
                   12778:                            '</ul></p>';
                   12779:             }
                   12780:         }
1.1055    raeburn  12781:     } else {
                   12782:         $warning = &mt('No items found in archive.');
                   12783:     }
                   12784:     if ($error) {
                   12785:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12786:                    $error.'</p>'."\n";
                   12787:     }
                   12788:     if ($warning) {
                   12789:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12790:     }
                   12791:     return $output;
                   12792: }
                   12793: 
1.1066    raeburn  12794: sub cleanup_empty_dirs {
                   12795:     my ($path) = @_;
                   12796:     if (($path ne '') && (-d $path)) {
                   12797:         if (opendir(my $dirh,$path)) {
                   12798:             my @dircontents = grep(!/^\./,readdir($dirh));
                   12799:             my $numitems = 0;
                   12800:             foreach my $item (@dircontents) {
                   12801:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  12802:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  12803:                     if (-e "$path/$item") {
                   12804:                         $numitems ++;
                   12805:                     }
                   12806:                 } else {
                   12807:                     $numitems ++;
                   12808:                 }
                   12809:             }
                   12810:             if ($numitems == 0) {
                   12811:                 rmdir($path);
                   12812:             }
                   12813:             closedir($dirh);
                   12814:         }
                   12815:     }
                   12816:     return;
                   12817: }
                   12818: 
1.41      ng       12819: =pod
1.45      matthew  12820: 
1.1075.2.56  raeburn  12821: =item * &get_folder_hierarchy()
1.1068    raeburn  12822: 
                   12823: Provides hierarchy of names of folders/sub-folders containing the current
                   12824: item,
                   12825: 
                   12826: Inputs: 3
                   12827:      - $navmap - navmaps object
                   12828: 
                   12829:      - $map - url for map (either the trigger itself, or map containing
                   12830:                            the resource, which is the trigger).
                   12831: 
                   12832:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   12833: 
                   12834: Outputs: 1 @pathitems - array of folder/subfolder names.
                   12835: 
                   12836: =cut
                   12837: 
                   12838: sub get_folder_hierarchy {
                   12839:     my ($navmap,$map,$showitem) = @_;
                   12840:     my @pathitems;
                   12841:     if (ref($navmap)) {
                   12842:         my $mapres = $navmap->getResourceByUrl($map);
                   12843:         if (ref($mapres)) {
                   12844:             my $pcslist = $mapres->map_hierarchy();
                   12845:             if ($pcslist ne '') {
                   12846:                 my @pcs = split(/,/,$pcslist);
                   12847:                 foreach my $pc (@pcs) {
                   12848:                     if ($pc == 1) {
1.1075.2.38  raeburn  12849:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  12850:                     } else {
                   12851:                         my $res = $navmap->getByMapPc($pc);
                   12852:                         if (ref($res)) {
                   12853:                             my $title = $res->compTitle();
                   12854:                             $title =~ s/\W+/_/g;
                   12855:                             if ($title ne '') {
                   12856:                                 push(@pathitems,$title);
                   12857:                             }
                   12858:                         }
                   12859:                     }
                   12860:                 }
                   12861:             }
1.1071    raeburn  12862:             if ($showitem) {
                   12863:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  12864:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  12865:                 } else {
                   12866:                     my $maptitle = $mapres->compTitle();
                   12867:                     $maptitle =~ s/\W+/_/g;
                   12868:                     if ($maptitle ne '') {
                   12869:                         push(@pathitems,$maptitle);
                   12870:                     }
1.1068    raeburn  12871:                 }
                   12872:             }
                   12873:         }
                   12874:     }
                   12875:     return @pathitems;
                   12876: }
                   12877: 
                   12878: =pod
                   12879: 
1.1015    raeburn  12880: =item * &get_turnedin_filepath()
                   12881: 
                   12882: Determines path in a user's portfolio file for storage of files uploaded
                   12883: to a specific essayresponse or dropbox item.
                   12884: 
                   12885: Inputs: 3 required + 1 optional.
                   12886: $symb is symb for resource, $uname and $udom are for current user (required).
                   12887: $caller is optional (can be "submission", if routine is called when storing
                   12888: an upoaded file when "Submit Answer" button was pressed).
                   12889: 
                   12890: Returns array containing $path and $multiresp. 
                   12891: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   12892: than one file upload item.  Callers of routine should append partid as a 
                   12893: subdirectory to $path in cases where $multiresp is 1.
                   12894: 
                   12895: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   12896: 
                   12897: =cut
                   12898: 
                   12899: sub get_turnedin_filepath {
                   12900:     my ($symb,$uname,$udom,$caller) = @_;
                   12901:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   12902:     my $turnindir;
                   12903:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   12904:     $turnindir = $userhash{'turnindir'};
                   12905:     my ($path,$multiresp);
                   12906:     if ($turnindir eq '') {
                   12907:         if ($caller eq 'submission') {
                   12908:             $turnindir = &mt('turned in');
                   12909:             $turnindir =~ s/\W+/_/g;
                   12910:             my %newhash = (
                   12911:                             'turnindir' => $turnindir,
                   12912:                           );
                   12913:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   12914:         }
                   12915:     }
                   12916:     if ($turnindir ne '') {
                   12917:         $path = '/'.$turnindir.'/';
                   12918:         my ($multipart,$turnin,@pathitems);
                   12919:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12920:         if (defined($navmap)) {
                   12921:             my $mapres = $navmap->getResourceByUrl($map);
                   12922:             if (ref($mapres)) {
                   12923:                 my $pcslist = $mapres->map_hierarchy();
                   12924:                 if ($pcslist ne '') {
                   12925:                     foreach my $pc (split(/,/,$pcslist)) {
                   12926:                         my $res = $navmap->getByMapPc($pc);
                   12927:                         if (ref($res)) {
                   12928:                             my $title = $res->compTitle();
                   12929:                             $title =~ s/\W+/_/g;
                   12930:                             if ($title ne '') {
1.1075.2.48  raeburn  12931:                                 if (($pc > 1) && (length($title) > 12)) {
                   12932:                                     $title = substr($title,0,12);
                   12933:                                 }
1.1015    raeburn  12934:                                 push(@pathitems,$title);
                   12935:                             }
                   12936:                         }
                   12937:                     }
                   12938:                 }
                   12939:                 my $maptitle = $mapres->compTitle();
                   12940:                 $maptitle =~ s/\W+/_/g;
                   12941:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  12942:                     if (length($maptitle) > 12) {
                   12943:                         $maptitle = substr($maptitle,0,12);
                   12944:                     }
1.1015    raeburn  12945:                     push(@pathitems,$maptitle);
                   12946:                 }
                   12947:                 unless ($env{'request.state'} eq 'construct') {
                   12948:                     my $res = $navmap->getBySymb($symb);
                   12949:                     if (ref($res)) {
                   12950:                         my $partlist = $res->parts();
                   12951:                         my $totaluploads = 0;
                   12952:                         if (ref($partlist) eq 'ARRAY') {
                   12953:                             foreach my $part (@{$partlist}) {
                   12954:                                 my @types = $res->responseType($part);
                   12955:                                 my @ids = $res->responseIds($part);
                   12956:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   12957:                                     if ($types[$i] eq 'essay') {
                   12958:                                         my $partid = $part.'_'.$ids[$i];
                   12959:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   12960:                                             $totaluploads ++;
                   12961:                                         }
                   12962:                                     }
                   12963:                                 }
                   12964:                             }
                   12965:                             if ($totaluploads > 1) {
                   12966:                                 $multiresp = 1;
                   12967:                             }
                   12968:                         }
                   12969:                     }
                   12970:                 }
                   12971:             } else {
                   12972:                 return;
                   12973:             }
                   12974:         } else {
                   12975:             return;
                   12976:         }
                   12977:         my $restitle=&Apache::lonnet::gettitle($symb);
                   12978:         $restitle =~ s/\W+/_/g;
                   12979:         if ($restitle eq '') {
                   12980:             $restitle = ($resurl =~ m{/[^/]+$});
                   12981:             if ($restitle eq '') {
                   12982:                 $restitle = time;
                   12983:             }
                   12984:         }
1.1075.2.48  raeburn  12985:         if (length($restitle) > 12) {
                   12986:             $restitle = substr($restitle,0,12);
                   12987:         }
1.1015    raeburn  12988:         push(@pathitems,$restitle);
                   12989:         $path .= join('/',@pathitems);
                   12990:     }
                   12991:     return ($path,$multiresp);
                   12992: }
                   12993: 
                   12994: =pod
                   12995: 
1.464     albertel 12996: =back
1.41      ng       12997: 
1.112     bowersj2 12998: =head1 CSV Upload/Handling functions
1.38      albertel 12999: 
1.41      ng       13000: =over 4
                   13001: 
1.648     raeburn  13002: =item * &upfile_store($r)
1.41      ng       13003: 
                   13004: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13005: needs $env{'form.upfile'}
1.41      ng       13006: returns $datatoken to be put into hidden field
                   13007: 
                   13008: =cut
1.31      albertel 13009: 
                   13010: sub upfile_store {
                   13011:     my $r=shift;
1.258     albertel 13012:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13013:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13014:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13015:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13016: 
1.258     albertel 13017:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   13018: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 13019:     {
1.158     raeburn  13020:         my $datafile = $r->dir_config('lonDaemons').
                   13021:                            '/tmp/'.$datatoken.'.tmp';
                   13022:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 13023:             print $fh $env{'form.upfile'};
1.158     raeburn  13024:             close($fh);
                   13025:         }
1.31      albertel 13026:     }
                   13027:     return $datatoken;
                   13028: }
                   13029: 
1.56      matthew  13030: =pod
                   13031: 
1.648     raeburn  13032: =item * &load_tmp_file($r)
1.41      ng       13033: 
                   13034: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 13035: needs $env{'form.datatoken'},
                   13036: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13037: 
                   13038: =cut
1.31      albertel 13039: 
                   13040: sub load_tmp_file {
                   13041:     my $r=shift;
                   13042:     my @studentdata=();
                   13043:     {
1.158     raeburn  13044:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 13045:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  13046:         if ( open(my $fh,"<$studentfile") ) {
                   13047:             @studentdata=<$fh>;
                   13048:             close($fh);
                   13049:         }
1.31      albertel 13050:     }
1.258     albertel 13051:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13052: }
                   13053: 
1.56      matthew  13054: =pod
                   13055: 
1.648     raeburn  13056: =item * &upfile_record_sep()
1.41      ng       13057: 
                   13058: Separate uploaded file into records
                   13059: returns array of records,
1.258     albertel 13060: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13061: 
                   13062: =cut
1.31      albertel 13063: 
                   13064: sub upfile_record_sep {
1.258     albertel 13065:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13066:     } else {
1.248     albertel 13067: 	my @records;
1.258     albertel 13068: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13069: 	    if ($line=~/^\s*$/) { next; }
                   13070: 	    push(@records,$line);
                   13071: 	}
                   13072: 	return @records;
1.31      albertel 13073:     }
                   13074: }
                   13075: 
1.56      matthew  13076: =pod
                   13077: 
1.648     raeburn  13078: =item * &record_sep($record)
1.41      ng       13079: 
1.258     albertel 13080: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13081: 
                   13082: =cut
                   13083: 
1.263     www      13084: sub takeleft {
                   13085:     my $index=shift;
                   13086:     return substr('0000'.$index,-4,4);
                   13087: }
                   13088: 
1.31      albertel 13089: sub record_sep {
                   13090:     my $record=shift;
                   13091:     my %components=();
1.258     albertel 13092:     if ($env{'form.upfiletype'} eq 'xml') {
                   13093:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13094:         my $i=0;
1.356     albertel 13095:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13096:             $field=~s/^(\"|\')//;
                   13097:             $field=~s/(\"|\')$//;
1.263     www      13098:             $components{&takeleft($i)}=$field;
1.31      albertel 13099:             $i++;
                   13100:         }
1.258     albertel 13101:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13102:         my $i=0;
1.356     albertel 13103:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13104:             $field=~s/^(\"|\')//;
                   13105:             $field=~s/(\"|\')$//;
1.263     www      13106:             $components{&takeleft($i)}=$field;
1.31      albertel 13107:             $i++;
                   13108:         }
                   13109:     } else {
1.561     www      13110:         my $separator=',';
1.480     banghart 13111:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13112:             $separator=';';
1.480     banghart 13113:         }
1.31      albertel 13114:         my $i=0;
1.561     www      13115: # the character we are looking for to indicate the end of a quote or a record 
                   13116:         my $looking_for=$separator;
                   13117: # do not add the characters to the fields
                   13118:         my $ignore=0;
                   13119: # we just encountered a separator (or the beginning of the record)
                   13120:         my $just_found_separator=1;
                   13121: # store the field we are working on here
                   13122:         my $field='';
                   13123: # work our way through all characters in record
                   13124:         foreach my $character ($record=~/(.)/g) {
                   13125:             if ($character eq $looking_for) {
                   13126:                if ($character ne $separator) {
                   13127: # Found the end of a quote, again looking for separator
                   13128:                   $looking_for=$separator;
                   13129:                   $ignore=1;
                   13130:                } else {
                   13131: # Found a separator, store away what we got
                   13132:                   $components{&takeleft($i)}=$field;
                   13133: 	          $i++;
                   13134:                   $just_found_separator=1;
                   13135:                   $ignore=0;
                   13136:                   $field='';
                   13137:                }
                   13138:                next;
                   13139:             }
                   13140: # single or double quotation marks after a separator indicate beginning of a quote
                   13141: # we are now looking for the end of the quote and need to ignore separators
                   13142:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13143:                $looking_for=$character;
                   13144:                next;
                   13145:             }
                   13146: # ignore would be true after we reached the end of a quote
                   13147:             if ($ignore) { next; }
                   13148:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13149:             $field.=$character;
                   13150:             $just_found_separator=0; 
1.31      albertel 13151:         }
1.561     www      13152: # catch the very last entry, since we never encountered the separator
                   13153:         $components{&takeleft($i)}=$field;
1.31      albertel 13154:     }
                   13155:     return %components;
                   13156: }
                   13157: 
1.144     matthew  13158: ######################################################
                   13159: ######################################################
                   13160: 
1.56      matthew  13161: =pod
                   13162: 
1.648     raeburn  13163: =item * &upfile_select_html()
1.41      ng       13164: 
1.144     matthew  13165: Return HTML code to select a file from the users machine and specify 
                   13166: the file type.
1.41      ng       13167: 
                   13168: =cut
                   13169: 
1.144     matthew  13170: ######################################################
                   13171: ######################################################
1.31      albertel 13172: sub upfile_select_html {
1.144     matthew  13173:     my %Types = (
                   13174:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13175:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13176:                  space => &mt('Space separated'),
                   13177:                  tab   => &mt('Tabulator separated'),
                   13178: #                 xml   => &mt('HTML/XML'),
                   13179:                  );
                   13180:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13181:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13182:     foreach my $type (sort(keys(%Types))) {
                   13183:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13184:     }
                   13185:     $Str .= "</select>\n";
                   13186:     return $Str;
1.31      albertel 13187: }
                   13188: 
1.301     albertel 13189: sub get_samples {
                   13190:     my ($records,$toget) = @_;
                   13191:     my @samples=({});
                   13192:     my $got=0;
                   13193:     foreach my $rec (@$records) {
                   13194: 	my %temp = &record_sep($rec);
                   13195: 	if (! grep(/\S/, values(%temp))) { next; }
                   13196: 	if (%temp) {
                   13197: 	    $samples[$got]=\%temp;
                   13198: 	    $got++;
                   13199: 	    if ($got == $toget) { last; }
                   13200: 	}
                   13201:     }
                   13202:     return \@samples;
                   13203: }
                   13204: 
1.144     matthew  13205: ######################################################
                   13206: ######################################################
                   13207: 
1.56      matthew  13208: =pod
                   13209: 
1.648     raeburn  13210: =item * &csv_print_samples($r,$records)
1.41      ng       13211: 
                   13212: Prints a table of sample values from each column uploaded $r is an
                   13213: Apache Request ref, $records is an arrayref from
                   13214: &Apache::loncommon::upfile_record_sep
                   13215: 
                   13216: =cut
                   13217: 
1.144     matthew  13218: ######################################################
                   13219: ######################################################
1.31      albertel 13220: sub csv_print_samples {
                   13221:     my ($r,$records) = @_;
1.662     bisitz   13222:     my $samples = &get_samples($records,5);
1.301     albertel 13223: 
1.594     raeburn  13224:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13225:               &start_data_table_header_row());
1.356     albertel 13226:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13227:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13228:     $r->print(&end_data_table_header_row());
1.301     albertel 13229:     foreach my $hash (@$samples) {
1.594     raeburn  13230: 	$r->print(&start_data_table_row());
1.356     albertel 13231: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13232: 	    $r->print('<td>');
1.356     albertel 13233: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13234: 	    $r->print('</td>');
                   13235: 	}
1.594     raeburn  13236: 	$r->print(&end_data_table_row());
1.31      albertel 13237:     }
1.594     raeburn  13238:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13239: }
                   13240: 
1.144     matthew  13241: ######################################################
                   13242: ######################################################
                   13243: 
1.56      matthew  13244: =pod
                   13245: 
1.648     raeburn  13246: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13247: 
                   13248: Prints a table to create associations between values and table columns.
1.144     matthew  13249: 
1.41      ng       13250: $r is an Apache Request ref,
                   13251: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13252: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13253: 
                   13254: =cut
                   13255: 
1.144     matthew  13256: ######################################################
                   13257: ######################################################
1.31      albertel 13258: sub csv_print_select_table {
                   13259:     my ($r,$records,$d) = @_;
1.301     albertel 13260:     my $i=0;
                   13261:     my $samples = &get_samples($records,1);
1.144     matthew  13262:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13263: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13264:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13265:               '<th>'.&mt('Column').'</th>'.
                   13266:               &end_data_table_header_row()."\n");
1.356     albertel 13267:     foreach my $array_ref (@$d) {
                   13268: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13269: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13270: 
1.875     bisitz   13271: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13272: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13273: 	$r->print('<option value="none"></option>');
1.356     albertel 13274: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13275: 	    $r->print('<option value="'.$sample.'"'.
                   13276:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13277:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13278: 	}
1.594     raeburn  13279: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13280: 	$i++;
                   13281:     }
1.594     raeburn  13282:     $r->print(&end_data_table());
1.31      albertel 13283:     $i--;
                   13284:     return $i;
                   13285: }
1.56      matthew  13286: 
1.144     matthew  13287: ######################################################
                   13288: ######################################################
                   13289: 
1.56      matthew  13290: =pod
1.31      albertel 13291: 
1.648     raeburn  13292: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13293: 
                   13294: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13295: 
                   13296: $r is an Apache Request ref,
                   13297: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13298: $d is an array of 2 element arrays (internal name, displayed name)
                   13299: 
                   13300: =cut
                   13301: 
1.144     matthew  13302: ######################################################
                   13303: ######################################################
1.31      albertel 13304: sub csv_samples_select_table {
                   13305:     my ($r,$records,$d) = @_;
                   13306:     my $i=0;
1.144     matthew  13307:     #
1.662     bisitz   13308:     my $max_samples = 5;
                   13309:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13310:     $r->print(&start_data_table().
                   13311:               &start_data_table_header_row().'<th>'.
                   13312:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13313:               &end_data_table_header_row());
1.301     albertel 13314: 
                   13315:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13316: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13317: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13318: 	foreach my $option (@$d) {
                   13319: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13320: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13321:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13322:                       $display.'</option>');
1.31      albertel 13323: 	}
                   13324: 	$r->print('</select></td><td>');
1.662     bisitz   13325: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13326: 	    if (defined($samples->[$line]{$key})) { 
                   13327: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13328: 	    }
                   13329: 	}
1.594     raeburn  13330: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13331: 	$i++;
                   13332:     }
1.594     raeburn  13333:     $r->print(&end_data_table());
1.31      albertel 13334:     $i--;
                   13335:     return($i);
1.115     matthew  13336: }
                   13337: 
1.144     matthew  13338: ######################################################
                   13339: ######################################################
                   13340: 
1.115     matthew  13341: =pod
                   13342: 
1.648     raeburn  13343: =item * &clean_excel_name($name)
1.115     matthew  13344: 
                   13345: Returns a replacement for $name which does not contain any illegal characters.
                   13346: 
                   13347: =cut
                   13348: 
1.144     matthew  13349: ######################################################
                   13350: ######################################################
1.115     matthew  13351: sub clean_excel_name {
                   13352:     my ($name) = @_;
                   13353:     $name =~ s/[:\*\?\/\\]//g;
                   13354:     if (length($name) > 31) {
                   13355:         $name = substr($name,0,31);
                   13356:     }
                   13357:     return $name;
1.25      albertel 13358: }
1.84      albertel 13359: 
1.85      albertel 13360: =pod
                   13361: 
1.648     raeburn  13362: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13363: 
                   13364: Returns either 1 or undef
                   13365: 
                   13366: 1 if the part is to be hidden, undef if it is to be shown
                   13367: 
                   13368: Arguments are:
                   13369: 
                   13370: $id the id of the part to be checked
                   13371: $symb, optional the symb of the resource to check
                   13372: $udom, optional the domain of the user to check for
                   13373: $uname, optional the username of the user to check for
                   13374: 
                   13375: =cut
1.84      albertel 13376: 
                   13377: sub check_if_partid_hidden {
                   13378:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13379:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13380: 					 $symb,$udom,$uname);
1.141     albertel 13381:     my $truth=1;
                   13382:     #if the string starts with !, then the list is the list to show not hide
                   13383:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13384:     my @hiddenlist=split(/,/,$hiddenparts);
                   13385:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13386: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13387:     }
1.141     albertel 13388:     return !$truth;
1.84      albertel 13389: }
1.127     matthew  13390: 
1.138     matthew  13391: 
                   13392: ############################################################
                   13393: ############################################################
                   13394: 
                   13395: =pod
                   13396: 
1.157     matthew  13397: =back 
                   13398: 
1.138     matthew  13399: =head1 cgi-bin script and graphing routines
                   13400: 
1.157     matthew  13401: =over 4
                   13402: 
1.648     raeburn  13403: =item * &get_cgi_id()
1.138     matthew  13404: 
                   13405: Inputs: none
                   13406: 
                   13407: Returns an id which can be used to pass environment variables
                   13408: to various cgi-bin scripts.  These environment variables will
                   13409: be removed from the users environment after a given time by
                   13410: the routine &Apache::lonnet::transfer_profile_to_env.
                   13411: 
                   13412: =cut
                   13413: 
                   13414: ############################################################
                   13415: ############################################################
1.152     albertel 13416: my $uniq=0;
1.136     matthew  13417: sub get_cgi_id {
1.154     albertel 13418:     $uniq=($uniq+1)%100000;
1.280     albertel 13419:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13420: }
                   13421: 
1.127     matthew  13422: ############################################################
                   13423: ############################################################
                   13424: 
                   13425: =pod
                   13426: 
1.648     raeburn  13427: =item * &DrawBarGraph()
1.127     matthew  13428: 
1.138     matthew  13429: Facilitates the plotting of data in a (stacked) bar graph.
                   13430: Puts plot definition data into the users environment in order for 
                   13431: graph.png to plot it.  Returns an <img> tag for the plot.
                   13432: The bars on the plot are labeled '1','2',...,'n'.
                   13433: 
                   13434: Inputs:
                   13435: 
                   13436: =over 4
                   13437: 
                   13438: =item $Title: string, the title of the plot
                   13439: 
                   13440: =item $xlabel: string, text describing the X-axis of the plot
                   13441: 
                   13442: =item $ylabel: string, text describing the Y-axis of the plot
                   13443: 
                   13444: =item $Max: scalar, the maximum Y value to use in the plot
                   13445: If $Max is < any data point, the graph will not be rendered.
                   13446: 
1.140     matthew  13447: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13448: they are plotted.  If undefined, default values will be used.
                   13449: 
1.178     matthew  13450: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13451: 
1.138     matthew  13452: =item @Values: An array of array references.  Each array reference holds data
                   13453: to be plotted in a stacked bar chart.
                   13454: 
1.239     matthew  13455: =item If the final element of @Values is a hash reference the key/value
                   13456: pairs will be added to the graph definition.
                   13457: 
1.138     matthew  13458: =back
                   13459: 
                   13460: Returns:
                   13461: 
                   13462: An <img> tag which references graph.png and the appropriate identifying
                   13463: information for the plot.
                   13464: 
1.127     matthew  13465: =cut
                   13466: 
                   13467: ############################################################
                   13468: ############################################################
1.134     matthew  13469: sub DrawBarGraph {
1.178     matthew  13470:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13471:     #
                   13472:     if (! defined($colors)) {
                   13473:         $colors = ['#33ff00', 
                   13474:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13475:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13476:                   ]; 
                   13477:     }
1.228     matthew  13478:     my $extra_settings = {};
                   13479:     if (ref($Values[-1]) eq 'HASH') {
                   13480:         $extra_settings = pop(@Values);
                   13481:     }
1.127     matthew  13482:     #
1.136     matthew  13483:     my $identifier = &get_cgi_id();
                   13484:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13485:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13486:         return '';
                   13487:     }
1.225     matthew  13488:     #
                   13489:     my @Labels;
                   13490:     if (defined($labels)) {
                   13491:         @Labels = @$labels;
                   13492:     } else {
                   13493:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   13494:             push (@Labels,$i+1);
                   13495:         }
                   13496:     }
                   13497:     #
1.129     matthew  13498:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13499:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13500:     my %ValuesHash;
                   13501:     my $NumSets=1;
                   13502:     foreach my $array (@Values) {
                   13503:         next if (! ref($array));
1.136     matthew  13504:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13505:             join(',',@$array);
1.129     matthew  13506:     }
1.127     matthew  13507:     #
1.136     matthew  13508:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13509:     if ($NumBars < 3) {
                   13510:         $width = 120+$NumBars*32;
1.220     matthew  13511:         $xskip = 1;
1.225     matthew  13512:         $bar_width = 30;
                   13513:     } elsif ($NumBars < 5) {
                   13514:         $width = 120+$NumBars*20;
                   13515:         $xskip = 1;
                   13516:         $bar_width = 20;
1.220     matthew  13517:     } elsif ($NumBars < 10) {
1.136     matthew  13518:         $width = 120+$NumBars*15;
                   13519:         $xskip = 1;
                   13520:         $bar_width = 15;
                   13521:     } elsif ($NumBars <= 25) {
                   13522:         $width = 120+$NumBars*11;
                   13523:         $xskip = 5;
                   13524:         $bar_width = 8;
                   13525:     } elsif ($NumBars <= 50) {
                   13526:         $width = 120+$NumBars*8;
                   13527:         $xskip = 5;
                   13528:         $bar_width = 4;
                   13529:     } else {
                   13530:         $width = 120+$NumBars*8;
                   13531:         $xskip = 5;
                   13532:         $bar_width = 4;
                   13533:     }
                   13534:     #
1.137     matthew  13535:     $Max = 1 if ($Max < 1);
                   13536:     if ( int($Max) < $Max ) {
                   13537:         $Max++;
                   13538:         $Max = int($Max);
                   13539:     }
1.127     matthew  13540:     $Title  = '' if (! defined($Title));
                   13541:     $xlabel = '' if (! defined($xlabel));
                   13542:     $ylabel = '' if (! defined($ylabel));
1.369     www      13543:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13544:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13545:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13546:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13547:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13548:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13549:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13550:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13551:     $ValuesHash{$id.'.height'}   = $height;
                   13552:     $ValuesHash{$id.'.width'}    = $width;
                   13553:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13554:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13555:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13556:     #
1.228     matthew  13557:     # Deal with other parameters
                   13558:     while (my ($key,$value) = each(%$extra_settings)) {
                   13559:         $ValuesHash{$id.'.'.$key} = $value;
                   13560:     }
                   13561:     #
1.646     raeburn  13562:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13563:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13564: }
                   13565: 
                   13566: ############################################################
                   13567: ############################################################
                   13568: 
                   13569: =pod
                   13570: 
1.648     raeburn  13571: =item * &DrawXYGraph()
1.137     matthew  13572: 
1.138     matthew  13573: Facilitates the plotting of data in an XY graph.
                   13574: Puts plot definition data into the users environment in order for 
                   13575: graph.png to plot it.  Returns an <img> tag for the plot.
                   13576: 
                   13577: Inputs:
                   13578: 
                   13579: =over 4
                   13580: 
                   13581: =item $Title: string, the title of the plot
                   13582: 
                   13583: =item $xlabel: string, text describing the X-axis of the plot
                   13584: 
                   13585: =item $ylabel: string, text describing the Y-axis of the plot
                   13586: 
                   13587: =item $Max: scalar, the maximum Y value to use in the plot
                   13588: If $Max is < any data point, the graph will not be rendered.
                   13589: 
                   13590: =item $colors: Array ref containing the hex color codes for the data to be 
                   13591: plotted in.  If undefined, default values will be used.
                   13592: 
                   13593: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13594: 
                   13595: =item $Ydata: Array ref containing Array refs.  
1.185     www      13596: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13597: 
                   13598: =item %Values: hash indicating or overriding any default values which are 
                   13599: passed to graph.png.  
                   13600: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13601: 
                   13602: =back
                   13603: 
                   13604: Returns:
                   13605: 
                   13606: An <img> tag which references graph.png and the appropriate identifying
                   13607: information for the plot.
                   13608: 
1.137     matthew  13609: =cut
                   13610: 
                   13611: ############################################################
                   13612: ############################################################
                   13613: sub DrawXYGraph {
                   13614:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13615:     #
                   13616:     # Create the identifier for the graph
                   13617:     my $identifier = &get_cgi_id();
                   13618:     my $id = 'cgi.'.$identifier;
                   13619:     #
                   13620:     $Title  = '' if (! defined($Title));
                   13621:     $xlabel = '' if (! defined($xlabel));
                   13622:     $ylabel = '' if (! defined($ylabel));
                   13623:     my %ValuesHash = 
                   13624:         (
1.369     www      13625:          $id.'.title'  => &escape($Title),
                   13626:          $id.'.xlabel' => &escape($xlabel),
                   13627:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13628:          $id.'.y_max_value'=> $Max,
                   13629:          $id.'.labels'     => join(',',@$Xlabels),
                   13630:          $id.'.PlotType'   => 'XY',
                   13631:          );
                   13632:     #
                   13633:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13634:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13635:     }
                   13636:     #
                   13637:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13638:         return '';
                   13639:     }
                   13640:     my $NumSets=1;
1.138     matthew  13641:     foreach my $array (@{$Ydata}){
1.137     matthew  13642:         next if (! ref($array));
                   13643:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13644:     }
1.138     matthew  13645:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  13646:     #
                   13647:     # Deal with other parameters
                   13648:     while (my ($key,$value) = each(%Values)) {
                   13649:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  13650:     }
                   13651:     #
1.646     raeburn  13652:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  13653:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13654: }
                   13655: 
                   13656: ############################################################
                   13657: ############################################################
                   13658: 
                   13659: =pod
                   13660: 
1.648     raeburn  13661: =item * &DrawXYYGraph()
1.138     matthew  13662: 
                   13663: Facilitates the plotting of data in an XY graph with two Y axes.
                   13664: Puts plot definition data into the users environment in order for 
                   13665: graph.png to plot it.  Returns an <img> tag for the plot.
                   13666: 
                   13667: Inputs:
                   13668: 
                   13669: =over 4
                   13670: 
                   13671: =item $Title: string, the title of the plot
                   13672: 
                   13673: =item $xlabel: string, text describing the X-axis of the plot
                   13674: 
                   13675: =item $ylabel: string, text describing the Y-axis of the plot
                   13676: 
                   13677: =item $colors: Array ref containing the hex color codes for the data to be 
                   13678: plotted in.  If undefined, default values will be used.
                   13679: 
                   13680: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13681: 
                   13682: =item $Ydata1: The first data set
                   13683: 
                   13684: =item $Min1: The minimum value of the left Y-axis
                   13685: 
                   13686: =item $Max1: The maximum value of the left Y-axis
                   13687: 
                   13688: =item $Ydata2: The second data set
                   13689: 
                   13690: =item $Min2: The minimum value of the right Y-axis
                   13691: 
                   13692: =item $Max2: The maximum value of the left Y-axis
                   13693: 
                   13694: =item %Values: hash indicating or overriding any default values which are 
                   13695: passed to graph.png.  
                   13696: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13697: 
                   13698: =back
                   13699: 
                   13700: Returns:
                   13701: 
                   13702: An <img> tag which references graph.png and the appropriate identifying
                   13703: information for the plot.
1.136     matthew  13704: 
                   13705: =cut
                   13706: 
                   13707: ############################################################
                   13708: ############################################################
1.137     matthew  13709: sub DrawXYYGraph {
                   13710:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   13711:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  13712:     #
                   13713:     # Create the identifier for the graph
                   13714:     my $identifier = &get_cgi_id();
                   13715:     my $id = 'cgi.'.$identifier;
                   13716:     #
                   13717:     $Title  = '' if (! defined($Title));
                   13718:     $xlabel = '' if (! defined($xlabel));
                   13719:     $ylabel = '' if (! defined($ylabel));
                   13720:     my %ValuesHash = 
                   13721:         (
1.369     www      13722:          $id.'.title'  => &escape($Title),
                   13723:          $id.'.xlabel' => &escape($xlabel),
                   13724:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  13725:          $id.'.labels' => join(',',@$Xlabels),
                   13726:          $id.'.PlotType' => 'XY',
                   13727:          $id.'.NumSets' => 2,
1.137     matthew  13728:          $id.'.two_axes' => 1,
                   13729:          $id.'.y1_max_value' => $Max1,
                   13730:          $id.'.y1_min_value' => $Min1,
                   13731:          $id.'.y2_max_value' => $Max2,
                   13732:          $id.'.y2_min_value' => $Min2,
1.136     matthew  13733:          );
                   13734:     #
1.137     matthew  13735:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13736:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13737:     }
                   13738:     #
                   13739:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   13740:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  13741:         return '';
                   13742:     }
                   13743:     my $NumSets=1;
1.137     matthew  13744:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  13745:         next if (! ref($array));
                   13746:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  13747:     }
                   13748:     #
                   13749:     # Deal with other parameters
                   13750:     while (my ($key,$value) = each(%Values)) {
                   13751:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  13752:     }
                   13753:     #
1.646     raeburn  13754:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 13755:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  13756: }
                   13757: 
                   13758: ############################################################
                   13759: ############################################################
                   13760: 
                   13761: =pod
                   13762: 
1.157     matthew  13763: =back 
                   13764: 
1.139     matthew  13765: =head1 Statistics helper routines?  
                   13766: 
                   13767: Bad place for them but what the hell.
                   13768: 
1.157     matthew  13769: =over 4
                   13770: 
1.648     raeburn  13771: =item * &chartlink()
1.139     matthew  13772: 
                   13773: Returns a link to the chart for a specific student.  
                   13774: 
                   13775: Inputs:
                   13776: 
                   13777: =over 4
                   13778: 
                   13779: =item $linktext: The text of the link
                   13780: 
                   13781: =item $sname: The students username
                   13782: 
                   13783: =item $sdomain: The students domain
                   13784: 
                   13785: =back
                   13786: 
1.157     matthew  13787: =back
                   13788: 
1.139     matthew  13789: =cut
                   13790: 
                   13791: ############################################################
                   13792: ############################################################
                   13793: sub chartlink {
                   13794:     my ($linktext, $sname, $sdomain) = @_;
                   13795:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      13796:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 13797:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  13798:        '">'.$linktext.'</a>';
1.153     matthew  13799: }
                   13800: 
                   13801: #######################################################
                   13802: #######################################################
                   13803: 
                   13804: =pod
                   13805: 
                   13806: =head1 Course Environment Routines
1.157     matthew  13807: 
                   13808: =over 4
1.153     matthew  13809: 
1.648     raeburn  13810: =item * &restore_course_settings()
1.153     matthew  13811: 
1.648     raeburn  13812: =item * &store_course_settings()
1.153     matthew  13813: 
                   13814: Restores/Store indicated form parameters from the course environment.
                   13815: Will not overwrite existing values of the form parameters.
                   13816: 
                   13817: Inputs: 
                   13818: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   13819: 
                   13820: a hash ref describing the data to be stored.  For example:
                   13821:    
                   13822: %Save_Parameters = ('Status' => 'scalar',
                   13823:     'chartoutputmode' => 'scalar',
                   13824:     'chartoutputdata' => 'scalar',
                   13825:     'Section' => 'array',
1.373     raeburn  13826:     'Group' => 'array',
1.153     matthew  13827:     'StudentData' => 'array',
                   13828:     'Maps' => 'array');
                   13829: 
                   13830: Returns: both routines return nothing
                   13831: 
1.631     raeburn  13832: =back
                   13833: 
1.153     matthew  13834: =cut
                   13835: 
                   13836: #######################################################
                   13837: #######################################################
                   13838: sub store_course_settings {
1.496     albertel 13839:     return &store_settings($env{'request.course.id'},@_);
                   13840: }
                   13841: 
                   13842: sub store_settings {
1.153     matthew  13843:     # save to the environment
                   13844:     # appenv the same items, just to be safe
1.300     albertel 13845:     my $udom  = $env{'user.domain'};
                   13846:     my $uname = $env{'user.name'};
1.496     albertel 13847:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13848:     my %SaveHash;
                   13849:     my %AppHash;
                   13850:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 13851:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 13852:         my $envname = 'environment.'.$basename;
1.258     albertel 13853:         if (exists($env{'form.'.$setting})) {
1.153     matthew  13854:             # Save this value away
                   13855:             if ($type eq 'scalar' &&
1.258     albertel 13856:                 (! exists($env{$envname}) || 
                   13857:                  $env{$envname} ne $env{'form.'.$setting})) {
                   13858:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   13859:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  13860:             } elsif ($type eq 'array') {
                   13861:                 my $stored_form;
1.258     albertel 13862:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  13863:                     $stored_form = join(',',
                   13864:                                         map {
1.369     www      13865:                                             &escape($_);
1.258     albertel 13866:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  13867:                 } else {
                   13868:                     $stored_form = 
1.369     www      13869:                         &escape($env{'form.'.$setting});
1.153     matthew  13870:                 }
                   13871:                 # Determine if the array contents are the same.
1.258     albertel 13872:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  13873:                     $SaveHash{$basename} = $stored_form;
                   13874:                     $AppHash{$envname}   = $stored_form;
                   13875:                 }
                   13876:             }
                   13877:         }
                   13878:     }
                   13879:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 13880:                                           $udom,$uname);
1.153     matthew  13881:     if ($put_result !~ /^(ok|delayed)/) {
                   13882:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   13883:                                  'got error:'.$put_result);
                   13884:     }
                   13885:     # Make sure these settings stick around in this session, too
1.646     raeburn  13886:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  13887:     return;
                   13888: }
                   13889: 
                   13890: sub restore_course_settings {
1.499     albertel 13891:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 13892: }
                   13893: 
                   13894: sub restore_settings {
                   13895:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13896:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 13897:         next if (exists($env{'form.'.$setting}));
1.496     albertel 13898:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  13899:             '.'.$setting;
1.258     albertel 13900:         if (exists($env{$envname})) {
1.153     matthew  13901:             if ($type eq 'scalar') {
1.258     albertel 13902:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  13903:             } elsif ($type eq 'array') {
1.258     albertel 13904:                 $env{'form.'.$setting} = [ 
1.153     matthew  13905:                                            map { 
1.369     www      13906:                                                &unescape($_); 
1.258     albertel 13907:                                            } split(',',$env{$envname})
1.153     matthew  13908:                                            ];
                   13909:             }
                   13910:         }
                   13911:     }
1.127     matthew  13912: }
                   13913: 
1.618     raeburn  13914: #######################################################
                   13915: #######################################################
                   13916: 
                   13917: =pod
                   13918: 
                   13919: =head1 Domain E-mail Routines  
                   13920: 
                   13921: =over 4
                   13922: 
1.648     raeburn  13923: =item * &build_recipient_list()
1.618     raeburn  13924: 
1.1075.2.44  raeburn  13925: Build recipient lists for following types of e-mail:
1.766     raeburn  13926: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  13927: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   13928: module change checking, student/employee ID conflict checks, as
                   13929: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   13930: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  13931: 
                   13932: Inputs:
1.1075.2.44  raeburn  13933: defmail (scalar - email address of default recipient),
                   13934: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   13935: requestsmail, updatesmail, or idconflictsmail).
                   13936: 
1.619     raeburn  13937: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  13938: 
                   13939: origmail (scalar - email address of recipient from loncapa.conf,
                   13940: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  13941: 
1.655     raeburn  13942: Returns: comma separated list of addresses to which to send e-mail.
                   13943: 
                   13944: =back
1.618     raeburn  13945: 
                   13946: =cut
                   13947: 
                   13948: ############################################################
                   13949: ############################################################
                   13950: sub build_recipient_list {
1.619     raeburn  13951:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  13952:     my @recipients;
                   13953:     my $otheremails;
                   13954:     my %domconfig =
                   13955:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   13956:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  13957:         if (exists($domconfig{'contacts'}{$mailing})) {
                   13958:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   13959:                 my @contacts = ('adminemail','supportemail');
                   13960:                 foreach my $item (@contacts) {
                   13961:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   13962:                         my $addr = $domconfig{'contacts'}{$item}; 
                   13963:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13964:                             push(@recipients,$addr);
                   13965:                         }
1.619     raeburn  13966:                     }
1.766     raeburn  13967:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  13968:                 }
                   13969:             }
1.766     raeburn  13970:         } elsif ($origmail ne '') {
                   13971:             push(@recipients,$origmail);
1.618     raeburn  13972:         }
1.619     raeburn  13973:     } elsif ($origmail ne '') {
                   13974:         push(@recipients,$origmail);
1.618     raeburn  13975:     }
1.688     raeburn  13976:     if (defined($defmail)) {
                   13977:         if ($defmail ne '') {
                   13978:             push(@recipients,$defmail);
                   13979:         }
1.618     raeburn  13980:     }
                   13981:     if ($otheremails) {
1.619     raeburn  13982:         my @others;
                   13983:         if ($otheremails =~ /,/) {
                   13984:             @others = split(/,/,$otheremails);
1.618     raeburn  13985:         } else {
1.619     raeburn  13986:             push(@others,$otheremails);
                   13987:         }
                   13988:         foreach my $addr (@others) {
                   13989:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13990:                 push(@recipients,$addr);
                   13991:             }
1.618     raeburn  13992:         }
                   13993:     }
1.619     raeburn  13994:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  13995:     return $recipientlist;
                   13996: }
                   13997: 
1.127     matthew  13998: ############################################################
                   13999: ############################################################
1.154     albertel 14000: 
1.655     raeburn  14001: =pod
                   14002: 
                   14003: =head1 Course Catalog Routines
                   14004: 
                   14005: =over 4
                   14006: 
                   14007: =item * &gather_categories()
                   14008: 
                   14009: Converts category definitions - keys of categories hash stored in  
                   14010: coursecategories in configuration.db on the primary library server in a 
                   14011: domain - to an array.  Also generates javascript and idx hash used to 
                   14012: generate Domain Coordinator interface for editing Course Categories.
                   14013: 
                   14014: Inputs:
1.663     raeburn  14015: 
1.655     raeburn  14016: categories (reference to hash of category definitions).
1.663     raeburn  14017: 
1.655     raeburn  14018: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14019:       categories and subcategories).
1.663     raeburn  14020: 
1.655     raeburn  14021: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14022:       editing Course Categories).
1.663     raeburn  14023: 
1.655     raeburn  14024: jsarray (reference to array of categories used to create Javascript arrays for
                   14025:          Domain Coordinator interface for editing Course Categories).
                   14026: 
                   14027: Returns: nothing
                   14028: 
                   14029: Side effects: populates cats, idx and jsarray. 
                   14030: 
                   14031: =cut
                   14032: 
                   14033: sub gather_categories {
                   14034:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14035:     my %counters;
                   14036:     my $num = 0;
                   14037:     foreach my $item (keys(%{$categories})) {
                   14038:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14039:         if ($container eq '' && $depth == 0) {
                   14040:             $cats->[$depth][$categories->{$item}] = $cat;
                   14041:         } else {
                   14042:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14043:         }
                   14044:         my ($escitem,$tail) = split(/:/,$item,2);
                   14045:         if ($counters{$tail} eq '') {
                   14046:             $counters{$tail} = $num;
                   14047:             $num ++;
                   14048:         }
                   14049:         if (ref($idx) eq 'HASH') {
                   14050:             $idx->{$item} = $counters{$tail};
                   14051:         }
                   14052:         if (ref($jsarray) eq 'ARRAY') {
                   14053:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14054:         }
                   14055:     }
                   14056:     return;
                   14057: }
                   14058: 
                   14059: =pod
                   14060: 
                   14061: =item * &extract_categories()
                   14062: 
                   14063: Used to generate breadcrumb trails for course categories.
                   14064: 
                   14065: Inputs:
1.663     raeburn  14066: 
1.655     raeburn  14067: categories (reference to hash of category definitions).
1.663     raeburn  14068: 
1.655     raeburn  14069: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14070:       categories and subcategories).
1.663     raeburn  14071: 
1.655     raeburn  14072: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14073: 
1.655     raeburn  14074: allitems (reference to hash - key is category key 
                   14075:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14076: 
1.655     raeburn  14077: idx (reference to hash of counters used in Domain Coordinator interface for
                   14078:       editing Course Categories).
1.663     raeburn  14079: 
1.655     raeburn  14080: jsarray (reference to array of categories used to create Javascript arrays for
                   14081:          Domain Coordinator interface for editing Course Categories).
                   14082: 
1.665     raeburn  14083: subcats (reference to hash of arrays containing all subcategories within each 
                   14084:          category, -recursive)
                   14085: 
1.655     raeburn  14086: Returns: nothing
                   14087: 
                   14088: Side effects: populates trails and allitems hash references.
                   14089: 
                   14090: =cut
                   14091: 
                   14092: sub extract_categories {
1.665     raeburn  14093:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  14094:     if (ref($categories) eq 'HASH') {
                   14095:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14096:         if (ref($cats->[0]) eq 'ARRAY') {
                   14097:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14098:                 my $name = $cats->[0][$i];
                   14099:                 my $item = &escape($name).'::0';
                   14100:                 my $trailstr;
                   14101:                 if ($name eq 'instcode') {
                   14102:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14103:                 } elsif ($name eq 'communities') {
                   14104:                     $trailstr = &mt('Communities');
1.655     raeburn  14105:                 } else {
                   14106:                     $trailstr = $name;
                   14107:                 }
                   14108:                 if ($allitems->{$item} eq '') {
                   14109:                     push(@{$trails},$trailstr);
                   14110:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14111:                 }
                   14112:                 my @parents = ($name);
                   14113:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14114:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14115:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14116:                         if (ref($subcats) eq 'HASH') {
                   14117:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14118:                         }
                   14119:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   14120:                     }
                   14121:                 } else {
                   14122:                     if (ref($subcats) eq 'HASH') {
                   14123:                         $subcats->{$item} = [];
1.655     raeburn  14124:                     }
                   14125:                 }
                   14126:             }
                   14127:         }
                   14128:     }
                   14129:     return;
                   14130: }
                   14131: 
                   14132: =pod
                   14133: 
1.1075.2.56  raeburn  14134: =item * &recurse_categories()
1.655     raeburn  14135: 
                   14136: Recursively used to generate breadcrumb trails for course categories.
                   14137: 
                   14138: Inputs:
1.663     raeburn  14139: 
1.655     raeburn  14140: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14141:       categories and subcategories).
1.663     raeburn  14142: 
1.655     raeburn  14143: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14144: 
                   14145: category (current course category, for which breadcrumb trail is being generated).
                   14146: 
                   14147: trails (reference to array of breadcrumb trails for each category).
                   14148: 
1.655     raeburn  14149: allitems (reference to hash - key is category key
                   14150:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14151: 
1.655     raeburn  14152: parents (array containing containers directories for current category, 
                   14153:          back to top level). 
                   14154: 
                   14155: Returns: nothing
                   14156: 
                   14157: Side effects: populates trails and allitems hash references
                   14158: 
                   14159: =cut
                   14160: 
                   14161: sub recurse_categories {
1.665     raeburn  14162:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  14163:     my $shallower = $depth - 1;
                   14164:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14165:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14166:             my $name = $cats->[$depth]{$category}[$k];
                   14167:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14168:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14169:             if ($allitems->{$item} eq '') {
                   14170:                 push(@{$trails},$trailstr);
                   14171:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14172:             }
                   14173:             my $deeper = $depth+1;
                   14174:             push(@{$parents},$category);
1.665     raeburn  14175:             if (ref($subcats) eq 'HASH') {
                   14176:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14177:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14178:                     my $higher;
                   14179:                     if ($j > 0) {
                   14180:                         $higher = &escape($parents->[$j]).':'.
                   14181:                                   &escape($parents->[$j-1]).':'.$j;
                   14182:                     } else {
                   14183:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14184:                     }
                   14185:                     push(@{$subcats->{$higher}},$subcat);
                   14186:                 }
                   14187:             }
                   14188:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   14189:                                 $subcats);
1.655     raeburn  14190:             pop(@{$parents});
                   14191:         }
                   14192:     } else {
                   14193:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14194:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14195:         if ($allitems->{$item} eq '') {
                   14196:             push(@{$trails},$trailstr);
                   14197:             $allitems->{$item} = scalar(@{$trails})-1;
                   14198:         }
                   14199:     }
                   14200:     return;
                   14201: }
                   14202: 
1.663     raeburn  14203: =pod
                   14204: 
1.1075.2.56  raeburn  14205: =item * &assign_categories_table()
1.663     raeburn  14206: 
                   14207: Create a datatable for display of hierarchical categories in a domain,
                   14208: with checkboxes to allow a course to be categorized. 
                   14209: 
                   14210: Inputs:
                   14211: 
                   14212: cathash - reference to hash of categories defined for the domain (from
                   14213:           configuration.db)
                   14214: 
                   14215: currcat - scalar with an & separated list of categories assigned to a course. 
                   14216: 
1.919     raeburn  14217: type    - scalar contains course type (Course or Community).
                   14218: 
1.1075.2.117  raeburn  14219: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14220:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14221: 
1.663     raeburn  14222: Returns: $output (markup to be displayed) 
                   14223: 
                   14224: =cut
                   14225: 
                   14226: sub assign_categories_table {
1.1075.2.117  raeburn  14227:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  14228:     my $output;
                   14229:     if (ref($cathash) eq 'HASH') {
                   14230:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   14231:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   14232:         $maxdepth = scalar(@cats);
                   14233:         if (@cats > 0) {
                   14234:             my $itemcount = 0;
                   14235:             if (ref($cats[0]) eq 'ARRAY') {
                   14236:                 my @currcategories;
                   14237:                 if ($currcat ne '') {
                   14238:                     @currcategories = split('&',$currcat);
                   14239:                 }
1.919     raeburn  14240:                 my $table;
1.663     raeburn  14241:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14242:                     my $parent = $cats[0][$i];
1.919     raeburn  14243:                     next if ($parent eq 'instcode');
                   14244:                     if ($type eq 'Community') {
                   14245:                         next unless ($parent eq 'communities');
                   14246:                     } else {
                   14247:                         next if ($parent eq 'communities');
                   14248:                     }
1.663     raeburn  14249:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14250:                     my $item = &escape($parent).'::0';
                   14251:                     my $checked = '';
                   14252:                     if (@currcategories > 0) {
                   14253:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14254:                             $checked = ' checked="checked"';
1.663     raeburn  14255:                         }
                   14256:                     }
1.919     raeburn  14257:                     my $parent_title = $parent;
                   14258:                     if ($parent eq 'communities') {
                   14259:                         $parent_title = &mt('Communities');
                   14260:                     }
                   14261:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14262:                               '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14263:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  14264:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14265:                     my $depth = 1;
                   14266:                     push(@path,$parent);
1.1075.2.117  raeburn  14267:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  14268:                     pop(@path);
1.919     raeburn  14269:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14270:                     $itemcount ++;
                   14271:                 }
1.919     raeburn  14272:                 if ($itemcount) {
                   14273:                     $output = &Apache::loncommon::start_data_table().
                   14274:                               $table.
                   14275:                               &Apache::loncommon::end_data_table();
                   14276:                 }
1.663     raeburn  14277:             }
                   14278:         }
                   14279:     }
                   14280:     return $output;
                   14281: }
                   14282: 
                   14283: =pod
                   14284: 
1.1075.2.56  raeburn  14285: =item * &assign_category_rows()
1.663     raeburn  14286: 
                   14287: Create a datatable row for display of nested categories in a domain,
                   14288: with checkboxes to allow a course to be categorized,called recursively.
                   14289: 
                   14290: Inputs:
                   14291: 
                   14292: itemcount - track row number for alternating colors
                   14293: 
                   14294: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14295:       categories and subcategories.
                   14296: 
                   14297: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14298: 
                   14299: parent - parent of current category item
                   14300: 
                   14301: path - Array containing all categories back up through the hierarchy from the
                   14302:        current category to the top level.
                   14303: 
                   14304: currcategories - reference to array of current categories assigned to the course
                   14305: 
1.1075.2.117  raeburn  14306: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14307:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14308: 
1.663     raeburn  14309: Returns: $output (markup to be displayed).
                   14310: 
                   14311: =cut
                   14312: 
                   14313: sub assign_category_rows {
1.1075.2.117  raeburn  14314:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  14315:     my ($text,$name,$item,$chgstr);
                   14316:     if (ref($cats) eq 'ARRAY') {
                   14317:         my $maxdepth = scalar(@{$cats});
                   14318:         if (ref($cats->[$depth]) eq 'HASH') {
                   14319:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14320:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14321:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  14322:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14323:                 for (my $j=0; $j<$numchildren; $j++) {
                   14324:                     $name = $cats->[$depth]{$parent}[$j];
                   14325:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14326:                     my $deeper = $depth+1;
                   14327:                     my $checked = '';
                   14328:                     if (ref($currcategories) eq 'ARRAY') {
                   14329:                         if (@{$currcategories} > 0) {
                   14330:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14331:                                 $checked = ' checked="checked"';
1.663     raeburn  14332:                             }
                   14333:                         }
                   14334:                     }
1.664     raeburn  14335:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14336:                              '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14337:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  14338:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14339:                              '</td><td>';
1.663     raeburn  14340:                     if (ref($path) eq 'ARRAY') {
                   14341:                         push(@{$path},$name);
1.1075.2.117  raeburn  14342:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  14343:                         pop(@{$path});
                   14344:                     }
                   14345:                     $text .= '</td></tr>';
                   14346:                 }
                   14347:                 $text .= '</table></td>';
                   14348:             }
                   14349:         }
                   14350:     }
                   14351:     return $text;
                   14352: }
                   14353: 
1.1075.2.69  raeburn  14354: =pod
                   14355: 
                   14356: =back
                   14357: 
                   14358: =cut
                   14359: 
1.655     raeburn  14360: ############################################################
                   14361: ############################################################
                   14362: 
                   14363: 
1.443     albertel 14364: sub commit_customrole {
1.664     raeburn  14365:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14366:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14367:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14368:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14369:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14370:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14371:                  '</b><br />';
                   14372:     return $output;
                   14373: }
                   14374: 
                   14375: sub commit_standardrole {
1.1075.2.31  raeburn  14376:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14377:     my ($output,$logmsg,$linefeed);
                   14378:     if ($context eq 'auto') {
                   14379:         $linefeed = "\n";
                   14380:     } else {
                   14381:         $linefeed = "<br />\n";
                   14382:     }  
1.443     albertel 14383:     if ($three eq 'st') {
1.541     raeburn  14384:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  14385:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14386:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14387:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14388:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14389:         } else {
1.541     raeburn  14390:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14391:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14392:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14393:             if ($context eq 'auto') {
                   14394:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14395:             } else {
                   14396:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14397:                &mt('Add to classlist').': <b>ok</b>';
                   14398:             }
                   14399:             $output .= $linefeed;
1.443     albertel 14400:         }
                   14401:     } else {
                   14402:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14403:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14404:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14405:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14406:         if ($context eq 'auto') {
                   14407:             $output .= $result.$linefeed;
                   14408:         } else {
                   14409:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14410:         }
1.443     albertel 14411:     }
                   14412:     return $output;
                   14413: }
                   14414: 
                   14415: sub commit_studentrole {
1.1075.2.31  raeburn  14416:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14417:         $credits) = @_;
1.626     raeburn  14418:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  14419:     if ($context eq 'auto') {
                   14420:         $linefeed = "\n";
                   14421:     } else {
                   14422:         $linefeed = '<br />'."\n";
                   14423:     }
1.443     albertel 14424:     if (defined($one) && defined($two)) {
                   14425:         my $cid=$one.'_'.$two;
                   14426:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   14427:         my $secchange = 0;
                   14428:         my $expire_role_result;
                   14429:         my $modify_section_result;
1.628     raeburn  14430:         if ($oldsec ne '-1') { 
                   14431:             if ($oldsec ne $sec) {
1.443     albertel 14432:                 $secchange = 1;
1.628     raeburn  14433:                 my $now = time;
1.443     albertel 14434:                 my $uurl='/'.$cid;
                   14435:                 $uurl=~s/\_/\//g;
                   14436:                 if ($oldsec) {
                   14437:                     $uurl.='/'.$oldsec;
                   14438:                 }
1.626     raeburn  14439:                 $oldsecurl = $uurl;
1.628     raeburn  14440:                 $expire_role_result = 
1.652     raeburn  14441:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  14442:                 if ($env{'request.course.sec'} ne '') { 
                   14443:                     if ($expire_role_result eq 'refused') {
                   14444:                         my @roles = ('st');
                   14445:                         my @statuses = ('previous');
                   14446:                         my @roledoms = ($one);
                   14447:                         my $withsec = 1;
                   14448:                         my %roleshash = 
                   14449:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   14450:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   14451:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   14452:                             my ($oldstart,$oldend) = 
                   14453:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   14454:                             if ($oldend > 0 && $oldend <= $now) {
                   14455:                                 $expire_role_result = 'ok';
                   14456:                             }
                   14457:                         }
                   14458:                     }
                   14459:                 }
1.443     albertel 14460:                 $result = $expire_role_result;
                   14461:             }
                   14462:         }
                   14463:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  14464:             $modify_section_result = 
                   14465:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   14466:                                                            undef,undef,undef,$sec,
                   14467:                                                            $end,$start,'','',$cid,
                   14468:                                                            '',$context,$credits);
1.443     albertel 14469:             if ($modify_section_result =~ /^ok/) {
                   14470:                 if ($secchange == 1) {
1.628     raeburn  14471:                     if ($sec eq '') {
                   14472:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   14473:                     } else {
                   14474:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   14475:                     }
1.443     albertel 14476:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  14477:                     if ($sec eq '') {
                   14478:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   14479:                     } else {
                   14480:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14481:                     }
1.443     albertel 14482:                 } else {
1.628     raeburn  14483:                     if ($sec eq '') {
                   14484:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   14485:                     } else {
                   14486:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14487:                     }
1.443     albertel 14488:                 }
                   14489:             } else {
1.628     raeburn  14490:                 if ($secchange) {       
                   14491:                     $$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;
                   14492:                 } else {
                   14493:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   14494:                 }
1.443     albertel 14495:             }
                   14496:             $result = $modify_section_result;
                   14497:         } elsif ($secchange == 1) {
1.628     raeburn  14498:             if ($oldsec eq '') {
1.1075.2.20  raeburn  14499:                 $$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  14500:             } else {
                   14501:                 $$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;
                   14502:             }
1.626     raeburn  14503:             if ($expire_role_result eq 'refused') {
                   14504:                 my $newsecurl = '/'.$cid;
                   14505:                 $newsecurl =~ s/\_/\//g;
                   14506:                 if ($sec ne '') {
                   14507:                     $newsecurl.='/'.$sec;
                   14508:                 }
                   14509:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   14510:                     if ($sec eq '') {
                   14511:                         $$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;
                   14512:                     } else {
                   14513:                         $$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;
                   14514:                     }
                   14515:                 }
                   14516:             }
1.443     albertel 14517:         }
                   14518:     } else {
1.626     raeburn  14519:         $$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 14520:         $result = "error: incomplete course id\n";
                   14521:     }
                   14522:     return $result;
                   14523: }
                   14524: 
1.1075.2.25  raeburn  14525: sub show_role_extent {
                   14526:     my ($scope,$context,$role) = @_;
                   14527:     $scope =~ s{^/}{};
                   14528:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   14529:     push(@courseroles,'co');
                   14530:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   14531:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   14532:         $scope =~ s{/}{_};
                   14533:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   14534:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   14535:         my ($audom,$auname) = split(/\//,$scope);
                   14536:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   14537:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   14538:     } else {
                   14539:         $scope =~ s{/$}{};
                   14540:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   14541:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   14542:     }
                   14543: }
                   14544: 
1.443     albertel 14545: ############################################################
                   14546: ############################################################
                   14547: 
1.566     albertel 14548: sub check_clone {
1.578     raeburn  14549:     my ($args,$linefeed) = @_;
1.566     albertel 14550:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   14551:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   14552:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   14553:     my $clonemsg;
                   14554:     my $can_clone = 0;
1.944     raeburn  14555:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  14556:     if ($lctype ne 'community') {
                   14557:         $lctype = 'course';
                   14558:     }
1.566     albertel 14559:     if ($clonehome eq 'no_host') {
1.944     raeburn  14560:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14561:             $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'});
                   14562:         } else {
                   14563:             $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'});
                   14564:         }     
1.566     albertel 14565:     } else {
                   14566: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  14567:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14568:             if ($clonedesc{'type'} ne 'Community') {
                   14569:                  $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'});
                   14570:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14571:             }
                   14572:         }
1.882     raeburn  14573: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   14574:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 14575: 	    $can_clone = 1;
                   14576: 	} else {
1.1075.2.95  raeburn  14577: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 14578: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  14579:             if ($clonehash{'cloners'} eq '') {
                   14580:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   14581:                 if ($domdefs{'canclone'}) {
                   14582:                     unless ($domdefs{'canclone'} eq 'none') {
                   14583:                         if ($domdefs{'canclone'} eq 'domain') {
                   14584:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   14585:                                 $can_clone = 1;
                   14586:                             }
                   14587:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   14588:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   14589:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   14590:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   14591:                                 $can_clone = 1;
                   14592:                             }
                   14593:                         }
                   14594:                     }
1.908     raeburn  14595:                 }
1.1075.2.95  raeburn  14596:             } else {
                   14597: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   14598:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  14599:                     $can_clone = 1;
1.1075.2.95  raeburn  14600:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  14601:                     $can_clone = 1;
1.1075.2.96  raeburn  14602:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   14603:                     $can_clone = 1;
1.1075.2.95  raeburn  14604:                 }
                   14605:                 unless ($can_clone) {
1.1075.2.96  raeburn  14606:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   14607:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  14608:                         my (%gotdomdefaults,%gotcodedefaults);
                   14609:                         foreach my $cloner (@cloners) {
                   14610:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   14611:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   14612:                                 my (%codedefaults,@code_order);
                   14613:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   14614:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   14615:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   14616:                                     }
                   14617:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   14618:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   14619:                                     }
                   14620:                                 } else {
                   14621:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   14622:                                                                             \%codedefaults,
                   14623:                                                                             \@code_order);
                   14624:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   14625:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   14626:                                 }
                   14627:                                 if (@code_order > 0) {
                   14628:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   14629:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   14630:                                                                                 $args->{'crscode'})) {
                   14631:                                         $can_clone = 1;
                   14632:                                         last;
                   14633:                                     }
                   14634:                                 }
                   14635:                             }
                   14636:                         }
                   14637:                     }
1.1075.2.96  raeburn  14638:                 }
                   14639:             }
                   14640:             unless ($can_clone) {
                   14641:                 my $ccrole = 'cc';
                   14642:                 if ($args->{'crstype'} eq 'Community') {
                   14643:                     $ccrole = 'co';
                   14644:                 }
                   14645:                 my %roleshash =
                   14646:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   14647:                                                   $args->{'ccdomain'},
                   14648:                                                   'userroles',['active'],[$ccrole],
                   14649:                                                   [$args->{'clonedomain'}]);
                   14650:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   14651:                     $can_clone = 1;
                   14652:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   14653:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   14654:                     $can_clone = 1;
1.1075.2.95  raeburn  14655:                 }
                   14656:             }
                   14657:             unless ($can_clone) {
                   14658:                 if ($args->{'crstype'} eq 'Community') {
                   14659:                     $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'});
                   14660:                 } else {
                   14661:                     $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  14662: 	        }
1.566     albertel 14663: 	    }
1.578     raeburn  14664:         }
1.566     albertel 14665:     }
                   14666:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14667: }
                   14668: 
1.444     albertel 14669: sub construct_course {
1.1075.2.59  raeburn  14670:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
1.444     albertel 14671:     my $outcome;
1.541     raeburn  14672:     my $linefeed =  '<br />'."\n";
                   14673:     if ($context eq 'auto') {
                   14674:         $linefeed = "\n";
                   14675:     }
1.566     albertel 14676: 
                   14677: #
                   14678: # Are we cloning?
                   14679: #
                   14680:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14681:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  14682: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 14683: 	if ($context ne 'auto') {
1.578     raeburn  14684:             if ($clonemsg ne '') {
                   14685: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   14686:             }
1.566     albertel 14687: 	}
                   14688: 	$outcome .= $clonemsg.$linefeed;
                   14689: 
                   14690:         if (!$can_clone) {
                   14691: 	    return (0,$outcome);
                   14692: 	}
                   14693:     }
                   14694: 
1.444     albertel 14695: #
                   14696: # Open course
                   14697: #
                   14698:     my $crstype = lc($args->{'crstype'});
                   14699:     my %cenv=();
                   14700:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   14701:                                              $args->{'cdescr'},
                   14702:                                              $args->{'curl'},
                   14703:                                              $args->{'course_home'},
                   14704:                                              $args->{'nonstandard'},
                   14705:                                              $args->{'crscode'},
                   14706:                                              $args->{'ccuname'}.':'.
                   14707:                                              $args->{'ccdomain'},
1.882     raeburn  14708:                                              $args->{'crstype'},
1.885     raeburn  14709:                                              $cnum,$context,$category);
1.444     albertel 14710: 
                   14711:     # Note: The testing routines depend on this being output; see 
                   14712:     # Utils::Course. This needs to at least be output as a comment
                   14713:     # if anyone ever decides to not show this, and Utils::Course::new
                   14714:     # will need to be suitably modified.
1.541     raeburn  14715:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  14716:     if ($$courseid =~ /^error:/) {
                   14717:         return (0,$outcome);
                   14718:     }
                   14719: 
1.444     albertel 14720: #
                   14721: # Check if created correctly
                   14722: #
1.479     albertel 14723:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 14724:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  14725:     if ($crsuhome eq 'no_host') {
                   14726:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   14727:         return (0,$outcome);
                   14728:     }
1.541     raeburn  14729:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 14730: 
1.444     albertel 14731: #
1.566     albertel 14732: # Do the cloning
                   14733: #   
                   14734:     if ($can_clone && $cloneid) {
                   14735: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   14736: 	if ($context ne 'auto') {
                   14737: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   14738: 	}
                   14739: 	$outcome .= $clonemsg.$linefeed;
                   14740: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 14741: # Copy all files
1.637     www      14742: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 14743: # Restore URL
1.566     albertel 14744: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 14745: # Restore title
1.566     albertel 14746: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  14747: # Restore creation date, creator and creation context.
                   14748:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   14749:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   14750:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 14751: # Mark as cloned
1.566     albertel 14752: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      14753: # Need to clone grading mode
                   14754:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   14755:         $cenv{'grading'}=$newenv{'grading'};
                   14756: # Do not clone these environment entries
                   14757:         &Apache::lonnet::del('environment',
                   14758:                   ['default_enrollment_start_date',
                   14759:                    'default_enrollment_end_date',
                   14760:                    'question.email',
                   14761:                    'policy.email',
                   14762:                    'comment.email',
                   14763:                    'pch.users.denied',
1.725     raeburn  14764:                    'plc.users.denied',
                   14765:                    'hidefromcat',
1.1075.2.36  raeburn  14766:                    'checkforpriv',
1.1075.2.59  raeburn  14767:                    'categories',
                   14768:                    'internal.uniquecode'],
1.638     www      14769:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  14770:         if ($args->{'textbook'}) {
                   14771:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   14772:         }
1.444     albertel 14773:     }
1.566     albertel 14774: 
1.444     albertel 14775: #
                   14776: # Set environment (will override cloned, if existing)
                   14777: #
                   14778:     my @sections = ();
                   14779:     my @xlists = ();
                   14780:     if ($args->{'crstype'}) {
                   14781:         $cenv{'type'}=$args->{'crstype'};
                   14782:     }
                   14783:     if ($args->{'crsid'}) {
                   14784:         $cenv{'courseid'}=$args->{'crsid'};
                   14785:     }
                   14786:     if ($args->{'crscode'}) {
                   14787:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   14788:     }
                   14789:     if ($args->{'crsquota'} ne '') {
                   14790:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   14791:     } else {
                   14792:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   14793:     }
                   14794:     if ($args->{'ccuname'}) {
                   14795:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   14796:                                         ':'.$args->{'ccdomain'};
                   14797:     } else {
                   14798:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   14799:     }
1.1075.2.31  raeburn  14800:     if ($args->{'defaultcredits'}) {
                   14801:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   14802:     }
1.444     albertel 14803:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   14804:     if ($args->{'crssections'}) {
                   14805:         $cenv{'internal.sectionnums'} = '';
                   14806:         if ($args->{'crssections'} =~ m/,/) {
                   14807:             @sections = split/,/,$args->{'crssections'};
                   14808:         } else {
                   14809:             $sections[0] = $args->{'crssections'};
                   14810:         }
                   14811:         if (@sections > 0) {
                   14812:             foreach my $item (@sections) {
                   14813:                 my ($sec,$gp) = split/:/,$item;
                   14814:                 my $class = $args->{'crscode'}.$sec;
                   14815:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   14816:                 $cenv{'internal.sectionnums'} .= $item.',';
                   14817:                 unless ($addcheck eq 'ok') {
                   14818:                     push @badclasses, $class;
                   14819:                 }
                   14820:             }
                   14821:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   14822:         }
                   14823:     }
                   14824: # do not hide course coordinator from staff listing, 
                   14825: # even if privileged
                   14826:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  14827: # add course coordinator's domain to domains to check for privileged users
                   14828: # if different to course domain
                   14829:     if ($$crsudom ne $args->{'ccdomain'}) {
                   14830:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   14831:     }
1.444     albertel 14832: # add crosslistings
                   14833:     if ($args->{'crsxlist'}) {
                   14834:         $cenv{'internal.crosslistings'}='';
                   14835:         if ($args->{'crsxlist'} =~ m/,/) {
                   14836:             @xlists = split/,/,$args->{'crsxlist'};
                   14837:         } else {
                   14838:             $xlists[0] = $args->{'crsxlist'};
                   14839:         }
                   14840:         if (@xlists > 0) {
                   14841:             foreach my $item (@xlists) {
                   14842:                 my ($xl,$gp) = split/:/,$item;
                   14843:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   14844:                 $cenv{'internal.crosslistings'} .= $item.',';
                   14845:                 unless ($addcheck eq 'ok') {
                   14846:                     push @badclasses, $xl;
                   14847:                 }
                   14848:             }
                   14849:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   14850:         }
                   14851:     }
                   14852:     if ($args->{'autoadds'}) {
                   14853:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   14854:     }
                   14855:     if ($args->{'autodrops'}) {
                   14856:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   14857:     }
                   14858: # check for notification of enrollment changes
                   14859:     my @notified = ();
                   14860:     if ($args->{'notify_owner'}) {
                   14861:         if ($args->{'ccuname'} ne '') {
                   14862:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   14863:         }
                   14864:     }
                   14865:     if ($args->{'notify_dc'}) {
                   14866:         if ($uname ne '') { 
1.630     raeburn  14867:             push(@notified,$uname.':'.$udom);
1.444     albertel 14868:         }
                   14869:     }
                   14870:     if (@notified > 0) {
                   14871:         my $notifylist;
                   14872:         if (@notified > 1) {
                   14873:             $notifylist = join(',',@notified);
                   14874:         } else {
                   14875:             $notifylist = $notified[0];
                   14876:         }
                   14877:         $cenv{'internal.notifylist'} = $notifylist;
                   14878:     }
                   14879:     if (@badclasses > 0) {
                   14880:         my %lt=&Apache::lonlocal::texthash(
                   14881:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.  However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
                   14882:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   14883:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   14884:         );
1.541     raeburn  14885:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   14886:                            ' ('.$lt{'adby'}.')';
                   14887:         if ($context eq 'auto') {
                   14888:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 14889:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  14890:             foreach my $item (@badclasses) {
                   14891:                 if ($context eq 'auto') {
                   14892:                     $outcome .= " - $item\n";
                   14893:                 } else {
                   14894:                     $outcome .= "<li>$item</li>\n";
                   14895:                 }
                   14896:             }
                   14897:             if ($context eq 'auto') {
                   14898:                 $outcome .= $linefeed;
                   14899:             } else {
1.566     albertel 14900:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  14901:             }
                   14902:         } 
1.444     albertel 14903:     }
                   14904:     if ($args->{'no_end_date'}) {
                   14905:         $args->{'endaccess'} = 0;
                   14906:     }
                   14907:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   14908:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   14909:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   14910:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   14911:     if ($args->{'showphotos'}) {
                   14912:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   14913:     }
                   14914:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   14915:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   14916:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   14917:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  14918:             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'); 
                   14919:             if ($context eq 'auto') {
                   14920:                 $outcome .= $krb_msg;
                   14921:             } else {
1.566     albertel 14922:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  14923:             }
                   14924:             $outcome .= $linefeed;
1.444     albertel 14925:         }
                   14926:     }
                   14927:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   14928:        if ($args->{'setpolicy'}) {
                   14929:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14930:        }
                   14931:        if ($args->{'setcontent'}) {
                   14932:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14933:        }
1.1075.2.110  raeburn  14934:        if ($args->{'setcomment'}) {
                   14935:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14936:        }
1.444     albertel 14937:     }
                   14938:     if ($args->{'reshome'}) {
                   14939: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   14940: 	$cenv{'reshome'}=~s/\/+$/\//;
                   14941:     }
                   14942: #
                   14943: # course has keyed access
                   14944: #
                   14945:     if ($args->{'setkeys'}) {
                   14946:        $cenv{'keyaccess'}='yes';
                   14947:     }
                   14948: # if specified, key authority is not course, but user
                   14949: # only active if keyaccess is yes
                   14950:     if ($args->{'keyauth'}) {
1.487     albertel 14951: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   14952: 	$user = &LONCAPA::clean_username($user);
                   14953: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     14954: 	if ($user ne '' && $domain ne '') {
1.487     albertel 14955: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 14956: 	}
                   14957:     }
                   14958: 
1.1075.2.59  raeburn  14959: #
                   14960: #  generate and store uniquecode (available to course requester), if course should have one.
                   14961: #
                   14962:     if ($args->{'uniquecode'}) {
                   14963:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   14964:         if ($code) {
                   14965:             $cenv{'internal.uniquecode'} = $code;
                   14966:             my %crsinfo =
                   14967:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   14968:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   14969:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   14970:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   14971:             }
                   14972:             if (ref($coderef)) {
                   14973:                 $$coderef = $code;
                   14974:             }
                   14975:         }
                   14976:     }
                   14977: 
1.444     albertel 14978:     if ($args->{'disresdis'}) {
                   14979:         $cenv{'pch.roles.denied'}='st';
                   14980:     }
                   14981:     if ($args->{'disablechat'}) {
                   14982:         $cenv{'plc.roles.denied'}='st';
                   14983:     }
                   14984: 
                   14985:     # Record we've not yet viewed the Course Initialization Helper for this 
                   14986:     # course
                   14987:     $cenv{'course.helper.not.run'} = 1;
                   14988:     #
                   14989:     # Use new Randomseed
                   14990:     #
                   14991:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   14992:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   14993:     #
                   14994:     # The encryption code and receipt prefix for this course
                   14995:     #
                   14996:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   14997:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   14998:     #
                   14999:     # By default, use standard grading
                   15000:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15001: 
1.541     raeburn  15002:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15003:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15004: #
                   15005: # Open all assignments
                   15006: #
                   15007:     if ($args->{'openall'}) {
                   15008:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   15009:        my %storecontent = ($storeunder         => time,
                   15010:                            $storeunder.'.type' => 'date_start');
                   15011:        
                   15012:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  15013:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15014:    }
                   15015: #
                   15016: # Set first page
                   15017: #
                   15018:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15019: 	    || ($cloneid)) {
1.445     albertel 15020: 	use LONCAPA::map;
1.444     albertel 15021: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15022: 
                   15023: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15024:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15025: 
1.444     albertel 15026:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15027:         my $title; my $url;
                   15028:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15029: 	    $title=&mt('Syllabus');
1.444     albertel 15030:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15031:         } else {
1.963     raeburn  15032:             $title=&mt('Table of Contents');
1.444     albertel 15033:             $url='/adm/navmaps';
                   15034:         }
1.445     albertel 15035: 
                   15036:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15037: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15038: 
                   15039: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15040:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15041:     }
1.566     albertel 15042: 
                   15043:     return (1,$outcome);
1.444     albertel 15044: }
                   15045: 
1.1075.2.59  raeburn  15046: sub make_unique_code {
                   15047:     my ($cdom,$cnum) = @_;
                   15048:     # get lock on uniquecodes db
                   15049:     my $lockhash = {
                   15050:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15051:                                                   ':'.$env{'user.domain'},
                   15052:                    };
                   15053:     my $tries = 0;
                   15054:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15055:     my ($code,$error);
                   15056: 
                   15057:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15058:         $tries ++;
                   15059:         sleep 1;
                   15060:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15061:     }
                   15062:     if ($gotlock eq 'ok') {
                   15063:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15064:         my $gotcode;
                   15065:         my $attempts = 0;
                   15066:         while ((!$gotcode) && ($attempts < 100)) {
                   15067:             $code = &generate_code();
                   15068:             if (!exists($currcodes{$code})) {
                   15069:                 $gotcode = 1;
                   15070:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15071:                     $error = 'nostore';
                   15072:                 }
                   15073:             }
                   15074:             $attempts ++;
                   15075:         }
                   15076:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15077:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15078:     } else {
                   15079:         $error = 'nolock';
                   15080:     }
                   15081:     return ($code,$error);
                   15082: }
                   15083: 
                   15084: sub generate_code {
                   15085:     my $code;
                   15086:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15087:     for (my $i=0; $i<6; $i++) {
                   15088:         my $lettnum = int (rand 2);
                   15089:         my $item = '';
                   15090:         if ($lettnum) {
                   15091:             $item = $letts[int( rand(18) )];
                   15092:         } else {
                   15093:             $item = 1+int( rand(8) );
                   15094:         }
                   15095:         $code .= $item;
                   15096:     }
                   15097:     return $code;
                   15098: }
                   15099: 
1.444     albertel 15100: ############################################################
                   15101: ############################################################
                   15102: 
1.953     droeschl 15103: #SD
                   15104: # only Community and Course, or anything else?
1.378     raeburn  15105: sub course_type {
                   15106:     my ($cid) = @_;
                   15107:     if (!defined($cid)) {
                   15108:         $cid = $env{'request.course.id'};
                   15109:     }
1.404     albertel 15110:     if (defined($env{'course.'.$cid.'.type'})) {
                   15111:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15112:     } else {
                   15113:         return 'Course';
1.377     raeburn  15114:     }
                   15115: }
1.156     albertel 15116: 
1.406     raeburn  15117: sub group_term {
                   15118:     my $crstype = &course_type();
                   15119:     my %names = (
                   15120:                   'Course' => 'group',
1.865     raeburn  15121:                   'Community' => 'group',
1.406     raeburn  15122:                 );
                   15123:     return $names{$crstype};
                   15124: }
                   15125: 
1.902     raeburn  15126: sub course_types {
1.1075.2.59  raeburn  15127:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  15128:     my %typename = (
                   15129:                          official   => 'Official course',
                   15130:                          unofficial => 'Unofficial course',
                   15131:                          community  => 'Community',
1.1075.2.59  raeburn  15132:                          textbook   => 'Textbook course',
1.902     raeburn  15133:                    );
                   15134:     return (\@types,\%typename);
                   15135: }
                   15136: 
1.156     albertel 15137: sub icon {
                   15138:     my ($file)=@_;
1.505     albertel 15139:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15140:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15141:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15142:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15143: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15144: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15145: 	            $curfext.".gif") {
                   15146: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15147: 		$curfext.".gif";
                   15148: 	}
                   15149:     }
1.249     albertel 15150:     return &lonhttpdurl($iconname);
1.154     albertel 15151: } 
1.84      albertel 15152: 
1.575     albertel 15153: sub lonhttpdurl {
1.692     www      15154: #
                   15155: # Had been used for "small fry" static images on separate port 8080.
                   15156: # Modify here if lightweight http functionality desired again.
                   15157: # Currently eliminated due to increasing firewall issues.
                   15158: #
1.575     albertel 15159:     my ($url)=@_;
1.692     www      15160:     return $url;
1.215     albertel 15161: }
                   15162: 
1.213     albertel 15163: sub connection_aborted {
                   15164:     my ($r)=@_;
                   15165:     $r->print(" ");$r->rflush();
                   15166:     my $c = $r->connection;
                   15167:     return $c->aborted();
                   15168: }
                   15169: 
1.221     foxr     15170: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15171: #    strings as 'strings'.
                   15172: sub escape_single {
1.221     foxr     15173:     my ($input) = @_;
1.223     albertel 15174:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15175:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15176:     return $input;
                   15177: }
1.223     albertel 15178: 
1.222     foxr     15179: #  Same as escape_single, but escape's "'s  This 
                   15180: #  can be used for  "strings"
                   15181: sub escape_double {
                   15182:     my ($input) = @_;
                   15183:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15184:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15185:     return $input;
                   15186: }
1.223     albertel 15187:  
1.222     foxr     15188: #   Escapes the last element of a full URL.
                   15189: sub escape_url {
                   15190:     my ($url)   = @_;
1.238     raeburn  15191:     my @urlslices = split(/\//, $url,-1);
1.369     www      15192:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  15193:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15194: }
1.462     albertel 15195: 
1.820     raeburn  15196: sub compare_arrays {
                   15197:     my ($arrayref1,$arrayref2) = @_;
                   15198:     my (@difference,%count);
                   15199:     @difference = ();
                   15200:     %count = ();
                   15201:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   15202:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   15203:         foreach my $element (keys(%count)) {
                   15204:             if ($count{$element} == 1) {
                   15205:                 push(@difference,$element);
                   15206:             }
                   15207:         }
                   15208:     }
                   15209:     return @difference;
                   15210: }
                   15211: 
1.817     bisitz   15212: # -------------------------------------------------------- Initialize user login
1.462     albertel 15213: sub init_user_environment {
1.463     albertel 15214:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 15215:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   15216: 
                   15217:     my $public=($username eq 'public' && $domain eq 'public');
                   15218: 
                   15219: # See if old ID present, if so, remove
                   15220: 
1.1062    raeburn  15221:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 15222:     my $now=time;
                   15223: 
                   15224:     if ($public) {
                   15225: 	my $max_public=100;
                   15226: 	my $oldest;
                   15227: 	my $oldest_time=0;
                   15228: 	for(my $next=1;$next<=$max_public;$next++) {
                   15229: 	    if (-e $lonids."/publicuser_$next.id") {
                   15230: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   15231: 		if ($mtime<$oldest_time || !$oldest_time) {
                   15232: 		    $oldest_time=$mtime;
                   15233: 		    $oldest=$next;
                   15234: 		}
                   15235: 	    } else {
                   15236: 		$cookie="publicuser_$next";
                   15237: 		last;
                   15238: 	    }
                   15239: 	}
                   15240: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   15241:     } else {
1.463     albertel 15242: 	# if this isn't a robot, kill any existing non-robot sessions
                   15243: 	if (!$args->{'robot'}) {
                   15244: 	    opendir(DIR,$lonids);
                   15245: 	    while ($filename=readdir(DIR)) {
                   15246: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   15247: 		    unlink($lonids.'/'.$filename);
                   15248: 		}
1.462     albertel 15249: 	    }
1.463     albertel 15250: 	    closedir(DIR);
1.1075.2.84  raeburn  15251: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   15252:             my $namespace = 'nohist_courseeditor';
                   15253:             my $lockingkey = 'paste'."\0".'locked_num';
                   15254:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15255:                                                 $domain,$username);
                   15256:             if (exists($lockhash{$lockingkey})) {
                   15257:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15258:                 unless ($delresult eq 'ok') {
                   15259:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15260:                 }
                   15261:             }
1.462     albertel 15262: 	}
                   15263: # Give them a new cookie
1.463     albertel 15264: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15265: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15266: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15267:     
                   15268: # Initialize roles
                   15269: 
1.1062    raeburn  15270: 	($userroles,$firstaccenv,$timerintenv) = 
                   15271:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15272:     }
                   15273: # ------------------------------------ Check browser type and MathML capability
                   15274: 
1.1075.2.77  raeburn  15275:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15276:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15277: 
                   15278: # ------------------------------------------------------------- Get environment
                   15279: 
                   15280:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15281:     my ($tmp) = keys(%userenv);
                   15282:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15283:     } else {
                   15284: 	undef(%userenv);
                   15285:     }
                   15286:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15287: 	$form->{'interface'}=$userenv{'interface'};
                   15288:     }
                   15289:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15290: 
                   15291: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15292:     foreach my $option ('interface','localpath','localres') {
                   15293:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15294:     }
                   15295: # --------------------------------------------------------- Write first profile
                   15296: 
                   15297:     {
                   15298: 	my %initial_env = 
                   15299: 	    ("user.name"          => $username,
                   15300: 	     "user.domain"        => $domain,
                   15301: 	     "user.home"          => $authhost,
                   15302: 	     "browser.type"       => $clientbrowser,
                   15303: 	     "browser.version"    => $clientversion,
                   15304: 	     "browser.mathml"     => $clientmathml,
                   15305: 	     "browser.unicode"    => $clientunicode,
                   15306: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  15307:              "browser.mobile"     => $clientmobile,
                   15308:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  15309:              "browser.osversion"  => $clientosversion,
1.462     albertel 15310: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15311: 	     "request.course.fn"  => '',
                   15312: 	     "request.course.uri" => '',
                   15313: 	     "request.course.sec" => '',
                   15314: 	     "request.role"       => 'cm',
                   15315: 	     "request.role.adv"   => $env{'user.adv'},
                   15316: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   15317: 
                   15318:         if ($form->{'localpath'}) {
                   15319: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15320: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15321:         }
                   15322: 	
                   15323: 	if ($form->{'interface'}) {
                   15324: 	    $form->{'interface'}=~s/\W//gs;
                   15325: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15326: 	    $env{'browser.interface'}=$form->{'interface'};
                   15327: 	}
                   15328: 
1.1075.2.54  raeburn  15329:         if ($form->{'iptoken'}) {
                   15330:             my $lonhost = $r->dir_config('lonHostID');
                   15331:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15332:             $env{'user.noloadbalance'} = $lonhost;
                   15333:         }
                   15334: 
1.981     raeburn  15335:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  15336:         my %domdef;
                   15337:         unless ($domain eq 'public') {
                   15338:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   15339:         }
1.980     raeburn  15340: 
1.1075.2.7  raeburn  15341:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  15342:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  15343:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   15344:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  15345:         }
                   15346: 
1.1075.2.59  raeburn  15347:         foreach my $crstype ('official','unofficial','community','textbook') {
1.765     raeburn  15348:             $userenv{'canrequest.'.$crstype} =
                   15349:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  15350:                                                   'reload','requestcourses',
                   15351:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  15352:         }
                   15353: 
1.1075.2.14  raeburn  15354:         $userenv{'canrequest.author'} =
                   15355:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   15356:                                         'reload','requestauthor',
                   15357:                                         \%userenv,\%domdef,\%is_adv);
                   15358:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   15359:                                              $domain,$username);
                   15360:         my $reqstatus = $reqauthor{'author_status'};
                   15361:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   15362:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   15363:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   15364:                                                   $reqauthor{'author'}{'timestamp'};
                   15365:             }
                   15366:         }
                   15367: 
1.462     albertel 15368: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  15369: 
1.462     albertel 15370: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   15371: 		 &GDBM_WRCREAT(),0640)) {
                   15372: 	    &_add_to_env(\%disk_env,\%initial_env);
                   15373: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   15374: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  15375:             if (ref($firstaccenv) eq 'HASH') {
                   15376:                 &_add_to_env(\%disk_env,$firstaccenv);
                   15377:             }
                   15378:             if (ref($timerintenv) eq 'HASH') {
                   15379:                 &_add_to_env(\%disk_env,$timerintenv);
                   15380:             }
1.463     albertel 15381: 	    if (ref($args->{'extra_env'})) {
                   15382: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   15383: 	    }
1.462     albertel 15384: 	    untie(%disk_env);
                   15385: 	} else {
1.705     tempelho 15386: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   15387: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 15388: 	    return 'error: '.$!;
                   15389: 	}
                   15390:     }
                   15391:     $env{'request.role'}='cm';
                   15392:     $env{'request.role.adv'}=$env{'user.adv'};
                   15393:     $env{'browser.type'}=$clientbrowser;
                   15394: 
                   15395:     return $cookie;
                   15396: 
                   15397: }
                   15398: 
                   15399: sub _add_to_env {
                   15400:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  15401:     if (ref($env_data) eq 'HASH') {
                   15402:         while (my ($key,$value) = each(%$env_data)) {
                   15403: 	    $idf->{$prefix.$key} = $value;
                   15404: 	    $env{$prefix.$key}   = $value;
                   15405:         }
1.462     albertel 15406:     }
                   15407: }
                   15408: 
1.685     tempelho 15409: # --- Get the symbolic name of a problem and the url
                   15410: sub get_symb {
                   15411:     my ($request,$silent) = @_;
1.726     raeburn  15412:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 15413:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   15414:     if ($symb eq '') {
                   15415:         if (!$silent) {
1.1071    raeburn  15416:             if (ref($request)) { 
                   15417:                 $request->print("Unable to handle ambiguous references:$url:.");
                   15418:             }
1.685     tempelho 15419:             return ();
                   15420:         }
                   15421:     }
                   15422:     &Apache::lonenc::check_decrypt(\$symb);
                   15423:     return ($symb);
                   15424: }
                   15425: 
                   15426: # --------------------------------------------------------------Get annotation
                   15427: 
                   15428: sub get_annotation {
                   15429:     my ($symb,$enc) = @_;
                   15430: 
                   15431:     my $key = $symb;
                   15432:     if (!$enc) {
                   15433:         $key =
                   15434:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   15435:     }
                   15436:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   15437:     return $annotation{$key};
                   15438: }
                   15439: 
                   15440: sub clean_symb {
1.731     raeburn  15441:     my ($symb,$delete_enc) = @_;
1.685     tempelho 15442: 
                   15443:     &Apache::lonenc::check_decrypt(\$symb);
                   15444:     my $enc = $env{'request.enc'};
1.731     raeburn  15445:     if ($delete_enc) {
1.730     raeburn  15446:         delete($env{'request.enc'});
                   15447:     }
1.685     tempelho 15448: 
                   15449:     return ($symb,$enc);
                   15450: }
1.462     albertel 15451: 
1.1075.2.69  raeburn  15452: ############################################################
                   15453: ############################################################
                   15454: 
                   15455: =pod
                   15456: 
                   15457: =head1 Routines for building display used to search for courses
                   15458: 
                   15459: 
                   15460: =over 4
                   15461: 
                   15462: =item * &build_filters()
                   15463: 
                   15464: Create markup for a table used to set filters to use when selecting
                   15465: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   15466: and quotacheck.pl
                   15467: 
                   15468: 
                   15469: Inputs:
                   15470: 
                   15471: filterlist - anonymous array of fields to include as potential filters
                   15472: 
                   15473: crstype - course type
                   15474: 
                   15475: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   15476:               to pop-open a course selector (will contain "extra element").
                   15477: 
                   15478: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   15479: 
                   15480: filter - anonymous hash of criteria and their values
                   15481: 
                   15482: action - form action
                   15483: 
                   15484: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   15485: 
                   15486: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   15487: 
                   15488: cloneruname - username of owner of new course who wants to clone
                   15489: 
                   15490: clonerudom - domain of owner of new course who wants to clone
                   15491: 
                   15492: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   15493: 
                   15494: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   15495: 
                   15496: codedom - domain
                   15497: 
                   15498: formname - value of form element named "form".
                   15499: 
                   15500: fixeddom - domain, if fixed.
                   15501: 
                   15502: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   15503: 
                   15504: cnameelement - name of form element in form on opener page which will receive title of selected course
                   15505: 
                   15506: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   15507: 
                   15508: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   15509: 
                   15510: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   15511: 
                   15512: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   15513: 
                   15514: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   15515: 
                   15516: 
                   15517: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   15518: 
                   15519: 
                   15520: Side Effects: None
                   15521: 
                   15522: =cut
                   15523: 
                   15524: # ---------------------------------------------- search for courses based on last activity etc.
                   15525: 
                   15526: sub build_filters {
                   15527:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   15528:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   15529:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   15530:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   15531:         $clonetext,$clonewarning) = @_;
                   15532:     my ($list,$jscript);
                   15533:     my $onchange = 'javascript:updateFilters(this)';
                   15534:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   15535:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   15536:         $typeselectform,$instcodetitle);
                   15537:     if ($formname eq '') {
                   15538:         $formname = $caller;
                   15539:     }
                   15540:     foreach my $item (@{$filterlist}) {
                   15541:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   15542:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   15543:             if ($item eq 'domainfilter') {
                   15544:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   15545:             } elsif ($item eq 'coursefilter') {
                   15546:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   15547:             } elsif ($item eq 'ownerfilter') {
                   15548:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15549:             } elsif ($item eq 'ownerdomfilter') {
                   15550:                 $filter->{'ownerdomfilter'} =
                   15551:                     &LONCAPA::clean_domain($filter->{$item});
                   15552:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   15553:                                                        'ownerdomfilter',1);
                   15554:             } elsif ($item eq 'personfilter') {
                   15555:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15556:             } elsif ($item eq 'persondomfilter') {
                   15557:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   15558:                                                         'persondomfilter',1);
                   15559:             } else {
                   15560:                 $filter->{$item} =~ s/\W//g;
                   15561:             }
                   15562:             if (!$filter->{$item}) {
                   15563:                 $filter->{$item} = '';
                   15564:             }
                   15565:         }
                   15566:         if ($item eq 'domainfilter') {
                   15567:             my $allow_blank = 1;
                   15568:             if ($formname eq 'portform') {
                   15569:                 $allow_blank=0;
                   15570:             } elsif ($formname eq 'studentform') {
                   15571:                 $allow_blank=0;
                   15572:             }
                   15573:             if ($fixeddom) {
                   15574:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   15575:                                     ' value="'.$codedom.'" />'.
                   15576:                                     &Apache::lonnet::domain($codedom,'description');
                   15577:             } else {
                   15578:                 $domainselectform = &select_dom_form($filter->{$item},
                   15579:                                                      'domainfilter',
                   15580:                                                       $allow_blank,'',$onchange);
                   15581:             }
                   15582:         } else {
                   15583:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   15584:         }
                   15585:     }
                   15586: 
                   15587:     # last course activity filter and selection
                   15588:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   15589: 
                   15590:     # course created filter and selection
                   15591:     if (exists($filter->{'createdfilter'})) {
                   15592:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   15593:     }
                   15594: 
                   15595:     my %lt = &Apache::lonlocal::texthash(
                   15596:                 'cac' => "$crstype Activity",
                   15597:                 'ccr' => "$crstype Created",
                   15598:                 'cde' => "$crstype Title",
                   15599:                 'cdo' => "$crstype Domain",
                   15600:                 'ins' => 'Institutional Code',
                   15601:                 'inc' => 'Institutional Categorization',
                   15602:                 'cow' => "$crstype Owner/Co-owner",
                   15603:                 'cop' => "$crstype Personnel Includes",
                   15604:                 'cog' => 'Type',
                   15605:              );
                   15606: 
                   15607:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15608:         my $typeval = 'Course';
                   15609:         if ($crstype eq 'Community') {
                   15610:             $typeval = 'Community';
                   15611:         }
                   15612:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   15613:     } else {
                   15614:         $typeselectform =  '<select name="type" size="1"';
                   15615:         if ($onchange) {
                   15616:             $typeselectform .= ' onchange="'.$onchange.'"';
                   15617:         }
                   15618:         $typeselectform .= '>'."\n";
                   15619:         foreach my $posstype ('Course','Community') {
                   15620:             $typeselectform.='<option value="'.$posstype.'"'.
                   15621:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   15622:         }
                   15623:         $typeselectform.="</select>";
                   15624:     }
                   15625: 
                   15626:     my ($cloneableonlyform,$cloneabletitle);
                   15627:     if (exists($filter->{'cloneableonly'})) {
                   15628:         my $cloneableon = '';
                   15629:         my $cloneableoff = ' checked="checked"';
                   15630:         if ($filter->{'cloneableonly'}) {
                   15631:             $cloneableon = $cloneableoff;
                   15632:             $cloneableoff = '';
                   15633:         }
                   15634:         $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>';
                   15635:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  15636:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  15637:         } else {
                   15638:             $cloneabletitle = &mt('Cloneable by you');
                   15639:         }
                   15640:     }
                   15641:     my $officialjs;
                   15642:     if ($crstype eq 'Course') {
                   15643:         if (exists($filter->{'instcodefilter'})) {
                   15644: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   15645: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   15646:             if ($codedom) {
                   15647:                 $officialjs = 1;
                   15648:                 ($instcodeform,$jscript,$$numtitlesref) =
                   15649:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   15650:                                                                   $officialjs,$codetitlesref);
                   15651:                 if ($jscript) {
                   15652:                     $jscript = '<script type="text/javascript">'."\n".
                   15653:                                '// <![CDATA['."\n".
                   15654:                                $jscript."\n".
                   15655:                                '// ]]>'."\n".
                   15656:                                '</script>'."\n";
                   15657:                 }
                   15658:             }
                   15659:             if ($instcodeform eq '') {
                   15660:                 $instcodeform =
                   15661:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   15662:                     $list->{'instcodefilter'}.'" />';
                   15663:                 $instcodetitle = $lt{'ins'};
                   15664:             } else {
                   15665:                 $instcodetitle = $lt{'inc'};
                   15666:             }
                   15667:             if ($fixeddom) {
                   15668:                 $instcodetitle .= '<br />('.$codedom.')';
                   15669:             }
                   15670:         }
                   15671:     }
                   15672:     my $output = qq|
                   15673: <form method="post" name="filterpicker" action="$action">
                   15674: <input type="hidden" name="form" value="$formname" />
                   15675: |;
                   15676:     if ($formname eq 'modifycourse') {
                   15677:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   15678:                    '<input type="hidden" name="prevphase" value="'.
                   15679:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  15680:     } elsif ($formname eq 'quotacheck') {
                   15681:         $output .= qq|
                   15682: <input type="hidden" name="sortby" value="" />
                   15683: <input type="hidden" name="sortorder" value="" />
                   15684: |;
                   15685:     } else {
1.1075.2.69  raeburn  15686:         my $name_input;
                   15687:         if ($cnameelement ne '') {
                   15688:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   15689:                           $cnameelement.'" />';
                   15690:         }
                   15691:         $output .= qq|
                   15692: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   15693: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   15694: $name_input
                   15695: $roleelement
                   15696: $multelement
                   15697: $typeelement
                   15698: |;
                   15699:         if ($formname eq 'portform') {
                   15700:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   15701:         }
                   15702:     }
                   15703:     if ($fixeddom) {
                   15704:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   15705:     }
                   15706:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   15707:     if ($sincefilterform) {
                   15708:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   15709:                   .$sincefilterform
                   15710:                   .&Apache::lonhtmlcommon::row_closure();
                   15711:     }
                   15712:     if ($createdfilterform) {
                   15713:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   15714:                   .$createdfilterform
                   15715:                   .&Apache::lonhtmlcommon::row_closure();
                   15716:     }
                   15717:     if ($domainselectform) {
                   15718:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   15719:                   .$domainselectform
                   15720:                   .&Apache::lonhtmlcommon::row_closure();
                   15721:     }
                   15722:     if ($typeselectform) {
                   15723:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15724:             $output .= $typeselectform;
                   15725:         } else {
                   15726:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   15727:                       .$typeselectform
                   15728:                       .&Apache::lonhtmlcommon::row_closure();
                   15729:         }
                   15730:     }
                   15731:     if ($instcodeform) {
                   15732:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   15733:                   .$instcodeform
                   15734:                   .&Apache::lonhtmlcommon::row_closure();
                   15735:     }
                   15736:     if (exists($filter->{'ownerfilter'})) {
                   15737:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   15738:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15739:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   15740:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15741:                    $ownerdomselectform.'</td></tr></table>'.
                   15742:                    &Apache::lonhtmlcommon::row_closure();
                   15743:     }
                   15744:     if (exists($filter->{'personfilter'})) {
                   15745:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   15746:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15747:                    '<input type="text" name="personfilter" size="20" value="'.
                   15748:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15749:                    $persondomselectform.'</td></tr></table>'.
                   15750:                    &Apache::lonhtmlcommon::row_closure();
                   15751:     }
                   15752:     if (exists($filter->{'coursefilter'})) {
                   15753:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   15754:                   .'<input type="text" name="coursefilter" size="25" value="'
                   15755:                   .$list->{'coursefilter'}.'" />'
                   15756:                   .&Apache::lonhtmlcommon::row_closure();
                   15757:     }
                   15758:     if ($cloneableonlyform) {
                   15759:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   15760:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   15761:     }
                   15762:     if (exists($filter->{'descriptfilter'})) {
                   15763:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   15764:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   15765:                   .$list->{'descriptfilter'}.'" />'
                   15766:                   .&Apache::lonhtmlcommon::row_closure(1);
                   15767:     }
                   15768:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   15769:                '<input type="hidden" name="updater" value="" />'."\n".
                   15770:                '<input type="submit" name="gosearch" value="'.
                   15771:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   15772:     return $jscript.$clonewarning.$output;
                   15773: }
                   15774: 
                   15775: =pod
                   15776: 
                   15777: =item * &timebased_select_form()
                   15778: 
                   15779: Create markup for a dropdown list used to select a time-based
                   15780: filter e.g., Course Activity, Course Created, when searching for courses
                   15781: or communities
                   15782: 
                   15783: Inputs:
                   15784: 
                   15785: item - name of form element (sincefilter or createdfilter)
                   15786: 
                   15787: filter - anonymous hash of criteria and their values
                   15788: 
                   15789: Returns: HTML for a select box contained a blank, then six time selections,
                   15790:          with value set in incoming form variables currently selected.
                   15791: 
                   15792: Side Effects: None
                   15793: 
                   15794: =cut
                   15795: 
                   15796: sub timebased_select_form {
                   15797:     my ($item,$filter) = @_;
                   15798:     if (ref($filter) eq 'HASH') {
                   15799:         $filter->{$item} =~ s/[^\d-]//g;
                   15800:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   15801:         return &select_form(
                   15802:                             $filter->{$item},
                   15803:                             $item,
                   15804:                             {      '-1' => '',
                   15805:                                 '86400' => &mt('today'),
                   15806:                                '604800' => &mt('last week'),
                   15807:                               '2592000' => &mt('last month'),
                   15808:                               '7776000' => &mt('last three months'),
                   15809:                              '15552000' => &mt('last six months'),
                   15810:                              '31104000' => &mt('last year'),
                   15811:                     'select_form_order' =>
                   15812:                            ['-1','86400','604800','2592000','7776000',
                   15813:                             '15552000','31104000']});
                   15814:     }
                   15815: }
                   15816: 
                   15817: =pod
                   15818: 
                   15819: =item * &js_changer()
                   15820: 
                   15821: Create script tag containing Javascript used to submit course search form
                   15822: when course type or domain is changed, and also to hide 'Searching ...' on
                   15823: page load completion for page showing search result.
                   15824: 
                   15825: Inputs: None
                   15826: 
                   15827: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   15828: 
                   15829: Side Effects: None
                   15830: 
                   15831: =cut
                   15832: 
                   15833: sub js_changer {
                   15834:     return <<ENDJS;
                   15835: <script type="text/javascript">
                   15836: // <![CDATA[
                   15837: function updateFilters(caller) {
                   15838:     if (typeof(caller) != "undefined") {
                   15839:         document.filterpicker.updater.value = caller.name;
                   15840:     }
                   15841:     document.filterpicker.submit();
                   15842: }
                   15843: 
                   15844: function hideSearching() {
                   15845:     if (document.getElementById('searching')) {
                   15846:         document.getElementById('searching').style.display = 'none';
                   15847:     }
                   15848:     return;
                   15849: }
                   15850: 
                   15851: // ]]>
                   15852: </script>
                   15853: 
                   15854: ENDJS
                   15855: }
                   15856: 
                   15857: =pod
                   15858: 
                   15859: =item * &search_courses()
                   15860: 
                   15861: Process selected filters form course search form and pass to lonnet::courseiddump
                   15862: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   15863: 
                   15864: Inputs:
                   15865: 
                   15866: dom - domain being searched
                   15867: 
                   15868: type - course type ('Course' or 'Community' or '.' if any).
                   15869: 
                   15870: filter - anonymous hash of criteria and their values
                   15871: 
                   15872: numtitles - for institutional codes - number of categories
                   15873: 
                   15874: cloneruname - optional username of new course owner
                   15875: 
                   15876: clonerudom - optional domain of new course owner
                   15877: 
1.1075.2.95  raeburn  15878: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  15879:             (used when DC is using course creation form)
                   15880: 
                   15881: codetitles - reference to array of titles of components in institutional codes (official courses).
                   15882: 
1.1075.2.95  raeburn  15883: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   15884:            (and so can clone automatically)
                   15885: 
                   15886: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   15887: 
                   15888: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   15889:               courses to clone
1.1075.2.69  raeburn  15890: 
                   15891: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   15892: 
                   15893: 
                   15894: Side Effects: None
                   15895: 
                   15896: =cut
                   15897: 
                   15898: 
                   15899: sub search_courses {
1.1075.2.95  raeburn  15900:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   15901:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  15902:     my (%courses,%showcourses,$cloner);
                   15903:     if (($filter->{'ownerfilter'} ne '') ||
                   15904:         ($filter->{'ownerdomfilter'} ne '')) {
                   15905:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   15906:                                        $filter->{'ownerdomfilter'};
                   15907:     }
                   15908:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   15909:         if (!$filter->{$item}) {
                   15910:             $filter->{$item}='.';
                   15911:         }
                   15912:     }
                   15913:     my $now = time;
                   15914:     my $timefilter =
                   15915:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   15916:     my ($createdbefore,$createdafter);
                   15917:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   15918:         $createdbefore = $now;
                   15919:         $createdafter = $now-$filter->{'createdfilter'};
                   15920:     }
                   15921:     my ($instcodefilter,$regexpok);
                   15922:     if ($numtitles) {
                   15923:         if ($env{'form.official'} eq 'on') {
                   15924:             $instcodefilter =
                   15925:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   15926:             $regexpok = 1;
                   15927:         } elsif ($env{'form.official'} eq 'off') {
                   15928:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   15929:             unless ($instcodefilter eq '') {
                   15930:                 $regexpok = -1;
                   15931:             }
                   15932:         }
                   15933:     } else {
                   15934:         $instcodefilter = $filter->{'instcodefilter'};
                   15935:     }
                   15936:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   15937:     if ($type eq '') { $type = '.'; }
                   15938: 
                   15939:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   15940:         $cloner = $cloneruname.':'.$clonerudom;
                   15941:     }
                   15942:     %courses = &Apache::lonnet::courseiddump($dom,
                   15943:                                              $filter->{'descriptfilter'},
                   15944:                                              $timefilter,
                   15945:                                              $instcodefilter,
                   15946:                                              $filter->{'combownerfilter'},
                   15947:                                              $filter->{'coursefilter'},
                   15948:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  15949:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  15950:                                              $filter->{'cloneableonly'},
                   15951:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  15952:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  15953:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   15954:         my $ccrole;
                   15955:         if ($type eq 'Community') {
                   15956:             $ccrole = 'co';
                   15957:         } else {
                   15958:             $ccrole = 'cc';
                   15959:         }
                   15960:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   15961:                                                      $filter->{'persondomfilter'},
                   15962:                                                      'userroles',undef,
                   15963:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   15964:                                                      $dom);
                   15965:         foreach my $role (keys(%rolehash)) {
                   15966:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   15967:             my $cid = $cdom.'_'.$cnum;
                   15968:             if (exists($courses{$cid})) {
                   15969:                 if (ref($courses{$cid}) eq 'HASH') {
                   15970:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   15971:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
                   15972:                             push (@{$courses{$cid}{roles}},$courserole);
                   15973:                         }
                   15974:                     } else {
                   15975:                         $courses{$cid}{roles} = [$courserole];
                   15976:                     }
                   15977:                     $showcourses{$cid} = $courses{$cid};
                   15978:                 }
                   15979:             }
                   15980:         }
                   15981:         %courses = %showcourses;
                   15982:     }
                   15983:     return %courses;
                   15984: }
                   15985: 
                   15986: =pod
                   15987: 
                   15988: =back
                   15989: 
1.1075.2.88  raeburn  15990: =head1 Routines for version requirements for current course.
                   15991: 
                   15992: =over 4
                   15993: 
                   15994: =item * &check_release_required()
                   15995: 
                   15996: Compares required LON-CAPA version with version on server, and
                   15997: if required version is newer looks for a server with the required version.
                   15998: 
                   15999: Looks first at servers in user's owen domain; if none suitable, looks at
                   16000: servers in course's domain are permitted to host sessions for user's domain.
                   16001: 
                   16002: Inputs:
                   16003: 
                   16004: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16005: 
                   16006: $courseid - Course ID of current course
                   16007: 
                   16008: $rolecode - User's current role in course (for switchserver query string).
                   16009: 
                   16010: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16011: 
                   16012: 
                   16013: Returns:
                   16014: 
                   16015: $switchserver - query string tp append to /adm/switchserver call (if
                   16016:                 current server's LON-CAPA version is too old.
                   16017: 
                   16018: $warning - Message is displayed if no suitable server could be found.
                   16019: 
                   16020: =cut
                   16021: 
                   16022: sub check_release_required {
                   16023:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16024:     my ($switchserver,$warning);
                   16025:     if ($required ne '') {
                   16026:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16027:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16028:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16029:             my $otherserver;
                   16030:             if (($major eq '' && $minor eq '') ||
                   16031:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16032:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16033:                 my $switchlcrev =
                   16034:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16035:                                                            $userdomserver);
                   16036:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16037:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16038:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16039:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16040:                     if ($cdom ne $env{'user.domain'}) {
                   16041:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16042:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16043:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16044:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16045:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16046:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16047:                         my $canhost =
                   16048:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16049:                                                               $coursedomserver,
                   16050:                                                               $remoterev,
                   16051:                                                               $udomdefaults{'remotesessions'},
                   16052:                                                               $defdomdefaults{'hostedsessions'});
                   16053: 
                   16054:                         if ($canhost) {
                   16055:                             $otherserver = $coursedomserver;
                   16056:                         } else {
                   16057:                             $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.");
                   16058:                         }
                   16059:                     } else {
                   16060:                         $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).");
                   16061:                     }
                   16062:                 } else {
                   16063:                     $otherserver = $userdomserver;
                   16064:                 }
                   16065:             }
                   16066:             if ($otherserver ne '') {
                   16067:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16068:             }
                   16069:         }
                   16070:     }
                   16071:     return ($switchserver,$warning);
                   16072: }
                   16073: 
                   16074: =pod
                   16075: 
                   16076: =item * &check_release_result()
                   16077: 
                   16078: Inputs:
                   16079: 
                   16080: $switchwarning - Warning message if no suitable server found to host session.
                   16081: 
                   16082: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16083:                 and current role.
                   16084: 
                   16085: Returns: HTML to display with information about requirement to switch server.
                   16086:          Either displaying warning with link to Roles/Courses screen or
                   16087:          display link to switchserver.
                   16088: 
1.1075.2.69  raeburn  16089: =cut
                   16090: 
1.1075.2.88  raeburn  16091: sub check_release_result {
                   16092:     my ($switchwarning,$switchserver) = @_;
                   16093:     my $output = &start_page('Selected course unavailable on this server').
                   16094:                  '<p class="LC_warning">';
                   16095:     if ($switchwarning) {
                   16096:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16097:         if (&show_course()) {
                   16098:             $output .= &mt('Display courses');
                   16099:         } else {
                   16100:             $output .= &mt('Display roles');
                   16101:         }
                   16102:         $output .= '</a>';
                   16103:     } elsif ($switchserver) {
                   16104:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16105:                    '<br />'.
                   16106:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16107:                    &mt('Switch Server').
                   16108:                    '</a>';
                   16109:     }
                   16110:     $output .= '</p>'.&end_page();
                   16111:     return $output;
                   16112: }
                   16113: 
                   16114: =pod
                   16115: 
                   16116: =item * &needs_coursereinit()
                   16117: 
                   16118: Determine if course contents stored for user's session needs to be
                   16119: refreshed, because content has changed since "Big Hash" last tied.
                   16120: 
                   16121: Check for change is made if time last checked is more than 10 minutes ago
                   16122: (by default).
                   16123: 
                   16124: Inputs:
                   16125: 
                   16126: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16127: 
                   16128: $interval (optional) - Time which may elapse (in s) between last check for content
                   16129:                        change in current course. (default: 600 s).
                   16130: 
                   16131: Returns: an array; first element is:
                   16132: 
                   16133: =over 4
                   16134: 
                   16135: 'switch' - if content updates mean user's session
                   16136:            needs to be switched to a server running a newer LON-CAPA version
                   16137: 
                   16138: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16139:            on current server hosting user's session
                   16140: 
                   16141: ''       - if no action required.
                   16142: 
                   16143: =back
                   16144: 
                   16145: If first item element is 'switch':
                   16146: 
                   16147: second item is $switchwarning - Warning message if no suitable server found to host session.
                   16148: 
                   16149: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16150:                               and current role.
                   16151: 
                   16152: otherwise: no other elements returned.
                   16153: 
                   16154: =back
                   16155: 
                   16156: =cut
                   16157: 
                   16158: sub needs_coursereinit {
                   16159:     my ($loncaparev,$interval) = @_;
                   16160:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16161:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16162:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16163:     my $now = time;
                   16164:     if ($interval eq '') {
                   16165:         $interval = 600;
                   16166:     }
                   16167:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16168:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16169:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   16170:         if ($lastchange > $env{'request.course.tied'}) {
                   16171:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16172:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16173:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16174:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16175:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16176:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16177:                     my ($switchserver,$switchwarning) =
                   16178:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   16179:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   16180:                     if ($switchwarning ne '' || $switchserver ne '') {
                   16181:                         return ('switch',$switchwarning,$switchserver);
                   16182:                     }
                   16183:                 }
                   16184:             }
                   16185:             return ('update');
                   16186:         }
                   16187:     }
                   16188:     return ();
                   16189: }
1.1075.2.69  raeburn  16190: 
1.1075.2.11  raeburn  16191: sub update_content_constraints {
                   16192:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16193:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16194:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   16195:     my %checkresponsetypes;
                   16196:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   16197:         my ($item,$name,$value) = split(/:/,$key);
                   16198:         if ($item eq 'resourcetag') {
                   16199:             if ($name eq 'responsetype') {
                   16200:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   16201:             }
                   16202:         }
                   16203:     }
                   16204:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16205:     if (defined($navmap)) {
                   16206:         my %allresponses;
                   16207:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   16208:             my %responses = $res->responseTypes();
                   16209:             foreach my $key (keys(%responses)) {
                   16210:                 next unless(exists($checkresponsetypes{$key}));
                   16211:                 $allresponses{$key} += $responses{$key};
                   16212:             }
                   16213:         }
                   16214:         foreach my $key (keys(%allresponses)) {
                   16215:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   16216:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   16217:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   16218:             }
                   16219:         }
                   16220:         undef($navmap);
                   16221:     }
                   16222:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   16223:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   16224:     }
                   16225:     return;
                   16226: }
                   16227: 
1.1075.2.27  raeburn  16228: sub allmaps_incourse {
                   16229:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16230:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   16231:         $cid = $env{'request.course.id'};
                   16232:         $cdom = $env{'course.'.$cid.'.domain'};
                   16233:         $cnum = $env{'course.'.$cid.'.num'};
                   16234:         $chome = $env{'course.'.$cid.'.home'};
                   16235:     }
                   16236:     my %allmaps = ();
                   16237:     my $lastchange =
                   16238:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16239:     if ($lastchange > $env{'request.course.tied'}) {
                   16240:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   16241:         unless ($ferr) {
                   16242:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   16243:         }
                   16244:     }
                   16245:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16246:     if (defined($navmap)) {
                   16247:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   16248:             $allmaps{$res->src()} = 1;
                   16249:         }
                   16250:     }
                   16251:     return \%allmaps;
                   16252: }
                   16253: 
1.1075.2.11  raeburn  16254: sub parse_supplemental_title {
                   16255:     my ($title) = @_;
                   16256: 
                   16257:     my ($foldertitle,$renametitle);
                   16258:     if ($title =~ /&amp;&amp;&amp;/) {
                   16259:         $title = &HTML::Entites::decode($title);
                   16260:     }
                   16261:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   16262:         $renametitle=$4;
                   16263:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16264:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16265:         my $name =  &plainname($uname,$udom);
                   16266:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16267:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16268:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16269:             $name.': <br />'.$foldertitle;
                   16270:     }
                   16271:     if (wantarray) {
                   16272:         return ($title,$foldertitle,$renametitle);
                   16273:     }
                   16274:     return $title;
                   16275: }
                   16276: 
1.1075.2.43  raeburn  16277: sub recurse_supplemental {
                   16278:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16279:     if ($suppmap) {
                   16280:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16281:         if ($fatal) {
                   16282:             $errors ++;
                   16283:         } else {
                   16284:             if ($#LONCAPA::map::resources > 0) {
                   16285:                 foreach my $res (@LONCAPA::map::resources) {
                   16286:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16287:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  16288:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16289:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  16290:                         } else {
                   16291:                             $numfiles ++;
                   16292:                         }
                   16293:                     }
                   16294:                 }
                   16295:             }
                   16296:         }
                   16297:     }
                   16298:     return ($numfiles,$errors);
                   16299: }
                   16300: 
1.1075.2.18  raeburn  16301: sub symb_to_docspath {
                   16302:     my ($symb) = @_;
                   16303:     return unless ($symb);
                   16304:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16305:     if ($resurl=~/\.(sequence|page)$/) {
                   16306:         $mapurl=$resurl;
                   16307:     } elsif ($resurl eq 'adm/navmaps') {
                   16308:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16309:     }
                   16310:     my $mapresobj;
                   16311:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16312:     if (ref($navmap)) {
                   16313:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   16314:     }
                   16315:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16316:     my $type=$2;
                   16317:     my $path;
                   16318:     if (ref($mapresobj)) {
                   16319:         my $pcslist = $mapresobj->map_hierarchy();
                   16320:         if ($pcslist ne '') {
                   16321:             foreach my $pc (split(/,/,$pcslist)) {
                   16322:                 next if ($pc <= 1);
                   16323:                 my $res = $navmap->getByMapPc($pc);
                   16324:                 if (ref($res)) {
                   16325:                     my $thisurl = $res->src();
                   16326:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16327:                     my $thistitle = $res->title();
                   16328:                     $path .= '&'.
                   16329:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  16330:                              &escape($thistitle).
1.1075.2.18  raeburn  16331:                              ':'.$res->randompick().
                   16332:                              ':'.$res->randomout().
                   16333:                              ':'.$res->encrypted().
                   16334:                              ':'.$res->randomorder().
                   16335:                              ':'.$res->is_page();
                   16336:                 }
                   16337:             }
                   16338:         }
                   16339:         $path =~ s/^\&//;
                   16340:         my $maptitle = $mapresobj->title();
                   16341:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16342:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16343:         }
                   16344:         $path .= (($path ne '')? '&' : '').
                   16345:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16346:                  &escape($maptitle).
1.1075.2.18  raeburn  16347:                  ':'.$mapresobj->randompick().
                   16348:                  ':'.$mapresobj->randomout().
                   16349:                  ':'.$mapresobj->encrypted().
                   16350:                  ':'.$mapresobj->randomorder().
                   16351:                  ':'.$mapresobj->is_page();
                   16352:     } else {
                   16353:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   16354:         my $ispage = (($type eq 'page')? 1 : '');
                   16355:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16356:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16357:         }
                   16358:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16359:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  16360:     }
                   16361:     unless ($mapurl eq 'default') {
                   16362:         $path = 'default&'.
1.1075.2.46  raeburn  16363:                 &escape('Main Content').
1.1075.2.18  raeburn  16364:                 ':::::&'.$path;
                   16365:     }
                   16366:     return $path;
                   16367: }
                   16368: 
1.1075.2.14  raeburn  16369: sub captcha_display {
                   16370:     my ($context,$lonhost) = @_;
                   16371:     my ($output,$error);
1.1075.2.107  raeburn  16372:     my ($captcha,$pubkey,$privkey,$version) =
                   16373:         &get_captcha_config($context,$lonhost);
1.1075.2.14  raeburn  16374:     if ($captcha eq 'original') {
                   16375:         $output = &create_captcha();
                   16376:         unless ($output) {
                   16377:             $error = 'captcha';
                   16378:         }
                   16379:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  16380:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  16381:         unless ($output) {
                   16382:             $error = 'recaptcha';
                   16383:         }
                   16384:     }
1.1075.2.107  raeburn  16385:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  16386: }
                   16387: 
                   16388: sub captcha_response {
                   16389:     my ($context,$lonhost) = @_;
                   16390:     my ($captcha_chk,$captcha_error);
1.1075.2.109  raeburn  16391:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
1.1075.2.14  raeburn  16392:     if ($captcha eq 'original') {
                   16393:         ($captcha_chk,$captcha_error) = &check_captcha();
                   16394:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  16395:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  16396:     } else {
                   16397:         $captcha_chk = 1;
                   16398:     }
                   16399:     return ($captcha_chk,$captcha_error);
                   16400: }
                   16401: 
                   16402: sub get_captcha_config {
                   16403:     my ($context,$lonhost) = @_;
1.1075.2.107  raeburn  16404:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  16405:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   16406:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   16407:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16408:     if ($context eq 'usercreation') {
                   16409:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   16410:         if (ref($domconfig{$context}) eq 'HASH') {
                   16411:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   16412:             if (ref($hashtocheck) eq 'HASH') {
                   16413:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   16414:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   16415:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   16416:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   16417:                     }
                   16418:                     if ($privkey && $pubkey) {
                   16419:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  16420:                         $version = $hashtocheck->{'recaptchaversion'};
                   16421:                         if ($version ne '2') {
                   16422:                             $version = 1;
                   16423:                         }
1.1075.2.14  raeburn  16424:                     } else {
                   16425:                         $captcha = 'original';
                   16426:                     }
                   16427:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   16428:                     $captcha = 'original';
                   16429:                 }
                   16430:             }
                   16431:         } else {
                   16432:             $captcha = 'captcha';
                   16433:         }
                   16434:     } elsif ($context eq 'login') {
                   16435:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   16436:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   16437:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   16438:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   16439:             if ($privkey && $pubkey) {
                   16440:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  16441:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   16442:                 if ($version ne '2') {
                   16443:                     $version = 1;
                   16444:                 }
1.1075.2.14  raeburn  16445:             } else {
                   16446:                 $captcha = 'original';
                   16447:             }
                   16448:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   16449:             $captcha = 'original';
                   16450:         }
                   16451:     }
1.1075.2.107  raeburn  16452:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  16453: }
                   16454: 
                   16455: sub create_captcha {
                   16456:     my %captcha_params = &captcha_settings();
                   16457:     my ($output,$maxtries,$tries) = ('',10,0);
                   16458:     while ($tries < $maxtries) {
                   16459:         $tries ++;
                   16460:         my $captcha = Authen::Captcha->new (
                   16461:                                            output_folder => $captcha_params{'output_dir'},
                   16462:                                            data_folder   => $captcha_params{'db_dir'},
                   16463:                                           );
                   16464:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   16465: 
                   16466:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   16467:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   16468:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.66  raeburn  16469:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   16470:                       '<br />'.
                   16471:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  16472:             last;
                   16473:         }
                   16474:     }
                   16475:     return $output;
                   16476: }
                   16477: 
                   16478: sub captcha_settings {
                   16479:     my %captcha_params = (
                   16480:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   16481:                            www_output_dir => "/captchaspool",
                   16482:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   16483:                            numchars       => '5',
                   16484:                          );
                   16485:     return %captcha_params;
                   16486: }
                   16487: 
                   16488: sub check_captcha {
                   16489:     my ($captcha_chk,$captcha_error);
                   16490:     my $code = $env{'form.code'};
                   16491:     my $md5sum = $env{'form.crypt'};
                   16492:     my %captcha_params = &captcha_settings();
                   16493:     my $captcha = Authen::Captcha->new(
                   16494:                       output_folder => $captcha_params{'output_dir'},
                   16495:                       data_folder   => $captcha_params{'db_dir'},
                   16496:                   );
1.1075.2.26  raeburn  16497:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  16498:     my %captcha_hash = (
                   16499:                         0       => 'Code not checked (file error)',
                   16500:                        -1      => 'Failed: code expired',
                   16501:                        -2      => 'Failed: invalid code (not in database)',
                   16502:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   16503:     );
                   16504:     if ($captcha_chk != 1) {
                   16505:         $captcha_error = $captcha_hash{$captcha_chk}
                   16506:     }
                   16507:     return ($captcha_chk,$captcha_error);
                   16508: }
                   16509: 
                   16510: sub create_recaptcha {
1.1075.2.107  raeburn  16511:     my ($pubkey,$version) = @_;
                   16512:     if ($version >= 2) {
                   16513:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   16514:     } else {
                   16515:         my $use_ssl;
                   16516:         if ($ENV{'SERVER_PORT'} == 443) {
                   16517:             $use_ssl = 1;
                   16518:         }
                   16519:         my $captcha = Captcha::reCAPTCHA->new;
                   16520:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   16521:                $captcha->get_html($pubkey,undef,$use_ssl).
                   16522:                &mt('If the text is hard to read, [_1] will replace them.',
                   16523:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   16524:                '<br /><br />';
                   16525:      }
1.1075.2.14  raeburn  16526: }
                   16527: 
                   16528: sub check_recaptcha {
1.1075.2.107  raeburn  16529:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  16530:     my $captcha_chk;
1.1075.2.107  raeburn  16531:     if ($version >= 2) {
                   16532:         my $ua = LWP::UserAgent->new;
                   16533:         $ua->timeout(10);
                   16534:         my %info = (
                   16535:                      secret   => $privkey,
                   16536:                      response => $env{'form.g-recaptcha-response'},
                   16537:                      remoteip => $ENV{'REMOTE_ADDR'},
                   16538:                    );
                   16539:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   16540:         if ($response->is_success)  {
                   16541:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   16542:             if (ref($data) eq 'HASH') {
                   16543:                 if ($data->{'success'}) {
                   16544:                     $captcha_chk = 1;
                   16545:                 }
                   16546:             }
                   16547:         }
                   16548:     } else {
                   16549:         my $captcha = Captcha::reCAPTCHA->new;
                   16550:         my $captcha_result =
                   16551:             $captcha->check_answer(
                   16552:                                     $privkey,
                   16553:                                     $ENV{'REMOTE_ADDR'},
                   16554:                                     $env{'form.recaptcha_challenge_field'},
                   16555:                                     $env{'form.recaptcha_response_field'},
                   16556:                                   );
                   16557:         if ($captcha_result->{is_valid}) {
                   16558:             $captcha_chk = 1;
                   16559:         }
1.1075.2.14  raeburn  16560:     }
                   16561:     return $captcha_chk;
                   16562: }
                   16563: 
1.1075.2.64  raeburn  16564: sub emailusername_info {
1.1075.2.103  raeburn  16565:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  16566:     my %titles = &Apache::lonlocal::texthash (
                   16567:                      lastname      => 'Last Name',
                   16568:                      firstname     => 'First Name',
                   16569:                      institution   => 'School/college/university',
                   16570:                      location      => "School's city, state/province, country",
                   16571:                      web           => "School's web address",
                   16572:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  16573:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  16574:                  );
                   16575:     return (\@fields,\%titles);
                   16576: }
                   16577: 
1.1075.2.56  raeburn  16578: sub cleanup_html {
                   16579:     my ($incoming) = @_;
                   16580:     my $outgoing;
                   16581:     if ($incoming ne '') {
                   16582:         $outgoing = $incoming;
                   16583:         $outgoing =~ s/;/&#059;/g;
                   16584:         $outgoing =~ s/\#/&#035;/g;
                   16585:         $outgoing =~ s/\&/&#038;/g;
                   16586:         $outgoing =~ s/</&#060;/g;
                   16587:         $outgoing =~ s/>/&#062;/g;
                   16588:         $outgoing =~ s/\(/&#040/g;
                   16589:         $outgoing =~ s/\)/&#041;/g;
                   16590:         $outgoing =~ s/"/&#034;/g;
                   16591:         $outgoing =~ s/'/&#039;/g;
                   16592:         $outgoing =~ s/\$/&#036;/g;
                   16593:         $outgoing =~ s{/}{&#047;}g;
                   16594:         $outgoing =~ s/=/&#061;/g;
                   16595:         $outgoing =~ s/\\/&#092;/g
                   16596:     }
                   16597:     return $outgoing;
                   16598: }
                   16599: 
1.1075.2.74  raeburn  16600: # Checks for critical messages and returns a redirect url if one exists.
                   16601: # $interval indicates how often to check for messages.
                   16602: sub critical_redirect {
                   16603:     my ($interval) = @_;
                   16604:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   16605:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   16606:                                         $env{'user.name'});
                   16607:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   16608:         my $redirecturl;
                   16609:         if ($what[0]) {
                   16610:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   16611:                 $redirecturl='/adm/email?critical=display';
                   16612:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   16613:                 return (1, $url);
                   16614:             }
                   16615:         }
                   16616:     }
                   16617:     return ();
                   16618: }
                   16619: 
1.1075.2.64  raeburn  16620: # Use:
                   16621: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   16622: #
                   16623: ##################################################
                   16624: #          password associated functions         #
                   16625: ##################################################
                   16626: sub des_keys {
                   16627:     # Make a new key for DES encryption.
                   16628:     # Each key has two parts which are returned separately.
                   16629:     # Please note:  Each key must be passed through the &hex function
                   16630:     # before it is output to the web browser.  The hex versions cannot
                   16631:     # be used to decrypt.
                   16632:     my @hexstr=('0','1','2','3','4','5','6','7',
                   16633:                 '8','9','a','b','c','d','e','f');
                   16634:     my $lkey='';
                   16635:     for (0..7) {
                   16636:         $lkey.=$hexstr[rand(15)];
                   16637:     }
                   16638:     my $ukey='';
                   16639:     for (0..7) {
                   16640:         $ukey.=$hexstr[rand(15)];
                   16641:     }
                   16642:     return ($lkey,$ukey);
                   16643: }
                   16644: 
                   16645: sub des_decrypt {
                   16646:     my ($key,$cyphertext) = @_;
                   16647:     my $keybin=pack("H16",$key);
                   16648:     my $cypher;
                   16649:     if ($Crypt::DES::VERSION>=2.03) {
                   16650:         $cypher=new Crypt::DES $keybin;
                   16651:     } else {
                   16652:         $cypher=new DES $keybin;
                   16653:     }
1.1075.2.106  raeburn  16654:     my $plaintext='';
                   16655:     my $cypherlength = length($cyphertext);
                   16656:     my $numchunks = int($cypherlength/32);
                   16657:     for (my $j=0; $j<$numchunks; $j++) {
                   16658:         my $start = $j*32;
                   16659:         my $cypherblock = substr($cyphertext,$start,32);
                   16660:         my $chunk =
                   16661:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   16662:         $chunk .=
                   16663:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   16664:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   16665:         $plaintext .= $chunk;
                   16666:     }
1.1075.2.64  raeburn  16667:     return $plaintext;
                   16668: }
                   16669: 
1.112     bowersj2 16670: 1;
                   16671: __END__;
1.41      ng       16672: 

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