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

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.123! raeburn     4: # $Id: loncommon.pm,v 1.1075.2.122 2017/01/23 21:28:37 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1075.2.25  raeburn    70: use Apache::lonuserutils();
1.1075.2.27  raeburn    71: use Apache::lonuserstate();
1.1075.2.69  raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    74: use DateTime::TimeZone;
1.1075.2.102  raeburn    75: use DateTime::Locale;
1.1075.2.94  raeburn    76: use Encode();
1.1075.2.14  raeburn    77: use Authen::Captcha;
                     78: use Captcha::reCAPTCHA;
1.1075.2.107  raeburn    79: use JSON::DWIW;
                     80: use LWP::UserAgent;
1.1075.2.64  raeburn    81: use Crypt::DES;
                     82: use DynaLoader; # for Crypt::DES version
1.117     www        83: 
1.517     raeburn    84: # ---------------------------------------------- Designs
                     85: use vars qw(%defaultdesign);
                     86: 
1.22      www        87: my $readit;
                     88: 
1.517     raeburn    89: 
1.157     matthew    90: ##
                     91: ## Global Variables
                     92: ##
1.46      matthew    93: 
1.643     foxr       94: 
                     95: # ----------------------------------------------- SSI with retries:
                     96: #
                     97: 
                     98: =pod
                     99: 
1.648     raeburn   100: =head1 Server Side include with retries:
1.643     foxr      101: 
                    102: =over 4
                    103: 
1.648     raeburn   104: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      105: 
                    106: Performs an ssi with some number of retries.  Retries continue either
                    107: until the result is ok or until the retry count supplied by the
                    108: caller is exhausted.  
                    109: 
                    110: Inputs:
1.648     raeburn   111: 
                    112: =over 4
                    113: 
1.643     foxr      114: resource   - Identifies the resource to insert.
1.648     raeburn   115: 
1.643     foxr      116: retries    - Count of the number of retries allowed.
1.648     raeburn   117: 
1.643     foxr      118: form       - Hash that identifies the rendering options.
                    119: 
1.648     raeburn   120: =back
                    121: 
                    122: Returns:
                    123: 
                    124: =over 4
                    125: 
1.643     foxr      126: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   127: 
1.643     foxr      128: response   - The response from the last attempt (which may or may not have been successful.
                    129: 
1.648     raeburn   130: =back
                    131: 
                    132: =back
                    133: 
1.643     foxr      134: =cut
                    135: 
                    136: sub ssi_with_retries {
                    137:     my ($resource, $retries, %form) = @_;
                    138: 
                    139: 
                    140:     my $ok = 0;			# True if we got a good response.
                    141:     my $content;
                    142:     my $response;
                    143: 
                    144:     # Try to get the ssi done. within the retries count:
                    145: 
                    146:     do {
                    147: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    148: 	$ok      = $response->is_success;
1.650     www       149:         if (!$ok) {
                    150:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    151:         }
1.643     foxr      152: 	$retries--;
                    153:     } while (!$ok && ($retries > 0));
                    154: 
                    155:     if (!$ok) {
                    156: 	$content = '';		# On error return an empty content.
                    157:     }
                    158:     return ($content, $response);
                    159: 
                    160: }
                    161: 
                    162: 
                    163: 
1.20      www       164: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  165: my %language;
1.124     www       166: my %supported_language;
1.1048    foxr      167: my %latex_language;		# For choosing hyphenation in <transl..>
                    168: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  169: my %cprtag;
1.192     taceyjo1  170: my %scprtag;
1.351     www       171: my %fe; my %fd; my %fm;
1.41      ng        172: my %category_extensions;
1.12      harris41  173: 
1.46      matthew   174: # ---------------------------------------------- Thesaurus variables
1.144     matthew   175: #
                    176: # %Keywords:
                    177: #      A hash used by &keyword to determine if a word is considered a keyword.
                    178: # $thesaurus_db_file 
                    179: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   180: 
                    181: my %Keywords;
                    182: my $thesaurus_db_file;
                    183: 
1.144     matthew   184: #
                    185: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    186: # thesaurus.tab, and filecategories.tab.
                    187: #
1.18      www       188: BEGIN {
1.46      matthew   189:     # Variable initialization
                    190:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    191:     #
1.22      www       192:     unless ($readit) {
1.12      harris41  193: # ------------------------------------------------------------------- languages
                    194:     {
1.158     raeburn   195:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    196:                                    '/language.tab';
                    197:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  198:             while (my $line = <$fh>) {
                    199:                 next if ($line=~/^\#/);
                    200:                 chomp($line);
1.1048    foxr      201:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   202:                 $language{$key}=$val.' - '.$enc;
                    203:                 if ($sup) {
                    204:                     $supported_language{$key}=$sup;
                    205:                 }
1.1048    foxr      206: 		if ($latex) {
                    207: 		    $latex_language_bykey{$key} = $latex;
                    208: 		    $latex_language{$two} = $latex;
                    209: 		}
1.158     raeburn   210:             }
                    211:             close($fh);
                    212:         }
1.12      harris41  213:     }
                    214: # ------------------------------------------------------------------ copyrights
                    215:     {
1.158     raeburn   216:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    217:                                   '/copyright.tab';
                    218:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  219:             while (my $line = <$fh>) {
                    220:                 next if ($line=~/^\#/);
                    221:                 chomp($line);
                    222:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   223:                 $cprtag{$key}=$val;
                    224:             }
                    225:             close($fh);
                    226:         }
1.12      harris41  227:     }
1.351     www       228: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  229:     {
                    230:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    231:                                   '/source_copyright.tab';
                    232:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  233:             while (my $line = <$fh>) {
                    234:                 next if ($line =~ /^\#/);
                    235:                 chomp($line);
                    236:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  237:                 $scprtag{$key}=$val;
                    238:             }
                    239:             close($fh);
                    240:         }
                    241:     }
1.63      www       242: 
1.517     raeburn   243: # -------------------------------------------------------------- default domain designs
1.63      www       244:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   245:     my $designfile = $designdir.'/default.tab';
                    246:     if ( open (my $fh,"<$designfile") ) {
                    247:         while (my $line = <$fh>) {
                    248:             next if ($line =~ /^\#/);
                    249:             chomp($line);
                    250:             my ($key,$val)=(split(/\=/,$line));
                    251:             if ($val) { $defaultdesign{$key}=$val; }
                    252:         }
                    253:         close($fh);
1.63      www       254:     }
                    255: 
1.15      harris41  256: # ------------------------------------------------------------- file categories
                    257:     {
1.158     raeburn   258:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    259:                                   '/filecategories.tab';
                    260:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  261: 	    while (my $line = <$fh>) {
                    262: 		next if ($line =~ /^\#/);
                    263: 		chomp($line);
                    264:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1075.2.119  raeburn   265:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   266:             }
                    267:             close($fh);
                    268:         }
                    269: 
1.15      harris41  270:     }
1.12      harris41  271: # ------------------------------------------------------------------ file types
                    272:     {
1.158     raeburn   273:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    274:                '/filetypes.tab';
                    275:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  276:             while (my $line = <$fh>) {
                    277: 		next if ($line =~ /^\#/);
                    278: 		chomp($line);
                    279:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   280:                 if ($descr ne '') {
                    281:                     $fe{$ending}=lc($emb);
                    282:                     $fd{$ending}=$descr;
1.351     www       283:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   284:                 }
                    285:             }
                    286:             close($fh);
                    287:         }
1.12      harris41  288:     }
1.22      www       289:     &Apache::lonnet::logthis(
1.705     tempelho  290:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       291:     $readit=1;
1.46      matthew   292:     }  # end of unless($readit) 
1.32      matthew   293:     
                    294: }
1.112     bowersj2  295: 
1.42      matthew   296: ###############################################################
                    297: ##           HTML and Javascript Helper Functions            ##
                    298: ###############################################################
                    299: 
                    300: =pod 
                    301: 
1.112     bowersj2  302: =head1 HTML and Javascript Functions
1.42      matthew   303: 
1.112     bowersj2  304: =over 4
                    305: 
1.648     raeburn   306: =item * &browser_and_searcher_javascript()
1.112     bowersj2  307: 
                    308: X<browsing, javascript>X<searching, javascript>Returns a string
                    309: containing javascript with two functions, C<openbrowser> and
                    310: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    311: tags.
1.42      matthew   312: 
1.648     raeburn   313: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   314: 
                    315: inputs: formname, elementname, only, omit
                    316: 
                    317: formname and elementname indicate the name of the html form and name of
                    318: the element that the results of the browsing selection are to be placed in. 
                    319: 
                    320: Specifying 'only' will restrict the browser to displaying only files
1.185     www       321: with the given extension.  Can be a comma separated list.
1.42      matthew   322: 
                    323: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       324: with the given extension.  Can be a comma separated list.
1.42      matthew   325: 
1.648     raeburn   326: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   327: 
                    328: Inputs: formname, elementname
                    329: 
                    330: formname and elementname specify the name of the html form and the name
                    331: of the element the selection from the search results will be placed in.
1.542     raeburn   332: 
1.42      matthew   333: =cut
                    334: 
                    335: sub browser_and_searcher_javascript {
1.199     albertel  336:     my ($mode)=@_;
                    337:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  338:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   339:     return <<END;
1.219     albertel  340: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   341:     var editbrowser = null;
1.135     albertel  342:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       343:         var url = '$resurl/?';
1.42      matthew   344:         if (editbrowser == null) {
                    345:             url += 'launch=1&';
                    346:         }
                    347:         url += 'catalogmode=interactive&';
1.199     albertel  348:         url += 'mode=$mode&';
1.611     albertel  349:         url += 'inhibitmenu=yes&';
1.42      matthew   350:         url += 'form=' + formname + '&';
                    351:         if (only != null) {
                    352:             url += 'only=' + only + '&';
1.217     albertel  353:         } else {
                    354:             url += 'only=&';
                    355: 	}
1.42      matthew   356:         if (omit != null) {
                    357:             url += 'omit=' + omit + '&';
1.217     albertel  358:         } else {
                    359:             url += 'omit=&';
                    360: 	}
1.135     albertel  361:         if (titleelement != null) {
                    362:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  363:         } else {
                    364: 	    url += 'titleelement=&';
                    365: 	}
1.42      matthew   366:         url += 'element=' + elementname + '';
                    367:         var title = 'Browser';
1.435     albertel  368:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   369:         options += ',width=700,height=600';
                    370:         editbrowser = open(url,title,options,'1');
                    371:         editbrowser.focus();
                    372:     }
                    373:     var editsearcher;
1.135     albertel  374:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   375:         var url = '/adm/searchcat?';
                    376:         if (editsearcher == null) {
                    377:             url += 'launch=1&';
                    378:         }
                    379:         url += 'catalogmode=interactive&';
1.199     albertel  380:         url += 'mode=$mode&';
1.42      matthew   381:         url += 'form=' + formname + '&';
1.135     albertel  382:         if (titleelement != null) {
                    383:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  384:         } else {
                    385: 	    url += 'titleelement=&';
                    386: 	}
1.42      matthew   387:         url += 'element=' + elementname + '';
                    388:         var title = 'Search';
1.435     albertel  389:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   390:         options += ',width=700,height=600';
                    391:         editsearcher = open(url,title,options,'1');
                    392:         editsearcher.focus();
                    393:     }
1.219     albertel  394: // END LON-CAPA Internal -->
1.42      matthew   395: END
1.170     www       396: }
                    397: 
                    398: sub lastresurl {
1.258     albertel  399:     if ($env{'environment.lastresurl'}) {
                    400: 	return $env{'environment.lastresurl'}
1.170     www       401:     } else {
                    402: 	return '/res';
                    403:     }
                    404: }
                    405: 
                    406: sub storeresurl {
                    407:     my $resurl=&Apache::lonnet::clutter(shift);
                    408:     unless ($resurl=~/^\/res/) { return 0; }
                    409:     $resurl=~s/\/$//;
                    410:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   411:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       412:     return 1;
1.42      matthew   413: }
                    414: 
1.74      www       415: sub studentbrowser_javascript {
1.111     www       416:    unless (
1.258     albertel  417:             (($env{'request.course.id'}) && 
1.302     albertel  418:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    419: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    420: 					  '/'.$env{'request.course.sec'})
                    421: 	      ))
1.258     albertel  422:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       423:           ) { return ''; }  
1.74      www       424:    return (<<'ENDSTDBRW');
1.776     bisitz    425: <script type="text/javascript" language="Javascript">
1.824     bisitz    426: // <![CDATA[
1.74      www       427:     var stdeditbrowser;
1.999     www       428:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       429:         var url = '/adm/pickstudent?';
                    430:         var filter;
1.558     albertel  431: 	if (!ignorefilter) {
                    432: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    433: 	}
1.74      www       434:         if (filter != null) {
                    435:            if (filter != '') {
                    436:                url += 'filter='+filter+'&';
                    437: 	   }
                    438:         }
                    439:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       440:                                     '&udomelement='+udom+
                    441:                                     '&clicker='+clicker;
1.111     www       442: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   443:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       444:         var title = 'Student_Browser';
1.74      www       445:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    446:         options += ',width=700,height=600';
                    447:         stdeditbrowser = open(url,title,options,'1');
                    448:         stdeditbrowser.focus();
                    449:     }
1.824     bisitz    450: // ]]>
1.74      www       451: </script>
                    452: ENDSTDBRW
                    453: }
1.42      matthew   454: 
1.1003    www       455: sub resourcebrowser_javascript {
                    456:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       457:    return (<<'ENDRESBRW');
1.1003    www       458: <script type="text/javascript" language="Javascript">
                    459: // <![CDATA[
                    460:     var reseditbrowser;
1.1004    www       461:     function openresbrowser(formname,reslink) {
1.1005    www       462:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       463:         var title = 'Resource_Browser';
                    464:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       465:         options += ',width=700,height=500';
1.1004    www       466:         reseditbrowser = open(url,title,options,'1');
                    467:         reseditbrowser.focus();
1.1003    www       468:     }
                    469: // ]]>
                    470: </script>
1.1004    www       471: ENDRESBRW
1.1003    www       472: }
                    473: 
1.74      www       474: sub selectstudent_link {
1.999     www       475:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    476:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    477:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    478:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  479:    if ($env{'request.course.id'}) {  
1.302     albertel  480:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    481: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    482: 					'/'.$env{'request.course.sec'})) {
1.111     www       483: 	   return '';
                    484:        }
1.999     www       485:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   486:        if ($courseadvonly)  {
                    487:            $callargs .= ",'',1,1";
                    488:        }
                    489:        return '<span class="LC_nobreak">'.
                    490:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    491:               &mt('Select User').'</a></span>';
1.74      www       492:    }
1.258     albertel  493:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       494:        $callargs .= ",'',1"; 
1.793     raeburn   495:        return '<span class="LC_nobreak">'.
                    496:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    497:               &mt('Select User').'</a></span>';
1.111     www       498:    }
                    499:    return '';
1.91      www       500: }
                    501: 
1.1004    www       502: sub selectresource_link {
                    503:    my ($form,$reslink,$arg)=@_;
                    504:    
                    505:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    506:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    507:    unless ($env{'request.course.id'}) { return $arg; }
                    508:    return '<span class="LC_nobreak">'.
                    509:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    510:               $arg.'</a></span>';
                    511: }
                    512: 
                    513: 
                    514: 
1.653     raeburn   515: sub authorbrowser_javascript {
                    516:     return <<"ENDAUTHORBRW";
1.776     bisitz    517: <script type="text/javascript" language="JavaScript">
1.824     bisitz    518: // <![CDATA[
1.653     raeburn   519: var stdeditbrowser;
                    520: 
                    521: function openauthorbrowser(formname,udom) {
                    522:     var url = '/adm/pickauthor?';
                    523:     url += 'form='+formname+'&roledom='+udom;
                    524:     var title = 'Author_Browser';
                    525:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    526:     options += ',width=700,height=600';
                    527:     stdeditbrowser = open(url,title,options,'1');
                    528:     stdeditbrowser.focus();
                    529: }
                    530: 
1.824     bisitz    531: // ]]>
1.653     raeburn   532: </script>
                    533: ENDAUTHORBRW
                    534: }
                    535: 
1.91      www       536: sub coursebrowser_javascript {
1.1075.2.31  raeburn   537:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1075.2.95  raeburn   538:         $credits_element,$instcode) = @_;
1.932     raeburn   539:     my $wintitle = 'Course_Browser';
1.931     raeburn   540:     if ($crstype eq 'Community') {
1.932     raeburn   541:         $wintitle = 'Community_Browser';
1.909     raeburn   542:     }
1.876     raeburn   543:     my $id_functions = &javascript_index_functions();
                    544:     my $output = '
1.776     bisitz    545: <script type="text/javascript" language="JavaScript">
1.824     bisitz    546: // <![CDATA[
1.468     raeburn   547:     var stdeditbrowser;'."\n";
1.876     raeburn   548: 
                    549:     $output .= <<"ENDSTDBRW";
1.909     raeburn   550:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       551:         var url = '/adm/pickcourse?';
1.895     raeburn   552:         var formid = getFormIdByName(formname);
1.876     raeburn   553:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  554:         if (domainfilter != null) {
                    555:            if (domainfilter != '') {
                    556:                url += 'domainfilter='+domainfilter+'&';
                    557: 	   }
                    558:         }
1.91      www       559:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  560: 	                            '&cdomelement='+udom+
                    561:                                     '&cnameelement='+desc;
1.468     raeburn   562:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   563:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   564:                 url += '&roleelement='+extra_element;
                    565:                 if (domainfilter == null || domainfilter == '') {
                    566:                     url += '&domainfilter='+extra_element;
                    567:                 }
1.234     raeburn   568:             }
1.468     raeburn   569:             else {
                    570:                 if (formname == 'portform') {
                    571:                     url += '&setroles='+extra_element;
1.800     raeburn   572:                 } else {
                    573:                     if (formname == 'rules') {
                    574:                         url += '&fixeddom='+extra_element; 
                    575:                     }
1.468     raeburn   576:                 }
                    577:             }     
1.230     raeburn   578:         }
1.909     raeburn   579:         if (type != null && type != '') {
                    580:             url += '&type='+type;
                    581:         }
                    582:         if (type_elem != null && type_elem != '') {
                    583:             url += '&typeelement='+type_elem;
                    584:         }
1.872     raeburn   585:         if (formname == 'ccrs') {
                    586:             var ownername = document.forms[formid].ccuname.value;
                    587:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1075.2.101  raeburn   588:             url += '&cloner='+ownername+':'+ownerdom;
                    589:             if (type == 'Course') {
                    590:                 url += '&crscode='+document.forms[formid].crscode.value;
                    591:             }
1.1075.2.95  raeburn   592:         }
                    593:         if (formname == 'requestcrs') {
                    594:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   595:         }
1.293     raeburn   596:         if (multflag !=null && multflag != '') {
                    597:             url += '&multiple='+multflag;
                    598:         }
1.909     raeburn   599:         var title = '$wintitle';
1.91      www       600:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    601:         options += ',width=700,height=600';
                    602:         stdeditbrowser = open(url,title,options,'1');
                    603:         stdeditbrowser.focus();
                    604:     }
1.876     raeburn   605: $id_functions
                    606: ENDSTDBRW
1.1075.2.31  raeburn   607:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    608:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    609:                                       $credits_element);
1.876     raeburn   610:     }
                    611:     $output .= '
                    612: // ]]>
                    613: </script>';
                    614:     return $output;
                    615: }
                    616: 
                    617: sub javascript_index_functions {
                    618:     return <<"ENDJS";
                    619: 
                    620: function getFormIdByName(formname) {
                    621:     for (var i=0;i<document.forms.length;i++) {
                    622:         if (document.forms[i].name == formname) {
                    623:             return i;
                    624:         }
                    625:     }
                    626:     return -1;
                    627: }
                    628: 
                    629: function getIndexByName(formid,item) {
                    630:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    631:         if (document.forms[formid].elements[i].name == item) {
                    632:             return i;
                    633:         }
                    634:     }
                    635:     return -1;
                    636: }
1.468     raeburn   637: 
1.876     raeburn   638: function getDomainFromSelectbox(formname,udom) {
                    639:     var userdom;
                    640:     var formid = getFormIdByName(formname);
                    641:     if (formid > -1) {
                    642:         var domid = getIndexByName(formid,udom);
                    643:         if (domid > -1) {
                    644:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    645:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    646:             }
                    647:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    648:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   649:             }
                    650:         }
                    651:     }
1.876     raeburn   652:     return userdom;
                    653: }
                    654: 
                    655: ENDJS
1.468     raeburn   656: 
1.876     raeburn   657: }
                    658: 
1.1017    raeburn   659: sub javascript_array_indexof {
1.1018    raeburn   660:     return <<ENDJS;
1.1017    raeburn   661: <script type="text/javascript" language="JavaScript">
                    662: // <![CDATA[
                    663: 
                    664: if (!Array.prototype.indexOf) {
                    665:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    666:         "use strict";
                    667:         if (this === void 0 || this === null) {
                    668:             throw new TypeError();
                    669:         }
                    670:         var t = Object(this);
                    671:         var len = t.length >>> 0;
                    672:         if (len === 0) {
                    673:             return -1;
                    674:         }
                    675:         var n = 0;
                    676:         if (arguments.length > 0) {
                    677:             n = Number(arguments[1]);
                    678:             if (n !== n) { // shortcut for verifying if it's NaN
                    679:                 n = 0;
                    680:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    681:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    682:             }
                    683:         }
                    684:         if (n >= len) {
                    685:             return -1;
                    686:         }
                    687:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    688:         for (; k < len; k++) {
                    689:             if (k in t && t[k] === searchElement) {
                    690:                 return k;
                    691:             }
                    692:         }
                    693:         return -1;
                    694:     }
                    695: }
                    696: 
                    697: // ]]>
                    698: </script>
                    699: 
                    700: ENDJS
                    701: 
                    702: }
                    703: 
1.876     raeburn   704: sub userbrowser_javascript {
                    705:     my $id_functions = &javascript_index_functions();
                    706:     return <<"ENDUSERBRW";
                    707: 
1.888     raeburn   708: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   709:     var url = '/adm/pickuser?';
                    710:     var userdom = getDomainFromSelectbox(formname,udom);
                    711:     if (userdom != null) {
                    712:        if (userdom != '') {
                    713:            url += 'srchdom='+userdom+'&';
                    714:        }
                    715:     }
                    716:     url += 'form=' + formname + '&unameelement='+uname+
                    717:                                 '&udomelement='+udom+
                    718:                                 '&ulastelement='+ulast+
                    719:                                 '&ufirstelement='+ufirst+
                    720:                                 '&uemailelement='+uemail+
1.881     raeburn   721:                                 '&hideudomelement='+hideudom+
                    722:                                 '&coursedom='+crsdom;
1.888     raeburn   723:     if ((caller != null) && (caller != undefined)) {
                    724:         url += '&caller='+caller;
                    725:     }
1.876     raeburn   726:     var title = 'User_Browser';
                    727:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    728:     options += ',width=700,height=600';
                    729:     var stdeditbrowser = open(url,title,options,'1');
                    730:     stdeditbrowser.focus();
                    731: }
                    732: 
1.888     raeburn   733: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   734:     var formid = getFormIdByName(formname);
                    735:     if (formid > -1) {
1.888     raeburn   736:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   737:         var domid = getIndexByName(formid,udom);
                    738:         var hidedomid = getIndexByName(formid,origdom);
                    739:         if (hidedomid > -1) {
                    740:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   741:             var unameval = document.forms[formid].elements[unameid].value;
                    742:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    743:                 if (domid > -1) {
                    744:                     var slct = document.forms[formid].elements[domid];
                    745:                     if (slct.type == 'select-one') {
                    746:                         var i;
                    747:                         for (i=0;i<slct.length;i++) {
                    748:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    749:                         }
                    750:                     }
                    751:                     if (slct.type == 'hidden') {
                    752:                         slct.value = fixeddom;
1.876     raeburn   753:                     }
                    754:                 }
1.468     raeburn   755:             }
                    756:         }
                    757:     }
1.876     raeburn   758:     return;
                    759: }
                    760: 
                    761: $id_functions
                    762: ENDUSERBRW
1.468     raeburn   763: }
                    764: 
                    765: sub setsec_javascript {
1.1075.2.31  raeburn   766:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   767:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    768:         $communityrolestr);
                    769:     if ($role_element ne '') {
                    770:         my @allroles = ('st','ta','ep','in','ad');
                    771:         foreach my $crstype ('Course','Community') {
                    772:             if ($crstype eq 'Community') {
                    773:                 foreach my $role (@allroles) {
                    774:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    775:                 }
                    776:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    777:             } else {
                    778:                 foreach my $role (@allroles) {
                    779:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    780:                 }
                    781:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    782:             }
                    783:         }
                    784:         $rolestr = '"'.join('","',@allroles).'"';
                    785:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    786:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    787:     }
1.468     raeburn   788:     my $setsections = qq|
                    789: function setSect(sectionlist) {
1.629     raeburn   790:     var sectionsArray = new Array();
                    791:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    792:         sectionsArray = sectionlist.split(",");
                    793:     }
1.468     raeburn   794:     var numSections = sectionsArray.length;
                    795:     document.$formname.$sec_element.length = 0;
                    796:     if (numSections == 0) {
                    797:         document.$formname.$sec_element.multiple=false;
                    798:         document.$formname.$sec_element.size=1;
                    799:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    800:     } else {
                    801:         if (numSections == 1) {
                    802:             document.$formname.$sec_element.multiple=false;
                    803:             document.$formname.$sec_element.size=1;
                    804:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    805:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    806:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    807:         } else {
                    808:             for (var i=0; i<numSections; i++) {
                    809:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    810:             }
                    811:             document.$formname.$sec_element.multiple=true
                    812:             if (numSections < 3) {
                    813:                 document.$formname.$sec_element.size=numSections;
                    814:             } else {
                    815:                 document.$formname.$sec_element.size=3;
                    816:             }
                    817:             document.$formname.$sec_element.options[0].selected = false
                    818:         }
                    819:     }
1.91      www       820: }
1.905     raeburn   821: 
                    822: function setRole(crstype) {
1.468     raeburn   823: |;
1.905     raeburn   824:     if ($role_element eq '') {
                    825:         $setsections .= '    return;
                    826: }
                    827: ';
                    828:     } else {
                    829:         $setsections .= qq|
                    830:     var elementLength = document.$formname.$role_element.length;
                    831:     var allroles = Array($rolestr);
                    832:     var courserolenames = Array($courserolestr);
                    833:     var communityrolenames = Array($communityrolestr);
                    834:     if (elementLength != undefined) {
                    835:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    836:             if (crstype == 'Course') {
                    837:                 return;
                    838:             } else {
                    839:                 allroles[5] = 'co';
                    840:                 for (var i=0; i<6; i++) {
                    841:                     document.$formname.$role_element.options[i].value = allroles[i];
                    842:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    843:                 }
                    844:             }
                    845:         } else {
                    846:             if (crstype == 'Community') {
                    847:                 return;
                    848:             } else {
                    849:                 allroles[5] = 'cc';
                    850:                 for (var i=0; i<6; i++) {
                    851:                     document.$formname.$role_element.options[i].value = allroles[i];
                    852:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    853:                 }
                    854:             }
                    855:         }
                    856:     }
                    857:     return;
                    858: }
                    859: |;
                    860:     }
1.1075.2.31  raeburn   861:     if ($credits_element) {
                    862:         $setsections .= qq|
                    863: function setCredits(defaultcredits) {
                    864:     document.$formname.$credits_element.value = defaultcredits;
                    865:     return;
                    866: }
                    867: |;
                    868:     }
1.468     raeburn   869:     return $setsections;
                    870: }
                    871: 
1.91      www       872: sub selectcourse_link {
1.909     raeburn   873:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    874:        $typeelement) = @_;
                    875:    my $type = $selecttype;
1.871     raeburn   876:    my $linktext = &mt('Select Course');
                    877:    if ($selecttype eq 'Community') {
1.909     raeburn   878:        $linktext = &mt('Select Community');
1.906     raeburn   879:    } elsif ($selecttype eq 'Course/Community') {
                    880:        $linktext = &mt('Select Course/Community');
1.909     raeburn   881:        $type = '';
1.1019    raeburn   882:    } elsif ($selecttype eq 'Select') {
                    883:        $linktext = &mt('Select');
                    884:        $type = '';
1.871     raeburn   885:    }
1.787     bisitz    886:    return '<span class="LC_nobreak">'
                    887:          ."<a href='"
                    888:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    889:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   890:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   891:          ."'>".$linktext.'</a>'
1.787     bisitz    892:          .'</span>';
1.74      www       893: }
1.42      matthew   894: 
1.653     raeburn   895: sub selectauthor_link {
                    896:    my ($form,$udom)=@_;
                    897:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    898:           &mt('Select Author').'</a>';
                    899: }
                    900: 
1.876     raeburn   901: sub selectuser_link {
1.881     raeburn   902:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   903:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   904:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   905:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   906:            ');">'.$linktext.'</a>';
1.876     raeburn   907: }
                    908: 
1.273     raeburn   909: sub check_uncheck_jscript {
                    910:     my $jscript = <<"ENDSCRT";
                    911: function checkAll(field) {
                    912:     if (field.length > 0) {
                    913:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   914:             if (!field[i].disabled) {
                    915:                 field[i].checked = true;
                    916:             }
1.273     raeburn   917:         }
                    918:     } else {
1.1075.2.14  raeburn   919:         if (!field.disabled) {
                    920:             field.checked = true;
                    921:         }
1.273     raeburn   922:     }
                    923: }
                    924:  
                    925: function uncheckAll(field) {
                    926:     if (field.length > 0) {
                    927:         for (i = 0; i < field.length; i++) {
                    928:             field[i].checked = false ;
1.543     albertel  929:         }
                    930:     } else {
1.273     raeburn   931:         field.checked = false ;
                    932:     }
                    933: }
                    934: ENDSCRT
                    935:     return $jscript;
                    936: }
                    937: 
1.656     www       938: sub select_timezone {
1.1075.2.115  raeburn   939:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    940:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   941:    if ($includeempty) {
                    942:        $output .= '<option value=""';
                    943:        if (($selected eq '') || ($selected eq 'local')) {
                    944:            $output .= ' selected="selected" ';
                    945:        }
                    946:        $output .= '> </option>';
                    947:    }
1.657     raeburn   948:    my @timezones = DateTime::TimeZone->all_names;
                    949:    foreach my $tzone (@timezones) {
                    950:        $output.= '<option value="'.$tzone.'"';
                    951:        if ($tzone eq $selected) {
                    952:            $output.=' selected="selected"';
                    953:        }
                    954:        $output.=">$tzone</option>\n";
1.656     www       955:    }
                    956:    $output.="</select>";
                    957:    return $output;
                    958: }
1.273     raeburn   959: 
1.687     raeburn   960: sub select_datelocale {
1.1075.2.115  raeburn   961:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    962:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   963:     if ($includeempty) {
                    964:         $output .= '<option value=""';
                    965:         if ($selected eq '') {
                    966:             $output .= ' selected="selected" ';
                    967:         }
                    968:         $output .= '> </option>';
                    969:     }
1.1075.2.102  raeburn   970:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   971:     my (@possibles,%locale_names);
1.1075.2.102  raeburn   972:     my @locales = DateTime::Locale->ids();
                    973:     foreach my $id (@locales) {
                    974:         if ($id ne '') {
                    975:             my ($en_terr,$native_terr);
                    976:             my $loc = DateTime::Locale->load($id);
                    977:             if (ref($loc)) {
                    978:                 $en_terr = $loc->name();
                    979:                 $native_terr = $loc->native_name();
1.687     raeburn   980:                 if (grep(/^en$/,@languages) || !@languages) {
                    981:                     if ($en_terr ne '') {
                    982:                         $locale_names{$id} = '('.$en_terr.')';
                    983:                     } elsif ($native_terr ne '') {
                    984:                         $locale_names{$id} = $native_terr;
                    985:                     }
                    986:                 } else {
                    987:                     if ($native_terr ne '') {
                    988:                         $locale_names{$id} = $native_terr.' ';
                    989:                     } elsif ($en_terr ne '') {
                    990:                         $locale_names{$id} = '('.$en_terr.')';
                    991:                     }
                    992:                 }
1.1075.2.94  raeburn   993:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1075.2.102  raeburn   994:                 push(@possibles,$id);
1.687     raeburn   995:             }
                    996:         }
                    997:     }
                    998:     foreach my $item (sort(@possibles)) {
                    999:         $output.= '<option value="'.$item.'"';
                   1000:         if ($item eq $selected) {
                   1001:             $output.=' selected="selected"';
                   1002:         }
                   1003:         $output.=">$item";
                   1004:         if ($locale_names{$item} ne '') {
1.1075.2.94  raeburn  1005:             $output.='  '.$locale_names{$item};
1.687     raeburn  1006:         }
                   1007:         $output.="</option>\n";
                   1008:     }
                   1009:     $output.="</select>";
                   1010:     return $output;
                   1011: }
                   1012: 
1.792     raeburn  1013: sub select_language {
1.1075.2.115  raeburn  1014:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1015:     my %langchoices;
                   1016:     if ($includeempty) {
1.1075.2.32  raeburn  1017:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1018:     }
                   1019:     foreach my $id (&languageids()) {
                   1020:         my $code = &supportedlanguagecode($id);
                   1021:         if ($code) {
                   1022:             $langchoices{$code} = &plainlanguagedescription($id);
                   1023:         }
                   1024:     }
1.1075.2.32  raeburn  1025:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1075.2.115  raeburn  1026:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1027: }
                   1028: 
1.42      matthew  1029: =pod
1.36      matthew  1030: 
1.648     raeburn  1031: =item * &linked_select_forms(...)
1.36      matthew  1032: 
                   1033: linked_select_forms returns a string containing a <script></script> block
                   1034: and html for two <select> menus.  The select menus will be linked in that
                   1035: changing the value of the first menu will result in new values being placed
                   1036: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1037: order unless a defined order is provided.
1.36      matthew  1038: 
                   1039: linked_select_forms takes the following ordered inputs:
                   1040: 
                   1041: =over 4
                   1042: 
1.112     bowersj2 1043: =item * $formname, the name of the <form> tag
1.36      matthew  1044: 
1.112     bowersj2 1045: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1046: 
1.112     bowersj2 1047: =item * $firstdefault, the default value for the first menu
1.36      matthew  1048: 
1.112     bowersj2 1049: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1050: 
1.112     bowersj2 1051: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1052: 
1.112     bowersj2 1053: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1054: 
1.609     raeburn  1055: =item * $menuorder, the order of values in the first menu
                   1056: 
1.1075.2.31  raeburn  1057: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1058:         event for the first <select> tag
                   1059: 
                   1060: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1061:         event for the second <select> tag
                   1062: 
1.41      ng       1063: =back 
                   1064: 
1.36      matthew  1065: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1066: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1067: values for the first select menu.  The text that coincides with the 
1.41      ng       1068: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1069: and text for the second menu are given in the hash pointed to by 
                   1070: $menu{$choice1}->{'select2'}.  
                   1071: 
1.112     bowersj2 1072:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1073:                        default => "B3",
                   1074:                        select2 => { 
                   1075:                            B1 => "Choice B1",
                   1076:                            B2 => "Choice B2",
                   1077:                            B3 => "Choice B3",
                   1078:                            B4 => "Choice B4"
1.609     raeburn  1079:                            },
                   1080:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1081:                    },
                   1082:                A2 => { text =>"Choice A2" ,
                   1083:                        default => "C2",
                   1084:                        select2 => { 
                   1085:                            C1 => "Choice C1",
                   1086:                            C2 => "Choice C2",
                   1087:                            C3 => "Choice C3"
1.609     raeburn  1088:                            },
                   1089:                        order => ['C2','C1','C3'],
1.112     bowersj2 1090:                    },
                   1091:                A3 => { text =>"Choice A3" ,
                   1092:                        default => "D6",
                   1093:                        select2 => { 
                   1094:                            D1 => "Choice D1",
                   1095:                            D2 => "Choice D2",
                   1096:                            D3 => "Choice D3",
                   1097:                            D4 => "Choice D4",
                   1098:                            D5 => "Choice D5",
                   1099:                            D6 => "Choice D6",
                   1100:                            D7 => "Choice D7"
1.609     raeburn  1101:                            },
                   1102:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1103:                    }
                   1104:                );
1.36      matthew  1105: 
                   1106: =cut
                   1107: 
                   1108: sub linked_select_forms {
                   1109:     my ($formname,
                   1110:         $middletext,
                   1111:         $firstdefault,
                   1112:         $firstselectname,
                   1113:         $secondselectname, 
1.609     raeburn  1114:         $hashref,
                   1115:         $menuorder,
1.1075.2.31  raeburn  1116:         $onchangefirst,
                   1117:         $onchangesecond
1.36      matthew  1118:         ) = @_;
                   1119:     my $second = "document.$formname.$secondselectname";
                   1120:     my $first = "document.$formname.$firstselectname";
                   1121:     # output the javascript to do the changing
                   1122:     my $result = '';
1.776     bisitz   1123:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1124:     $result.="// <![CDATA[\n";
1.36      matthew  1125:     $result.="var select2data = new Object();\n";
                   1126:     $" = '","';
                   1127:     my $debug = '';
                   1128:     foreach my $s1 (sort(keys(%$hashref))) {
                   1129:         $result.="select2data.d_$s1 = new Object();\n";        
                   1130:         $result.="select2data.d_$s1.def = new String('".
                   1131:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1132:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1133:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1134:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1135:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1136:         }
1.36      matthew  1137:         $result.="\"@s2values\");\n";
                   1138:         $result.="select2data.d_$s1.texts = new Array(";        
                   1139:         my @s2texts;
                   1140:         foreach my $value (@s2values) {
1.1075.2.119  raeburn  1141:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1142:         }
                   1143:         $result.="\"@s2texts\");\n";
                   1144:     }
                   1145:     $"=' ';
                   1146:     $result.= <<"END";
                   1147: 
                   1148: function select1_changed() {
                   1149:     // Determine new choice
                   1150:     var newvalue = "d_" + $first.value;
                   1151:     // update select2
                   1152:     var values     = select2data[newvalue].values;
                   1153:     var texts      = select2data[newvalue].texts;
                   1154:     var select2def = select2data[newvalue].def;
                   1155:     var i;
                   1156:     // out with the old
                   1157:     for (i = 0; i < $second.options.length; i++) {
                   1158:         $second.options[i] = null;
                   1159:     }
                   1160:     // in with the nuclear
                   1161:     for (i=0;i<values.length; i++) {
                   1162:         $second.options[i] = new Option(values[i]);
1.143     matthew  1163:         $second.options[i].value = values[i];
1.36      matthew  1164:         $second.options[i].text = texts[i];
                   1165:         if (values[i] == select2def) {
                   1166:             $second.options[i].selected = true;
                   1167:         }
                   1168:     }
                   1169: }
1.824     bisitz   1170: // ]]>
1.36      matthew  1171: </script>
                   1172: END
                   1173:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1174:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1175:     my @order = sort(keys(%{$hashref}));
                   1176:     if (ref($menuorder) eq 'ARRAY') {
                   1177:         @order = @{$menuorder};
                   1178:     }
                   1179:     foreach my $value (@order) {
1.36      matthew  1180:         $result.="    <option value=\"$value\" ";
1.253     albertel 1181:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1182:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1183:     }
                   1184:     $result .= "</select>\n";
                   1185:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1186:     $result .= $middletext;
1.1075.2.31  raeburn  1187:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1188:     if ($onchangesecond) {
                   1189:         $result .= ' onchange="'.$onchangesecond.'"';
                   1190:     }
                   1191:     $result .= ">\n";
1.36      matthew  1192:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1193:     
                   1194:     my @secondorder = sort(keys(%select2));
                   1195:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1196:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1197:     }
                   1198:     foreach my $value (@secondorder) {
1.36      matthew  1199:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1200:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1201:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1202:     }
                   1203:     $result .= "</select>\n";
                   1204:     #    return $debug;
                   1205:     return $result;
                   1206: }   #  end of sub linked_select_forms {
                   1207: 
1.45      matthew  1208: =pod
1.44      bowersj2 1209: 
1.973     raeburn  1210: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1211: 
1.112     bowersj2 1212: Returns a string corresponding to an HTML link to the given help
                   1213: $topic, where $topic corresponds to the name of a .tex file in
                   1214: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1215: spaces. 
                   1216: 
                   1217: $text will optionally be linked to the same topic, allowing you to
                   1218: link text in addition to the graphic. If you do not want to link
                   1219: text, but wish to specify one of the later parameters, pass an
                   1220: empty string. 
                   1221: 
                   1222: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1223: the link will not open a new window. If false, the link will open
                   1224: a new window using Javascript. (Default is false.) 
                   1225: 
                   1226: $width and $height are optional numerical parameters that will
                   1227: override the width and height of the popped up window, which may
1.973     raeburn  1228: be useful for certain help topics with big pictures included.
                   1229: 
                   1230: $imgid is the id of the img tag used for the help icon. This may be
                   1231: used in a javascript call to switch the image src.  See 
                   1232: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1233: 
                   1234: =cut
                   1235: 
                   1236: sub help_open_topic {
1.973     raeburn  1237:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1238:     $text = "" if (not defined $text);
1.44      bowersj2 1239:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1240:     $width = 500 if (not defined $width);
1.44      bowersj2 1241:     $height = 400 if (not defined $height);
                   1242:     my $filename = $topic;
                   1243:     $filename =~ s/ /_/g;
                   1244: 
1.48      bowersj2 1245:     my $template = "";
                   1246:     my $link;
1.572     banghart 1247:     
1.159     www      1248:     $topic=~s/\W/\_/g;
1.44      bowersj2 1249: 
1.572     banghart 1250:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1251:         if ($env{'browser.mobile'}) {
                   1252: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1253:         } else {
                   1254:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1255:         }
1.1037    www      1256:     } elsif ($stayOnPage eq 'popup') {
                   1257:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1.572     banghart 1258:     } else {
1.48      bowersj2 1259: 	$link = "/adm/help/${filename}.hlp";
                   1260:     }
                   1261: 
                   1262:     # Add the text
1.755     neumanie 1263:     if ($text ne "") {	
1.763     bisitz   1264: 	$template.='<span class="LC_help_open_topic">'
                   1265:                   .'<a target="_top" href="'.$link.'">'
                   1266:                   .$text.'</a>';
1.48      bowersj2 1267:     }
                   1268: 
1.763     bisitz   1269:     # (Always) Add the graphic
1.179     matthew  1270:     my $title = &mt('Online Help');
1.667     raeburn  1271:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1272:     if ($imgid ne '') {
                   1273:         $imgid = ' id="'.$imgid.'"';
                   1274:     }
1.763     bisitz   1275:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1276:               .'<img src="'.$helpicon.'" border="0"'
                   1277:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1278:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1279:               .' /></a>';
                   1280:     if ($text ne "") {	
                   1281:         $template.='</span>';
                   1282:     }
1.44      bowersj2 1283:     return $template;
                   1284: 
1.106     bowersj2 1285: }
                   1286: 
                   1287: # This is a quicky function for Latex cheatsheet editing, since it 
                   1288: # appears in at least four places
                   1289: sub helpLatexCheatsheet {
1.1037    www      1290:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1291:     my $out;
1.106     bowersj2 1292:     my $addOther = '';
1.732     raeburn  1293:     if ($topic) {
1.1037    www      1294: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1295:     }
                   1296:     $out = '<span>' # Start cheatsheet
                   1297: 	  .$addOther
                   1298:           .'<span>'
1.1037    www      1299: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1300: 	  .'</span> <span>'
1.1037    www      1301: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1302: 	  .'</span>';
1.732     raeburn  1303:     unless ($not_author) {
1.763     bisitz   1304:         $out .= ' <span>'
1.1037    www      1305: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1306: 	       .'</span> <span>'
1.1075.2.78  raeburn  1307:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1308:                .'</span>';
1.732     raeburn  1309:     }
1.763     bisitz   1310:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1311:     return $out;
1.172     www      1312: }
                   1313: 
1.430     albertel 1314: sub general_help {
                   1315:     my $helptopic='Student_Intro';
                   1316:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1317: 	$helptopic='Authoring_Intro';
1.907     raeburn  1318:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1319: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1320:     } elsif ($env{'request.role'}=~/^dc/) {
                   1321:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1322:     }
                   1323:     return $helptopic;
                   1324: }
                   1325: 
                   1326: sub update_help_link {
                   1327:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1328:     my $origurl = $ENV{'REQUEST_URI'};
                   1329:     $origurl=~s|^/~|/priv/|;
                   1330:     my $timestamp = time;
                   1331:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1332:         $$datum = &escape($$datum);
                   1333:     }
                   1334: 
                   1335:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
                   1336:     my $output .= <<"ENDOUTPUT";
                   1337: <script type="text/javascript">
1.824     bisitz   1338: // <![CDATA[
1.430     albertel 1339: banner_link = '$banner_link';
1.824     bisitz   1340: // ]]>
1.430     albertel 1341: </script>
                   1342: ENDOUTPUT
                   1343:     return $output;
                   1344: }
                   1345: 
                   1346: # now just updates the help link and generates a blue icon
1.193     raeburn  1347: sub help_open_menu {
1.430     albertel 1348:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1349: 	= @_;    
1.949     droeschl 1350:     $stayOnPage = 1;
1.430     albertel 1351:     my $output;
                   1352:     if ($component_help) {
                   1353: 	if (!$text) {
                   1354: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1355: 				       $width,$height);
                   1356: 	} else {
                   1357: 	    my $help_text;
                   1358: 	    $help_text=&unescape($topic);
                   1359: 	    $output='<table><tr><td>'.
                   1360: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1361: 				 $width,$height).'</td></tr></table>';
                   1362: 	}
                   1363:     }
                   1364:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1365:     return $output.$banner_link;
                   1366: }
                   1367: 
                   1368: sub top_nav_help {
                   1369:     my ($text) = @_;
1.436     albertel 1370:     $text = &mt($text);
1.1075.2.60  raeburn  1371:     my $stay_on_page;
                   1372:     unless ($env{'environment.remote'} eq 'on') {
                   1373:         $stay_on_page = 1;
                   1374:     }
1.1075.2.61  raeburn  1375:     my ($link,$banner_link);
                   1376:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1377:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1378: 	                         : "javascript:helpMenu('open')";
                   1379:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1380:     }
1.201     raeburn  1381:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1382:     if ($link) {
                   1383:         return <<"END";
1.436     albertel 1384: $banner_link
1.1075.2.56  raeburn  1385: <a href="$link" title="$title">$text</a>
1.436     albertel 1386: END
1.1075.2.61  raeburn  1387:     } else {
                   1388:         return '&nbsp;'.$text.'&nbsp;';
                   1389:     }
1.436     albertel 1390: }
                   1391: 
                   1392: sub help_menu_js {
1.1075.2.52  raeburn  1393:     my ($httphost) = @_;
1.949     droeschl 1394:     my $stayOnPage = 1;
1.436     albertel 1395:     my $width = 620;
                   1396:     my $height = 600;
1.430     albertel 1397:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1398:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1399:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1400:     my $start_page =
                   1401:         &Apache::loncommon::start_page('Help Menu', undef,
                   1402: 				       {'frameset'    => 1,
                   1403: 					'js_ready'    => 1,
1.1075.2.52  raeburn  1404:                                         'use_absolute' => $httphost, 
1.331     albertel 1405: 					'add_entries' => {
                   1406: 					    'border' => '0',
1.579     raeburn  1407: 					    'rows'   => "110,*",},});
1.331     albertel 1408:     my $end_page =
                   1409:         &Apache::loncommon::end_page({'frameset' => 1,
                   1410: 				      'js_ready' => 1,});
                   1411: 
1.436     albertel 1412:     my $template .= <<"ENDTEMPLATE";
                   1413: <script type="text/javascript">
1.877     bisitz   1414: // <![CDATA[
1.253     albertel 1415: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1416: var banner_link = '';
1.243     raeburn  1417: function helpMenu(target) {
                   1418:     var caller = this;
                   1419:     if (target == 'open') {
                   1420:         var newWindow = null;
                   1421:         try {
1.262     albertel 1422:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1423:         }
                   1424:         catch(error) {
                   1425:             writeHelp(caller);
                   1426:             return;
                   1427:         }
                   1428:         if (newWindow) {
                   1429:             caller = newWindow;
                   1430:         }
1.193     raeburn  1431:     }
1.243     raeburn  1432:     writeHelp(caller);
                   1433:     return;
                   1434: }
                   1435: function writeHelp(caller) {
1.1075.2.61  raeburn  1436:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1437:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1438:     caller.document.close();
                   1439:     caller.focus();
1.193     raeburn  1440: }
1.877     bisitz   1441: // END LON-CAPA Internal -->
1.253     albertel 1442: // ]]>
1.436     albertel 1443: </script>
1.193     raeburn  1444: ENDTEMPLATE
                   1445:     return $template;
                   1446: }
                   1447: 
1.172     www      1448: sub help_open_bug {
                   1449:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1450:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1451:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1452:     $text = "" if (not defined $text);
                   1453: 	$stayOnPage=1;
1.184     albertel 1454:     $width = 600 if (not defined $width);
                   1455:     $height = 600 if (not defined $height);
1.172     www      1456: 
                   1457:     $topic=~s/\W+/\+/g;
                   1458:     my $link='';
                   1459:     my $template='';
1.379     albertel 1460:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1461: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1462:     if (!$stayOnPage)
                   1463:     {
                   1464: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1465:     }
                   1466:     else
                   1467:     {
                   1468: 	$link = $url;
                   1469:     }
                   1470:     # Add the text
                   1471:     if ($text ne "")
                   1472:     {
                   1473: 	$template .= 
                   1474:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1475:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1476:     }
                   1477: 
                   1478:     # Add the graphic
1.179     matthew  1479:     my $title = &mt('Report a Bug');
1.215     albertel 1480:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1481:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1482:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1483: ENDTEMPLATE
                   1484:     if ($text ne '') { $template.='</td></tr></table>' };
                   1485:     return $template;
                   1486: 
                   1487: }
                   1488: 
                   1489: sub help_open_faq {
                   1490:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1491:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1492:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1493:     $text = "" if (not defined $text);
                   1494: 	$stayOnPage=1;
                   1495:     $width = 350 if (not defined $width);
                   1496:     $height = 400 if (not defined $height);
                   1497: 
                   1498:     $topic=~s/\W+/\+/g;
                   1499:     my $link='';
                   1500:     my $template='';
                   1501:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1502:     if (!$stayOnPage)
                   1503:     {
                   1504: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1505:     }
                   1506:     else
                   1507:     {
                   1508: 	$link = $url;
                   1509:     }
                   1510: 
                   1511:     # Add the text
                   1512:     if ($text ne "")
                   1513:     {
                   1514: 	$template .= 
1.173     www      1515:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1516:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1517:     }
                   1518: 
                   1519:     # Add the graphic
1.179     matthew  1520:     my $title = &mt('View the FAQ');
1.215     albertel 1521:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1522:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1523:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1524: ENDTEMPLATE
                   1525:     if ($text ne '') { $template.='</td></tr></table>' };
                   1526:     return $template;
                   1527: 
1.44      bowersj2 1528: }
1.37      matthew  1529: 
1.180     matthew  1530: ###############################################################
                   1531: ###############################################################
                   1532: 
1.45      matthew  1533: =pod
                   1534: 
1.648     raeburn  1535: =item * &change_content_javascript():
1.256     matthew  1536: 
                   1537: This and the next function allow you to create small sections of an
                   1538: otherwise static HTML page that you can update on the fly with
                   1539: Javascript, even in Netscape 4.
                   1540: 
                   1541: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1542: must be written to the HTML page once. It will prove the Javascript
                   1543: function "change(name, content)". Calling the change function with the
                   1544: name of the section 
                   1545: you want to update, matching the name passed to C<changable_area>, and
                   1546: the new content you want to put in there, will put the content into
                   1547: that area.
                   1548: 
                   1549: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1550: to contain room for the original contents. You need to "make space"
                   1551: for whatever changes you wish to make, and be B<sure> to check your
                   1552: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1553: it's adequate for updating a one-line status display, but little more.
                   1554: This script will set the space to 100% width, so you only need to
                   1555: worry about height in Netscape 4.
                   1556: 
                   1557: Modern browsers are much less limiting, and if you can commit to the
                   1558: user not using Netscape 4, this feature may be used freely with
                   1559: pretty much any HTML.
                   1560: 
                   1561: =cut
                   1562: 
                   1563: sub change_content_javascript {
                   1564:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1565:     if ($env{'browser.type'} eq 'netscape' &&
                   1566: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1567: 	return (<<NETSCAPE4);
                   1568: 	function change(name, content) {
                   1569: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1570: 	    doc.open();
                   1571: 	    doc.write(content);
                   1572: 	    doc.close();
                   1573: 	}
                   1574: NETSCAPE4
                   1575:     } else {
                   1576: 	# Otherwise, we need to use semi-standards-compliant code
                   1577: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1578: 	# is really scary, and every useful browser supports it
                   1579: 	return (<<DOMBASED);
                   1580: 	function change(name, content) {
                   1581: 	    element = document.getElementById(name);
                   1582: 	    element.innerHTML = content;
                   1583: 	}
                   1584: DOMBASED
                   1585:     }
                   1586: }
                   1587: 
                   1588: =pod
                   1589: 
1.648     raeburn  1590: =item * &changable_area($name,$origContent):
1.256     matthew  1591: 
                   1592: This provides a "changable area" that can be modified on the fly via
                   1593: the Javascript code provided in C<change_content_javascript>. $name is
                   1594: the name you will use to reference the area later; do not repeat the
                   1595: same name on a given HTML page more then once. $origContent is what
                   1596: the area will originally contain, which can be left blank.
                   1597: 
                   1598: =cut
                   1599: 
                   1600: sub changable_area {
                   1601:     my ($name, $origContent) = @_;
                   1602: 
1.258     albertel 1603:     if ($env{'browser.type'} eq 'netscape' &&
                   1604: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1605: 	# If this is netscape 4, we need to use the Layer tag
                   1606: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1607:     } else {
                   1608: 	return "<span id='$name'>$origContent</span>";
                   1609:     }
                   1610: }
                   1611: 
                   1612: =pod
                   1613: 
1.648     raeburn  1614: =item * &viewport_geometry_js 
1.590     raeburn  1615: 
                   1616: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1617: 
                   1618: =cut
                   1619: 
                   1620: 
                   1621: sub viewport_geometry_js { 
                   1622:     return <<"GEOMETRY";
                   1623: var Geometry = {};
                   1624: function init_geometry() {
                   1625:     if (Geometry.init) { return };
                   1626:     Geometry.init=1;
                   1627:     if (window.innerHeight) {
                   1628:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1629:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1630:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1631:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1632:     }
                   1633:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1634:         Geometry.getViewportHeight =
                   1635:             function() { return document.documentElement.clientHeight; };
                   1636:         Geometry.getViewportWidth =
                   1637:             function() { return document.documentElement.clientWidth; };
                   1638: 
                   1639:         Geometry.getHorizontalScroll =
                   1640:             function() { return document.documentElement.scrollLeft; };
                   1641:         Geometry.getVerticalScroll =
                   1642:             function() { return document.documentElement.scrollTop; };
                   1643:     }
                   1644:     else if (document.body.clientHeight) {
                   1645:         Geometry.getViewportHeight =
                   1646:             function() { return document.body.clientHeight; };
                   1647:         Geometry.getViewportWidth =
                   1648:             function() { return document.body.clientWidth; };
                   1649:         Geometry.getHorizontalScroll =
                   1650:             function() { return document.body.scrollLeft; };
                   1651:         Geometry.getVerticalScroll =
                   1652:             function() { return document.body.scrollTop; };
                   1653:     }
                   1654: }
                   1655: 
                   1656: GEOMETRY
                   1657: }
                   1658: 
                   1659: =pod
                   1660: 
1.648     raeburn  1661: =item * &viewport_size_js()
1.590     raeburn  1662: 
                   1663: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
                   1664: 
                   1665: =cut
                   1666: 
                   1667: sub viewport_size_js {
                   1668:     my $geometry = &viewport_geometry_js();
                   1669:     return <<"DIMS";
                   1670: 
                   1671: $geometry
                   1672: 
                   1673: function getViewportDims(width,height) {
                   1674:     init_geometry();
                   1675:     width.value = Geometry.getViewportWidth();
                   1676:     height.value = Geometry.getViewportHeight();
                   1677:     return;
                   1678: }
                   1679: 
                   1680: DIMS
                   1681: }
                   1682: 
                   1683: =pod
                   1684: 
1.648     raeburn  1685: =item * &resize_textarea_js()
1.565     albertel 1686: 
                   1687: emits the needed javascript to resize a textarea to be as big as possible
                   1688: 
                   1689: creates a function resize_textrea that takes two IDs first should be
                   1690: the id of the element to resize, second should be the id of a div that
                   1691: surrounds everything that comes after the textarea, this routine needs
                   1692: to be attached to the <body> for the onload and onresize events.
                   1693: 
1.648     raeburn  1694: =back
1.565     albertel 1695: 
                   1696: =cut
                   1697: 
                   1698: sub resize_textarea_js {
1.590     raeburn  1699:     my $geometry = &viewport_geometry_js();
1.565     albertel 1700:     return <<"RESIZE";
                   1701:     <script type="text/javascript">
1.824     bisitz   1702: // <![CDATA[
1.590     raeburn  1703: $geometry
1.565     albertel 1704: 
1.588     albertel 1705: function getX(element) {
                   1706:     var x = 0;
                   1707:     while (element) {
                   1708: 	x += element.offsetLeft;
                   1709: 	element = element.offsetParent;
                   1710:     }
                   1711:     return x;
                   1712: }
                   1713: function getY(element) {
                   1714:     var y = 0;
                   1715:     while (element) {
                   1716: 	y += element.offsetTop;
                   1717: 	element = element.offsetParent;
                   1718:     }
                   1719:     return y;
                   1720: }
                   1721: 
                   1722: 
1.565     albertel 1723: function resize_textarea(textarea_id,bottom_id) {
                   1724:     init_geometry();
                   1725:     var textarea        = document.getElementById(textarea_id);
                   1726:     //alert(textarea);
                   1727: 
1.588     albertel 1728:     var textarea_top    = getY(textarea);
1.565     albertel 1729:     var textarea_height = textarea.offsetHeight;
                   1730:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1731:     var bottom_top      = getY(bottom);
1.565     albertel 1732:     var bottom_height   = bottom.offsetHeight;
                   1733:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1734:     var fudge           = 23;
1.565     albertel 1735:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1736:     if (new_height < 300) {
                   1737: 	new_height = 300;
                   1738:     }
                   1739:     textarea.style.height=new_height+'px';
                   1740: }
1.824     bisitz   1741: // ]]>
1.565     albertel 1742: </script>
                   1743: RESIZE
                   1744: 
                   1745: }
                   1746: 
1.1075.2.112  raeburn  1747: sub colorfuleditor_js {
                   1748:     return <<"COLORFULEDIT"
                   1749: <script type="text/javascript">
                   1750: // <![CDATA[>
                   1751:     function fold_box(curDepth, lastresource){
                   1752: 
                   1753:     // we need a list because there can be several blocks you need to fold in one tag
                   1754:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1755:     // but there is only one folding button per tag
                   1756:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1757: 
                   1758:         if(block.item(0).style.display == 'none'){
                   1759: 
                   1760:             foldbutton.value = '@{[&mt("Hide")]}';
                   1761:             for (i = 0; i < block.length; i++){
                   1762:                 block.item(i).style.display = '';
                   1763:             }
                   1764:         }else{
                   1765: 
                   1766:             foldbutton.value = '@{[&mt("Show")]}';
                   1767:             for (i = 0; i < block.length; i++){
                   1768:                 // block.item(i).style.visibility = 'collapse';
                   1769:                 block.item(i).style.display = 'none';
                   1770:             }
                   1771:         };
                   1772:         saveState(lastresource);
                   1773:     }
                   1774: 
                   1775:     function saveState (lastresource) {
                   1776: 
                   1777:         var tag_list = getTagList();
                   1778:         if(tag_list != null){
                   1779:             var timestamp = new Date().getTime();
                   1780:             var key = lastresource;
                   1781: 
                   1782:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1783:             // starting with timestamp
                   1784:             var value = timestamp+';';
                   1785: 
                   1786:             // building the list of key-value pairs
                   1787:             for(var i = 0; i < tag_list.length; i++){
                   1788:                 value += tag_list[i]+',';
                   1789:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1790:             }
                   1791: 
                   1792:             // only iterate whole storage if nothing to override
                   1793:             if(localStorage.getItem(key) == null){
                   1794: 
                   1795:                 // prevent storage from growing large
                   1796:                 if(localStorage.length > 50){
                   1797:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1798:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1799:                     var oldest_key;
                   1800: 
                   1801:                     for(var i = 1; i < localStorage.length; i++){
                   1802:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1803:                             oldest_key = localStorage.key(i);
                   1804:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1805:                         }
                   1806:                     }
                   1807:                     localStorage.removeItem(oldest_key);
                   1808:                 }
                   1809:             }
                   1810:             localStorage.setItem(key,value);
                   1811:         }
                   1812:     }
                   1813: 
                   1814:     // restore folding status of blocks (on page load)
                   1815:     function restoreState (lastresource) {
                   1816:         if(localStorage.getItem(lastresource) != null){
                   1817:             var key = lastresource;
                   1818:             var value = localStorage.getItem(key);
                   1819:             var regex_delTimestamp = /^\d+;/;
                   1820: 
                   1821:             value.replace(regex_delTimestamp, '');
                   1822: 
                   1823:             var valueArr = value.split(';');
                   1824:             var pairs;
                   1825:             var elements;
                   1826:             for (var i = 0; i < valueArr.length; i++){
                   1827:                 pairs = valueArr[i].split(',');
                   1828:                 elements = document.getElementsByName(pairs[0]);
                   1829: 
                   1830:                 for (var j = 0; j < elements.length; j++){
                   1831:                     elements[j].style.display = pairs[1];
                   1832:                     if (pairs[1] == "none"){
                   1833:                         var regex_id = /([_\\d]+)\$/;
                   1834:                         regex_id.exec(pairs[0]);
                   1835:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1836:                     }
                   1837:                 }
                   1838:             }
                   1839:         }
                   1840:     }
                   1841: 
                   1842:     function getTagList () {
                   1843: 
                   1844:         var stringToSearch = document.lonhomework.innerHTML;
                   1845: 
                   1846:         var ret = new Array();
                   1847:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1848:         var tag_list = stringToSearch.match(regex_findBlock);
                   1849: 
                   1850:         if(tag_list != null){
                   1851:             for(var i = 0; i < tag_list.length; i++){
                   1852:                 ret.push(tag_list[i].replace(/"/, ''));
                   1853:             }
                   1854:         }
                   1855:         return ret;
                   1856:     }
                   1857: 
                   1858:     function saveScrollPosition (resource) {
                   1859:         var tag_list = getTagList();
                   1860: 
                   1861:         // we dont always want to jump to the first block
                   1862:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1863:         if(\$(window).scrollTop() > 170){
                   1864:             if(tag_list != null){
                   1865:                 var result;
                   1866:                 for(var i = 0; i < tag_list.length; i++){
                   1867:                     if(isElementInViewport(tag_list[i])){
                   1868:                         result += tag_list[i]+';';
                   1869:                     }
                   1870:                 }
                   1871:                 sessionStorage.setItem('anchor_'+resource, result);
                   1872:             }
                   1873:         } else {
                   1874:             // we dont need to save zero, just delete the item to leave everything tidy
                   1875:             sessionStorage.removeItem('anchor_'+resource);
                   1876:         }
                   1877:     }
                   1878: 
                   1879:     function restoreScrollPosition(resource){
                   1880: 
                   1881:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1882:         if(elem != null){
                   1883:             var tag_list = elem.split(';');
                   1884:             var elem_list;
                   1885: 
                   1886:             for(var i = 0; i < tag_list.length; i++){
                   1887:                 elem_list = document.getElementsByName(tag_list[i]);
                   1888: 
                   1889:                 if(elem_list.length > 0){
                   1890:                     elem = elem_list[0];
                   1891:                     break;
                   1892:                 }
                   1893:             }
                   1894:             elem.scrollIntoView();
                   1895:         }
                   1896:     }
                   1897: 
                   1898:     function isElementInViewport(el) {
                   1899: 
                   1900:         // change to last element instead of first
                   1901:         var elem = document.getElementsByName(el);
                   1902:         var rect = elem[0].getBoundingClientRect();
                   1903: 
                   1904:         return (
                   1905:             rect.top >= 0 &&
                   1906:             rect.left >= 0 &&
                   1907:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1908:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1909:         );
                   1910:     }
                   1911: 
                   1912:     function autosize(depth){
                   1913:         var cmInst = window['cm'+depth];
                   1914:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1915: 
                   1916:         // is fixed size, switching to dynamic
                   1917:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1918:             cmInst.setSize("","auto");
                   1919:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1920:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1921: 
                   1922:         // is dynamic size, switching to fixed
                   1923:         } else {
                   1924:             cmInst.setSize("","300px");
                   1925:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1926:             sessionStorage.removeItem("autosized_"+depth);
                   1927:         }
                   1928:     }
                   1929: 
                   1930: 
                   1931: 
                   1932: // ]]>
                   1933: </script>
                   1934: COLORFULEDIT
                   1935: }
                   1936: 
                   1937: sub xmleditor_js {
                   1938:     return <<XMLEDIT
                   1939: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1940: <script type="text/javascript">
                   1941: // <![CDATA[>
                   1942: 
                   1943:     function saveScrollPosition (resource) {
                   1944: 
                   1945:         var scrollPos = \$(window).scrollTop();
                   1946:         sessionStorage.setItem(resource,scrollPos);
                   1947:     }
                   1948: 
                   1949:     function restoreScrollPosition(resource){
                   1950: 
                   1951:         var scrollPos = sessionStorage.getItem(resource);
                   1952:         \$(window).scrollTop(scrollPos);
                   1953:     }
                   1954: 
                   1955:     // unless internet explorer
                   1956:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1957: 
                   1958:         \$(document).ready(function() {
                   1959:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1960:         });
                   1961:     }
                   1962: 
                   1963:     // inserts text at cursor position into codemirror (xml editor only)
                   1964:     function insertText(text){
                   1965:         cm.focus();
                   1966:         var curPos = cm.getCursor();
                   1967:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   1968:     }
                   1969: // ]]>
                   1970: </script>
                   1971: XMLEDIT
                   1972: }
                   1973: 
                   1974: sub insert_folding_button {
                   1975:     my $curDepth = $Apache::lonxml::curdepth;
                   1976:     my $lastresource = $env{'request.ambiguous'};
                   1977: 
                   1978:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
                   1979:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   1980: }
                   1981: 
                   1982: 
1.565     albertel 1983: =pod
                   1984: 
1.256     matthew  1985: =head1 Excel and CSV file utility routines
                   1986: 
                   1987: =cut
                   1988: 
                   1989: ###############################################################
                   1990: ###############################################################
                   1991: 
                   1992: =pod
                   1993: 
1.1075.2.56  raeburn  1994: =over 4
                   1995: 
1.648     raeburn  1996: =item * &csv_translate($text) 
1.37      matthew  1997: 
1.185     www      1998: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  1999: format.
                   2000: 
                   2001: =cut
                   2002: 
1.180     matthew  2003: ###############################################################
                   2004: ###############################################################
1.37      matthew  2005: sub csv_translate {
                   2006:     my $text = shift;
                   2007:     $text =~ s/\"/\"\"/g;
1.209     albertel 2008:     $text =~ s/\n/ /g;
1.37      matthew  2009:     return $text;
                   2010: }
1.180     matthew  2011: 
                   2012: ###############################################################
                   2013: ###############################################################
                   2014: 
                   2015: =pod
                   2016: 
1.648     raeburn  2017: =item * &define_excel_formats()
1.180     matthew  2018: 
                   2019: Define some commonly used Excel cell formats.
                   2020: 
                   2021: Currently supported formats:
                   2022: 
                   2023: =over 4
                   2024: 
                   2025: =item header
                   2026: 
                   2027: =item bold
                   2028: 
                   2029: =item h1
                   2030: 
                   2031: =item h2
                   2032: 
                   2033: =item h3
                   2034: 
1.256     matthew  2035: =item h4
                   2036: 
                   2037: =item i
                   2038: 
1.180     matthew  2039: =item date
                   2040: 
                   2041: =back
                   2042: 
                   2043: Inputs: $workbook
                   2044: 
                   2045: Returns: $format, a hash reference.
                   2046: 
1.1057    foxr     2047: 
1.180     matthew  2048: =cut
                   2049: 
                   2050: ###############################################################
                   2051: ###############################################################
                   2052: sub define_excel_formats {
                   2053:     my ($workbook) = @_;
                   2054:     my $format;
                   2055:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2056:                                                 bottom    => 1,
                   2057:                                                 align     => 'center');
                   2058:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2059:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2060:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2061:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2062:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2063:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2064:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2065:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2066:     return $format;
                   2067: }
                   2068: 
                   2069: ###############################################################
                   2070: ###############################################################
1.113     bowersj2 2071: 
                   2072: =pod
                   2073: 
1.648     raeburn  2074: =item * &create_workbook()
1.255     matthew  2075: 
                   2076: Create an Excel worksheet.  If it fails, output message on the
                   2077: request object and return undefs.
                   2078: 
                   2079: Inputs: Apache request object
                   2080: 
                   2081: Returns (undef) on failure, 
                   2082:     Excel worksheet object, scalar with filename, and formats 
                   2083:     from &Apache::loncommon::define_excel_formats on success
                   2084: 
                   2085: =cut
                   2086: 
                   2087: ###############################################################
                   2088: ###############################################################
                   2089: sub create_workbook {
                   2090:     my ($r) = @_;
                   2091:         #
                   2092:     # Create the excel spreadsheet
                   2093:     my $filename = '/prtspool/'.
1.258     albertel 2094:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2095:         time.'_'.rand(1000000000).'.xls';
                   2096:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2097:     if (! defined($workbook)) {
                   2098:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2099:         $r->print(
                   2100:             '<p class="LC_error">'
                   2101:            .&mt('Problems occurred in creating the new Excel file.')
                   2102:            .' '.&mt('This error has been logged.')
                   2103:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2104:            .'</p>'
                   2105:         );
1.255     matthew  2106:         return (undef);
                   2107:     }
                   2108:     #
1.1014    foxr     2109:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2110:     #
                   2111:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2112:     return ($workbook,$filename,$format);
                   2113: }
                   2114: 
                   2115: ###############################################################
                   2116: ###############################################################
                   2117: 
                   2118: =pod
                   2119: 
1.648     raeburn  2120: =item * &create_text_file()
1.113     bowersj2 2121: 
1.542     raeburn  2122: Create a file to write to and eventually make available to the user.
1.256     matthew  2123: If file creation fails, outputs an error message on the request object and 
                   2124: return undefs.
1.113     bowersj2 2125: 
1.256     matthew  2126: Inputs: Apache request object, and file suffix
1.113     bowersj2 2127: 
1.256     matthew  2128: Returns (undef) on failure, 
                   2129:     Filehandle and filename on success.
1.113     bowersj2 2130: 
                   2131: =cut
                   2132: 
1.256     matthew  2133: ###############################################################
                   2134: ###############################################################
                   2135: sub create_text_file {
                   2136:     my ($r,$suffix) = @_;
                   2137:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2138:     my $fh;
                   2139:     my $filename = '/prtspool/'.
1.258     albertel 2140:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2141:         time.'_'.rand(1000000000).'.'.$suffix;
                   2142:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2143:     if (! defined($fh)) {
                   2144:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2145:         $r->print(
                   2146:             '<p class="LC_error">'
                   2147:            .&mt('Problems occurred in creating the output file.')
                   2148:            .' '.&mt('This error has been logged.')
                   2149:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2150:            .'</p>'
                   2151:         );
1.113     bowersj2 2152:     }
1.256     matthew  2153:     return ($fh,$filename)
1.113     bowersj2 2154: }
                   2155: 
                   2156: 
1.256     matthew  2157: =pod 
1.113     bowersj2 2158: 
                   2159: =back
                   2160: 
                   2161: =cut
1.37      matthew  2162: 
                   2163: ###############################################################
1.33      matthew  2164: ##        Home server <option> list generating code          ##
                   2165: ###############################################################
1.35      matthew  2166: 
1.169     www      2167: # ------------------------------------------
                   2168: 
                   2169: sub domain_select {
                   2170:     my ($name,$value,$multiple)=@_;
                   2171:     my %domains=map { 
1.514     albertel 2172: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2173:     } &Apache::lonnet::all_domains();
1.169     www      2174:     if ($multiple) {
                   2175: 	$domains{''}=&mt('Any domain');
1.550     albertel 2176: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2177: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2178:     } else {
1.550     albertel 2179: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2180: 	return &select_form($name,$value,\%domains);
1.169     www      2181:     }
                   2182: }
                   2183: 
1.282     albertel 2184: #-------------------------------------------
                   2185: 
                   2186: =pod
                   2187: 
1.519     raeburn  2188: =head1 Routines for form select boxes
                   2189: 
                   2190: =over 4
                   2191: 
1.648     raeburn  2192: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2193: 
                   2194: Returns a string containing a <select> element int multiple mode
                   2195: 
                   2196: 
                   2197: Args:
                   2198:   $name - name of the <select> element
1.506     raeburn  2199:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2200:   $size - number of rows long the select element is
1.283     albertel 2201:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2202:           (shown text should already have been &mt())
1.506     raeburn  2203:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2204: 
1.282     albertel 2205: =cut
                   2206: 
                   2207: #-------------------------------------------
1.169     www      2208: sub multiple_select_form {
1.284     albertel 2209:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2210:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2211:     my $output='';
1.191     matthew  2212:     if (! defined($size)) {
                   2213:         $size = 4;
1.283     albertel 2214:         if (scalar(keys(%$hash))<4) {
                   2215:             $size = scalar(keys(%$hash));
1.191     matthew  2216:         }
                   2217:     }
1.734     bisitz   2218:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2219:     my @order;
1.506     raeburn  2220:     if (ref($order) eq 'ARRAY')  {
                   2221:         @order = @{$order};
                   2222:     } else {
                   2223:         @order = sort(keys(%$hash));
1.501     banghart 2224:     }
                   2225:     if (exists($$hash{'select_form_order'})) {
                   2226:         @order = @{$$hash{'select_form_order'}};
                   2227:     }
                   2228:         
1.284     albertel 2229:     foreach my $key (@order) {
1.356     albertel 2230:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2231:         $output.='selected="selected" ' if ($selected{$key});
                   2232:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2233:     }
                   2234:     $output.="</select>\n";
                   2235:     return $output;
                   2236: }
                   2237: 
1.88      www      2238: #-------------------------------------------
                   2239: 
                   2240: =pod
                   2241: 
1.1075.2.115  raeburn  2242: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2243: 
                   2244: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2245: allow a user to select options from a ref to a hash containing:
                   2246: option_name => displayed text. An optional $onchange can include
1.1075.2.115  raeburn  2247: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2248: An optional arg -- $readonly -- if true will cause the select form
                   2249: to be disabled, e.g., for the case where an instructor has a section-
                   2250: specific role, and is viewing/modifying parameters.  
1.970     raeburn  2251: 
1.88      www      2252: See lonrights.pm for an example invocation and use.
                   2253: 
                   2254: =cut
                   2255: 
                   2256: #-------------------------------------------
                   2257: sub select_form {
1.1075.2.115  raeburn  2258:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2259:     return unless (ref($hashref) eq 'HASH');
                   2260:     if ($onchange) {
                   2261:         $onchange = ' onchange="'.$onchange.'"';
                   2262:     }
                   2263:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.128     albertel 2264:     my @keys;
1.970     raeburn  2265:     if (exists($hashref->{'select_form_order'})) {
                   2266: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2267:     } else {
1.970     raeburn  2268: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2269:     }
1.356     albertel 2270:     foreach my $key (@keys) {
                   2271:         $selectform.=
                   2272: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2273:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2274:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2275:     }
                   2276:     $selectform.="</select>";
                   2277:     return $selectform;
                   2278: }
                   2279: 
1.475     www      2280: # For display filters
                   2281: 
                   2282: sub display_filter {
1.1074    raeburn  2283:     my ($context) = @_;
1.475     www      2284:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2285:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2286:     my $phraseinput = 'hidden';
                   2287:     my $includeinput = 'hidden';
                   2288:     my ($checked,$includetypestext);
                   2289:     if ($env{'form.displayfilter'} eq 'containing') {
                   2290:         $phraseinput = 'text'; 
                   2291:         if ($context eq 'parmslog') {
                   2292:             $includeinput = 'checkbox';
                   2293:             if ($env{'form.includetypes'}) {
                   2294:                 $checked = ' checked="checked"';
                   2295:             }
                   2296:             $includetypestext = &mt('Include parameter types');
                   2297:         }
                   2298:     } else {
                   2299:         $includetypestext = '&nbsp;';
                   2300:     }
                   2301:     my ($additional,$secondid,$thirdid);
                   2302:     if ($context eq 'parmslog') {
                   2303:         $additional = 
                   2304:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2305:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2306:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2307:             '</label>';
                   2308:         $secondid = 'includetypes';
                   2309:         $thirdid = 'includetypestext';
                   2310:     }
                   2311:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2312:                                                     '$secondid','$thirdid')";
                   2313:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2314: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2315: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2316: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2317:            &mt('Filter: [_1]',
1.477     www      2318: 	   &select_form($env{'form.displayfilter'},
                   2319: 			'displayfilter',
1.970     raeburn  2320: 			{'currentfolder' => 'Current folder/page',
1.477     www      2321: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2322: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2323: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2324:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2325:                          '" />'.$additional;
                   2326: }
                   2327: 
                   2328: sub display_filter_js {
                   2329:     my $includetext = &mt('Include parameter types');
                   2330:     return <<"ENDJS";
                   2331:   
                   2332: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2333:     var firstType = 'hidden';
                   2334:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2335:         firstType = 'text';
                   2336:     }
                   2337:     firstObject = document.getElementById(firstid);
                   2338:     if (typeof(firstObject) == 'object') {
                   2339:         if (firstObject.type != firstType) {
                   2340:             changeInputType(firstObject,firstType);
                   2341:         }
                   2342:     }
                   2343:     if (context == 'parmslog') {
                   2344:         var secondType = 'hidden';
                   2345:         if (firstType == 'text') {
                   2346:             secondType = 'checkbox';
                   2347:         }
                   2348:         secondObject = document.getElementById(secondid);  
                   2349:         if (typeof(secondObject) == 'object') {
                   2350:             if (secondObject.type != secondType) {
                   2351:                 changeInputType(secondObject,secondType);
                   2352:             }
                   2353:         }
                   2354:         var textItem = document.getElementById(thirdid);
                   2355:         var currtext = textItem.innerHTML;
                   2356:         var newtext;
                   2357:         if (firstType == 'text') {
                   2358:             newtext = '$includetext';
                   2359:         } else {
                   2360:             newtext = '&nbsp;';
                   2361:         }
                   2362:         if (currtext != newtext) {
                   2363:             textItem.innerHTML = newtext;
                   2364:         }
                   2365:     }
                   2366:     return;
                   2367: }
                   2368: 
                   2369: function changeInputType(oldObject,newType) {
                   2370:     var newObject = document.createElement('input');
                   2371:     newObject.type = newType;
                   2372:     if (oldObject.size) {
                   2373:         newObject.size = oldObject.size;
                   2374:     }
                   2375:     if (oldObject.value) {
                   2376:         newObject.value = oldObject.value;
                   2377:     }
                   2378:     if (oldObject.name) {
                   2379:         newObject.name = oldObject.name;
                   2380:     }
                   2381:     if (oldObject.id) {
                   2382:         newObject.id = oldObject.id;
                   2383:     }
                   2384:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2385:     return;
                   2386: }
                   2387: 
                   2388: ENDJS
1.475     www      2389: }
                   2390: 
1.167     www      2391: sub gradeleveldescription {
                   2392:     my $gradelevel=shift;
                   2393:     my %gradelevels=(0 => 'Not specified',
                   2394: 		     1 => 'Grade 1',
                   2395: 		     2 => 'Grade 2',
                   2396: 		     3 => 'Grade 3',
                   2397: 		     4 => 'Grade 4',
                   2398: 		     5 => 'Grade 5',
                   2399: 		     6 => 'Grade 6',
                   2400: 		     7 => 'Grade 7',
                   2401: 		     8 => 'Grade 8',
                   2402: 		     9 => 'Grade 9',
                   2403: 		     10 => 'Grade 10',
                   2404: 		     11 => 'Grade 11',
                   2405: 		     12 => 'Grade 12',
                   2406: 		     13 => 'Grade 13',
                   2407: 		     14 => '100 Level',
                   2408: 		     15 => '200 Level',
                   2409: 		     16 => '300 Level',
                   2410: 		     17 => '400 Level',
                   2411: 		     18 => 'Graduate Level');
                   2412:     return &mt($gradelevels{$gradelevel});
                   2413: }
                   2414: 
1.163     www      2415: sub select_level_form {
                   2416:     my ($deflevel,$name)=@_;
                   2417:     unless ($deflevel) { $deflevel=0; }
1.167     www      2418:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2419:     for (my $i=0; $i<=18; $i++) {
                   2420:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2421:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2422:                 ">".&gradeleveldescription($i)."</option>\n";
                   2423:     }
                   2424:     $selectform.="</select>";
                   2425:     return $selectform;
1.163     www      2426: }
1.167     www      2427: 
1.35      matthew  2428: #-------------------------------------------
                   2429: 
1.45      matthew  2430: =pod
                   2431: 
1.1075.2.115  raeburn  2432: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2433: 
                   2434: Returns a string containing a <select name='$name' size='1'> form to 
                   2435: allow a user to select the domain to preform an operation in.  
                   2436: See loncreateuser.pm for an example invocation and use.
                   2437: 
1.90      www      2438: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2439: selected");
                   2440: 
1.743     raeburn  2441: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2442: 
1.910     raeburn  2443: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
                   2444: 
1.1075.2.36  raeburn  2445: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2446: 
1.1075.2.115  raeburn  2447: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
                   2448: 
                   2449: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
1.563     raeburn  2450: 
1.35      matthew  2451: =cut
                   2452: 
                   2453: #-------------------------------------------
1.34      matthew  2454: sub select_dom_form {
1.1075.2.115  raeburn  2455:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2456:     if ($onchange) {
1.874     raeburn  2457:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2458:     }
1.1075.2.115  raeburn  2459:     if ($disabled) {
                   2460:         $disabled = ' disabled="disabled"';
                   2461:     }
1.1075.2.36  raeburn  2462:     my (@domains,%exclude);
1.910     raeburn  2463:     if (ref($incdoms) eq 'ARRAY') {
                   2464:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2465:     } else {
                   2466:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2467:     }
1.90      www      2468:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2469:     if (ref($excdoms) eq 'ARRAY') {
                   2470:         map { $exclude{$_} = 1; } @{$excdoms};
                   2471:     }
1.1075.2.115  raeburn  2472:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2473:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2474:         next if ($exclude{$dom});
1.356     albertel 2475:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2476:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2477:         if ($showdomdesc) {
                   2478:             if ($dom ne '') {
                   2479:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2480:                 if ($domdesc ne '') {
                   2481:                     $selectdomain .= ' ('.$domdesc.')';
                   2482:                 }
                   2483:             } 
                   2484:         }
                   2485:         $selectdomain .= "</option>\n";
1.34      matthew  2486:     }
                   2487:     $selectdomain.="</select>";
                   2488:     return $selectdomain;
                   2489: }
                   2490: 
1.35      matthew  2491: #-------------------------------------------
                   2492: 
1.45      matthew  2493: =pod
                   2494: 
1.648     raeburn  2495: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2496: 
1.586     raeburn  2497: input: 4 arguments (two required, two optional) - 
                   2498:     $domain - domain of new user
                   2499:     $name - name of form element
                   2500:     $default - Value of 'default' causes a default item to be first 
                   2501:                             option, and selected by default. 
                   2502:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2503:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2504: output: returns 2 items: 
1.586     raeburn  2505: (a) form element which contains either:
                   2506:    (i) <select name="$name">
                   2507:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2508:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2509:        </select>
                   2510:        form item if there are multiple library servers in $domain, or
                   2511:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2512:        if there is only one library server in $domain.
                   2513: 
                   2514: (b) number of library servers found.
                   2515: 
                   2516: See loncreateuser.pm for example of use.
1.35      matthew  2517: 
                   2518: =cut
                   2519: 
                   2520: #-------------------------------------------
1.586     raeburn  2521: sub home_server_form_item {
                   2522:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2523:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2524:     my $result;
                   2525:     my $numlib = keys(%servers);
                   2526:     if ($numlib > 1) {
                   2527:         $result .= '<select name="'.$name.'" />'."\n";
                   2528:         if ($default) {
1.804     bisitz   2529:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2530:                        '</option>'."\n";
                   2531:         }
                   2532:         foreach my $hostid (sort(keys(%servers))) {
                   2533:             $result.= '<option value="'.$hostid.'">'.
                   2534: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2535:         }
                   2536:         $result .= '</select>'."\n";
                   2537:     } elsif ($numlib == 1) {
                   2538:         my $hostid;
                   2539:         foreach my $item (keys(%servers)) {
                   2540:             $hostid = $item;
                   2541:         }
                   2542:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2543:                    $hostid.'" />';
                   2544:                    if (!$hide) {
                   2545:                        $result .= $hostid.' '.$servers{$hostid};
                   2546:                    }
                   2547:                    $result .= "\n";
                   2548:     } elsif ($default) {
                   2549:         $result .= '<input type="hidden" name="'.$name.
                   2550:                    '" value="default" />';
                   2551:                    if (!$hide) {
                   2552:                        $result .= &mt('default');
                   2553:                    }
                   2554:                    $result .= "\n";
1.33      matthew  2555:     }
1.586     raeburn  2556:     return ($result,$numlib);
1.33      matthew  2557: }
1.112     bowersj2 2558: 
                   2559: =pod
                   2560: 
1.534     albertel 2561: =back 
                   2562: 
1.112     bowersj2 2563: =cut
1.87      matthew  2564: 
                   2565: ###############################################################
1.112     bowersj2 2566: ##                  Decoding User Agent                      ##
1.87      matthew  2567: ###############################################################
                   2568: 
                   2569: =pod
                   2570: 
1.112     bowersj2 2571: =head1 Decoding the User Agent
                   2572: 
                   2573: =over 4
                   2574: 
                   2575: =item * &decode_user_agent()
1.87      matthew  2576: 
                   2577: Inputs: $r
                   2578: 
                   2579: Outputs:
                   2580: 
                   2581: =over 4
                   2582: 
1.112     bowersj2 2583: =item * $httpbrowser
1.87      matthew  2584: 
1.112     bowersj2 2585: =item * $clientbrowser
1.87      matthew  2586: 
1.112     bowersj2 2587: =item * $clientversion
1.87      matthew  2588: 
1.112     bowersj2 2589: =item * $clientmathml
1.87      matthew  2590: 
1.112     bowersj2 2591: =item * $clientunicode
1.87      matthew  2592: 
1.112     bowersj2 2593: =item * $clientos
1.87      matthew  2594: 
1.1075.2.42  raeburn  2595: =item * $clientmobile
                   2596: 
                   2597: =item * $clientinfo
                   2598: 
1.1075.2.77  raeburn  2599: =item * $clientosversion
                   2600: 
1.87      matthew  2601: =back
                   2602: 
1.157     matthew  2603: =back 
                   2604: 
1.87      matthew  2605: =cut
                   2606: 
                   2607: ###############################################################
                   2608: ###############################################################
                   2609: sub decode_user_agent {
1.247     albertel 2610:     my ($r)=@_;
1.87      matthew  2611:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2612:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2613:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2614:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2615:     my $clientbrowser='unknown';
                   2616:     my $clientversion='0';
                   2617:     my $clientmathml='';
                   2618:     my $clientunicode='0';
1.1075.2.42  raeburn  2619:     my $clientmobile=0;
1.1075.2.77  raeburn  2620:     my $clientosversion='';
1.87      matthew  2621:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1075.2.76  raeburn  2622:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2623: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2624: 	    $clientbrowser=$bname;
                   2625:             $httpbrowser=~/$vreg/i;
                   2626: 	    $clientversion=$1;
                   2627:             $clientmathml=($clientversion>=$minv);
                   2628:             $clientunicode=($clientversion>=$univ);
                   2629: 	}
                   2630:     }
                   2631:     my $clientos='unknown';
1.1075.2.42  raeburn  2632:     my $clientinfo;
1.87      matthew  2633:     if (($httpbrowser=~/linux/i) ||
                   2634:         ($httpbrowser=~/unix/i) ||
                   2635:         ($httpbrowser=~/ux/i) ||
                   2636:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2637:     if (($httpbrowser=~/vax/i) ||
                   2638:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2639:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2640:     if (($httpbrowser=~/mac/i) ||
                   2641:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1075.2.77  raeburn  2642:     if ($httpbrowser=~/win/i) {
                   2643:         $clientos='win';
                   2644:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2645:             $clientosversion = $1;
                   2646:         }
                   2647:     }
1.87      matthew  2648:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2649:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2650:         $clientmobile=lc($1);
                   2651:     }
                   2652:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2653:         $clientinfo = 'firefox-'.$1;
                   2654:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2655:         $clientinfo = 'chromeframe-'.$1;
                   2656:     }
1.87      matthew  2657:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.77  raeburn  2658:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2659:             $clientosversion);
1.87      matthew  2660: }
                   2661: 
1.32      matthew  2662: ###############################################################
                   2663: ##    Authentication changing form generation subroutines    ##
                   2664: ###############################################################
                   2665: ##
                   2666: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2667: ## hash, and have reasonable default values.
                   2668: ##
                   2669: ##    formname = the name given in the <form> tag.
1.35      matthew  2670: #-------------------------------------------
                   2671: 
1.45      matthew  2672: =pod
                   2673: 
1.112     bowersj2 2674: =head1 Authentication Routines
                   2675: 
                   2676: =over 4
                   2677: 
1.648     raeburn  2678: =item * &authform_xxxxxx()
1.35      matthew  2679: 
                   2680: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2681: handle some of the conveniences required for authentication forms.  
                   2682: This is not an optimal method, but it works.  
                   2683: 
                   2684: =over 4
                   2685: 
1.112     bowersj2 2686: =item * authform_header
1.35      matthew  2687: 
1.112     bowersj2 2688: =item * authform_authorwarning
1.35      matthew  2689: 
1.112     bowersj2 2690: =item * authform_nochange
1.35      matthew  2691: 
1.112     bowersj2 2692: =item * authform_kerberos
1.35      matthew  2693: 
1.112     bowersj2 2694: =item * authform_internal
1.35      matthew  2695: 
1.112     bowersj2 2696: =item * authform_filesystem
1.35      matthew  2697: 
                   2698: =back
                   2699: 
1.648     raeburn  2700: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2701: 
1.35      matthew  2702: =cut
                   2703: 
                   2704: #-------------------------------------------
1.32      matthew  2705: sub authform_header{  
                   2706:     my %in = (
                   2707:         formname => 'cu',
1.80      albertel 2708:         kerb_def_dom => '',
1.32      matthew  2709:         @_,
                   2710:     );
                   2711:     $in{'formname'} = 'document.' . $in{'formname'};
                   2712:     my $result='';
1.80      albertel 2713: 
                   2714: #---------------------------------------------- Code for upper case translation
                   2715:     my $Javascript_toUpperCase;
                   2716:     unless ($in{kerb_def_dom}) {
                   2717:         $Javascript_toUpperCase =<<"END";
                   2718:         switch (choice) {
                   2719:            case 'krb': currentform.elements[choicearg].value =
                   2720:                currentform.elements[choicearg].value.toUpperCase();
                   2721:                break;
                   2722:            default:
                   2723:         }
                   2724: END
                   2725:     } else {
                   2726:         $Javascript_toUpperCase = "";
                   2727:     }
                   2728: 
1.165     raeburn  2729:     my $radioval = "'nochange'";
1.591     raeburn  2730:     if (defined($in{'curr_authtype'})) {
                   2731:         if ($in{'curr_authtype'} ne '') {
                   2732:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2733:         }
1.174     matthew  2734:     }
1.165     raeburn  2735:     my $argfield = 'null';
1.591     raeburn  2736:     if (defined($in{'mode'})) {
1.165     raeburn  2737:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2738:             if (defined($in{'curr_autharg'})) {
                   2739:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2740:                     $argfield = "'$in{'curr_autharg'}'";
                   2741:                 }
                   2742:             }
                   2743:         }
                   2744:     }
                   2745: 
1.32      matthew  2746:     $result.=<<"END";
                   2747: var current = new Object();
1.165     raeburn  2748: current.radiovalue = $radioval;
                   2749: current.argfield = $argfield;
1.32      matthew  2750: 
                   2751: function changed_radio(choice,currentform) {
                   2752:     var choicearg = choice + 'arg';
                   2753:     // If a radio button in changed, we need to change the argfield
                   2754:     if (current.radiovalue != choice) {
                   2755:         current.radiovalue = choice;
                   2756:         if (current.argfield != null) {
                   2757:             currentform.elements[current.argfield].value = '';
                   2758:         }
                   2759:         if (choice == 'nochange') {
                   2760:             current.argfield = null;
                   2761:         } else {
                   2762:             current.argfield = choicearg;
                   2763:             switch(choice) {
                   2764:                 case 'krb': 
                   2765:                     currentform.elements[current.argfield].value = 
                   2766:                         "$in{'kerb_def_dom'}";
                   2767:                 break;
                   2768:               default:
                   2769:                 break;
                   2770:             }
                   2771:         }
                   2772:     }
                   2773:     return;
                   2774: }
1.22      www      2775: 
1.32      matthew  2776: function changed_text(choice,currentform) {
                   2777:     var choicearg = choice + 'arg';
                   2778:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2779:         $Javascript_toUpperCase
1.32      matthew  2780:         // clear old field
                   2781:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2782:             currentform.elements[current.argfield].value = '';
                   2783:         }
                   2784:         current.argfield = choicearg;
                   2785:     }
                   2786:     set_auth_radio_buttons(choice,currentform);
                   2787:     return;
1.20      www      2788: }
1.32      matthew  2789: 
                   2790: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2791:     var numauthchoices = currentform.login.length;
                   2792:     if (typeof numauthchoices  == "undefined") {
                   2793:         return;
                   2794:     } 
1.32      matthew  2795:     var i=0;
1.986     raeburn  2796:     while (i < numauthchoices) {
1.32      matthew  2797:         if (currentform.login[i].value == newvalue) { break; }
                   2798:         i++;
                   2799:     }
1.986     raeburn  2800:     if (i == numauthchoices) {
1.32      matthew  2801:         return;
                   2802:     }
                   2803:     current.radiovalue = newvalue;
                   2804:     currentform.login[i].checked = true;
                   2805:     return;
                   2806: }
                   2807: END
                   2808:     return $result;
                   2809: }
                   2810: 
1.1075.2.20  raeburn  2811: sub authform_authorwarning {
1.32      matthew  2812:     my $result='';
1.144     matthew  2813:     $result='<i>'.
                   2814:         &mt('As a general rule, only authors or co-authors should be '.
                   2815:             'filesystem authenticated '.
                   2816:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2817:     return $result;
                   2818: }
                   2819: 
1.1075.2.20  raeburn  2820: sub authform_nochange {
1.32      matthew  2821:     my %in = (
                   2822:               formname => 'document.cu',
                   2823:               kerb_def_dom => 'MSU.EDU',
                   2824:               @_,
                   2825:           );
1.1075.2.20  raeburn  2826:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2827:     my $result;
1.1075.2.20  raeburn  2828:     if (!$authnum) {
                   2829:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2830:     } else {
                   2831:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2832:                   '<input type="radio" name="login" value="nochange" '.
                   2833:                   'checked="checked" onclick="'.
1.281     albertel 2834:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2835: 	    '</label>';
1.586     raeburn  2836:     }
1.32      matthew  2837:     return $result;
                   2838: }
                   2839: 
1.591     raeburn  2840: sub authform_kerberos {
1.32      matthew  2841:     my %in = (
                   2842:               formname => 'document.cu',
                   2843:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2844:               kerb_def_auth => 'krb4',
1.32      matthew  2845:               @_,
                   2846:               );
1.586     raeburn  2847:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1075.2.117  raeburn  2848:         $autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2849:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2850:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2851:        $check5 = ' checked="checked"';
1.80      albertel 2852:     } else {
1.772     bisitz   2853:        $check4 = ' checked="checked"';
1.80      albertel 2854:     }
1.1075.2.117  raeburn  2855:     if ($in{'readonly'}) {
                   2856:         $disabled = ' disabled="disabled"';
                   2857:     }
1.165     raeburn  2858:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2859:     if (defined($in{'curr_authtype'})) {
                   2860:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2861:             $krbcheck = ' checked="checked"';
1.623     raeburn  2862:             if (defined($in{'mode'})) {
                   2863:                 if ($in{'mode'} eq 'modifyuser') {
                   2864:                     $krbcheck = '';
                   2865:                 }
                   2866:             }
1.591     raeburn  2867:             if (defined($in{'curr_kerb_ver'})) {
                   2868:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2869:                     $check5 = ' checked="checked"';
1.591     raeburn  2870:                     $check4 = '';
                   2871:                 } else {
1.772     bisitz   2872:                     $check4 = ' checked="checked"';
1.591     raeburn  2873:                     $check5 = '';
                   2874:                 }
1.586     raeburn  2875:             }
1.591     raeburn  2876:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2877:                 $krbarg = $in{'curr_autharg'};
                   2878:             }
1.586     raeburn  2879:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2880:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2881:                     $result = 
                   2882:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2883:         $in{'curr_autharg'},$krbver);
                   2884:                 } else {
                   2885:                     $result =
                   2886:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2887:                 }
                   2888:                 return $result; 
                   2889:             }
                   2890:         }
                   2891:     } else {
                   2892:         if ($authnum == 1) {
1.784     bisitz   2893:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2894:         }
                   2895:     }
1.586     raeburn  2896:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2897:         return;
1.587     raeburn  2898:     } elsif ($authtype eq '') {
1.591     raeburn  2899:         if (defined($in{'mode'})) {
1.587     raeburn  2900:             if ($in{'mode'} eq 'modifycourse') {
                   2901:                 if ($authnum == 1) {
1.1075.2.117  raeburn  2902:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  2903:                 }
                   2904:             }
                   2905:         }
1.586     raeburn  2906:     }
                   2907:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2908:     if ($authtype eq '') {
                   2909:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2910:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1075.2.117  raeburn  2911:                     $krbcheck.$disabled.' />';
1.586     raeburn  2912:     }
                   2913:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2914:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2915:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2916:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2917:          $in{'curr_authtype'} eq 'krb4')) {
                   2918:         $result .= &mt
1.144     matthew  2919:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2920:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2921:          '<label>'.$authtype,
1.281     albertel 2922:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2923:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2924:              'onchange="'.$jscall.'"'.$disabled.' />',
                   2925:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   2926:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 2927: 	 '</label>');
1.586     raeburn  2928:     } elsif ($can_assign{'krb4'}) {
                   2929:         $result .= &mt
                   2930:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2931:          '[_3] Version 4 [_4]',
                   2932:          '<label>'.$authtype,
                   2933:          '</label><input type="text" size="10" name="krbarg" '.
                   2934:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2935:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2936:          '<label><input type="hidden" name="krbver" value="4" />',
                   2937:          '</label>');
                   2938:     } elsif ($can_assign{'krb5'}) {
                   2939:         $result .= &mt
                   2940:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2941:          '[_3] Version 5 [_4]',
                   2942:          '<label>'.$authtype,
                   2943:          '</label><input type="text" size="10" name="krbarg" '.
                   2944:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2945:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2946:          '<label><input type="hidden" name="krbver" value="5" />',
                   2947:          '</label>');
                   2948:     }
1.32      matthew  2949:     return $result;
                   2950: }
                   2951: 
1.1075.2.20  raeburn  2952: sub authform_internal {
1.586     raeburn  2953:     my %in = (
1.32      matthew  2954:                 formname => 'document.cu',
                   2955:                 kerb_def_dom => 'MSU.EDU',
                   2956:                 @_,
                   2957:                 );
1.1075.2.117  raeburn  2958:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2959:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  2960:     if ($in{'readonly'}) {
                   2961:         $disabled = ' disabled="disabled"';
                   2962:     }
1.591     raeburn  2963:     if (defined($in{'curr_authtype'})) {
                   2964:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2965:             if ($can_assign{'int'}) {
1.772     bisitz   2966:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2967:                 if (defined($in{'mode'})) {
                   2968:                     if ($in{'mode'} eq 'modifyuser') {
                   2969:                         $intcheck = '';
                   2970:                     }
                   2971:                 }
1.591     raeburn  2972:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2973:                     $intarg = $in{'curr_autharg'};
                   2974:                 }
                   2975:             } else {
                   2976:                 $result = &mt('Currently internally authenticated.');
                   2977:                 return $result;
1.165     raeburn  2978:             }
                   2979:         }
1.586     raeburn  2980:     } else {
                   2981:         if ($authnum == 1) {
1.784     bisitz   2982:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2983:         }
                   2984:     }
                   2985:     if (!$can_assign{'int'}) {
                   2986:         return;
1.587     raeburn  2987:     } elsif ($authtype eq '') {
1.591     raeburn  2988:         if (defined($in{'mode'})) {
1.587     raeburn  2989:             if ($in{'mode'} eq 'modifycourse') {
                   2990:                 if ($authnum == 1) {
1.1075.2.117  raeburn  2991:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  2992:                 }
                   2993:             }
                   2994:         }
1.165     raeburn  2995:     }
1.586     raeburn  2996:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2997:     if ($authtype eq '') {
                   2998:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1075.2.117  raeburn  2999:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3000:     }
1.605     bisitz   3001:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1075.2.117  raeburn  3002:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3003:     $result = &mt
1.144     matthew  3004:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3005:          '<label>'.$authtype,'</label>'.$autharg);
1.1075.2.118  raeburn  3006:     $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
1.32      matthew  3007:     return $result;
                   3008: }
                   3009: 
1.1075.2.20  raeburn  3010: sub authform_local {
1.32      matthew  3011:     my %in = (
                   3012:               formname => 'document.cu',
                   3013:               kerb_def_dom => 'MSU.EDU',
                   3014:               @_,
                   3015:               );
1.1075.2.117  raeburn  3016:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3017:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3018:     if ($in{'readonly'}) {
                   3019:         $disabled = ' disabled="disabled"';
                   3020:     }
1.591     raeburn  3021:     if (defined($in{'curr_authtype'})) {
                   3022:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3023:             if ($can_assign{'loc'}) {
1.772     bisitz   3024:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3025:                 if (defined($in{'mode'})) {
                   3026:                     if ($in{'mode'} eq 'modifyuser') {
                   3027:                         $loccheck = '';
                   3028:                     }
                   3029:                 }
1.591     raeburn  3030:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3031:                     $locarg = $in{'curr_autharg'};
                   3032:                 }
                   3033:             } else {
                   3034:                 $result = &mt('Currently using local (institutional) authentication.');
                   3035:                 return $result;
1.165     raeburn  3036:             }
                   3037:         }
1.586     raeburn  3038:     } else {
                   3039:         if ($authnum == 1) {
1.784     bisitz   3040:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3041:         }
                   3042:     }
                   3043:     if (!$can_assign{'loc'}) {
                   3044:         return;
1.587     raeburn  3045:     } elsif ($authtype eq '') {
1.591     raeburn  3046:         if (defined($in{'mode'})) {
1.587     raeburn  3047:             if ($in{'mode'} eq 'modifycourse') {
                   3048:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3049:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3050:                 }
                   3051:             }
                   3052:         }
1.165     raeburn  3053:     }
1.586     raeburn  3054:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3055:     if ($authtype eq '') {
                   3056:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3057:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3058:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3059:     }
                   3060:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1075.2.117  raeburn  3061:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3062:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3063:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3064:     return $result;
                   3065: }
                   3066: 
1.1075.2.20  raeburn  3067: sub authform_filesystem {
1.32      matthew  3068:     my %in = (
                   3069:               formname => 'document.cu',
                   3070:               kerb_def_dom => 'MSU.EDU',
                   3071:               @_,
                   3072:               );
1.1075.2.117  raeburn  3073:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3074:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3075:     if ($in{'readonly'}) {
                   3076:         $disabled = ' disabled="disabled"';
                   3077:     }
1.591     raeburn  3078:     if (defined($in{'curr_authtype'})) {
                   3079:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3080:             if ($can_assign{'fsys'}) {
1.772     bisitz   3081:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3082:                 if (defined($in{'mode'})) {
                   3083:                     if ($in{'mode'} eq 'modifyuser') {
                   3084:                         $fsyscheck = '';
                   3085:                     }
                   3086:                 }
1.586     raeburn  3087:             } else {
                   3088:                 $result = &mt('Currently Filesystem Authenticated.');
                   3089:                 return $result;
                   3090:             }           
                   3091:         }
                   3092:     } else {
                   3093:         if ($authnum == 1) {
1.784     bisitz   3094:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3095:         }
                   3096:     }
                   3097:     if (!$can_assign{'fsys'}) {
                   3098:         return;
1.587     raeburn  3099:     } elsif ($authtype eq '') {
1.591     raeburn  3100:         if (defined($in{'mode'})) {
1.587     raeburn  3101:             if ($in{'mode'} eq 'modifycourse') {
                   3102:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3103:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3104:                 }
                   3105:             }
                   3106:         }
1.586     raeburn  3107:     }
                   3108:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3109:     if ($authtype eq '') {
                   3110:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3111:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3112:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3113:     }
                   3114:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
1.1075.2.117  raeburn  3115:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3116:     $result = &mt
1.144     matthew  3117:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3118:          '<label><input type="radio" name="login" value="fsys" '.
1.1075.2.117  raeburn  3119:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
1.605     bisitz   3120:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.1075.2.117  raeburn  3121:                   'onchange="'.$jscall.'"'.$disabled.' />');
1.32      matthew  3122:     return $result;
                   3123: }
                   3124: 
1.586     raeburn  3125: sub get_assignable_auth {
                   3126:     my ($dom) = @_;
                   3127:     if ($dom eq '') {
                   3128:         $dom = $env{'request.role.domain'};
                   3129:     }
                   3130:     my %can_assign = (
                   3131:                           krb4 => 1,
                   3132:                           krb5 => 1,
                   3133:                           int  => 1,
                   3134:                           loc  => 1,
                   3135:                      );
                   3136:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3137:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3138:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3139:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3140:             my $context;
                   3141:             if ($env{'request.role'} =~ /^au/) {
                   3142:                 $context = 'author';
1.1075.2.117  raeburn  3143:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3144:                 $context = 'domain';
                   3145:             } elsif ($env{'request.course.id'}) {
                   3146:                 $context = 'course';
                   3147:             }
                   3148:             if ($context) {
                   3149:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3150:                    %can_assign = %{$authhash->{$context}}; 
                   3151:                 }
                   3152:             }
                   3153:         }
                   3154:     }
                   3155:     my $authnum = 0;
                   3156:     foreach my $key (keys(%can_assign)) {
                   3157:         if ($can_assign{$key}) {
                   3158:             $authnum ++;
                   3159:         }
                   3160:     }
                   3161:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3162:         $authnum --;
                   3163:     }
                   3164:     return ($authnum,%can_assign);
                   3165: }
                   3166: 
1.80      albertel 3167: ###############################################################
                   3168: ##    Get Kerberos Defaults for Domain                 ##
                   3169: ###############################################################
                   3170: ##
                   3171: ## Returns default kerberos version and an associated argument
                   3172: ## as listed in file domain.tab. If not listed, provides
                   3173: ## appropriate default domain and kerberos version.
                   3174: ##
                   3175: #-------------------------------------------
                   3176: 
                   3177: =pod
                   3178: 
1.648     raeburn  3179: =item * &get_kerberos_defaults()
1.80      albertel 3180: 
                   3181: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3182: version and domain. If not found, it defaults to version 4 and the 
                   3183: domain of the server.
1.80      albertel 3184: 
1.648     raeburn  3185: =over 4
                   3186: 
1.80      albertel 3187: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3188: 
1.648     raeburn  3189: =back
                   3190: 
                   3191: =back
                   3192: 
1.80      albertel 3193: =cut
                   3194: 
                   3195: #-------------------------------------------
                   3196: sub get_kerberos_defaults {
                   3197:     my $domain=shift;
1.641     raeburn  3198:     my ($krbdef,$krbdefdom);
                   3199:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3200:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3201:         $krbdef = $domdefaults{'auth_def'};
                   3202:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3203:     } else {
1.80      albertel 3204:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3205:         my $krbdefdom=$1;
                   3206:         $krbdefdom=~tr/a-z/A-Z/;
                   3207:         $krbdef = "krb4";
                   3208:     }
                   3209:     return ($krbdef,$krbdefdom);
                   3210: }
1.112     bowersj2 3211: 
1.32      matthew  3212: 
1.46      matthew  3213: ###############################################################
                   3214: ##                Thesaurus Functions                        ##
                   3215: ###############################################################
1.20      www      3216: 
1.46      matthew  3217: =pod
1.20      www      3218: 
1.112     bowersj2 3219: =head1 Thesaurus Functions
                   3220: 
                   3221: =over 4
                   3222: 
1.648     raeburn  3223: =item * &initialize_keywords()
1.46      matthew  3224: 
                   3225: Initializes the package variable %Keywords if it is empty.  Uses the
                   3226: package variable $thesaurus_db_file.
                   3227: 
                   3228: =cut
                   3229: 
                   3230: ###################################################
                   3231: 
                   3232: sub initialize_keywords {
                   3233:     return 1 if (scalar keys(%Keywords));
                   3234:     # If we are here, %Keywords is empty, so fill it up
                   3235:     #   Make sure the file we need exists...
                   3236:     if (! -e $thesaurus_db_file) {
                   3237:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3238:                                  " failed because it does not exist");
                   3239:         return 0;
                   3240:     }
                   3241:     #   Set up the hash as a database
                   3242:     my %thesaurus_db;
                   3243:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3244:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3245:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3246:                                  $thesaurus_db_file);
                   3247:         return 0;
                   3248:     } 
                   3249:     #  Get the average number of appearances of a word.
                   3250:     my $avecount = $thesaurus_db{'average.count'};
                   3251:     #  Put keywords (those that appear > average) into %Keywords
                   3252:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3253:         my ($count,undef) = split /:/,$data;
                   3254:         $Keywords{$word}++ if ($count > $avecount);
                   3255:     }
                   3256:     untie %thesaurus_db;
                   3257:     # Remove special values from %Keywords.
1.356     albertel 3258:     foreach my $value ('total.count','average.count') {
                   3259:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3260:   }
1.46      matthew  3261:     return 1;
                   3262: }
                   3263: 
                   3264: ###################################################
                   3265: 
                   3266: =pod
                   3267: 
1.648     raeburn  3268: =item * &keyword($word)
1.46      matthew  3269: 
                   3270: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3271: than the average number of times in the thesaurus database.  Calls 
                   3272: &initialize_keywords
                   3273: 
                   3274: =cut
                   3275: 
                   3276: ###################################################
1.20      www      3277: 
                   3278: sub keyword {
1.46      matthew  3279:     return if (!&initialize_keywords());
                   3280:     my $word=lc(shift());
                   3281:     $word=~s/\W//g;
                   3282:     return exists($Keywords{$word});
1.20      www      3283: }
1.46      matthew  3284: 
                   3285: ###############################################################
                   3286: 
                   3287: =pod 
1.20      www      3288: 
1.648     raeburn  3289: =item * &get_related_words()
1.46      matthew  3290: 
1.160     matthew  3291: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3292: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3293: will be returned.  The order of the words returned is determined by the
                   3294: database which holds them.
                   3295: 
                   3296: Uses global $thesaurus_db_file.
                   3297: 
1.1057    foxr     3298: 
1.46      matthew  3299: =cut
                   3300: 
                   3301: ###############################################################
                   3302: sub get_related_words {
                   3303:     my $keyword = shift;
                   3304:     my %thesaurus_db;
                   3305:     if (! -e $thesaurus_db_file) {
                   3306:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3307:                                  "failed because the file does not exist");
                   3308:         return ();
                   3309:     }
                   3310:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3311:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3312:         return ();
                   3313:     } 
                   3314:     my @Words=();
1.429     www      3315:     my $count=0;
1.46      matthew  3316:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3317: 	# The first element is the number of times
                   3318: 	# the word appears.  We do not need it now.
1.429     www      3319: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3320: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3321: 	my $threshold=$mostfrequentcount/10;
                   3322:         foreach my $possibleword (@RelatedWords) {
                   3323:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3324:             if ($wordcount>$threshold) {
                   3325: 		push(@Words,$word);
                   3326:                 $count++;
                   3327:                 if ($count>10) { last; }
                   3328: 	    }
1.20      www      3329:         }
                   3330:     }
1.46      matthew  3331:     untie %thesaurus_db;
                   3332:     return @Words;
1.14      harris41 3333: }
1.46      matthew  3334: 
1.112     bowersj2 3335: =pod
                   3336: 
                   3337: =back
                   3338: 
                   3339: =cut
1.61      www      3340: 
                   3341: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3342: =pod
                   3343: 
1.112     bowersj2 3344: =head1 User Name Functions
                   3345: 
                   3346: =over 4
                   3347: 
1.648     raeburn  3348: =item * &plainname($uname,$udom,$first)
1.81      albertel 3349: 
1.112     bowersj2 3350: Takes a users logon name and returns it as a string in
1.226     albertel 3351: "first middle last generation" form 
                   3352: if $first is set to 'lastname' then it returns it as
                   3353: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3354: 
                   3355: =cut
1.61      www      3356: 
1.295     www      3357: 
1.81      albertel 3358: ###############################################################
1.61      www      3359: sub plainname {
1.226     albertel 3360:     my ($uname,$udom,$first)=@_;
1.537     albertel 3361:     return if (!defined($uname) || !defined($udom));
1.295     www      3362:     my %names=&getnames($uname,$udom);
1.226     albertel 3363:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3364: 					  $names{'middlename'},
                   3365: 					  $names{'lastname'},
                   3366: 					  $names{'generation'},$first);
                   3367:     $name=~s/^\s+//;
1.62      www      3368:     $name=~s/\s+$//;
                   3369:     $name=~s/\s+/ /g;
1.353     albertel 3370:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3371:     return $name;
1.61      www      3372: }
1.66      www      3373: 
                   3374: # -------------------------------------------------------------------- Nickname
1.81      albertel 3375: =pod
                   3376: 
1.648     raeburn  3377: =item * &nickname($uname,$udom)
1.81      albertel 3378: 
                   3379: Gets a users name and returns it as a string as
                   3380: 
                   3381: "&quot;nickname&quot;"
1.66      www      3382: 
1.81      albertel 3383: if the user has a nickname or
                   3384: 
                   3385: "first middle last generation"
                   3386: 
                   3387: if the user does not
                   3388: 
                   3389: =cut
1.66      www      3390: 
                   3391: sub nickname {
                   3392:     my ($uname,$udom)=@_;
1.537     albertel 3393:     return if (!defined($uname) || !defined($udom));
1.295     www      3394:     my %names=&getnames($uname,$udom);
1.68      albertel 3395:     my $name=$names{'nickname'};
1.66      www      3396:     if ($name) {
                   3397:        $name='&quot;'.$name.'&quot;'; 
                   3398:     } else {
                   3399:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3400: 	     $names{'lastname'}.' '.$names{'generation'};
                   3401:        $name=~s/\s+$//;
                   3402:        $name=~s/\s+/ /g;
                   3403:     }
                   3404:     return $name;
                   3405: }
                   3406: 
1.295     www      3407: sub getnames {
                   3408:     my ($uname,$udom)=@_;
1.537     albertel 3409:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3410:     if ($udom eq 'public' && $uname eq 'public') {
                   3411: 	return ('lastname' => &mt('Public'));
                   3412:     }
1.295     www      3413:     my $id=$uname.':'.$udom;
                   3414:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3415:     if ($cached) {
                   3416: 	return %{$names};
                   3417:     } else {
                   3418: 	my %loadnames=&Apache::lonnet::get('environment',
                   3419:                     ['firstname','middlename','lastname','generation','nickname'],
                   3420: 					 $udom,$uname);
                   3421: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3422: 	return %loadnames;
                   3423:     }
                   3424: }
1.61      www      3425: 
1.542     raeburn  3426: # -------------------------------------------------------------------- getemails
1.648     raeburn  3427: 
1.542     raeburn  3428: =pod
                   3429: 
1.648     raeburn  3430: =item * &getemails($uname,$udom)
1.542     raeburn  3431: 
                   3432: Gets a user's email information and returns it as a hash with keys:
                   3433: notification, critnotification, permanentemail
                   3434: 
                   3435: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3436: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3437:  
1.648     raeburn  3438: 
1.542     raeburn  3439: =cut
                   3440: 
1.648     raeburn  3441: 
1.466     albertel 3442: sub getemails {
                   3443:     my ($uname,$udom)=@_;
                   3444:     if ($udom eq 'public' && $uname eq 'public') {
                   3445: 	return;
                   3446:     }
1.467     www      3447:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3448:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3449:     my $id=$uname.':'.$udom;
                   3450:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3451:     if ($cached) {
                   3452: 	return %{$names};
                   3453:     } else {
                   3454: 	my %loadnames=&Apache::lonnet::get('environment',
                   3455:                     			   ['notification','critnotification',
                   3456: 					    'permanentemail'],
                   3457: 					   $udom,$uname);
                   3458: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3459: 	return %loadnames;
                   3460:     }
                   3461: }
                   3462: 
1.551     albertel 3463: sub flush_email_cache {
                   3464:     my ($uname,$udom)=@_;
                   3465:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3466:     if (!$uname) { $uname=$env{'user.name'};   }
                   3467:     return if ($udom eq 'public' && $uname eq 'public');
                   3468:     my $id=$uname.':'.$udom;
                   3469:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3470: }
                   3471: 
1.728     raeburn  3472: # -------------------------------------------------------------------- getlangs
                   3473: 
                   3474: =pod
                   3475: 
                   3476: =item * &getlangs($uname,$udom)
                   3477: 
                   3478: Gets a user's language preference and returns it as a hash with key:
                   3479: language.
                   3480: 
                   3481: =cut
                   3482: 
                   3483: 
                   3484: sub getlangs {
                   3485:     my ($uname,$udom) = @_;
                   3486:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3487:     if (!$uname) { $uname=$env{'user.name'};   }
                   3488:     my $id=$uname.':'.$udom;
                   3489:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3490:     if ($cached) {
                   3491:         return %{$langs};
                   3492:     } else {
                   3493:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3494:                                            $udom,$uname);
                   3495:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3496:         return %loadlangs;
                   3497:     }
                   3498: }
                   3499: 
                   3500: sub flush_langs_cache {
                   3501:     my ($uname,$udom)=@_;
                   3502:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3503:     if (!$uname) { $uname=$env{'user.name'};   }
                   3504:     return if ($udom eq 'public' && $uname eq 'public');
                   3505:     my $id=$uname.':'.$udom;
                   3506:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3507: }
                   3508: 
1.61      www      3509: # ------------------------------------------------------------------ Screenname
1.81      albertel 3510: 
                   3511: =pod
                   3512: 
1.648     raeburn  3513: =item * &screenname($uname,$udom)
1.81      albertel 3514: 
                   3515: Gets a users screenname and returns it as a string
                   3516: 
                   3517: =cut
1.61      www      3518: 
                   3519: sub screenname {
                   3520:     my ($uname,$udom)=@_;
1.258     albertel 3521:     if ($uname eq $env{'user.name'} &&
                   3522: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3523:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3524:     return $names{'screenname'};
1.62      www      3525: }
                   3526: 
1.212     albertel 3527: 
1.802     bisitz   3528: # ------------------------------------------------------------- Confirm Wrapper
                   3529: =pod
                   3530: 
1.1075.2.42  raeburn  3531: =item * &confirmwrapper($message)
1.802     bisitz   3532: 
                   3533: Wrap messages about completion of operation in box
                   3534: 
                   3535: =cut
                   3536: 
                   3537: sub confirmwrapper {
                   3538:     my ($message)=@_;
                   3539:     if ($message) {
                   3540:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3541:                .$message."\n"
                   3542:                .'</div>'."\n";
                   3543:     } else {
                   3544:         return $message;
                   3545:     }
                   3546: }
                   3547: 
1.62      www      3548: # ------------------------------------------------------------- Message Wrapper
                   3549: 
                   3550: sub messagewrapper {
1.369     www      3551:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3552:     return 
1.441     albertel 3553:         '<a href="/adm/email?compose=individual&amp;'.
                   3554:         'recname='.$username.'&amp;recdom='.$domain.
                   3555: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3556:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3557: }
1.802     bisitz   3558: 
1.74      www      3559: # --------------------------------------------------------------- Notes Wrapper
                   3560: 
                   3561: sub noteswrapper {
                   3562:     my ($link,$un,$do)=@_;
                   3563:     return 
1.896     amueller 3564: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3565: }
1.802     bisitz   3566: 
1.62      www      3567: # ------------------------------------------------------------- Aboutme Wrapper
                   3568: 
                   3569: sub aboutmewrapper {
1.1070    raeburn  3570:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3571:     if (!defined($username)  && !defined($domain)) {
                   3572:         return;
                   3573:     }
1.1075.2.15  raeburn  3574:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3575: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3576: }
                   3577: 
                   3578: # ------------------------------------------------------------ Syllabus Wrapper
                   3579: 
                   3580: sub syllabuswrapper {
1.707     bisitz   3581:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3582:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3583: }
1.14      harris41 3584: 
1.802     bisitz   3585: # -----------------------------------------------------------------------------
                   3586: 
1.208     matthew  3587: sub track_student_link {
1.887     raeburn  3588:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3589:     my $link ="/adm/trackstudent?";
1.208     matthew  3590:     my $title = 'View recent activity';
                   3591:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3592:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3593:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3594:         $title .= ' of this student';
1.268     albertel 3595:     } 
1.208     matthew  3596:     if (defined($target) && $target !~ /^\s*$/) {
                   3597:         $target = qq{target="$target"};
                   3598:     } else {
                   3599:         $target = '';
                   3600:     }
1.268     albertel 3601:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3602:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3603:     $title = &mt($title);
                   3604:     $linktext = &mt($linktext);
1.448     albertel 3605:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3606: 	&help_open_topic('View_recent_activity');
1.208     matthew  3607: }
                   3608: 
1.781     raeburn  3609: sub slot_reservations_link {
                   3610:     my ($linktext,$sname,$sdom,$target) = @_;
                   3611:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3612:     my $title = 'View slot reservation history';
                   3613:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3614:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3615:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3616:         $title .= ' of this student';
                   3617:     }
                   3618:     if (defined($target) && $target !~ /^\s*$/) {
                   3619:         $target = qq{target="$target"};
                   3620:     } else {
                   3621:         $target = '';
                   3622:     }
                   3623:     $title = &mt($title);
                   3624:     $linktext = &mt($linktext);
                   3625:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3626: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3627: 
                   3628: }
                   3629: 
1.508     www      3630: # ===================================================== Display a student photo
                   3631: 
                   3632: 
1.509     albertel 3633: sub student_image_tag {
1.508     www      3634:     my ($domain,$user)=@_;
                   3635:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3636:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3637: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3638:     } else {
                   3639: 	return '';
                   3640:     }
                   3641: }
                   3642: 
1.112     bowersj2 3643: =pod
                   3644: 
                   3645: =back
                   3646: 
                   3647: =head1 Access .tab File Data
                   3648: 
                   3649: =over 4
                   3650: 
1.648     raeburn  3651: =item * &languageids() 
1.112     bowersj2 3652: 
                   3653: returns list of all language ids
                   3654: 
                   3655: =cut
                   3656: 
1.14      harris41 3657: sub languageids {
1.16      harris41 3658:     return sort(keys(%language));
1.14      harris41 3659: }
                   3660: 
1.112     bowersj2 3661: =pod
                   3662: 
1.648     raeburn  3663: =item * &languagedescription() 
1.112     bowersj2 3664: 
                   3665: returns description of a specified language id
                   3666: 
                   3667: =cut
                   3668: 
1.14      harris41 3669: sub languagedescription {
1.125     www      3670:     my $code=shift;
                   3671:     return  ($supported_language{$code}?'* ':'').
                   3672:             $language{$code}.
1.126     www      3673: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3674: }
                   3675: 
1.1048    foxr     3676: =pod
                   3677: 
                   3678: =item * &plainlanguagedescription
                   3679: 
                   3680: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3681: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3682: 
                   3683: =cut
                   3684: 
1.145     www      3685: sub plainlanguagedescription {
                   3686:     my $code=shift;
                   3687:     return $language{$code};
                   3688: }
                   3689: 
1.1048    foxr     3690: =pod
                   3691: 
                   3692: =item * &supportedlanguagecode
                   3693: 
                   3694: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3695: code.
                   3696: 
                   3697: =cut
                   3698: 
1.145     www      3699: sub supportedlanguagecode {
                   3700:     my $code=shift;
                   3701:     return $supported_language{$code};
1.97      www      3702: }
                   3703: 
1.112     bowersj2 3704: =pod
                   3705: 
1.1048    foxr     3706: =item * &latexlanguage()
                   3707: 
                   3708: Given a language key code returns the correspondnig language to use
                   3709: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3710: is no supported hyphenation for the language code.
                   3711: 
                   3712: =cut
                   3713: 
                   3714: sub latexlanguage {
                   3715:     my $code = shift;
                   3716:     return $latex_language{$code};
                   3717: }
                   3718: 
                   3719: =pod
                   3720: 
                   3721: =item * &latexhyphenation()
                   3722: 
                   3723: Same as above but what's supplied is the language as it might be stored
                   3724: in the metadata.
                   3725: 
                   3726: =cut
                   3727: 
                   3728: sub latexhyphenation {
                   3729:     my $key = shift;
                   3730:     return $latex_language_bykey{$key};
                   3731: }
                   3732: 
                   3733: =pod
                   3734: 
1.648     raeburn  3735: =item * &copyrightids() 
1.112     bowersj2 3736: 
                   3737: returns list of all copyrights
                   3738: 
                   3739: =cut
                   3740: 
                   3741: sub copyrightids {
                   3742:     return sort(keys(%cprtag));
                   3743: }
                   3744: 
                   3745: =pod
                   3746: 
1.648     raeburn  3747: =item * &copyrightdescription() 
1.112     bowersj2 3748: 
                   3749: returns description of a specified copyright id
                   3750: 
                   3751: =cut
                   3752: 
                   3753: sub copyrightdescription {
1.166     www      3754:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3755: }
1.197     matthew  3756: 
                   3757: =pod
                   3758: 
1.648     raeburn  3759: =item * &source_copyrightids() 
1.192     taceyjo1 3760: 
                   3761: returns list of all source copyrights
                   3762: 
                   3763: =cut
                   3764: 
                   3765: sub source_copyrightids {
                   3766:     return sort(keys(%scprtag));
                   3767: }
                   3768: 
                   3769: =pod
                   3770: 
1.648     raeburn  3771: =item * &source_copyrightdescription() 
1.192     taceyjo1 3772: 
                   3773: returns description of a specified source copyright id
                   3774: 
                   3775: =cut
                   3776: 
                   3777: sub source_copyrightdescription {
                   3778:     return &mt($scprtag{shift(@_)});
                   3779: }
1.112     bowersj2 3780: 
                   3781: =pod
                   3782: 
1.648     raeburn  3783: =item * &filecategories() 
1.112     bowersj2 3784: 
                   3785: returns list of all file categories
                   3786: 
                   3787: =cut
                   3788: 
                   3789: sub filecategories {
                   3790:     return sort(keys(%category_extensions));
                   3791: }
                   3792: 
                   3793: =pod
                   3794: 
1.648     raeburn  3795: =item * &filecategorytypes() 
1.112     bowersj2 3796: 
                   3797: returns list of file types belonging to a given file
                   3798: category
                   3799: 
                   3800: =cut
                   3801: 
                   3802: sub filecategorytypes {
1.356     albertel 3803:     my ($cat) = @_;
                   3804:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3805: }
                   3806: 
                   3807: =pod
                   3808: 
1.648     raeburn  3809: =item * &fileembstyle() 
1.112     bowersj2 3810: 
                   3811: returns embedding style for a specified file type
                   3812: 
                   3813: =cut
                   3814: 
                   3815: sub fileembstyle {
                   3816:     return $fe{lc(shift(@_))};
1.169     www      3817: }
                   3818: 
1.351     www      3819: sub filemimetype {
                   3820:     return $fm{lc(shift(@_))};
                   3821: }
                   3822: 
1.169     www      3823: 
                   3824: sub filecategoryselect {
                   3825:     my ($name,$value)=@_;
1.189     matthew  3826:     return &select_form($value,$name,
1.970     raeburn  3827:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3828: }
                   3829: 
                   3830: =pod
                   3831: 
1.648     raeburn  3832: =item * &filedescription() 
1.112     bowersj2 3833: 
                   3834: returns description for a specified file type
                   3835: 
                   3836: =cut
                   3837: 
                   3838: sub filedescription {
1.188     matthew  3839:     my $file_description = $fd{lc(shift())};
                   3840:     $file_description =~ s:([\[\]]):~$1:g;
                   3841:     return &mt($file_description);
1.112     bowersj2 3842: }
                   3843: 
                   3844: =pod
                   3845: 
1.648     raeburn  3846: =item * &filedescriptionex() 
1.112     bowersj2 3847: 
                   3848: returns description for a specified file type with
                   3849: extra formatting
                   3850: 
                   3851: =cut
                   3852: 
                   3853: sub filedescriptionex {
                   3854:     my $ex=shift;
1.188     matthew  3855:     my $file_description = $fd{lc($ex)};
                   3856:     $file_description =~ s:([\[\]]):~$1:g;
                   3857:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3858: }
                   3859: 
                   3860: # End of .tab access
                   3861: =pod
                   3862: 
                   3863: =back
                   3864: 
                   3865: =cut
                   3866: 
                   3867: # ------------------------------------------------------------------ File Types
                   3868: sub fileextensions {
                   3869:     return sort(keys(%fe));
                   3870: }
                   3871: 
1.97      www      3872: # ----------------------------------------------------------- Display Languages
                   3873: # returns a hash with all desired display languages
                   3874: #
                   3875: 
                   3876: sub display_languages {
                   3877:     my %languages=();
1.695     raeburn  3878:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3879: 	$languages{$lang}=1;
1.97      www      3880:     }
                   3881:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3882:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3883: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3884: 	    $languages{$lang}=1;
1.97      www      3885:         }
                   3886:     }
                   3887:     return %languages;
1.14      harris41 3888: }
                   3889: 
1.582     albertel 3890: sub languages {
                   3891:     my ($possible_langs) = @_;
1.695     raeburn  3892:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3893:     if (!ref($possible_langs)) {
                   3894: 	if( wantarray ) {
                   3895: 	    return @preferred_langs;
                   3896: 	} else {
                   3897: 	    return $preferred_langs[0];
                   3898: 	}
                   3899:     }
                   3900:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3901:     my @preferred_possibilities;
                   3902:     foreach my $preferred_lang (@preferred_langs) {
                   3903: 	if (exists($possibilities{$preferred_lang})) {
                   3904: 	    push(@preferred_possibilities, $preferred_lang);
                   3905: 	}
                   3906:     }
                   3907:     if( wantarray ) {
                   3908: 	return @preferred_possibilities;
                   3909:     }
                   3910:     return $preferred_possibilities[0];
                   3911: }
                   3912: 
1.742     raeburn  3913: sub user_lang {
                   3914:     my ($touname,$toudom,$fromcid) = @_;
                   3915:     my @userlangs;
                   3916:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3917:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3918:                     $env{'course.'.$fromcid.'.languages'}));
                   3919:     } else {
                   3920:         my %langhash = &getlangs($touname,$toudom);
                   3921:         if ($langhash{'languages'} ne '') {
                   3922:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3923:         } else {
                   3924:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3925:             if ($domdefs{'lang_def'} ne '') {
                   3926:                 @userlangs = ($domdefs{'lang_def'});
                   3927:             }
                   3928:         }
                   3929:     }
                   3930:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3931:     my $user_lh = Apache::localize->get_handle(@languages);
                   3932:     return $user_lh;
                   3933: }
                   3934: 
                   3935: 
1.112     bowersj2 3936: ###############################################################
                   3937: ##               Student Answer Attempts                     ##
                   3938: ###############################################################
                   3939: 
                   3940: =pod
                   3941: 
                   3942: =head1 Alternate Problem Views
                   3943: 
                   3944: =over 4
                   3945: 
1.648     raeburn  3946: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  3947:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 3948: 
                   3949: Return string with previous attempt on problem. Arguments:
                   3950: 
                   3951: =over 4
                   3952: 
                   3953: =item * $symb: Problem, including path
                   3954: 
                   3955: =item * $username: username of the desired student
                   3956: 
                   3957: =item * $domain: domain of the desired student
1.14      harris41 3958: 
1.112     bowersj2 3959: =item * $course: Course ID
1.14      harris41 3960: 
1.112     bowersj2 3961: =item * $getattempt: Leave blank for all attempts, otherwise put
                   3962:     something
1.14      harris41 3963: 
1.112     bowersj2 3964: =item * $regexp: if string matches this regexp, the string will be
                   3965:     sent to $gradesub
1.14      harris41 3966: 
1.112     bowersj2 3967: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 3968: 
1.1075.2.86  raeburn  3969: =item * $usec: section of the desired student
                   3970: 
                   3971: =item * $identifier: counter for student (multiple students one problem) or
                   3972:     problem (one student; whole sequence).
                   3973: 
1.112     bowersj2 3974: =back
1.14      harris41 3975: 
1.112     bowersj2 3976: The output string is a table containing all desired attempts, if any.
1.16      harris41 3977: 
1.112     bowersj2 3978: =cut
1.1       albertel 3979: 
                   3980: sub get_previous_attempt {
1.1075.2.86  raeburn  3981:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 3982:   my $prevattempts='';
1.43      ng       3983:   no strict 'refs';
1.1       albertel 3984:   if ($symb) {
1.3       albertel 3985:     my (%returnhash)=
                   3986:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 3987:     if ($returnhash{'version'}) {
                   3988:       my %lasthash=();
                   3989:       my $version;
                   3990:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  3991:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   3992:             if ($key =~ /\.rawrndseed$/) {
                   3993:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   3994:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   3995:             } else {
                   3996:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   3997:             }
1.19      harris41 3998:         }
1.1       albertel 3999:       }
1.596     albertel 4000:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4001:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  4002:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4003:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4004:       foreach my $key (sort(keys(%lasthash))) {
                   4005: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4006: 	if ($#parts > 0) {
1.31      albertel 4007: 	  my $data=$parts[-1];
1.989     raeburn  4008:           next if ($data eq 'foilorder');
1.31      albertel 4009: 	  pop(@parts);
1.1010    www      4010:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4011:           if ($data eq 'type') {
                   4012:               unless ($showsurv) {
                   4013:                   my $id = join(',',@parts);
                   4014:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4015:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4016:                       $lasthidden{$ign.'.'.$id} = 1;
                   4017:                   }
1.945     raeburn  4018:               }
1.1075.2.86  raeburn  4019:               if ($identifier ne '') {
                   4020:                   my $id = join(',',@parts);
                   4021:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4022:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4023:                       $hidestatus{$ign.'.'.$id} = 1;
                   4024:                   }
                   4025:               }
                   4026:           } elsif ($data eq 'regrader') {
                   4027:               if (($identifier ne '') && (@parts)) {
                   4028:                   my $id = join(',',@parts);
                   4029:                   $regraded{$ign.'.'.$id} = 1;
                   4030:               }
1.1010    www      4031:           } 
1.31      albertel 4032: 	} else {
1.41      ng       4033: 	  if ($#parts == 0) {
                   4034: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4035: 	  } else {
                   4036: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4037: 	  }
1.31      albertel 4038: 	}
1.16      harris41 4039:       }
1.596     albertel 4040:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4041:       if ($getattempt eq '') {
1.1075.2.86  raeburn  4042:         my (%solved,%resets,%probstatus);
                   4043:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4044:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4045:                 foreach my $id (keys(%regraded)) {
                   4046:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4047:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4048:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4049:                         push(@{$resets{$id}},$version);
                   4050:                     }
                   4051:                 }
                   4052:             }
                   4053:         }
1.40      ng       4054: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  4055:             my (@hidden,@unsolved);
1.945     raeburn  4056:             if (%typeparts) {
                   4057:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  4058:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   4059:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4060:                         push(@hidden,$id);
1.1075.2.86  raeburn  4061:                     } elsif ($identifier ne '') {
                   4062:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4063:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4064:                                 ($hidestatus{$id})) {
                   4065:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   4066:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4067:                                 push(@{$solved{$id}},$version);
                   4068:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4069:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4070:                                 my $skip;
                   4071:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4072:                                     foreach my $reset (@{$resets{$id}}) {
                   4073:                                         if ($reset > $solved{$id}[-1]) {
                   4074:                                             $skip=1;
                   4075:                                             last;
                   4076:                                         }
                   4077:                                     }
                   4078:                                 }
                   4079:                                 unless ($skip) {
                   4080:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4081:                                     push(@unsolved,$partslist);
                   4082:                                 }
                   4083:                             }
                   4084:                         }
1.945     raeburn  4085:                     }
                   4086:                 }
                   4087:             }
                   4088:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  4089:                            '<td>'.&mt('Transaction [_1]',$version);
                   4090:             if (@unsolved) {
                   4091:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4092:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4093:                                  &mt('Hide').'</label></span>';
                   4094:             }
                   4095:             $prevattempts .= '</td>';
1.945     raeburn  4096:             if (@hidden) {
                   4097:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4098:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4099:                     my $hide;
                   4100:                     foreach my $id (@hidden) {
                   4101:                         if ($key =~ /^\Q$id\E/) {
                   4102:                             $hide = 1;
                   4103:                             last;
                   4104:                         }
                   4105:                     }
                   4106:                     if ($hide) {
                   4107:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4108:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4109:                             my $value = &format_previous_attempt_value($key,
                   4110:                                              $returnhash{$version.':'.$key});
                   4111:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4112:                         } else {
                   4113:                             $prevattempts.='<td>&nbsp;</td>';
                   4114:                         }
                   4115:                     } else {
                   4116:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  4117:                             my $value = $returnhash{$version.':'.$key};
                   4118:                             if ($key =~ /\.rndseed$/) {
                   4119:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4120:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4121:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4122:                                 }
                   4123:                             }
                   4124:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4125:                                            '&nbsp;</td>';
1.945     raeburn  4126:                         } else {
                   4127:                             $prevattempts.='<td>&nbsp;</td>';
                   4128:                         }
                   4129:                     }
                   4130:                 }
                   4131:             } else {
                   4132: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4133:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  4134:                     my $value = $returnhash{$version.':'.$key};
                   4135:                     if ($key =~ /\.rndseed$/) {
                   4136:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4137:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4138:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4139:                         }
                   4140:                     }
                   4141:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4142:                                    '&nbsp;</td>';
1.945     raeburn  4143: 	        }
                   4144:             }
                   4145: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4146: 	 }
1.1       albertel 4147:       }
1.945     raeburn  4148:       my @currhidden = keys(%lasthidden);
1.596     albertel 4149:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4150:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4151:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4152:           if (%typeparts) {
                   4153:               my $hidden;
                   4154:               foreach my $id (@currhidden) {
                   4155:                   if ($key =~ /^\Q$id\E/) {
                   4156:                       $hidden = 1;
                   4157:                       last;
                   4158:                   }
                   4159:               }
                   4160:               if ($hidden) {
                   4161:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4162:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4163:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4164:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4165:                           $value = &$gradesub($value);
                   4166:                       }
                   4167:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4168:                   } else {
                   4169:                       $prevattempts.='<td>&nbsp;</td>';
                   4170:                   }
                   4171:               } else {
                   4172:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4173:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4174:                       $value = &$gradesub($value);
                   4175:                   }
                   4176:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4177:               }
                   4178:           } else {
                   4179: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4180: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4181:                   $value = &$gradesub($value);
                   4182:               }
                   4183: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4184:           }
1.16      harris41 4185:       }
1.596     albertel 4186:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4187:     } else {
1.596     albertel 4188:       $prevattempts=
                   4189: 	  &start_data_table().&start_data_table_row().
                   4190: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4191: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4192:     }
                   4193:   } else {
1.596     albertel 4194:     $prevattempts=
                   4195: 	  &start_data_table().&start_data_table_row().
                   4196: 	  '<td>'.&mt('No data.').'</td>'.
                   4197: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4198:   }
1.10      albertel 4199: }
                   4200: 
1.581     albertel 4201: sub format_previous_attempt_value {
                   4202:     my ($key,$value) = @_;
1.1011    www      4203:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 4204: 	$value = &Apache::lonlocal::locallocaltime($value);
                   4205:     } elsif (ref($value) eq 'ARRAY') {
                   4206: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  4207:     } elsif ($key =~ /answerstring$/) {
                   4208:         my %answers = &Apache::lonnet::str2hash($value);
                   4209:         my @anskeys = sort(keys(%answers));
                   4210:         if (@anskeys == 1) {
                   4211:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4212:             if ($answer =~ m{\0}) {
                   4213:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4214:             }
                   4215:             my $tag_internal_answer_name = 'INTERNAL';
                   4216:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4217:                 $value = $answer; 
                   4218:             } else {
                   4219:                 $value = $anskeys[0].'='.$answer;
                   4220:             }
                   4221:         } else {
                   4222:             foreach my $ans (@anskeys) {
                   4223:                 my $answer = $answers{$ans};
1.1001    raeburn  4224:                 if ($answer =~ m{\0}) {
                   4225:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4226:                 }
                   4227:                 $value .=  $ans.'='.$answer.'<br />';;
                   4228:             } 
                   4229:         }
1.581     albertel 4230:     } else {
                   4231: 	$value = &unescape($value);
                   4232:     }
                   4233:     return $value;
                   4234: }
                   4235: 
                   4236: 
1.107     albertel 4237: sub relative_to_absolute {
                   4238:     my ($url,$output)=@_;
                   4239:     my $parser=HTML::TokeParser->new(\$output);
                   4240:     my $token;
                   4241:     my $thisdir=$url;
                   4242:     my @rlinks=();
                   4243:     while ($token=$parser->get_token) {
                   4244: 	if ($token->[0] eq 'S') {
                   4245: 	    if ($token->[1] eq 'a') {
                   4246: 		if ($token->[2]->{'href'}) {
                   4247: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4248: 		}
                   4249: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4250: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4251: 	    } elsif ($token->[1] eq 'base') {
                   4252: 		$thisdir=$token->[2]->{'href'};
                   4253: 	    }
                   4254: 	}
                   4255:     }
                   4256:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4257:     foreach my $link (@rlinks) {
1.726     raeburn  4258: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4259: 		($link=~/^\//) ||
                   4260: 		($link=~/^javascript:/i) ||
                   4261: 		($link=~/^mailto:/i) ||
                   4262: 		($link=~/^\#/)) {
                   4263: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4264: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4265: 	}
                   4266:     }
                   4267: # -------------------------------------------------- Deal with Applet codebases
                   4268:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4269:     return $output;
                   4270: }
                   4271: 
1.112     bowersj2 4272: =pod
                   4273: 
1.648     raeburn  4274: =item * &get_student_view()
1.112     bowersj2 4275: 
                   4276: show a snapshot of what student was looking at
                   4277: 
                   4278: =cut
                   4279: 
1.10      albertel 4280: sub get_student_view {
1.186     albertel 4281:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4282:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4283:   my (%form);
1.10      albertel 4284:   my @elements=('symb','courseid','domain','username');
                   4285:   foreach my $element (@elements) {
1.186     albertel 4286:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4287:   }
1.186     albertel 4288:   if (defined($moreenv)) {
                   4289:       %form=(%form,%{$moreenv});
                   4290:   }
1.236     albertel 4291:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4292:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4293:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4294:   $userview=~s/\<body[^\>]*\>//gi;
                   4295:   $userview=~s/\<\/body\>//gi;
                   4296:   $userview=~s/\<html\>//gi;
                   4297:   $userview=~s/\<\/html\>//gi;
                   4298:   $userview=~s/\<head\>//gi;
                   4299:   $userview=~s/\<\/head\>//gi;
                   4300:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4301:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4302:   if (wantarray) {
                   4303:      return ($userview,$response);
                   4304:   } else {
                   4305:      return $userview;
                   4306:   }
                   4307: }
                   4308: 
                   4309: sub get_student_view_with_retries {
                   4310:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4311: 
                   4312:     my $ok = 0;                 # True if we got a good response.
                   4313:     my $content;
                   4314:     my $response;
                   4315: 
                   4316:     # Try to get the student_view done. within the retries count:
                   4317:     
                   4318:     do {
                   4319:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4320:          $ok      = $response->is_success;
                   4321:          if (!$ok) {
                   4322:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4323:          }
                   4324:          $retries--;
                   4325:     } while (!$ok && ($retries > 0));
                   4326:     
                   4327:     if (!$ok) {
                   4328:        $content = '';          # On error return an empty content.
                   4329:     }
1.651     www      4330:     if (wantarray) {
                   4331:        return ($content, $response);
                   4332:     } else {
                   4333:        return $content;
                   4334:     }
1.11      albertel 4335: }
                   4336: 
1.112     bowersj2 4337: =pod
                   4338: 
1.648     raeburn  4339: =item * &get_student_answers() 
1.112     bowersj2 4340: 
                   4341: show a snapshot of how student was answering problem
                   4342: 
                   4343: =cut
                   4344: 
1.11      albertel 4345: sub get_student_answers {
1.100     sakharuk 4346:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4347:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4348:   my (%moreenv);
1.11      albertel 4349:   my @elements=('symb','courseid','domain','username');
                   4350:   foreach my $element (@elements) {
1.186     albertel 4351:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4352:   }
1.186     albertel 4353:   $moreenv{'grade_target'}='answer';
                   4354:   %moreenv=(%form,%moreenv);
1.497     raeburn  4355:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4356:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4357:   return $userview;
1.1       albertel 4358: }
1.116     albertel 4359: 
                   4360: =pod
                   4361: 
                   4362: =item * &submlink()
                   4363: 
1.242     albertel 4364: Inputs: $text $uname $udom $symb $target
1.116     albertel 4365: 
                   4366: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4367: 
                   4368: =cut
                   4369: 
                   4370: ###############################################
                   4371: sub submlink {
1.242     albertel 4372:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4373:     if (!($uname && $udom)) {
                   4374: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4375: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4376: 	if (!$symb) { $symb=$cursymb; }
                   4377:     }
1.254     matthew  4378:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4379:     $symb=&escape($symb);
1.960     bisitz   4380:     if ($target) { $target=" target=\"$target\""; }
                   4381:     return
                   4382:         '<a href="/adm/grades?command=submission'.
                   4383:         '&amp;symb='.$symb.
                   4384:         '&amp;student='.$uname.
                   4385:         '&amp;userdom='.$udom.'"'.
                   4386:         $target.'>'.$text.'</a>';
1.242     albertel 4387: }
                   4388: ##############################################
                   4389: 
                   4390: =pod
                   4391: 
                   4392: =item * &pgrdlink()
                   4393: 
                   4394: Inputs: $text $uname $udom $symb $target
                   4395: 
                   4396: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4397: 
                   4398: =cut
                   4399: 
                   4400: ###############################################
                   4401: sub pgrdlink {
                   4402:     my $link=&submlink(@_);
                   4403:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4404:     return $link;
                   4405: }
                   4406: ##############################################
                   4407: 
                   4408: =pod
                   4409: 
                   4410: =item * &pprmlink()
                   4411: 
                   4412: Inputs: $text $uname $udom $symb $target
                   4413: 
                   4414: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4415: student and a specific resource
1.242     albertel 4416: 
                   4417: =cut
                   4418: 
                   4419: ###############################################
                   4420: sub pprmlink {
                   4421:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4422:     if (!($uname && $udom)) {
                   4423: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4424: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4425: 	if (!$symb) { $symb=$cursymb; }
                   4426:     }
1.254     matthew  4427:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4428:     $symb=&escape($symb);
1.242     albertel 4429:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4430:     return '<a href="/adm/parmset?command=set&amp;'.
                   4431: 	'symb='.$symb.'&amp;uname='.$uname.
                   4432: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4433: }
                   4434: ##############################################
1.37      matthew  4435: 
1.112     bowersj2 4436: =pod
                   4437: 
                   4438: =back
                   4439: 
                   4440: =cut
                   4441: 
1.37      matthew  4442: ###############################################
1.51      www      4443: 
                   4444: 
                   4445: sub timehash {
1.687     raeburn  4446:     my ($thistime) = @_;
                   4447:     my $timezone = &Apache::lonlocal::gettimezone();
                   4448:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4449:                      ->set_time_zone($timezone);
                   4450:     my $wday = $dt->day_of_week();
                   4451:     if ($wday == 7) { $wday = 0; }
                   4452:     return ( 'second' => $dt->second(),
                   4453:              'minute' => $dt->minute(),
                   4454:              'hour'   => $dt->hour(),
                   4455:              'day'     => $dt->day_of_month(),
                   4456:              'month'   => $dt->month(),
                   4457:              'year'    => $dt->year(),
                   4458:              'weekday' => $wday,
                   4459:              'dayyear' => $dt->day_of_year(),
                   4460:              'dlsav'   => $dt->is_dst() );
1.51      www      4461: }
                   4462: 
1.370     www      4463: sub utc_string {
                   4464:     my ($date)=@_;
1.371     www      4465:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4466: }
                   4467: 
1.51      www      4468: sub maketime {
                   4469:     my %th=@_;
1.687     raeburn  4470:     my ($epoch_time,$timezone,$dt);
                   4471:     $timezone = &Apache::lonlocal::gettimezone();
                   4472:     eval {
                   4473:         $dt = DateTime->new( year   => $th{'year'},
                   4474:                              month  => $th{'month'},
                   4475:                              day    => $th{'day'},
                   4476:                              hour   => $th{'hour'},
                   4477:                              minute => $th{'minute'},
                   4478:                              second => $th{'second'},
                   4479:                              time_zone => $timezone,
                   4480:                          );
                   4481:     };
                   4482:     if (!$@) {
                   4483:         $epoch_time = $dt->epoch;
                   4484:         if ($epoch_time) {
                   4485:             return $epoch_time;
                   4486:         }
                   4487:     }
1.51      www      4488:     return POSIX::mktime(
                   4489:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4490:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4491: }
                   4492: 
                   4493: #########################################
1.51      www      4494: 
                   4495: sub findallcourses {
1.482     raeburn  4496:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4497:     my %roles;
                   4498:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4499:     my %courses;
1.51      www      4500:     my $now=time;
1.482     raeburn  4501:     if (!defined($uname)) {
                   4502:         $uname = $env{'user.name'};
                   4503:     }
                   4504:     if (!defined($udom)) {
                   4505:         $udom = $env{'user.domain'};
                   4506:     }
                   4507:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4508:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4509:         if (!%roles) {
                   4510:             %roles = (
                   4511:                        cc => 1,
1.907     raeburn  4512:                        co => 1,
1.482     raeburn  4513:                        in => 1,
                   4514:                        ep => 1,
                   4515:                        ta => 1,
                   4516:                        cr => 1,
                   4517:                        st => 1,
                   4518:              );
                   4519:         }
                   4520:         foreach my $entry (keys(%roleshash)) {
                   4521:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4522:             if ($trole =~ /^cr/) { 
                   4523:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4524:             } else {
                   4525:                 next if (!exists($roles{$trole}));
                   4526:             }
                   4527:             if ($tend) {
                   4528:                 next if ($tend < $now);
                   4529:             }
                   4530:             if ($tstart) {
                   4531:                 next if ($tstart > $now);
                   4532:             }
1.1058    raeburn  4533:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4534:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4535:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4536:             if ($secpart eq '') {
                   4537:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4538:                 $sec = 'none';
1.1058    raeburn  4539:                 $value .= $cnum.'/';
1.482     raeburn  4540:             } else {
                   4541:                 $cnum = $cnumpart;
                   4542:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4543:                 $value .= $cnum.'/'.$sec;
                   4544:             }
                   4545:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4546:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4547:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4548:                 }
                   4549:             } else {
                   4550:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4551:             }
1.482     raeburn  4552:         }
                   4553:     } else {
                   4554:         foreach my $key (keys(%env)) {
1.483     albertel 4555: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4556:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4557: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4558: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4559: 	        next if (%roles && !exists($roles{$role}));
                   4560: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4561:                 my $active=1;
                   4562:                 if ($starttime) {
                   4563: 		    if ($now<$starttime) { $active=0; }
                   4564:                 }
                   4565:                 if ($endtime) {
                   4566:                     if ($now>$endtime) { $active=0; }
                   4567:                 }
                   4568:                 if ($active) {
1.1058    raeburn  4569:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4570:                     if ($sec eq '') {
                   4571:                         $sec = 'none';
1.1058    raeburn  4572:                     } else {
                   4573:                         $value .= $sec;
                   4574:                     }
                   4575:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4576:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4577:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4578:                         }
                   4579:                     } else {
                   4580:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4581:                     }
1.474     raeburn  4582:                 }
                   4583:             }
1.51      www      4584:         }
                   4585:     }
1.474     raeburn  4586:     return %courses;
1.51      www      4587: }
1.37      matthew  4588: 
1.54      www      4589: ###############################################
1.474     raeburn  4590: 
                   4591: sub blockcheck {
1.1075.2.73  raeburn  4592:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4593: 
1.1075.2.73  raeburn  4594:     if (defined($udom) && defined($uname)) {
                   4595:         # If uname and udom are for a course, check for blocks in the course.
                   4596:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4597:             my ($startblock,$endblock,$triggerblock) =
                   4598:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4599:             return ($startblock,$endblock,$triggerblock);
                   4600:         }
                   4601:     } else {
1.490     raeburn  4602:         $udom = $env{'user.domain'};
                   4603:         $uname = $env{'user.name'};
                   4604:     }
                   4605: 
1.502     raeburn  4606:     my $startblock = 0;
                   4607:     my $endblock = 0;
1.1062    raeburn  4608:     my $triggerblock = '';
1.482     raeburn  4609:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4610: 
1.490     raeburn  4611:     # If uname is for a user, and activity is course-specific, i.e.,
                   4612:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4613: 
1.490     raeburn  4614:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.73  raeburn  4615:          $activity eq 'groups' || $activity eq 'printout') &&
                   4616:         ($env{'request.course.id'})) {
1.490     raeburn  4617:         foreach my $key (keys(%live_courses)) {
                   4618:             if ($key ne $env{'request.course.id'}) {
                   4619:                 delete($live_courses{$key});
                   4620:             }
                   4621:         }
                   4622:     }
                   4623: 
                   4624:     my $otheruser = 0;
                   4625:     my %own_courses;
                   4626:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4627:         # Resource belongs to user other than current user.
                   4628:         $otheruser = 1;
                   4629:         # Gather courses for current user
                   4630:         %own_courses = 
                   4631:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4632:     }
                   4633: 
                   4634:     # Gather active course roles - course coordinator, instructor, 
                   4635:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4636: 
                   4637:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4638:         my ($cdom,$cnum);
                   4639:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4640:             $cdom = $env{'course.'.$course.'.domain'};
                   4641:             $cnum = $env{'course.'.$course.'.num'};
                   4642:         } else {
1.490     raeburn  4643:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4644:         }
                   4645:         my $no_ownblock = 0;
                   4646:         my $no_userblock = 0;
1.533     raeburn  4647:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4648:             # Check if current user has 'evb' priv for this
                   4649:             if (defined($own_courses{$course})) {
                   4650:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4651:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4652:                     if ($sec ne 'none') {
                   4653:                         $checkrole .= '/'.$sec;
                   4654:                     }
                   4655:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4656:                         $no_ownblock = 1;
                   4657:                         last;
                   4658:                     }
                   4659:                 }
                   4660:             }
                   4661:             # if they have 'evb' priv and are currently not playing student
                   4662:             next if (($no_ownblock) &&
                   4663:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4664:         }
1.474     raeburn  4665:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4666:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4667:             if ($sec ne 'none') {
1.482     raeburn  4668:                 $checkrole .= '/'.$sec;
1.474     raeburn  4669:             }
1.490     raeburn  4670:             if ($otheruser) {
                   4671:                 # Resource belongs to user other than current user.
                   4672:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4673:                 my (%allroles,%userroles);
                   4674:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4675:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4676:                         my ($trole,$tdom,$tnum,$tsec);
                   4677:                         if ($entry =~ /^cr/) {
                   4678:                             ($trole,$tdom,$tnum,$tsec) = 
                   4679:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4680:                         } else {
                   4681:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4682:                         }
                   4683:                         my ($spec,$area,$trest);
                   4684:                         $area = '/'.$tdom.'/'.$tnum;
                   4685:                         $trest = $tnum;
                   4686:                         if ($tsec ne '') {
                   4687:                             $area .= '/'.$tsec;
                   4688:                             $trest .= '/'.$tsec;
                   4689:                         }
                   4690:                         $spec = $trole.'.'.$area;
                   4691:                         if ($trole =~ /^cr/) {
                   4692:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4693:                                                               $tdom,$spec,$trest,$area);
                   4694:                         } else {
                   4695:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4696:                                                                 $tdom,$spec,$trest,$area);
                   4697:                         }
                   4698:                     }
                   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+)$}) {
1.1075.2.121  raeburn  5444:             if ($env{'request.role.desc'}) {
                   5445:                 $role = $env{'request.role.desc'};
                   5446:             } else {
                   5447:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   5448:             }
1.1075.2.115  raeburn  5449:         } else {
                   5450:             $role = (split(/\//,$role,4))[-1];
1.378     raeburn  5451:         }
1.898     raeburn  5452:         if ($env{'request.course.sec'}) {
                   5453:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5454:         }   
1.359     albertel 5455: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5456:     } else {
                   5457:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5458:     }
1.433     albertel 5459: 
1.359     albertel 5460:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5461: 
1.438     albertel 5462:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5463: 
1.101     www      5464: # construct main body tag
1.359     albertel 5465:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  5466: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5467: 
1.1075.2.38  raeburn  5468:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5469: 
                   5470:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5471:         return $bodytag;
1.1075.2.38  raeburn  5472:     }
1.359     albertel 5473: 
1.954     raeburn  5474:     if ($public) {
1.433     albertel 5475: 	undef($role);
                   5476:     }
1.359     albertel 5477:     
1.762     bisitz   5478:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5479:     #
                   5480:     # Extra info if you are the DC
                   5481:     my $dc_info = '';
                   5482:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5483:                         $env{'course.'.$env{'request.course.id'}.
                   5484:                                  '.domain'}.'/'})) {
                   5485:         my $cid = $env{'request.course.id'};
1.917     raeburn  5486:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5487:         $dc_info =~ s/\s+$//;
1.359     albertel 5488:     }
                   5489: 
1.1075.2.108  raeburn  5490:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 5491: 
1.1075.2.13  raeburn  5492:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5493: 
1.1075.2.38  raeburn  5494: 
                   5495: 
1.1075.2.21  raeburn  5496:     my $funclist;
                   5497:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  5498:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  5499:                     Apache::lonmenu::serverform();
                   5500:         my $forbodytag;
                   5501:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5502:                                             $forcereg,$args->{'group'},
                   5503:                                             $args->{'bread_crumbs'},
                   5504:                                             $advtoolsref,'',\$forbodytag);
                   5505:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5506:             $funclist = $forbodytag;
                   5507:         }
                   5508:     } else {
1.903     droeschl 5509: 
                   5510:         #    if ($env{'request.state'} eq 'construct') {
                   5511:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5512:         #    }
                   5513: 
1.1075.2.38  raeburn  5514:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5515:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5516: 
1.1075.2.38  raeburn  5517:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.1075.2.2  raeburn  5518: 
1.916     droeschl 5519:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.1075.2.22  raeburn  5520:             if ($dc_info) {
                   5521:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
1.1075.2.1  raeburn  5522:             }
1.1075.2.38  raeburn  5523:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.1075.2.22  raeburn  5524:                            <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5525:             return $bodytag;
                   5526:         }
1.894     droeschl 5527: 
1.927     raeburn  5528:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1075.2.38  raeburn  5529:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5530:         }
1.916     droeschl 5531: 
1.1075.2.38  raeburn  5532:         $bodytag .= $right;
1.852     droeschl 5533: 
1.917     raeburn  5534:         if ($dc_info) {
                   5535:             $dc_info = &dc_courseid_toggle($dc_info);
                   5536:         }
                   5537:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5538: 
1.1075.2.61  raeburn  5539:         #if directed to not display the secondary menu, don't.
                   5540:         if ($args->{'no_secondary_menu'}) {
                   5541:             return $bodytag;
                   5542:         }
1.903     droeschl 5543:         #don't show menus for public users
1.954     raeburn  5544:         if (!$public){
1.1075.2.52  raeburn  5545:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5546:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5547:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5548:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5549:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5550:                                 $args->{'bread_crumbs'});
1.1075.2.116  raeburn  5551:             } elsif ($forcereg) {
1.1075.2.22  raeburn  5552:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1075.2.116  raeburn  5553:                                                             $args->{'group'},
                   5554:                                                             $args->{'hide_buttons'});
1.1075.2.15  raeburn  5555:             } else {
1.1075.2.21  raeburn  5556:                 my $forbodytag;
                   5557:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5558:                                                     $forcereg,$args->{'group'},
                   5559:                                                     $args->{'bread_crumbs'},
                   5560:                                                     $advtoolsref,'',\$forbodytag);
                   5561:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5562:                     $bodytag .= $forbodytag;
                   5563:                 }
1.920     raeburn  5564:             }
1.903     droeschl 5565:         }else{
                   5566:             # this is to seperate menu from content when there's no secondary
                   5567:             # menu. Especially needed for public accessible ressources.
                   5568:             $bodytag .= '<hr style="clear:both" />';
                   5569:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5570:         }
1.903     droeschl 5571: 
1.235     raeburn  5572:         return $bodytag;
1.1075.2.12  raeburn  5573:     }
                   5574: 
                   5575: #
                   5576: # Top frame rendering, Remote is up
                   5577: #
                   5578: 
                   5579:     my $imgsrc = $img;
                   5580:     if ($img =~ /^\/adm/) {
                   5581:         $imgsrc = &lonhttpdurl($img);
                   5582:     }
                   5583:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5584: 
1.1075.2.60  raeburn  5585:     my $help=($no_inline_link?''
                   5586:               :&Apache::loncommon::top_nav_help('Help'));
                   5587: 
1.1075.2.12  raeburn  5588:     # Explicit link to get inline menu
                   5589:     my $menu= ($no_inline_link?''
                   5590:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5591: 
                   5592:     if ($dc_info) {
                   5593:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5594:     }
                   5595: 
1.1075.2.38  raeburn  5596:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   5597:     unless ($public) {
                   5598:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5599:                                 undef,'LC_menubuttons_link');
                   5600:     }
                   5601: 
1.1075.2.12  raeburn  5602:     unless ($env{'form.inhibitmenu'}) {
                   5603:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  5604:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  5605:                        <li>$help</li>
1.1075.2.12  raeburn  5606:                        <li>$menu</li>
                   5607:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5608:     }
1.1075.2.13  raeburn  5609:     if ($env{'request.state'} eq 'construct') {
                   5610:         if (!$public){
                   5611:             if ($env{'request.state'} eq 'construct') {
                   5612:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5613:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  5614:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5615:                             &Apache::lonmenu::innerregister($forcereg,
                   5616:                                                             $args->{'bread_crumbs'});
                   5617:             }
                   5618:         }
                   5619:     }
1.1075.2.21  raeburn  5620:     return $bodytag."\n".$funclist;
1.182     matthew  5621: }
                   5622: 
1.917     raeburn  5623: sub dc_courseid_toggle {
                   5624:     my ($dc_info) = @_;
1.980     raeburn  5625:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5626:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5627:            &mt('(More ...)').'</a></span>'.
                   5628:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5629: }
                   5630: 
1.330     albertel 5631: sub make_attr_string {
                   5632:     my ($register,$attr_ref) = @_;
                   5633: 
                   5634:     if ($attr_ref && !ref($attr_ref)) {
                   5635: 	die("addentries Must be a hash ref ".
                   5636: 	    join(':',caller(1))." ".
                   5637: 	    join(':',caller(0))." ");
                   5638:     }
                   5639: 
                   5640:     if ($register) {
1.339     albertel 5641: 	my ($on_load,$on_unload);
                   5642: 	foreach my $key (keys(%{$attr_ref})) {
                   5643: 	    if      (lc($key) eq 'onload') {
                   5644: 		$on_load.=$attr_ref->{$key}.';';
                   5645: 		delete($attr_ref->{$key});
                   5646: 
                   5647: 	    } elsif (lc($key) eq 'onunload') {
                   5648: 		$on_unload.=$attr_ref->{$key}.';';
                   5649: 		delete($attr_ref->{$key});
                   5650: 	    }
                   5651: 	}
1.1075.2.12  raeburn  5652:         if ($env{'environment.remote'} eq 'on') {
                   5653:             $attr_ref->{'onload'}  =
                   5654:                 &Apache::lonmenu::loadevents().  $on_load;
                   5655:             $attr_ref->{'onunload'}=
                   5656:                 &Apache::lonmenu::unloadevents().$on_unload;
                   5657:         } else {  
                   5658: 	    $attr_ref->{'onload'}  = $on_load;
                   5659: 	    $attr_ref->{'onunload'}= $on_unload;
                   5660:         }
1.330     albertel 5661:     }
1.339     albertel 5662: 
1.330     albertel 5663:     my $attr_string;
1.1075.2.56  raeburn  5664:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5665: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5666:     }
                   5667:     return $attr_string;
                   5668: }
                   5669: 
                   5670: 
1.182     matthew  5671: ###############################################
1.251     albertel 5672: ###############################################
                   5673: 
                   5674: =pod
                   5675: 
                   5676: =item * &endbodytag()
                   5677: 
                   5678: Returns a uniform footer for LON-CAPA web pages.
                   5679: 
1.635     raeburn  5680: Inputs: 1 - optional reference to an args hash
                   5681: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5682: a 'Continue' link is not displayed if the page contains an
                   5683: internal redirect in the <head></head> section,
                   5684: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5685: 
                   5686: =cut
                   5687: 
                   5688: sub endbodytag {
1.635     raeburn  5689:     my ($args) = @_;
1.1075.2.6  raeburn  5690:     my $endbodytag;
                   5691:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5692:         $endbodytag='</body>';
                   5693:     }
1.315     albertel 5694:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5695:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5696: 	    $endbodytag=
                   5697: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5698: 	        &mt('Continue').'</a>'.
                   5699: 	        $endbodytag;
                   5700:         }
1.315     albertel 5701:     }
1.251     albertel 5702:     return $endbodytag;
                   5703: }
                   5704: 
1.352     albertel 5705: =pod
                   5706: 
                   5707: =item * &standard_css()
                   5708: 
                   5709: Returns a style sheet
                   5710: 
                   5711: Inputs: (all optional)
                   5712:             domain         -> force to color decorate a page for a specific
                   5713:                                domain
                   5714:             function       -> force usage of a specific rolish color scheme
                   5715:             bgcolor        -> override the default page bgcolor
                   5716: 
                   5717: =cut
                   5718: 
1.343     albertel 5719: sub standard_css {
1.345     albertel 5720:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5721:     $function  = &get_users_function() if (!$function);
                   5722:     my $img    = &designparm($function.'.img',   $domain);
                   5723:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5724:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5725:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5726: #second colour for later usage
1.345     albertel 5727:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5728:     my $pgbg_or_bgcolor =
                   5729: 	         $bgcolor ||
1.352     albertel 5730: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5731:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5732:     my $alink  = &designparm($function.'.alink', $domain);
                   5733:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5734:     my $link   = &designparm($function.'.link',  $domain);
                   5735: 
1.602     albertel 5736:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5737:     my $mono                 = 'monospace';
1.850     bisitz   5738:     my $data_table_head      = $sidebg;
                   5739:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5740:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5741:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5742:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5743:     my $mail_new             = '#FFBB77';
                   5744:     my $mail_new_hover       = '#DD9955';
                   5745:     my $mail_read            = '#BBBB77';
                   5746:     my $mail_read_hover      = '#999944';
                   5747:     my $mail_replied         = '#AAAA88';
                   5748:     my $mail_replied_hover   = '#888855';
                   5749:     my $mail_other           = '#99BBBB';
                   5750:     my $mail_other_hover     = '#669999';
1.391     albertel 5751:     my $table_header         = '#DDDDDD';
1.489     raeburn  5752:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5753:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5754:     my $button_hover         = '#BF2317';
1.392     albertel 5755: 
1.608     albertel 5756:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5757:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5758:                                              : '0 3px 0 4px';
1.448     albertel 5759: 
1.523     albertel 5760: 
1.343     albertel 5761:     return <<END;
1.947     droeschl 5762: 
                   5763: /* needed for iframe to allow 100% height in FF */
                   5764: body, html { 
                   5765:     margin: 0;
                   5766:     padding: 0 0.5%;
                   5767:     height: 99%; /* to avoid scrollbars */
                   5768: }
                   5769: 
1.795     www      5770: body {
1.911     bisitz   5771:   font-family: $sans;
                   5772:   line-height:130%;
                   5773:   font-size:0.83em;
                   5774:   color:$font;
1.795     www      5775: }
                   5776: 
1.959     onken    5777: a:focus,
                   5778: a:focus img {
1.795     www      5779:   color: red;
                   5780: }
1.698     harmsja  5781: 
1.911     bisitz   5782: form, .inline {
                   5783:   display: inline;
1.795     www      5784: }
1.721     harmsja  5785: 
1.795     www      5786: .LC_right {
1.911     bisitz   5787:   text-align:right;
1.795     www      5788: }
                   5789: 
                   5790: .LC_middle {
1.911     bisitz   5791:   vertical-align:middle;
1.795     www      5792: }
1.721     harmsja  5793: 
1.1075.2.38  raeburn  5794: .LC_floatleft {
                   5795:   float: left;
                   5796: }
                   5797: 
                   5798: .LC_floatright {
                   5799:   float: right;
                   5800: }
                   5801: 
1.911     bisitz   5802: .LC_400Box {
                   5803:   width:400px;
                   5804: }
1.721     harmsja  5805: 
1.947     droeschl 5806: .LC_iframecontainer {
                   5807:     width: 98%;
                   5808:     margin: 0;
                   5809:     position: fixed;
                   5810:     top: 8.5em;
                   5811:     bottom: 0;
                   5812: }
                   5813: 
                   5814: .LC_iframecontainer iframe{
                   5815:     border: none;
                   5816:     width: 100%;
                   5817:     height: 100%;
                   5818: }
                   5819: 
1.778     bisitz   5820: .LC_filename {
                   5821:   font-family: $mono;
                   5822:   white-space:pre;
1.921     bisitz   5823:   font-size: 120%;
1.778     bisitz   5824: }
                   5825: 
                   5826: .LC_fileicon {
                   5827:   border: none;
                   5828:   height: 1.3em;
                   5829:   vertical-align: text-bottom;
                   5830:   margin-right: 0.3em;
                   5831:   text-decoration:none;
                   5832: }
                   5833: 
1.1008    www      5834: .LC_setting {
                   5835:   text-decoration:underline;
                   5836: }
                   5837: 
1.350     albertel 5838: .LC_error {
                   5839:   color: red;
                   5840: }
1.795     www      5841: 
1.1075.2.15  raeburn  5842: .LC_warning {
                   5843:   color: darkorange;
                   5844: }
                   5845: 
1.457     albertel 5846: .LC_diff_removed {
1.733     bisitz   5847:   color: red;
1.394     albertel 5848: }
1.532     albertel 5849: 
                   5850: .LC_info,
1.457     albertel 5851: .LC_success,
                   5852: .LC_diff_added {
1.350     albertel 5853:   color: green;
                   5854: }
1.795     www      5855: 
1.802     bisitz   5856: div.LC_confirm_box {
                   5857:   background-color: #FAFAFA;
                   5858:   border: 1px solid $lg_border_color;
                   5859:   margin-right: 0;
                   5860:   padding: 5px;
                   5861: }
                   5862: 
                   5863: div.LC_confirm_box .LC_error img,
                   5864: div.LC_confirm_box .LC_success img {
                   5865:   vertical-align: middle;
                   5866: }
                   5867: 
1.1075.2.108  raeburn  5868: .LC_maxwidth {
                   5869:   max-width: 100%;
                   5870:   height: auto;
                   5871: }
                   5872: 
                   5873: .LC_textsize_mobile {
                   5874:   \@media only screen and (max-device-width: 480px) {
                   5875:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   5876:   }
                   5877: }
                   5878: 
1.440     albertel 5879: .LC_icon {
1.771     droeschl 5880:   border: none;
1.790     droeschl 5881:   vertical-align: middle;
1.771     droeschl 5882: }
                   5883: 
1.543     albertel 5884: .LC_docs_spacer {
                   5885:   width: 25px;
                   5886:   height: 1px;
1.771     droeschl 5887:   border: none;
1.543     albertel 5888: }
1.346     albertel 5889: 
1.532     albertel 5890: .LC_internal_info {
1.735     bisitz   5891:   color: #999999;
1.532     albertel 5892: }
                   5893: 
1.794     www      5894: .LC_discussion {
1.1050    www      5895:   background: $data_table_dark;
1.911     bisitz   5896:   border: 1px solid black;
                   5897:   margin: 2px;
1.794     www      5898: }
                   5899: 
                   5900: .LC_disc_action_left {
1.1050    www      5901:   background: $sidebg;
1.911     bisitz   5902:   text-align: left;
1.1050    www      5903:   padding: 4px;
                   5904:   margin: 2px;
1.794     www      5905: }
                   5906: 
                   5907: .LC_disc_action_right {
1.1050    www      5908:   background: $sidebg;
1.911     bisitz   5909:   text-align: right;
1.1050    www      5910:   padding: 4px;
                   5911:   margin: 2px;
1.794     www      5912: }
                   5913: 
                   5914: .LC_disc_new_item {
1.911     bisitz   5915:   background: white;
                   5916:   border: 2px solid red;
1.1050    www      5917:   margin: 4px;
                   5918:   padding: 4px;
1.794     www      5919: }
                   5920: 
                   5921: .LC_disc_old_item {
1.911     bisitz   5922:   background: white;
1.1050    www      5923:   margin: 4px;
                   5924:   padding: 4px;
1.794     www      5925: }
                   5926: 
1.458     albertel 5927: table.LC_pastsubmission {
                   5928:   border: 1px solid black;
                   5929:   margin: 2px;
                   5930: }
                   5931: 
1.924     bisitz   5932: table#LC_menubuttons {
1.345     albertel 5933:   width: 100%;
                   5934:   background: $pgbg;
1.392     albertel 5935:   border: 2px;
1.402     albertel 5936:   border-collapse: separate;
1.803     bisitz   5937:   padding: 0;
1.345     albertel 5938: }
1.392     albertel 5939: 
1.801     tempelho 5940: table#LC_title_bar a {
                   5941:   color: $fontmenu;
                   5942: }
1.836     bisitz   5943: 
1.807     droeschl 5944: table#LC_title_bar {
1.819     tempelho 5945:   clear: both;
1.836     bisitz   5946:   display: none;
1.807     droeschl 5947: }
                   5948: 
1.795     www      5949: table#LC_title_bar,
1.933     droeschl 5950: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5951: table#LC_title_bar.LC_with_remote {
1.359     albertel 5952:   width: 100%;
1.392     albertel 5953:   border-color: $pgbg;
                   5954:   border-style: solid;
                   5955:   border-width: $border;
1.379     albertel 5956:   background: $pgbg;
1.801     tempelho 5957:   color: $fontmenu;
1.392     albertel 5958:   border-collapse: collapse;
1.803     bisitz   5959:   padding: 0;
1.819     tempelho 5960:   margin: 0;
1.359     albertel 5961: }
1.795     www      5962: 
1.933     droeschl 5963: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5964:     margin: 0;
                   5965:     padding: 0;
1.933     droeschl 5966:     position: relative;
                   5967:     list-style: none;
1.913     droeschl 5968: }
1.933     droeschl 5969: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5970:     display: inline;
                   5971: }
1.933     droeschl 5972: 
                   5973: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5974:     padding: 0;
1.933     droeschl 5975:     margin: 0;
                   5976:     float: left;
1.913     droeschl 5977: }
1.933     droeschl 5978: .LC_breadcrumb_tools_tools {
                   5979:     padding: 0;
                   5980:     margin: 0;
1.913     droeschl 5981:     float: right;
                   5982: }
                   5983: 
1.359     albertel 5984: table#LC_title_bar td {
                   5985:   background: $tabbg;
                   5986: }
1.795     www      5987: 
1.911     bisitz   5988: table#LC_menubuttons img {
1.803     bisitz   5989:   border: none;
1.346     albertel 5990: }
1.795     www      5991: 
1.842     droeschl 5992: .LC_breadcrumbs_component {
1.911     bisitz   5993:   float: right;
                   5994:   margin: 0 1em;
1.357     albertel 5995: }
1.842     droeschl 5996: .LC_breadcrumbs_component img {
1.911     bisitz   5997:   vertical-align: middle;
1.777     tempelho 5998: }
1.795     www      5999: 
1.1075.2.108  raeburn  6000: .LC_breadcrumbs_hoverable {
                   6001:   background: $sidebg;
                   6002: }
                   6003: 
1.383     albertel 6004: td.LC_table_cell_checkbox {
                   6005:   text-align: center;
                   6006: }
1.795     www      6007: 
                   6008: .LC_fontsize_small {
1.911     bisitz   6009:   font-size: 70%;
1.705     tempelho 6010: }
                   6011: 
1.844     bisitz   6012: #LC_breadcrumbs {
1.911     bisitz   6013:   clear:both;
                   6014:   background: $sidebg;
                   6015:   border-bottom: 1px solid $lg_border_color;
                   6016:   line-height: 2.5em;
1.933     droeschl 6017:   overflow: hidden;
1.911     bisitz   6018:   margin: 0;
                   6019:   padding: 0;
1.995     raeburn  6020:   text-align: left;
1.819     tempelho 6021: }
1.862     bisitz   6022: 
1.1075.2.16  raeburn  6023: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6024:   clear:both;
                   6025:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6026:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  6027:   margin: 0 0 10px 0;
1.966     bisitz   6028:   padding: 3px;
1.995     raeburn  6029:   text-align: left;
1.822     bisitz   6030: }
                   6031: 
1.795     www      6032: .LC_fontsize_medium {
1.911     bisitz   6033:   font-size: 85%;
1.705     tempelho 6034: }
                   6035: 
1.795     www      6036: .LC_fontsize_large {
1.911     bisitz   6037:   font-size: 120%;
1.705     tempelho 6038: }
                   6039: 
1.346     albertel 6040: .LC_menubuttons_inline_text {
                   6041:   color: $font;
1.698     harmsja  6042:   font-size: 90%;
1.701     harmsja  6043:   padding-left:3px;
1.346     albertel 6044: }
                   6045: 
1.934     droeschl 6046: .LC_menubuttons_inline_text img{
                   6047:   vertical-align: middle;
                   6048: }
                   6049: 
1.1051    www      6050: li.LC_menubuttons_inline_text img {
1.951     onken    6051:   cursor:pointer;
1.1002    droeschl 6052:   text-decoration: none;
1.951     onken    6053: }
                   6054: 
1.526     www      6055: .LC_menubuttons_link {
                   6056:   text-decoration: none;
                   6057: }
1.795     www      6058: 
1.522     albertel 6059: .LC_menubuttons_category {
1.521     www      6060:   color: $font;
1.526     www      6061:   background: $pgbg;
1.521     www      6062:   font-size: larger;
                   6063:   font-weight: bold;
                   6064: }
                   6065: 
1.346     albertel 6066: td.LC_menubuttons_text {
1.911     bisitz   6067:   color: $font;
1.346     albertel 6068: }
1.706     harmsja  6069: 
1.346     albertel 6070: .LC_current_location {
                   6071:   background: $tabbg;
                   6072: }
1.795     www      6073: 
1.938     bisitz   6074: table.LC_data_table {
1.347     albertel 6075:   border: 1px solid #000000;
1.402     albertel 6076:   border-collapse: separate;
1.426     albertel 6077:   border-spacing: 1px;
1.610     albertel 6078:   background: $pgbg;
1.347     albertel 6079: }
1.795     www      6080: 
1.422     albertel 6081: .LC_data_table_dense {
                   6082:   font-size: small;
                   6083: }
1.795     www      6084: 
1.507     raeburn  6085: table.LC_nested_outer {
                   6086:   border: 1px solid #000000;
1.589     raeburn  6087:   border-collapse: collapse;
1.803     bisitz   6088:   border-spacing: 0;
1.507     raeburn  6089:   width: 100%;
                   6090: }
1.795     www      6091: 
1.879     raeburn  6092: table.LC_innerpickbox,
1.507     raeburn  6093: table.LC_nested {
1.803     bisitz   6094:   border: none;
1.589     raeburn  6095:   border-collapse: collapse;
1.803     bisitz   6096:   border-spacing: 0;
1.507     raeburn  6097:   width: 100%;
                   6098: }
1.795     www      6099: 
1.911     bisitz   6100: table.LC_data_table tr th,
                   6101: table.LC_calendar tr th,
1.879     raeburn  6102: table.LC_prior_tries tr th,
                   6103: table.LC_innerpickbox tr th {
1.349     albertel 6104:   font-weight: bold;
                   6105:   background-color: $data_table_head;
1.801     tempelho 6106:   color:$fontmenu;
1.701     harmsja  6107:   font-size:90%;
1.347     albertel 6108: }
1.795     www      6109: 
1.879     raeburn  6110: table.LC_innerpickbox tr th,
                   6111: table.LC_innerpickbox tr td {
                   6112:   vertical-align: top;
                   6113: }
                   6114: 
1.711     raeburn  6115: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6116:   background-color: #CCCCCC;
1.711     raeburn  6117:   font-weight: bold;
                   6118:   text-align: left;
                   6119: }
1.795     www      6120: 
1.912     bisitz   6121: table.LC_data_table tr.LC_odd_row > td {
                   6122:   background-color: $data_table_light;
                   6123:   padding: 2px;
                   6124:   vertical-align: top;
                   6125: }
                   6126: 
1.809     bisitz   6127: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6128:   background-color: $data_table_light;
1.912     bisitz   6129:   vertical-align: top;
                   6130: }
                   6131: 
                   6132: table.LC_data_table tr.LC_even_row > td {
                   6133:   background-color: $data_table_dark;
1.425     albertel 6134:   padding: 2px;
1.900     bisitz   6135:   vertical-align: top;
1.347     albertel 6136: }
1.795     www      6137: 
1.809     bisitz   6138: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6139:   background-color: $data_table_dark;
1.900     bisitz   6140:   vertical-align: top;
1.347     albertel 6141: }
1.795     www      6142: 
1.425     albertel 6143: table.LC_data_table tr.LC_data_table_highlight td {
                   6144:   background-color: $data_table_darker;
                   6145: }
1.795     www      6146: 
1.639     raeburn  6147: table.LC_data_table tr td.LC_leftcol_header {
                   6148:   background-color: $data_table_head;
                   6149:   font-weight: bold;
                   6150: }
1.795     www      6151: 
1.451     albertel 6152: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6153: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6154:   font-weight: bold;
                   6155:   font-style: italic;
                   6156:   text-align: center;
                   6157:   padding: 8px;
1.347     albertel 6158: }
1.795     www      6159: 
1.1075.2.30  raeburn  6160: table.LC_data_table tr.LC_empty_row td,
                   6161: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6162:   background-color: $sidebg;
                   6163: }
                   6164: 
                   6165: table.LC_nested tr.LC_empty_row td {
                   6166:   background-color: #FFFFFF;
                   6167: }
                   6168: 
1.890     droeschl 6169: table.LC_caption {
                   6170: }
                   6171: 
1.507     raeburn  6172: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6173:   padding: 4ex
                   6174: }
1.795     www      6175: 
1.507     raeburn  6176: table.LC_nested_outer tr th {
                   6177:   font-weight: bold;
1.801     tempelho 6178:   color:$fontmenu;
1.507     raeburn  6179:   background-color: $data_table_head;
1.701     harmsja  6180:   font-size: small;
1.507     raeburn  6181:   border-bottom: 1px solid #000000;
                   6182: }
1.795     www      6183: 
1.507     raeburn  6184: table.LC_nested_outer tr td.LC_subheader {
                   6185:   background-color: $data_table_head;
                   6186:   font-weight: bold;
                   6187:   font-size: small;
                   6188:   border-bottom: 1px solid #000000;
                   6189:   text-align: right;
1.451     albertel 6190: }
1.795     www      6191: 
1.507     raeburn  6192: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6193:   background-color: #CCCCCC;
1.451     albertel 6194:   font-weight: bold;
                   6195:   font-size: small;
1.507     raeburn  6196:   text-align: center;
                   6197: }
1.795     www      6198: 
1.589     raeburn  6199: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6200: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6201:   text-align: left;
1.451     albertel 6202: }
1.795     www      6203: 
1.507     raeburn  6204: table.LC_nested td {
1.735     bisitz   6205:   background-color: #FFFFFF;
1.451     albertel 6206:   font-size: small;
1.507     raeburn  6207: }
1.795     www      6208: 
1.507     raeburn  6209: table.LC_nested_outer tr th.LC_right_item,
                   6210: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6211: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6212: table.LC_nested tr td.LC_right_item {
1.451     albertel 6213:   text-align: right;
                   6214: }
                   6215: 
1.507     raeburn  6216: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6217:   background-color: #EEEEEE;
1.451     albertel 6218: }
                   6219: 
1.473     raeburn  6220: table.LC_createuser {
                   6221: }
                   6222: 
                   6223: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6224:   font-size: small;
1.473     raeburn  6225: }
                   6226: 
                   6227: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6228:   background-color: #CCCCCC;
1.473     raeburn  6229:   font-weight: bold;
                   6230:   text-align: center;
                   6231: }
                   6232: 
1.349     albertel 6233: table.LC_calendar {
                   6234:   border: 1px solid #000000;
                   6235:   border-collapse: collapse;
1.917     raeburn  6236:   width: 98%;
1.349     albertel 6237: }
1.795     www      6238: 
1.349     albertel 6239: table.LC_calendar_pickdate {
                   6240:   font-size: xx-small;
                   6241: }
1.795     www      6242: 
1.349     albertel 6243: table.LC_calendar tr td {
                   6244:   border: 1px solid #000000;
                   6245:   vertical-align: top;
1.917     raeburn  6246:   width: 14%;
1.349     albertel 6247: }
1.795     www      6248: 
1.349     albertel 6249: table.LC_calendar tr td.LC_calendar_day_empty {
                   6250:   background-color: $data_table_dark;
                   6251: }
1.795     www      6252: 
1.779     bisitz   6253: table.LC_calendar tr td.LC_calendar_day_current {
                   6254:   background-color: $data_table_highlight;
1.777     tempelho 6255: }
1.795     www      6256: 
1.938     bisitz   6257: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6258:   background-color: $mail_new;
                   6259: }
1.795     www      6260: 
1.938     bisitz   6261: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6262:   background-color: $mail_new_hover;
                   6263: }
1.795     www      6264: 
1.938     bisitz   6265: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6266:   background-color: $mail_read;
                   6267: }
1.795     www      6268: 
1.938     bisitz   6269: /*
                   6270: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6271:   background-color: $mail_read_hover;
                   6272: }
1.938     bisitz   6273: */
1.795     www      6274: 
1.938     bisitz   6275: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6276:   background-color: $mail_replied;
                   6277: }
1.795     www      6278: 
1.938     bisitz   6279: /*
                   6280: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6281:   background-color: $mail_replied_hover;
                   6282: }
1.938     bisitz   6283: */
1.795     www      6284: 
1.938     bisitz   6285: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6286:   background-color: $mail_other;
                   6287: }
1.795     www      6288: 
1.938     bisitz   6289: /*
                   6290: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6291:   background-color: $mail_other_hover;
                   6292: }
1.938     bisitz   6293: */
1.494     raeburn  6294: 
1.777     tempelho 6295: table.LC_data_table tr > td.LC_browser_file,
                   6296: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6297:   background: #AAEE77;
1.389     albertel 6298: }
1.795     www      6299: 
1.777     tempelho 6300: table.LC_data_table tr > td.LC_browser_file_locked,
                   6301: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6302:   background: #FFAA99;
1.387     albertel 6303: }
1.795     www      6304: 
1.777     tempelho 6305: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6306:   background: #888888;
1.779     bisitz   6307: }
1.795     www      6308: 
1.777     tempelho 6309: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6310: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6311:   background: #F8F866;
1.777     tempelho 6312: }
1.795     www      6313: 
1.696     bisitz   6314: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6315:   background: #E0E8FF;
1.387     albertel 6316: }
1.696     bisitz   6317: 
1.707     bisitz   6318: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6319:   /* background: #77FF77; */
1.707     bisitz   6320: }
1.795     www      6321: 
1.707     bisitz   6322: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6323:   border-right: 8px solid #FFFF77;
1.707     bisitz   6324: }
1.795     www      6325: 
1.707     bisitz   6326: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6327:   border-right: 8px solid #FFAA77;
1.707     bisitz   6328: }
1.795     www      6329: 
1.707     bisitz   6330: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6331:   border-right: 8px solid #FF7777;
1.707     bisitz   6332: }
1.795     www      6333: 
1.707     bisitz   6334: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6335:   border-right: 8px solid #AAFF77;
1.707     bisitz   6336: }
1.795     www      6337: 
1.707     bisitz   6338: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6339:   border-right: 8px solid #11CC55;
1.707     bisitz   6340: }
                   6341: 
1.388     albertel 6342: span.LC_current_location {
1.701     harmsja  6343:   font-size:larger;
1.388     albertel 6344:   background: $pgbg;
                   6345: }
1.387     albertel 6346: 
1.1029    www      6347: span.LC_current_nav_location {
                   6348:   font-weight:bold;
                   6349:   background: $sidebg;
                   6350: }
                   6351: 
1.395     albertel 6352: span.LC_parm_menu_item {
                   6353:   font-size: larger;
                   6354: }
1.795     www      6355: 
1.395     albertel 6356: span.LC_parm_scope_all {
                   6357:   color: red;
                   6358: }
1.795     www      6359: 
1.395     albertel 6360: span.LC_parm_scope_folder {
                   6361:   color: green;
                   6362: }
1.795     www      6363: 
1.395     albertel 6364: span.LC_parm_scope_resource {
                   6365:   color: orange;
                   6366: }
1.795     www      6367: 
1.395     albertel 6368: span.LC_parm_part {
                   6369:   color: blue;
                   6370: }
1.795     www      6371: 
1.911     bisitz   6372: span.LC_parm_folder,
                   6373: span.LC_parm_symb {
1.395     albertel 6374:   font-size: x-small;
                   6375:   font-family: $mono;
                   6376:   color: #AAAAAA;
                   6377: }
                   6378: 
1.977     bisitz   6379: ul.LC_parm_parmlist li {
                   6380:   display: inline-block;
                   6381:   padding: 0.3em 0.8em;
                   6382:   vertical-align: top;
                   6383:   width: 150px;
                   6384:   border-top:1px solid $lg_border_color;
                   6385: }
                   6386: 
1.795     www      6387: td.LC_parm_overview_level_menu,
                   6388: td.LC_parm_overview_map_menu,
                   6389: td.LC_parm_overview_parm_selectors,
                   6390: td.LC_parm_overview_restrictions  {
1.396     albertel 6391:   border: 1px solid black;
                   6392:   border-collapse: collapse;
                   6393: }
1.795     www      6394: 
1.396     albertel 6395: table.LC_parm_overview_restrictions td {
                   6396:   border-width: 1px 4px 1px 4px;
                   6397:   border-style: solid;
                   6398:   border-color: $pgbg;
                   6399:   text-align: center;
                   6400: }
1.795     www      6401: 
1.396     albertel 6402: table.LC_parm_overview_restrictions th {
                   6403:   background: $tabbg;
                   6404:   border-width: 1px 4px 1px 4px;
                   6405:   border-style: solid;
                   6406:   border-color: $pgbg;
                   6407: }
1.795     www      6408: 
1.398     albertel 6409: table#LC_helpmenu {
1.803     bisitz   6410:   border: none;
1.398     albertel 6411:   height: 55px;
1.803     bisitz   6412:   border-spacing: 0;
1.398     albertel 6413: }
                   6414: 
                   6415: table#LC_helpmenu fieldset legend {
                   6416:   font-size: larger;
                   6417: }
1.795     www      6418: 
1.397     albertel 6419: table#LC_helpmenu_links {
                   6420:   width: 100%;
                   6421:   border: 1px solid black;
                   6422:   background: $pgbg;
1.803     bisitz   6423:   padding: 0;
1.397     albertel 6424:   border-spacing: 1px;
                   6425: }
1.795     www      6426: 
1.397     albertel 6427: table#LC_helpmenu_links tr td {
                   6428:   padding: 1px;
                   6429:   background: $tabbg;
1.399     albertel 6430:   text-align: center;
                   6431:   font-weight: bold;
1.397     albertel 6432: }
1.396     albertel 6433: 
1.795     www      6434: table#LC_helpmenu_links a:link,
                   6435: table#LC_helpmenu_links a:visited,
1.397     albertel 6436: table#LC_helpmenu_links a:active {
                   6437:   text-decoration: none;
                   6438:   color: $font;
                   6439: }
1.795     www      6440: 
1.397     albertel 6441: table#LC_helpmenu_links a:hover {
                   6442:   text-decoration: underline;
                   6443:   color: $vlink;
                   6444: }
1.396     albertel 6445: 
1.417     albertel 6446: .LC_chrt_popup_exists {
                   6447:   border: 1px solid #339933;
                   6448:   margin: -1px;
                   6449: }
1.795     www      6450: 
1.417     albertel 6451: .LC_chrt_popup_up {
                   6452:   border: 1px solid yellow;
                   6453:   margin: -1px;
                   6454: }
1.795     www      6455: 
1.417     albertel 6456: .LC_chrt_popup {
                   6457:   border: 1px solid #8888FF;
                   6458:   background: #CCCCFF;
                   6459: }
1.795     www      6460: 
1.421     albertel 6461: table.LC_pick_box {
                   6462:   border-collapse: separate;
                   6463:   background: white;
                   6464:   border: 1px solid black;
                   6465:   border-spacing: 1px;
                   6466: }
1.795     www      6467: 
1.421     albertel 6468: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6469:   background: $sidebg;
1.421     albertel 6470:   font-weight: bold;
1.900     bisitz   6471:   text-align: left;
1.740     bisitz   6472:   vertical-align: top;
1.421     albertel 6473:   width: 184px;
                   6474:   padding: 8px;
                   6475: }
1.795     www      6476: 
1.579     raeburn  6477: table.LC_pick_box td.LC_pick_box_value {
                   6478:   text-align: left;
                   6479:   padding: 8px;
                   6480: }
1.795     www      6481: 
1.579     raeburn  6482: table.LC_pick_box td.LC_pick_box_select {
                   6483:   text-align: left;
                   6484:   padding: 8px;
                   6485: }
1.795     www      6486: 
1.424     albertel 6487: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6488:   padding: 0;
1.421     albertel 6489:   height: 1px;
                   6490:   background: black;
                   6491: }
1.795     www      6492: 
1.421     albertel 6493: table.LC_pick_box td.LC_pick_box_submit {
                   6494:   text-align: right;
                   6495: }
1.795     www      6496: 
1.579     raeburn  6497: table.LC_pick_box td.LC_evenrow_value {
                   6498:   text-align: left;
                   6499:   padding: 8px;
                   6500:   background-color: $data_table_light;
                   6501: }
1.795     www      6502: 
1.579     raeburn  6503: table.LC_pick_box td.LC_oddrow_value {
                   6504:   text-align: left;
                   6505:   padding: 8px;
                   6506:   background-color: $data_table_light;
                   6507: }
1.795     www      6508: 
1.579     raeburn  6509: span.LC_helpform_receipt_cat {
                   6510:   font-weight: bold;
                   6511: }
1.795     www      6512: 
1.424     albertel 6513: table.LC_group_priv_box {
                   6514:   background: white;
                   6515:   border: 1px solid black;
                   6516:   border-spacing: 1px;
                   6517: }
1.795     www      6518: 
1.424     albertel 6519: table.LC_group_priv_box td.LC_pick_box_title {
                   6520:   background: $tabbg;
                   6521:   font-weight: bold;
                   6522:   text-align: right;
                   6523:   width: 184px;
                   6524: }
1.795     www      6525: 
1.424     albertel 6526: table.LC_group_priv_box td.LC_groups_fixed {
                   6527:   background: $data_table_light;
                   6528:   text-align: center;
                   6529: }
1.795     www      6530: 
1.424     albertel 6531: table.LC_group_priv_box td.LC_groups_optional {
                   6532:   background: $data_table_dark;
                   6533:   text-align: center;
                   6534: }
1.795     www      6535: 
1.424     albertel 6536: table.LC_group_priv_box td.LC_groups_functionality {
                   6537:   background: $data_table_darker;
                   6538:   text-align: center;
                   6539:   font-weight: bold;
                   6540: }
1.795     www      6541: 
1.424     albertel 6542: table.LC_group_priv td {
                   6543:   text-align: left;
1.803     bisitz   6544:   padding: 0;
1.424     albertel 6545: }
                   6546: 
                   6547: .LC_navbuttons {
                   6548:   margin: 2ex 0ex 2ex 0ex;
                   6549: }
1.795     www      6550: 
1.423     albertel 6551: .LC_topic_bar {
                   6552:   font-weight: bold;
                   6553:   background: $tabbg;
1.918     wenzelju 6554:   margin: 1em 0em 1em 2em;
1.805     bisitz   6555:   padding: 3px;
1.918     wenzelju 6556:   font-size: 1.2em;
1.423     albertel 6557: }
1.795     www      6558: 
1.423     albertel 6559: .LC_topic_bar span {
1.918     wenzelju 6560:   left: 0.5em;
                   6561:   position: absolute;
1.423     albertel 6562:   vertical-align: middle;
1.918     wenzelju 6563:   font-size: 1.2em;
1.423     albertel 6564: }
1.795     www      6565: 
1.423     albertel 6566: table.LC_course_group_status {
                   6567:   margin: 20px;
                   6568: }
1.795     www      6569: 
1.423     albertel 6570: table.LC_status_selector td {
                   6571:   vertical-align: top;
                   6572:   text-align: center;
1.424     albertel 6573:   padding: 4px;
                   6574: }
1.795     www      6575: 
1.599     albertel 6576: div.LC_feedback_link {
1.616     albertel 6577:   clear: both;
1.829     kalberla 6578:   background: $sidebg;
1.779     bisitz   6579:   width: 100%;
1.829     kalberla 6580:   padding-bottom: 10px;
                   6581:   border: 1px $tabbg solid;
1.833     kalberla 6582:   height: 22px;
                   6583:   line-height: 22px;
                   6584:   padding-top: 5px;
                   6585: }
                   6586: 
                   6587: div.LC_feedback_link img {
                   6588:   height: 22px;
1.867     kalberla 6589:   vertical-align:middle;
1.829     kalberla 6590: }
                   6591: 
1.911     bisitz   6592: div.LC_feedback_link a {
1.829     kalberla 6593:   text-decoration: none;
1.489     raeburn  6594: }
1.795     www      6595: 
1.867     kalberla 6596: div.LC_comblock {
1.911     bisitz   6597:   display:inline;
1.867     kalberla 6598:   color:$font;
                   6599:   font-size:90%;
                   6600: }
                   6601: 
                   6602: div.LC_feedback_link div.LC_comblock {
                   6603:   padding-left:5px;
                   6604: }
                   6605: 
                   6606: div.LC_feedback_link div.LC_comblock a {
                   6607:   color:$font;
                   6608: }
                   6609: 
1.489     raeburn  6610: span.LC_feedback_link {
1.858     bisitz   6611:   /* background: $feedback_link_bg; */
1.599     albertel 6612:   font-size: larger;
                   6613: }
1.795     www      6614: 
1.599     albertel 6615: span.LC_message_link {
1.858     bisitz   6616:   /* background: $feedback_link_bg; */
1.599     albertel 6617:   font-size: larger;
                   6618:   position: absolute;
                   6619:   right: 1em;
1.489     raeburn  6620: }
1.421     albertel 6621: 
1.515     albertel 6622: table.LC_prior_tries {
1.524     albertel 6623:   border: 1px solid #000000;
                   6624:   border-collapse: separate;
                   6625:   border-spacing: 1px;
1.515     albertel 6626: }
1.523     albertel 6627: 
1.515     albertel 6628: table.LC_prior_tries td {
1.524     albertel 6629:   padding: 2px;
1.515     albertel 6630: }
1.523     albertel 6631: 
                   6632: .LC_answer_correct {
1.795     www      6633:   background: lightgreen;
                   6634:   color: darkgreen;
                   6635:   padding: 6px;
1.523     albertel 6636: }
1.795     www      6637: 
1.523     albertel 6638: .LC_answer_charged_try {
1.797     www      6639:   background: #FFAAAA;
1.795     www      6640:   color: darkred;
                   6641:   padding: 6px;
1.523     albertel 6642: }
1.795     www      6643: 
1.779     bisitz   6644: .LC_answer_not_charged_try,
1.523     albertel 6645: .LC_answer_no_grade,
                   6646: .LC_answer_late {
1.795     www      6647:   background: lightyellow;
1.523     albertel 6648:   color: black;
1.795     www      6649:   padding: 6px;
1.523     albertel 6650: }
1.795     www      6651: 
1.523     albertel 6652: .LC_answer_previous {
1.795     www      6653:   background: lightblue;
                   6654:   color: darkblue;
                   6655:   padding: 6px;
1.523     albertel 6656: }
1.795     www      6657: 
1.779     bisitz   6658: .LC_answer_no_message {
1.777     tempelho 6659:   background: #FFFFFF;
                   6660:   color: black;
1.795     www      6661:   padding: 6px;
1.779     bisitz   6662: }
1.795     www      6663: 
1.779     bisitz   6664: .LC_answer_unknown {
                   6665:   background: orange;
                   6666:   color: black;
1.795     www      6667:   padding: 6px;
1.777     tempelho 6668: }
1.795     www      6669: 
1.529     albertel 6670: span.LC_prior_numerical,
                   6671: span.LC_prior_string,
                   6672: span.LC_prior_custom,
                   6673: span.LC_prior_reaction,
                   6674: span.LC_prior_math {
1.925     bisitz   6675:   font-family: $mono;
1.523     albertel 6676:   white-space: pre;
                   6677: }
                   6678: 
1.525     albertel 6679: span.LC_prior_string {
1.925     bisitz   6680:   font-family: $mono;
1.525     albertel 6681:   white-space: pre;
                   6682: }
                   6683: 
1.523     albertel 6684: table.LC_prior_option {
                   6685:   width: 100%;
                   6686:   border-collapse: collapse;
                   6687: }
1.795     www      6688: 
1.911     bisitz   6689: table.LC_prior_rank,
1.795     www      6690: table.LC_prior_match {
1.528     albertel 6691:   border-collapse: collapse;
                   6692: }
1.795     www      6693: 
1.528     albertel 6694: table.LC_prior_option tr td,
                   6695: table.LC_prior_rank tr td,
                   6696: table.LC_prior_match tr td {
1.524     albertel 6697:   border: 1px solid #000000;
1.515     albertel 6698: }
                   6699: 
1.855     bisitz   6700: .LC_nobreak {
1.544     albertel 6701:   white-space: nowrap;
1.519     raeburn  6702: }
                   6703: 
1.576     raeburn  6704: span.LC_cusr_emph {
                   6705:   font-style: italic;
                   6706: }
                   6707: 
1.633     raeburn  6708: span.LC_cusr_subheading {
                   6709:   font-weight: normal;
                   6710:   font-size: 85%;
                   6711: }
                   6712: 
1.861     bisitz   6713: div.LC_docs_entry_move {
1.859     bisitz   6714:   border: 1px solid #BBBBBB;
1.545     albertel 6715:   background: #DDDDDD;
1.861     bisitz   6716:   width: 22px;
1.859     bisitz   6717:   padding: 1px;
                   6718:   margin: 0;
1.545     albertel 6719: }
                   6720: 
1.861     bisitz   6721: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6722: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6723:   font-size: x-small;
                   6724: }
1.795     www      6725: 
1.861     bisitz   6726: .LC_docs_entry_parameter {
                   6727:   white-space: nowrap;
                   6728: }
                   6729: 
1.544     albertel 6730: .LC_docs_copy {
1.545     albertel 6731:   color: #000099;
1.544     albertel 6732: }
1.795     www      6733: 
1.544     albertel 6734: .LC_docs_cut {
1.545     albertel 6735:   color: #550044;
1.544     albertel 6736: }
1.795     www      6737: 
1.544     albertel 6738: .LC_docs_rename {
1.545     albertel 6739:   color: #009900;
1.544     albertel 6740: }
1.795     www      6741: 
1.544     albertel 6742: .LC_docs_remove {
1.545     albertel 6743:   color: #990000;
                   6744: }
                   6745: 
1.547     albertel 6746: .LC_docs_reinit_warn,
                   6747: .LC_docs_ext_edit {
                   6748:   font-size: x-small;
                   6749: }
                   6750: 
1.545     albertel 6751: table.LC_docs_adddocs td,
                   6752: table.LC_docs_adddocs th {
                   6753:   border: 1px solid #BBBBBB;
                   6754:   padding: 4px;
                   6755:   background: #DDDDDD;
1.543     albertel 6756: }
                   6757: 
1.584     albertel 6758: table.LC_sty_begin {
                   6759:   background: #BBFFBB;
                   6760: }
1.795     www      6761: 
1.584     albertel 6762: table.LC_sty_end {
                   6763:   background: #FFBBBB;
                   6764: }
                   6765: 
1.589     raeburn  6766: table.LC_double_column {
1.803     bisitz   6767:   border-width: 0;
1.589     raeburn  6768:   border-collapse: collapse;
                   6769:   width: 100%;
                   6770:   padding: 2px;
                   6771: }
                   6772: 
                   6773: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6774:   top: 2px;
1.589     raeburn  6775:   left: 2px;
                   6776:   width: 47%;
                   6777:   vertical-align: top;
                   6778: }
                   6779: 
                   6780: table.LC_double_column tr td.LC_right_col {
                   6781:   top: 2px;
1.779     bisitz   6782:   right: 2px;
1.589     raeburn  6783:   width: 47%;
                   6784:   vertical-align: top;
                   6785: }
                   6786: 
1.591     raeburn  6787: div.LC_left_float {
                   6788:   float: left;
                   6789:   padding-right: 5%;
1.597     albertel 6790:   padding-bottom: 4px;
1.591     raeburn  6791: }
                   6792: 
                   6793: div.LC_clear_float_header {
1.597     albertel 6794:   padding-bottom: 2px;
1.591     raeburn  6795: }
                   6796: 
                   6797: div.LC_clear_float_footer {
1.597     albertel 6798:   padding-top: 10px;
1.591     raeburn  6799:   clear: both;
                   6800: }
                   6801: 
1.597     albertel 6802: div.LC_grade_show_user {
1.941     bisitz   6803: /*  border-left: 5px solid $sidebg; */
                   6804:   border-top: 5px solid #000000;
                   6805:   margin: 50px 0 0 0;
1.936     bisitz   6806:   padding: 15px 0 5px 10px;
1.597     albertel 6807: }
1.795     www      6808: 
1.936     bisitz   6809: div.LC_grade_show_user_odd_row {
1.941     bisitz   6810: /*  border-left: 5px solid #000000; */
                   6811: }
                   6812: 
                   6813: div.LC_grade_show_user div.LC_Box {
                   6814:   margin-right: 50px;
1.597     albertel 6815: }
                   6816: 
                   6817: div.LC_grade_submissions,
                   6818: div.LC_grade_message_center,
1.936     bisitz   6819: div.LC_grade_info_links {
1.597     albertel 6820:   margin: 5px;
                   6821:   width: 99%;
                   6822:   background: #FFFFFF;
                   6823: }
1.795     www      6824: 
1.597     albertel 6825: div.LC_grade_submissions_header,
1.936     bisitz   6826: div.LC_grade_message_center_header {
1.705     tempelho 6827:   font-weight: bold;
                   6828:   font-size: large;
1.597     albertel 6829: }
1.795     www      6830: 
1.597     albertel 6831: div.LC_grade_submissions_body,
1.936     bisitz   6832: div.LC_grade_message_center_body {
1.597     albertel 6833:   border: 1px solid black;
                   6834:   width: 99%;
                   6835:   background: #FFFFFF;
                   6836: }
1.795     www      6837: 
1.613     albertel 6838: table.LC_scantron_action {
                   6839:   width: 100%;
                   6840: }
1.795     www      6841: 
1.613     albertel 6842: table.LC_scantron_action tr th {
1.698     harmsja  6843:   font-weight:bold;
                   6844:   font-style:normal;
1.613     albertel 6845: }
1.795     www      6846: 
1.779     bisitz   6847: .LC_edit_problem_header,
1.614     albertel 6848: div.LC_edit_problem_footer {
1.705     tempelho 6849:   font-weight: normal;
                   6850:   font-size:  medium;
1.602     albertel 6851:   margin: 2px;
1.1060    bisitz   6852:   background-color: $sidebg;
1.600     albertel 6853: }
1.795     www      6854: 
1.600     albertel 6855: div.LC_edit_problem_header,
1.602     albertel 6856: div.LC_edit_problem_header div,
1.614     albertel 6857: div.LC_edit_problem_footer,
                   6858: div.LC_edit_problem_footer div,
1.602     albertel 6859: div.LC_edit_problem_editxml_header,
                   6860: div.LC_edit_problem_editxml_header div {
1.1075.2.112  raeburn  6861:   z-index: 100;
1.600     albertel 6862: }
1.795     www      6863: 
1.600     albertel 6864: div.LC_edit_problem_header_title {
1.705     tempelho 6865:   font-weight: bold;
                   6866:   font-size: larger;
1.602     albertel 6867:   background: $tabbg;
                   6868:   padding: 3px;
1.1060    bisitz   6869:   margin: 0 0 5px 0;
1.602     albertel 6870: }
1.795     www      6871: 
1.602     albertel 6872: table.LC_edit_problem_header_title {
                   6873:   width: 100%;
1.600     albertel 6874:   background: $tabbg;
1.602     albertel 6875: }
                   6876: 
1.1075.2.112  raeburn  6877: div.LC_edit_actionbar {
                   6878:     background-color: $sidebg;
                   6879:     margin: 0;
                   6880:     padding: 0;
                   6881:     line-height: 200%;
1.602     albertel 6882: }
1.795     www      6883: 
1.1075.2.112  raeburn  6884: div.LC_edit_actionbar div{
                   6885:     padding: 0;
                   6886:     margin: 0;
                   6887:     display: inline-block;
1.600     albertel 6888: }
1.795     www      6889: 
1.1075.2.34  raeburn  6890: .LC_edit_opt {
                   6891:   padding-left: 1em;
                   6892:   white-space: nowrap;
                   6893: }
                   6894: 
1.1075.2.57  raeburn  6895: .LC_edit_problem_latexhelper{
                   6896:     text-align: right;
                   6897: }
                   6898: 
                   6899: #LC_edit_problem_colorful div{
                   6900:     margin-left: 40px;
                   6901: }
                   6902: 
1.1075.2.112  raeburn  6903: #LC_edit_problem_codemirror div{
                   6904:     margin-left: 0px;
                   6905: }
                   6906: 
1.911     bisitz   6907: img.stift {
1.803     bisitz   6908:   border-width: 0;
                   6909:   vertical-align: middle;
1.677     riegler  6910: }
1.680     riegler  6911: 
1.923     bisitz   6912: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6913:   vertical-align: top;
1.777     tempelho 6914: }
1.795     www      6915: 
1.716     raeburn  6916: div.LC_createcourse {
1.911     bisitz   6917:   margin: 10px 10px 10px 10px;
1.716     raeburn  6918: }
                   6919: 
1.917     raeburn  6920: .LC_dccid {
1.1075.2.38  raeburn  6921:   float: right;
1.917     raeburn  6922:   margin: 0.2em 0 0 0;
                   6923:   padding: 0;
                   6924:   font-size: 90%;
                   6925:   display:none;
                   6926: }
                   6927: 
1.897     wenzelju 6928: ol.LC_primary_menu a:hover,
1.721     harmsja  6929: ol#LC_MenuBreadcrumbs a:hover,
                   6930: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6931: ul#LC_secondary_menu a:hover,
1.721     harmsja  6932: .LC_FormSectionClearButton input:hover
1.795     www      6933: ul.LC_TabContent   li:hover a {
1.952     onken    6934:   color:$button_hover;
1.911     bisitz   6935:   text-decoration:none;
1.693     droeschl 6936: }
                   6937: 
1.779     bisitz   6938: h1 {
1.911     bisitz   6939:   padding: 0;
                   6940:   line-height:130%;
1.693     droeschl 6941: }
1.698     harmsja  6942: 
1.911     bisitz   6943: h2,
                   6944: h3,
                   6945: h4,
                   6946: h5,
                   6947: h6 {
                   6948:   margin: 5px 0 5px 0;
                   6949:   padding: 0;
                   6950:   line-height:130%;
1.693     droeschl 6951: }
1.795     www      6952: 
                   6953: .LC_hcell {
1.911     bisitz   6954:   padding:3px 15px 3px 15px;
                   6955:   margin: 0;
                   6956:   background-color:$tabbg;
                   6957:   color:$fontmenu;
                   6958:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6959: }
1.795     www      6960: 
1.840     bisitz   6961: .LC_Box > .LC_hcell {
1.911     bisitz   6962:   margin: 0 -10px 10px -10px;
1.835     bisitz   6963: }
                   6964: 
1.721     harmsja  6965: .LC_noBorder {
1.911     bisitz   6966:   border: 0;
1.698     harmsja  6967: }
1.693     droeschl 6968: 
1.721     harmsja  6969: .LC_FormSectionClearButton input {
1.911     bisitz   6970:   background-color:transparent;
                   6971:   border: none;
                   6972:   cursor:pointer;
                   6973:   text-decoration:underline;
1.693     droeschl 6974: }
1.763     bisitz   6975: 
                   6976: .LC_help_open_topic {
1.911     bisitz   6977:   color: #FFFFFF;
                   6978:   background-color: #EEEEFF;
                   6979:   margin: 1px;
                   6980:   padding: 4px;
                   6981:   border: 1px solid #000033;
                   6982:   white-space: nowrap;
                   6983:   /* vertical-align: middle; */
1.759     neumanie 6984: }
1.693     droeschl 6985: 
1.911     bisitz   6986: dl,
                   6987: ul,
                   6988: div,
                   6989: fieldset {
                   6990:   margin: 10px 10px 10px 0;
                   6991:   /* overflow: hidden; */
1.693     droeschl 6992: }
1.795     www      6993: 
1.1075.2.90  raeburn  6994: article.geogebraweb div {
                   6995:     margin: 0;
                   6996: }
                   6997: 
1.838     bisitz   6998: fieldset > legend {
1.911     bisitz   6999:   font-weight: bold;
                   7000:   padding: 0 5px 0 5px;
1.838     bisitz   7001: }
                   7002: 
1.813     bisitz   7003: #LC_nav_bar {
1.911     bisitz   7004:   float: left;
1.995     raeburn  7005:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7006:   margin: 0 0 2px 0;
1.807     droeschl 7007: }
                   7008: 
1.916     droeschl 7009: #LC_realm {
                   7010:   margin: 0.2em 0 0 0;
                   7011:   padding: 0;
                   7012:   font-weight: bold;
                   7013:   text-align: center;
1.995     raeburn  7014:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7015: }
                   7016: 
1.911     bisitz   7017: #LC_nav_bar em {
                   7018:   font-weight: bold;
                   7019:   font-style: normal;
1.807     droeschl 7020: }
                   7021: 
1.897     wenzelju 7022: ol.LC_primary_menu {
1.934     droeschl 7023:   margin: 0;
1.1075.2.2  raeburn  7024:   padding: 0;
1.807     droeschl 7025: }
                   7026: 
1.852     droeschl 7027: ol#LC_PathBreadcrumbs {
1.911     bisitz   7028:   margin: 0;
1.693     droeschl 7029: }
                   7030: 
1.897     wenzelju 7031: ol.LC_primary_menu li {
1.1075.2.2  raeburn  7032:   color: RGB(80, 80, 80);
                   7033:   vertical-align: middle;
                   7034:   text-align: left;
                   7035:   list-style: none;
1.1075.2.112  raeburn  7036:   position: relative;
1.1075.2.2  raeburn  7037:   float: left;
1.1075.2.112  raeburn  7038:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7039:   line-height: 1.5em;
1.1075.2.2  raeburn  7040: }
                   7041: 
1.1075.2.113  raeburn  7042: ol.LC_primary_menu li a, 
1.1075.2.112  raeburn  7043: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  7044:   display: block;
                   7045:   margin: 0;
                   7046:   padding: 0 5px 0 10px;
                   7047:   text-decoration: none;
                   7048: }
                   7049: 
1.1075.2.112  raeburn  7050: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7051:   display: inline-block;
                   7052:   width: 95%;
                   7053:   text-align: left;
                   7054: }
                   7055: 
                   7056: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7057:   display: inline-block;
                   7058:   width: 5%;
                   7059:   float: right;
                   7060:   text-align: right;
                   7061:   font-size: 70%;
                   7062: }
                   7063: 
                   7064: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  7065:   display: none;
1.1075.2.112  raeburn  7066:   width: 15em;
1.1075.2.2  raeburn  7067:   background-color: $data_table_light;
1.1075.2.112  raeburn  7068:   position: absolute;
                   7069:   top: 100%;
                   7070: }
                   7071: 
                   7072: ol.LC_primary_menu ul ul {
                   7073:   left: 100%;
                   7074:   top: 0;
1.1075.2.2  raeburn  7075: }
                   7076: 
1.1075.2.112  raeburn  7077: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  7078:   display: block;
                   7079:   position: absolute;
                   7080:   margin: 0;
                   7081:   padding: 0;
1.1075.2.5  raeburn  7082:   z-index: 2;
1.1075.2.2  raeburn  7083: }
                   7084: 
                   7085: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112  raeburn  7086: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  7087:   font-size: 90%;
1.911     bisitz   7088:   vertical-align: top;
1.1075.2.2  raeburn  7089:   float: none;
1.1075.2.5  raeburn  7090:   border-left: 1px solid black;
                   7091:   border-right: 1px solid black;
1.1075.2.112  raeburn  7092: /* A dark bottom border to visualize different menu options;
                   7093: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7094:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  7095: }
                   7096: 
1.1075.2.112  raeburn  7097: ol.LC_primary_menu li li p:hover {
                   7098:   color:$button_hover;
                   7099:   text-decoration:none;
                   7100:   background-color:$data_table_dark;
1.1075.2.2  raeburn  7101: }
                   7102: 
                   7103: ol.LC_primary_menu li li a:hover {
                   7104:    color:$button_hover;
                   7105:    background-color:$data_table_dark;
1.693     droeschl 7106: }
                   7107: 
1.1075.2.112  raeburn  7108: /* Font-size equal to the size of the predecessors*/
                   7109: ol.LC_primary_menu li:hover li li {
                   7110:   font-size: 100%;
                   7111: }
                   7112: 
1.897     wenzelju 7113: ol.LC_primary_menu li img {
1.911     bisitz   7114:   vertical-align: bottom;
1.934     droeschl 7115:   height: 1.1em;
1.1075.2.3  raeburn  7116:   margin: 0.2em 0 0 0;
1.693     droeschl 7117: }
                   7118: 
1.897     wenzelju 7119: ol.LC_primary_menu a {
1.911     bisitz   7120:   color: RGB(80, 80, 80);
                   7121:   text-decoration: none;
1.693     droeschl 7122: }
1.795     www      7123: 
1.949     droeschl 7124: ol.LC_primary_menu a.LC_new_message {
                   7125:   font-weight:bold;
                   7126:   color: darkred;
                   7127: }
                   7128: 
1.975     raeburn  7129: ol.LC_docs_parameters {
                   7130:   margin-left: 0;
                   7131:   padding: 0;
                   7132:   list-style: none;
                   7133: }
                   7134: 
                   7135: ol.LC_docs_parameters li {
                   7136:   margin: 0;
                   7137:   padding-right: 20px;
                   7138:   display: inline;
                   7139: }
                   7140: 
1.976     raeburn  7141: ol.LC_docs_parameters li:before {
                   7142:   content: "\\002022 \\0020";
                   7143: }
                   7144: 
                   7145: li.LC_docs_parameters_title {
                   7146:   font-weight: bold;
                   7147: }
                   7148: 
                   7149: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7150:   content: "";
                   7151: }
                   7152: 
1.897     wenzelju 7153: ul#LC_secondary_menu {
1.1075.2.23  raeburn  7154:   clear: right;
1.911     bisitz   7155:   color: $fontmenu;
                   7156:   background: $tabbg;
                   7157:   list-style: none;
                   7158:   padding: 0;
                   7159:   margin: 0;
                   7160:   width: 100%;
1.995     raeburn  7161:   text-align: left;
1.1075.2.4  raeburn  7162:   float: left;
1.808     droeschl 7163: }
                   7164: 
1.897     wenzelju 7165: ul#LC_secondary_menu li {
1.911     bisitz   7166:   font-weight: bold;
                   7167:   line-height: 1.8em;
                   7168:   border-right: 1px solid black;
1.1075.2.4  raeburn  7169:   float: left;
                   7170: }
                   7171: 
                   7172: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7173:   background-color: $data_table_light;
                   7174: }
                   7175: 
                   7176: ul#LC_secondary_menu li a {
                   7177:   padding: 0 0.8em;
                   7178: }
                   7179: 
                   7180: ul#LC_secondary_menu li ul {
                   7181:   display: none;
                   7182: }
                   7183: 
                   7184: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7185:   display: block;
                   7186:   position: absolute;
                   7187:   margin: 0;
                   7188:   padding: 0;
                   7189:   list-style:none;
                   7190:   float: none;
                   7191:   background-color: $data_table_light;
1.1075.2.5  raeburn  7192:   z-index: 2;
1.1075.2.10  raeburn  7193:   margin-left: -1px;
1.1075.2.4  raeburn  7194: }
                   7195: 
                   7196: ul#LC_secondary_menu li ul li {
                   7197:   font-size: 90%;
                   7198:   vertical-align: top;
                   7199:   border-left: 1px solid black;
                   7200:   border-right: 1px solid black;
1.1075.2.33  raeburn  7201:   background-color: $data_table_light;
1.1075.2.4  raeburn  7202:   list-style:none;
                   7203:   float: none;
                   7204: }
                   7205: 
                   7206: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7207:   background-color: $data_table_dark;
1.807     droeschl 7208: }
                   7209: 
1.847     tempelho 7210: ul.LC_TabContent {
1.911     bisitz   7211:   display:block;
                   7212:   background: $sidebg;
                   7213:   border-bottom: solid 1px $lg_border_color;
                   7214:   list-style:none;
1.1020    raeburn  7215:   margin: -1px -10px 0 -10px;
1.911     bisitz   7216:   padding: 0;
1.693     droeschl 7217: }
                   7218: 
1.795     www      7219: ul.LC_TabContent li,
                   7220: ul.LC_TabContentBigger li {
1.911     bisitz   7221:   float:left;
1.741     harmsja  7222: }
1.795     www      7223: 
1.897     wenzelju 7224: ul#LC_secondary_menu li a {
1.911     bisitz   7225:   color: $fontmenu;
                   7226:   text-decoration: none;
1.693     droeschl 7227: }
1.795     www      7228: 
1.721     harmsja  7229: ul.LC_TabContent {
1.952     onken    7230:   min-height:20px;
1.721     harmsja  7231: }
1.795     www      7232: 
                   7233: ul.LC_TabContent li {
1.911     bisitz   7234:   vertical-align:middle;
1.959     onken    7235:   padding: 0 16px 0 10px;
1.911     bisitz   7236:   background-color:$tabbg;
                   7237:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7238:   border-left: solid 1px $font;
1.721     harmsja  7239: }
1.795     www      7240: 
1.847     tempelho 7241: ul.LC_TabContent .right {
1.911     bisitz   7242:   float:right;
1.847     tempelho 7243: }
                   7244: 
1.911     bisitz   7245: ul.LC_TabContent li a,
                   7246: ul.LC_TabContent li {
                   7247:   color:rgb(47,47,47);
                   7248:   text-decoration:none;
                   7249:   font-size:95%;
                   7250:   font-weight:bold;
1.952     onken    7251:   min-height:20px;
                   7252: }
                   7253: 
1.959     onken    7254: ul.LC_TabContent li a:hover,
                   7255: ul.LC_TabContent li a:focus {
1.952     onken    7256:   color: $button_hover;
1.959     onken    7257:   background:none;
                   7258:   outline:none;
1.952     onken    7259: }
                   7260: 
                   7261: ul.LC_TabContent li:hover {
                   7262:   color: $button_hover;
                   7263:   cursor:pointer;
1.721     harmsja  7264: }
1.795     www      7265: 
1.911     bisitz   7266: ul.LC_TabContent li.active {
1.952     onken    7267:   color: $font;
1.911     bisitz   7268:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7269:   border-bottom:solid 1px #FFFFFF;
                   7270:   cursor: default;
1.744     ehlerst  7271: }
1.795     www      7272: 
1.959     onken    7273: ul.LC_TabContent li.active a {
                   7274:   color:$font;
                   7275:   background:#FFFFFF;
                   7276:   outline: none;
                   7277: }
1.1047    raeburn  7278: 
                   7279: ul.LC_TabContent li.goback {
                   7280:   float: left;
                   7281:   border-left: none;
                   7282: }
                   7283: 
1.870     tempelho 7284: #maincoursedoc {
1.911     bisitz   7285:   clear:both;
1.870     tempelho 7286: }
                   7287: 
                   7288: ul.LC_TabContentBigger {
1.911     bisitz   7289:   display:block;
                   7290:   list-style:none;
                   7291:   padding: 0;
1.870     tempelho 7292: }
                   7293: 
1.795     www      7294: ul.LC_TabContentBigger li {
1.911     bisitz   7295:   vertical-align:bottom;
                   7296:   height: 30px;
                   7297:   font-size:110%;
                   7298:   font-weight:bold;
                   7299:   color: #737373;
1.841     tempelho 7300: }
                   7301: 
1.957     onken    7302: ul.LC_TabContentBigger li.active {
                   7303:   position: relative;
                   7304:   top: 1px;
                   7305: }
                   7306: 
1.870     tempelho 7307: ul.LC_TabContentBigger li a {
1.911     bisitz   7308:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7309:   height: 30px;
                   7310:   line-height: 30px;
                   7311:   text-align: center;
                   7312:   display: block;
                   7313:   text-decoration: none;
1.958     onken    7314:   outline: none;  
1.741     harmsja  7315: }
1.795     www      7316: 
1.870     tempelho 7317: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7318:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7319:   color:$font;
1.744     ehlerst  7320: }
1.795     www      7321: 
1.870     tempelho 7322: ul.LC_TabContentBigger li b {
1.911     bisitz   7323:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7324:   display: block;
                   7325:   float: left;
                   7326:   padding: 0 30px;
1.957     onken    7327:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7328: }
                   7329: 
1.956     onken    7330: ul.LC_TabContentBigger li:hover b {
                   7331:   color:$button_hover;
                   7332: }
                   7333: 
1.870     tempelho 7334: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7335:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7336:   color:$font;
1.957     onken    7337:   border: 0;
1.741     harmsja  7338: }
1.693     droeschl 7339: 
1.870     tempelho 7340: 
1.862     bisitz   7341: ul.LC_CourseBreadcrumbs {
                   7342:   background: $sidebg;
1.1020    raeburn  7343:   height: 2em;
1.862     bisitz   7344:   padding-left: 10px;
1.1020    raeburn  7345:   margin: 0;
1.862     bisitz   7346:   list-style-position: inside;
                   7347: }
                   7348: 
1.911     bisitz   7349: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7350: ol#LC_PathBreadcrumbs {
1.911     bisitz   7351:   padding-left: 10px;
                   7352:   margin: 0;
1.933     droeschl 7353:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7354: }
                   7355: 
1.911     bisitz   7356: ol#LC_MenuBreadcrumbs li,
                   7357: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7358: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7359:   display: inline;
1.933     droeschl 7360:   white-space: normal;  
1.693     droeschl 7361: }
                   7362: 
1.823     bisitz   7363: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7364: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7365:   text-decoration: none;
                   7366:   font-size:90%;
1.693     droeschl 7367: }
1.795     www      7368: 
1.969     droeschl 7369: ol#LC_MenuBreadcrumbs h1 {
                   7370:   display: inline;
                   7371:   font-size: 90%;
                   7372:   line-height: 2.5em;
                   7373:   margin: 0;
                   7374:   padding: 0;
                   7375: }
                   7376: 
1.795     www      7377: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7378:   text-decoration:none;
                   7379:   font-size:100%;
                   7380:   font-weight:bold;
1.693     droeschl 7381: }
1.795     www      7382: 
1.840     bisitz   7383: .LC_Box {
1.911     bisitz   7384:   border: solid 1px $lg_border_color;
                   7385:   padding: 0 10px 10px 10px;
1.746     neumanie 7386: }
1.795     www      7387: 
1.1020    raeburn  7388: .LC_DocsBox {
                   7389:   border: solid 1px $lg_border_color;
                   7390:   padding: 0 0 10px 10px;
                   7391: }
                   7392: 
1.795     www      7393: .LC_AboutMe_Image {
1.911     bisitz   7394:   float:left;
                   7395:   margin-right:10px;
1.747     neumanie 7396: }
1.795     www      7397: 
                   7398: .LC_Clear_AboutMe_Image {
1.911     bisitz   7399:   clear:left;
1.747     neumanie 7400: }
1.795     www      7401: 
1.721     harmsja  7402: dl.LC_ListStyleClean dt {
1.911     bisitz   7403:   padding-right: 5px;
                   7404:   display: table-header-group;
1.693     droeschl 7405: }
                   7406: 
1.721     harmsja  7407: dl.LC_ListStyleClean dd {
1.911     bisitz   7408:   display: table-row;
1.693     droeschl 7409: }
                   7410: 
1.721     harmsja  7411: .LC_ListStyleClean,
                   7412: .LC_ListStyleSimple,
                   7413: .LC_ListStyleNormal,
1.795     www      7414: .LC_ListStyleSpecial {
1.911     bisitz   7415:   /* display:block; */
                   7416:   list-style-position: inside;
                   7417:   list-style-type: none;
                   7418:   overflow: hidden;
                   7419:   padding: 0;
1.693     droeschl 7420: }
                   7421: 
1.721     harmsja  7422: .LC_ListStyleSimple li,
                   7423: .LC_ListStyleSimple dd,
                   7424: .LC_ListStyleNormal li,
                   7425: .LC_ListStyleNormal dd,
                   7426: .LC_ListStyleSpecial li,
1.795     www      7427: .LC_ListStyleSpecial dd {
1.911     bisitz   7428:   margin: 0;
                   7429:   padding: 5px 5px 5px 10px;
                   7430:   clear: both;
1.693     droeschl 7431: }
                   7432: 
1.721     harmsja  7433: .LC_ListStyleClean li,
                   7434: .LC_ListStyleClean dd {
1.911     bisitz   7435:   padding-top: 0;
                   7436:   padding-bottom: 0;
1.693     droeschl 7437: }
                   7438: 
1.721     harmsja  7439: .LC_ListStyleSimple dd,
1.795     www      7440: .LC_ListStyleSimple li {
1.911     bisitz   7441:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7442: }
                   7443: 
1.721     harmsja  7444: .LC_ListStyleSpecial li,
                   7445: .LC_ListStyleSpecial dd {
1.911     bisitz   7446:   list-style-type: none;
                   7447:   background-color: RGB(220, 220, 220);
                   7448:   margin-bottom: 4px;
1.693     droeschl 7449: }
                   7450: 
1.721     harmsja  7451: table.LC_SimpleTable {
1.911     bisitz   7452:   margin:5px;
                   7453:   border:solid 1px $lg_border_color;
1.795     www      7454: }
1.693     droeschl 7455: 
1.721     harmsja  7456: table.LC_SimpleTable tr {
1.911     bisitz   7457:   padding: 0;
                   7458:   border:solid 1px $lg_border_color;
1.693     droeschl 7459: }
1.795     www      7460: 
                   7461: table.LC_SimpleTable thead {
1.911     bisitz   7462:   background:rgb(220,220,220);
1.693     droeschl 7463: }
                   7464: 
1.721     harmsja  7465: div.LC_columnSection {
1.911     bisitz   7466:   display: block;
                   7467:   clear: both;
                   7468:   overflow: hidden;
                   7469:   margin: 0;
1.693     droeschl 7470: }
                   7471: 
1.721     harmsja  7472: div.LC_columnSection>* {
1.911     bisitz   7473:   float: left;
                   7474:   margin: 10px 20px 10px 0;
                   7475:   overflow:hidden;
1.693     droeschl 7476: }
1.721     harmsja  7477: 
1.795     www      7478: table em {
1.911     bisitz   7479:   font-weight: bold;
                   7480:   font-style: normal;
1.748     schulted 7481: }
1.795     www      7482: 
1.779     bisitz   7483: table.LC_tableBrowseRes,
1.795     www      7484: table.LC_tableOfContent {
1.911     bisitz   7485:   border:none;
                   7486:   border-spacing: 1px;
                   7487:   padding: 3px;
                   7488:   background-color: #FFFFFF;
                   7489:   font-size: 90%;
1.753     droeschl 7490: }
1.789     droeschl 7491: 
1.911     bisitz   7492: table.LC_tableOfContent {
                   7493:   border-collapse: collapse;
1.789     droeschl 7494: }
                   7495: 
1.771     droeschl 7496: table.LC_tableBrowseRes a,
1.768     schulted 7497: table.LC_tableOfContent a {
1.911     bisitz   7498:   background-color: transparent;
                   7499:   text-decoration: none;
1.753     droeschl 7500: }
                   7501: 
1.795     www      7502: table.LC_tableOfContent img {
1.911     bisitz   7503:   border: none;
                   7504:   height: 1.3em;
                   7505:   vertical-align: text-bottom;
                   7506:   margin-right: 0.3em;
1.753     droeschl 7507: }
1.757     schulted 7508: 
1.795     www      7509: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7510:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7511: }
                   7512: 
1.795     www      7513: a#LC_content_toolbar_everything {
1.911     bisitz   7514:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7515: }
                   7516: 
1.795     www      7517: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7518:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7519: }
                   7520: 
1.795     www      7521: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7522:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7523: }
                   7524: 
1.795     www      7525: a#LC_content_toolbar_changefolder {
1.911     bisitz   7526:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7527: }
                   7528: 
1.795     www      7529: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7530:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7531: }
                   7532: 
1.1043    raeburn  7533: a#LC_content_toolbar_edittoplevel {
                   7534:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7535: }
                   7536: 
1.795     www      7537: ul#LC_toolbar li a:hover {
1.911     bisitz   7538:   background-position: bottom center;
1.757     schulted 7539: }
                   7540: 
1.795     www      7541: ul#LC_toolbar {
1.911     bisitz   7542:   padding: 0;
                   7543:   margin: 2px;
                   7544:   list-style:none;
                   7545:   position:relative;
                   7546:   background-color:white;
1.1075.2.9  raeburn  7547:   overflow: auto;
1.757     schulted 7548: }
                   7549: 
1.795     www      7550: ul#LC_toolbar li {
1.911     bisitz   7551:   border:1px solid white;
                   7552:   padding: 0;
                   7553:   margin: 0;
                   7554:   float: left;
                   7555:   display:inline;
                   7556:   vertical-align:middle;
1.1075.2.9  raeburn  7557:   white-space: nowrap;
1.911     bisitz   7558: }
1.757     schulted 7559: 
1.783     amueller 7560: 
1.795     www      7561: a.LC_toolbarItem {
1.911     bisitz   7562:   display:block;
                   7563:   padding: 0;
                   7564:   margin: 0;
                   7565:   height: 32px;
                   7566:   width: 32px;
                   7567:   color:white;
                   7568:   border: none;
                   7569:   background-repeat:no-repeat;
                   7570:   background-color:transparent;
1.757     schulted 7571: }
                   7572: 
1.915     droeschl 7573: ul.LC_funclist {
                   7574:     margin: 0;
                   7575:     padding: 0.5em 1em 0.5em 0;
                   7576: }
                   7577: 
1.933     droeschl 7578: ul.LC_funclist > li:first-child {
                   7579:     font-weight:bold; 
                   7580:     margin-left:0.8em;
                   7581: }
                   7582: 
1.915     droeschl 7583: ul.LC_funclist + ul.LC_funclist {
                   7584:     /* 
                   7585:        left border as a seperator if we have more than
                   7586:        one list 
                   7587:     */
                   7588:     border-left: 1px solid $sidebg;
                   7589:     /* 
                   7590:        this hides the left border behind the border of the 
                   7591:        outer box if element is wrapped to the next 'line' 
                   7592:     */
                   7593:     margin-left: -1px;
                   7594: }
                   7595: 
1.843     bisitz   7596: ul.LC_funclist li {
1.915     droeschl 7597:   display: inline;
1.782     bisitz   7598:   white-space: nowrap;
1.915     droeschl 7599:   margin: 0 0 0 25px;
                   7600:   line-height: 150%;
1.782     bisitz   7601: }
                   7602: 
1.974     wenzelju 7603: .LC_hidden {
                   7604:   display: none;
                   7605: }
                   7606: 
1.1030    www      7607: .LCmodal-overlay {
                   7608: 		position:fixed;
                   7609: 		top:0;
                   7610: 		right:0;
                   7611: 		bottom:0;
                   7612: 		left:0;
                   7613: 		height:100%;
                   7614: 		width:100%;
                   7615: 		margin:0;
                   7616: 		padding:0;
                   7617: 		background:#999;
                   7618: 		opacity:.75;
                   7619: 		filter: alpha(opacity=75);
                   7620: 		-moz-opacity: 0.75;
                   7621: 		z-index:101;
                   7622: }
                   7623: 
                   7624: * html .LCmodal-overlay {   
                   7625: 		position: absolute;
                   7626: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7627: }
                   7628: 
                   7629: .LCmodal-window {
                   7630: 		position:fixed;
                   7631: 		top:50%;
                   7632: 		left:50%;
                   7633: 		margin:0;
                   7634: 		padding:0;
                   7635: 		z-index:102;
                   7636: 	}
                   7637: 
                   7638: * html .LCmodal-window {
                   7639: 		position:absolute;
                   7640: }
                   7641: 
                   7642: .LCclose-window {
                   7643: 		position:absolute;
                   7644: 		width:32px;
                   7645: 		height:32px;
                   7646: 		right:8px;
                   7647: 		top:8px;
                   7648: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7649: 		text-indent:-99999px;
                   7650: 		overflow:hidden;
                   7651: 		cursor:pointer;
                   7652: }
                   7653: 
1.1075.2.17  raeburn  7654: /*
                   7655:   styles used by TTH when "Default set of options to pass to tth/m
                   7656:   when converting TeX" in course settings has been set
                   7657: 
                   7658:   option passed: -t
                   7659: 
                   7660: */
                   7661: 
                   7662: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7663: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7664: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7665: td div.norm {line-height:normal;}
                   7666: 
                   7667: /*
                   7668:   option passed -y3
                   7669: */
                   7670: 
                   7671: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7672: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7673: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7674: 
1.1075.2.121  raeburn  7675: #LC_minitab_header {
                   7676:   float:left;
                   7677:   width:100%;
                   7678:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   7679:   font-size:93%;
                   7680:   line-height:normal;
                   7681:   margin: 0.5em 0 0.5em 0;
                   7682: }
                   7683: #LC_minitab_header ul {
                   7684:   margin:0;
                   7685:   padding:10px 10px 0;
                   7686:   list-style:none;
                   7687: }
                   7688: #LC_minitab_header li {
                   7689:   float:left;
                   7690:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   7691:   margin:0;
                   7692:   padding:0 0 0 9px;
                   7693: }
                   7694: #LC_minitab_header a {
                   7695:   display:block;
                   7696:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   7697:   padding:5px 15px 4px 6px;
                   7698: }
                   7699: #LC_minitab_header #LC_current_minitab {
                   7700:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   7701: }
                   7702: #LC_minitab_header #LC_current_minitab a {
                   7703:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   7704:   padding-bottom:5px;
                   7705: }
                   7706: 
                   7707: 
1.343     albertel 7708: END
                   7709: }
                   7710: 
1.306     albertel 7711: =pod
                   7712: 
                   7713: =item * &headtag()
                   7714: 
                   7715: Returns a uniform footer for LON-CAPA web pages.
                   7716: 
1.307     albertel 7717: Inputs: $title - optional title for the head
                   7718:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7719:         $args - optional arguments
1.319     albertel 7720:             force_register - if is true call registerurl so the remote is 
                   7721:                              informed
1.415     albertel 7722:             redirect       -> array ref of
                   7723:                                    1- seconds before redirect occurs
                   7724:                                    2- url to redirect to
                   7725:                                    3- whether the side effect should occur
1.315     albertel 7726:                            (side effect of setting 
                   7727:                                $env{'internal.head.redirect'} to the url 
                   7728:                                redirected too)
1.352     albertel 7729:             domain         -> force to color decorate a page for a specific
                   7730:                                domain
                   7731:             function       -> force usage of a specific rolish color scheme
                   7732:             bgcolor        -> override the default page bgcolor
1.460     albertel 7733:             no_auto_mt_title
                   7734:                            -> prevent &mt()ing the title arg
1.464     albertel 7735: 
1.306     albertel 7736: =cut
                   7737: 
                   7738: sub headtag {
1.313     albertel 7739:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7740:     
1.363     albertel 7741:     my $function = $args->{'function'} || &get_users_function();
                   7742:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7743:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  7744:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7745:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7746: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7747: 		   #time(),
1.418     albertel 7748: 		   $env{'environment.color.timestamp'},
1.363     albertel 7749: 		   $function,$domain,$bgcolor);
                   7750: 
1.369     www      7751:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7752: 
1.308     albertel 7753:     my $result =
                   7754: 	'<head>'.
1.1075.2.56  raeburn  7755: 	&font_settings($args);
1.319     albertel 7756: 
1.1075.2.72  raeburn  7757:     my $inhibitprint;
                   7758:     if ($args->{'print_suppress'}) {
                   7759:         $inhibitprint = &print_suppression();
                   7760:     }
1.1064    raeburn  7761: 
1.461     albertel 7762:     if (!$args->{'frameset'}) {
                   7763: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7764:     }
1.1075.2.12  raeburn  7765:     if ($args->{'force_register'}) {
                   7766:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 7767:     }
1.436     albertel 7768:     if (!$args->{'no_nav_bar'} 
                   7769: 	&& !$args->{'only_body'}
                   7770: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  7771: 	$result .= &help_menu_js($httphost);
1.1032    www      7772:         $result.=&modal_window();
1.1038    www      7773:         $result.=&togglebox_script();
1.1034    www      7774:         $result.=&wishlist_window();
1.1041    www      7775:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7776:     } else {
                   7777:         if ($args->{'add_modal'}) {
                   7778:            $result.=&modal_window();
                   7779:         }
                   7780:         if ($args->{'add_wishlist'}) {
                   7781:            $result.=&wishlist_window();
                   7782:         }
1.1038    www      7783:         if ($args->{'add_togglebox'}) {
                   7784:            $result.=&togglebox_script();
                   7785:         }
1.1041    www      7786:         if ($args->{'add_progressbar'}) {
                   7787:            $result.=&LCprogressbarUpdate_script();
                   7788:         }
1.436     albertel 7789:     }
1.314     albertel 7790:     if (ref($args->{'redirect'})) {
1.414     albertel 7791: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7792: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7793: 	if (!$inhibit_continue) {
                   7794: 	    $env{'internal.head.redirect'} = $url;
                   7795: 	}
1.313     albertel 7796: 	$result.=<<ADDMETA
                   7797: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7798: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7799: ADDMETA
1.1075.2.89  raeburn  7800:     } else {
                   7801:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7802:             my $requrl = $env{'request.uri'};
                   7803:             if ($requrl eq '') {
                   7804:                 $requrl = $ENV{'REQUEST_URI'};
                   7805:                 $requrl =~ s/\?.+$//;
                   7806:             }
                   7807:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7808:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7809:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7810:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7811:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7812:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   7813:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7814:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7815:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   7816:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   7817:                             if (($newserver) && ($newserver ne $lonhost)) {
                   7818:                                 my $numsec = 5;
                   7819:                                 my $timeout = $numsec * 1000;
                   7820:                                 my ($newurl,$locknum,%locks,$msg);
                   7821:                                 if ($env{'request.role.adv'}) {
                   7822:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   7823:                                 }
                   7824:                                 my $disable_submit = 0;
                   7825:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   7826:                                     $disable_submit = 1;
                   7827:                                 }
                   7828:                                 if ($locknum) {
                   7829:                                     my @lockinfo = sort(values(%locks));
                   7830:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   7831:                                            join(", ",sort(values(%locks)))."\\n".
                   7832:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   7833:                                 } else {
                   7834:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   7835:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   7836:                                     }
                   7837:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   7838:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   7839:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   7840:                                         $newurl .= '&role='.$env{'request.role'};
                   7841:                                     }
                   7842:                                     if ($env{'request.symb'}) {
                   7843:                                         $newurl .= '&symb='.$env{'request.symb'};
                   7844:                                     } else {
                   7845:                                         $newurl .= '&origurl='.$requrl;
                   7846:                                     }
                   7847:                                 }
1.1075.2.98  raeburn  7848:                                 &js_escape(\$msg);
1.1075.2.89  raeburn  7849:                                 $result.=<<OFFLOAD
                   7850: <meta http-equiv="pragma" content="no-cache" />
                   7851: <script type="text/javascript">
1.1075.2.92  raeburn  7852: // <![CDATA[
1.1075.2.89  raeburn  7853: function LC_Offload_Now() {
                   7854:     var dest = "$newurl";
                   7855:     if (dest != '') {
                   7856:         window.location.href="$newurl";
                   7857:     }
                   7858: }
1.1075.2.92  raeburn  7859: \$(document).ready(function () {
                   7860:     window.alert('$msg');
                   7861:     if ($disable_submit) {
1.1075.2.89  raeburn  7862:         \$(".LC_hwk_submit").prop("disabled", true);
                   7863:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  7864:     }
                   7865:     setTimeout('LC_Offload_Now()', $timeout);
                   7866: });
                   7867: // ]]>
1.1075.2.89  raeburn  7868: </script>
                   7869: OFFLOAD
                   7870:                             }
                   7871:                         }
                   7872:                     }
                   7873:                 }
                   7874:             }
                   7875:         }
1.313     albertel 7876:     }
1.306     albertel 7877:     if (!defined($title)) {
                   7878: 	$title = 'The LearningOnline Network with CAPA';
                   7879:     }
1.460     albertel 7880:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7881:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  7882: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   7883:     if (!$args->{'frameset'}) {
                   7884:         $result .= ' /';
                   7885:     }
                   7886:     $result .= '>'
1.1064    raeburn  7887:         .$inhibitprint
1.414     albertel 7888: 	.$head_extra;
1.1075.2.108  raeburn  7889:     my $clientmobile;
                   7890:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   7891:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   7892:     } else {
                   7893:         $clientmobile = $env{'browser.mobile'};
                   7894:     }
                   7895:     if ($clientmobile) {
1.1075.2.42  raeburn  7896:         $result .= '
                   7897: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   7898: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   7899:     }
1.962     droeschl 7900:     return $result.'</head>';
1.306     albertel 7901: }
                   7902: 
                   7903: =pod
                   7904: 
1.340     albertel 7905: =item * &font_settings()
                   7906: 
                   7907: Returns neccessary <meta> to set the proper encoding
                   7908: 
1.1075.2.56  raeburn  7909: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 7910: 
                   7911: =cut
                   7912: 
                   7913: sub font_settings {
1.1075.2.56  raeburn  7914:     my ($args) = @_;
1.340     albertel 7915:     my $headerstring='';
1.1075.2.56  raeburn  7916:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   7917:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 7918: 	$headerstring.=
1.1075.2.61  raeburn  7919: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   7920:         if (!$args->{'frameset'}) {
                   7921:             $headerstring.= ' /';
                   7922:         }
                   7923:         $headerstring .= '>'."\n";
1.340     albertel 7924:     }
                   7925:     return $headerstring;
                   7926: }
                   7927: 
1.341     albertel 7928: =pod
                   7929: 
1.1064    raeburn  7930: =item * &print_suppression()
                   7931: 
                   7932: In course context returns css which causes the body to be blank when media="print",
                   7933: if printout generation is unavailable for the current resource.
                   7934: 
                   7935: This could be because:
                   7936: 
                   7937: (a) printstartdate is in the future
                   7938: 
                   7939: (b) printenddate is in the past
                   7940: 
                   7941: (c) there is an active exam block with "printout"
                   7942: functionality blocked
                   7943: 
                   7944: Users with pav, pfo or evb privileges are exempt.
                   7945: 
                   7946: Inputs: none
                   7947: 
                   7948: =cut
                   7949: 
                   7950: 
                   7951: sub print_suppression {
                   7952:     my $noprint;
                   7953:     if ($env{'request.course.id'}) {
                   7954:         my $scope = $env{'request.course.id'};
                   7955:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7956:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7957:             return;
                   7958:         }
                   7959:         if ($env{'request.course.sec'} ne '') {
                   7960:             $scope .= "/$env{'request.course.sec'}";
                   7961:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7962:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7963:                 return;
1.1064    raeburn  7964:             }
                   7965:         }
                   7966:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7967:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.73  raeburn  7968:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  7969:         if ($blocked) {
                   7970:             my $checkrole = "cm./$cdom/$cnum";
                   7971:             if ($env{'request.course.sec'} ne '') {
                   7972:                 $checkrole .= "/$env{'request.course.sec'}";
                   7973:             }
                   7974:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7975:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7976:                 $noprint = 1;
                   7977:             }
                   7978:         }
                   7979:         unless ($noprint) {
                   7980:             my $symb = &Apache::lonnet::symbread();
                   7981:             if ($symb ne '') {
                   7982:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7983:                 if (ref($navmap)) {
                   7984:                     my $res = $navmap->getBySymb($symb);
                   7985:                     if (ref($res)) {
                   7986:                         if (!$res->resprintable()) {
                   7987:                             $noprint = 1;
                   7988:                         }
                   7989:                     }
                   7990:                 }
                   7991:             }
                   7992:         }
                   7993:         if ($noprint) {
                   7994:             return <<"ENDSTYLE";
                   7995: <style type="text/css" media="print">
                   7996:     body { display:none }
                   7997: </style>
                   7998: ENDSTYLE
                   7999:         }
                   8000:     }
                   8001:     return;
                   8002: }
                   8003: 
                   8004: =pod
                   8005: 
1.341     albertel 8006: =item * &xml_begin()
                   8007: 
                   8008: Returns the needed doctype and <html>
                   8009: 
                   8010: Inputs: none
                   8011: 
                   8012: =cut
                   8013: 
                   8014: sub xml_begin {
1.1075.2.61  raeburn  8015:     my ($is_frameset) = @_;
1.341     albertel 8016:     my $output='';
                   8017: 
                   8018:     if ($env{'browser.mathml'}) {
                   8019: 	$output='<?xml version="1.0"?>'
                   8020:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8021: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8022:             
                   8023: #	    .'<!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">] >'
                   8024: 	    .'<!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">'
                   8025:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8026: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  8027:     } elsif ($is_frameset) {
                   8028:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8029:                 '<html>'."\n";
1.341     albertel 8030:     } else {
1.1075.2.61  raeburn  8031: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8032:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8033:     }
                   8034:     return $output;
                   8035: }
1.340     albertel 8036: 
                   8037: =pod
                   8038: 
1.306     albertel 8039: =item * &start_page()
                   8040: 
                   8041: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8042: 
1.648     raeburn  8043: Inputs:
                   8044: 
                   8045: =over 4
                   8046: 
                   8047: $title - optional title for the page
                   8048: 
                   8049: $head_extra - optional extra HTML to incude inside the <head>
                   8050: 
                   8051: $args - additional optional args supported are:
                   8052: 
                   8053: =over 8
                   8054: 
                   8055:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8056:                                     arg on
1.814     bisitz   8057:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8058:              add_entries    -> additional attributes to add to the  <body>
                   8059:              domain         -> force to color decorate a page for a 
1.317     albertel 8060:                                     specific domain
1.648     raeburn  8061:              function       -> force usage of a specific rolish color
1.317     albertel 8062:                                     scheme
1.648     raeburn  8063:              redirect       -> see &headtag()
                   8064:              bgcolor        -> override the default page bg color
                   8065:              js_ready       -> return a string ready for being used in 
1.317     albertel 8066:                                     a javascript writeln
1.648     raeburn  8067:              html_encode    -> return a string ready for being used in 
1.320     albertel 8068:                                     a html attribute
1.648     raeburn  8069:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8070:                                     $forcereg arg
1.648     raeburn  8071:              frameset       -> if true will start with a <frameset>
1.330     albertel 8072:                                     rather than <body>
1.648     raeburn  8073:              skip_phases    -> hash ref of 
1.338     albertel 8074:                                     head -> skip the <html><head> generation
                   8075:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  8076:              no_inline_link -> if true and in remote mode, don't show the
                   8077:                                     'Switch To Inline Menu' link
1.648     raeburn  8078:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8079:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8080:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.123! raeburn  8081:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
        !          8082:                                     to lonhtmlcommon::breadcrumbs
1.1075.2.15  raeburn  8083:              group          -> includes the current group, if page is for a
                   8084:                                specific group
1.361     albertel 8085: 
1.648     raeburn  8086: =back
1.460     albertel 8087: 
1.648     raeburn  8088: =back
1.562     albertel 8089: 
1.306     albertel 8090: =cut
                   8091: 
                   8092: sub start_page {
1.309     albertel 8093:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8094:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8095: 
1.315     albertel 8096:     $env{'internal.start_page'}++;
1.1075.2.15  raeburn  8097:     my ($result,@advtools);
1.964     droeschl 8098: 
1.338     albertel 8099:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  8100:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8101:     }
                   8102:     
                   8103:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8104: 	if ($args->{'frameset'}) {
                   8105: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8106: 						$args->{'add_entries'});
                   8107: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8108:         } else {
                   8109:             $result .=
                   8110:                 &bodytag($title, 
                   8111:                          $args->{'function'},       $args->{'add_entries'},
                   8112:                          $args->{'only_body'},      $args->{'domain'},
                   8113:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  8114:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.15  raeburn  8115:                          $args,                     \@advtools);
1.831     bisitz   8116:         }
1.330     albertel 8117:     }
1.338     albertel 8118: 
1.315     albertel 8119:     if ($args->{'js_ready'}) {
1.713     kaisler  8120: 		$result = &js_ready($result);
1.315     albertel 8121:     }
1.320     albertel 8122:     if ($args->{'html_encode'}) {
1.713     kaisler  8123: 		$result = &html_encode($result);
                   8124:     }
                   8125: 
1.813     bisitz   8126:     # Preparation for new and consistent functionlist at top of screen
                   8127:     # if ($args->{'functionlist'}) {
                   8128:     #            $result .= &build_functionlist();
                   8129:     #}
                   8130: 
1.964     droeschl 8131:     # Don't add anything more if only_body wanted or in const space
                   8132:     return $result if    $args->{'only_body'} 
                   8133:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8134: 
                   8135:     #Breadcrumbs
1.758     kaisler  8136:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8137: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8138: 		#if any br links exists, add them to the breadcrumbs
                   8139: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8140: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8141: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8142: 			}
                   8143: 		}
1.1075.2.19  raeburn  8144:                 # if @advtools array contains items add then to the breadcrumbs
                   8145:                 if (@advtools > 0) {
                   8146:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8147:                 }
1.1075.2.123! raeburn  8148:                 my $menulink;
        !          8149:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
        !          8150:                 if (exists($args->{'bread_crumbs_nomenu'})) {
        !          8151:                     $menulink = 0;
        !          8152:                 } else {
        !          8153:                     undef($menulink);
        !          8154:                 }
1.758     kaisler  8155: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8156: 		if(exists($args->{'bread_crumbs_component'})){
1.1075.2.123! raeburn  8157: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.758     kaisler  8158: 		}else{
1.1075.2.123! raeburn  8159: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8160: 		}
1.1075.2.24  raeburn  8161:     } elsif (($env{'environment.remote'} eq 'on') &&
                   8162:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   8163:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   8164:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  8165:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 8166:     }
1.315     albertel 8167:     return $result;
1.306     albertel 8168: }
                   8169: 
                   8170: sub end_page {
1.315     albertel 8171:     my ($args) = @_;
                   8172:     $env{'internal.end_page'}++;
1.330     albertel 8173:     my $result;
1.335     albertel 8174:     if ($args->{'discussion'}) {
                   8175: 	my ($target,$parser);
                   8176: 	if (ref($args->{'discussion'})) {
                   8177: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8178: 				$args->{'discussion'}{'parser'});
                   8179: 	}
                   8180: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8181:     }
1.330     albertel 8182:     if ($args->{'frameset'}) {
                   8183: 	$result .= '</frameset>';
                   8184:     } else {
1.635     raeburn  8185: 	$result .= &endbodytag($args);
1.330     albertel 8186:     }
1.1075.2.6  raeburn  8187:     unless ($args->{'notbody'}) {
                   8188:         $result .= "\n</html>";
                   8189:     }
1.330     albertel 8190: 
1.315     albertel 8191:     if ($args->{'js_ready'}) {
1.317     albertel 8192: 	$result = &js_ready($result);
1.315     albertel 8193:     }
1.335     albertel 8194: 
1.320     albertel 8195:     if ($args->{'html_encode'}) {
                   8196: 	$result = &html_encode($result);
                   8197:     }
1.335     albertel 8198: 
1.315     albertel 8199:     return $result;
                   8200: }
                   8201: 
1.1034    www      8202: sub wishlist_window {
                   8203:     return(<<'ENDWISHLIST');
1.1046    raeburn  8204: <script type="text/javascript">
1.1034    www      8205: // <![CDATA[
                   8206: // <!-- BEGIN LON-CAPA Internal
                   8207: function set_wishlistlink(title, path) {
                   8208:     if (!title) {
                   8209:         title = document.title;
                   8210:         title = title.replace(/^LON-CAPA /,'');
                   8211:     }
1.1075.2.65  raeburn  8212:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  8213:     title = title.replace("'","\\\'");
1.1034    www      8214:     if (!path) {
                   8215:         path = location.pathname;
                   8216:     }
1.1075.2.65  raeburn  8217:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  8218:     path = path.replace("'","\\\'");
1.1034    www      8219:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8220:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8221: }
                   8222: // END LON-CAPA Internal -->
                   8223: // ]]>
                   8224: </script>
                   8225: ENDWISHLIST
                   8226: }
                   8227: 
1.1030    www      8228: sub modal_window {
                   8229:     return(<<'ENDMODAL');
1.1046    raeburn  8230: <script type="text/javascript">
1.1030    www      8231: // <![CDATA[
                   8232: // <!-- BEGIN LON-CAPA Internal
                   8233: var modalWindow = {
                   8234: 	parent:"body",
                   8235: 	windowId:null,
                   8236: 	content:null,
                   8237: 	width:null,
                   8238: 	height:null,
                   8239: 	close:function()
                   8240: 	{
                   8241: 	        $(".LCmodal-window").remove();
                   8242: 	        $(".LCmodal-overlay").remove();
                   8243: 	},
                   8244: 	open:function()
                   8245: 	{
                   8246: 		var modal = "";
                   8247: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8248: 		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;\">";
                   8249: 		modal += this.content;
                   8250: 		modal += "</div>";	
                   8251: 
                   8252: 		$(this.parent).append(modal);
                   8253: 
                   8254: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8255: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8256: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8257: 	}
                   8258: };
1.1075.2.42  raeburn  8259: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8260: 	{
1.1075.2.119  raeburn  8261:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8262: 		modalWindow.windowId = "myModal";
                   8263: 		modalWindow.width = width;
                   8264: 		modalWindow.height = height;
1.1075.2.80  raeburn  8265: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8266: 		modalWindow.open();
1.1075.2.87  raeburn  8267: 	};
1.1030    www      8268: // END LON-CAPA Internal -->
                   8269: // ]]>
                   8270: </script>
                   8271: ENDMODAL
                   8272: }
                   8273: 
                   8274: sub modal_link {
1.1075.2.42  raeburn  8275:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8276:     unless ($width) { $width=480; }
                   8277:     unless ($height) { $height=400; }
1.1031    www      8278:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  8279:     unless ($transparency) { $transparency='true'; }
                   8280: 
1.1074    raeburn  8281:     my $target_attr;
                   8282:     if (defined($target)) {
                   8283:         $target_attr = 'target="'.$target.'"';
                   8284:     }
                   8285:     return <<"ENDLINK";
1.1075.2.42  raeburn  8286: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8287:            $linktext</a>
                   8288: ENDLINK
1.1030    www      8289: }
                   8290: 
1.1032    www      8291: sub modal_adhoc_script {
                   8292:     my ($funcname,$width,$height,$content)=@_;
                   8293:     return (<<ENDADHOC);
1.1046    raeburn  8294: <script type="text/javascript">
1.1032    www      8295: // <![CDATA[
                   8296:         var $funcname = function()
                   8297:         {
                   8298:                 modalWindow.windowId = "myModal";
                   8299:                 modalWindow.width = $width;
                   8300:                 modalWindow.height = $height;
                   8301:                 modalWindow.content = '$content';
                   8302:                 modalWindow.open();
                   8303:         };  
                   8304: // ]]>
                   8305: </script>
                   8306: ENDADHOC
                   8307: }
                   8308: 
1.1041    www      8309: sub modal_adhoc_inner {
                   8310:     my ($funcname,$width,$height,$content)=@_;
                   8311:     my $innerwidth=$width-20;
                   8312:     $content=&js_ready(
1.1042    www      8313:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  8314:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8315:                  $content.
1.1041    www      8316:                  &end_scrollbox().
1.1075.2.42  raeburn  8317:                  &end_page()
1.1041    www      8318:              );
                   8319:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8320: }
                   8321: 
                   8322: sub modal_adhoc_window {
                   8323:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8324:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8325:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8326: }
                   8327: 
                   8328: sub modal_adhoc_launch {
                   8329:     my ($funcname,$width,$height,$content)=@_;
                   8330:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8331: <script type="text/javascript">
                   8332: // <![CDATA[
                   8333: $funcname();
                   8334: // ]]>
                   8335: </script>
                   8336: ENDLAUNCH
                   8337: }
                   8338: 
                   8339: sub modal_adhoc_close {
                   8340:     return (<<ENDCLOSE);
                   8341: <script type="text/javascript">
                   8342: // <![CDATA[
                   8343: modalWindow.close();
                   8344: // ]]>
                   8345: </script>
                   8346: ENDCLOSE
                   8347: }
                   8348: 
1.1038    www      8349: sub togglebox_script {
                   8350:    return(<<ENDTOGGLE);
                   8351: <script type="text/javascript"> 
                   8352: // <![CDATA[
                   8353: function LCtoggleDisplay(id,hidetext,showtext) {
                   8354:    link = document.getElementById(id + "link").childNodes[0];
                   8355:    with (document.getElementById(id).style) {
                   8356:       if (display == "none" ) {
                   8357:           display = "inline";
                   8358:           link.nodeValue = hidetext;
                   8359:         } else {
                   8360:           display = "none";
                   8361:           link.nodeValue = showtext;
                   8362:        }
                   8363:    }
                   8364: }
                   8365: // ]]>
                   8366: </script>
                   8367: ENDTOGGLE
                   8368: }
                   8369: 
1.1039    www      8370: sub start_togglebox {
                   8371:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8372:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8373:     unless ($showtext) { $showtext=&mt('show'); }
                   8374:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8375:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8376:     return &start_data_table().
                   8377:            &start_data_table_header_row().
                   8378:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8379:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8380:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8381:            &end_data_table_header_row().
                   8382:            '<tr id="'.$id.'" style="display:none""><td>';
                   8383: }
                   8384: 
                   8385: sub end_togglebox {
                   8386:     return '</td></tr>'.&end_data_table();
                   8387: }
                   8388: 
1.1041    www      8389: sub LCprogressbar_script {
1.1045    www      8390:    my ($id)=@_;
1.1041    www      8391:    return(<<ENDPROGRESS);
                   8392: <script type="text/javascript">
                   8393: // <![CDATA[
1.1045    www      8394: \$('#progressbar$id').progressbar({
1.1041    www      8395:   value: 0,
                   8396:   change: function(event, ui) {
                   8397:     var newVal = \$(this).progressbar('option', 'value');
                   8398:     \$('.pblabel', this).text(LCprogressTxt);
                   8399:   }
                   8400: });
                   8401: // ]]>
                   8402: </script>
                   8403: ENDPROGRESS
                   8404: }
                   8405: 
                   8406: sub LCprogressbarUpdate_script {
                   8407:    return(<<ENDPROGRESSUPDATE);
                   8408: <style type="text/css">
                   8409: .ui-progressbar { position:relative; }
                   8410: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8411: </style>
                   8412: <script type="text/javascript">
                   8413: // <![CDATA[
1.1045    www      8414: var LCprogressTxt='---';
                   8415: 
                   8416: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8417:    LCprogressTxt=progresstext;
1.1045    www      8418:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8419: }
                   8420: // ]]>
                   8421: </script>
                   8422: ENDPROGRESSUPDATE
                   8423: }
                   8424: 
1.1042    www      8425: my $LClastpercent;
1.1045    www      8426: my $LCidcnt;
                   8427: my $LCcurrentid;
1.1042    www      8428: 
1.1041    www      8429: sub LCprogressbar {
1.1042    www      8430:     my ($r)=(@_);
                   8431:     $LClastpercent=0;
1.1045    www      8432:     $LCidcnt++;
                   8433:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8434:     my $starting=&mt('Starting');
                   8435:     my $content=(<<ENDPROGBAR);
1.1045    www      8436:   <div id="progressbar$LCcurrentid">
1.1041    www      8437:     <span class="pblabel">$starting</span>
                   8438:   </div>
                   8439: ENDPROGBAR
1.1045    www      8440:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8441: }
                   8442: 
                   8443: sub LCprogressbarUpdate {
1.1042    www      8444:     my ($r,$val,$text)=@_;
                   8445:     unless ($val) { 
                   8446:        if ($LClastpercent) {
                   8447:            $val=$LClastpercent;
                   8448:        } else {
                   8449:            $val=0;
                   8450:        }
                   8451:     }
1.1041    www      8452:     if ($val<0) { $val=0; }
                   8453:     if ($val>100) { $val=0; }
1.1042    www      8454:     $LClastpercent=$val;
1.1041    www      8455:     unless ($text) { $text=$val.'%'; }
                   8456:     $text=&js_ready($text);
1.1044    www      8457:     &r_print($r,<<ENDUPDATE);
1.1041    www      8458: <script type="text/javascript">
                   8459: // <![CDATA[
1.1045    www      8460: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8461: // ]]>
                   8462: </script>
                   8463: ENDUPDATE
1.1035    www      8464: }
                   8465: 
1.1042    www      8466: sub LCprogressbarClose {
                   8467:     my ($r)=@_;
                   8468:     $LClastpercent=0;
1.1044    www      8469:     &r_print($r,<<ENDCLOSE);
1.1042    www      8470: <script type="text/javascript">
                   8471: // <![CDATA[
1.1045    www      8472: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8473: // ]]>
                   8474: </script>
                   8475: ENDCLOSE
1.1044    www      8476: }
                   8477: 
                   8478: sub r_print {
                   8479:     my ($r,$to_print)=@_;
                   8480:     if ($r) {
                   8481:       $r->print($to_print);
                   8482:       $r->rflush();
                   8483:     } else {
                   8484:       print($to_print);
                   8485:     }
1.1042    www      8486: }
                   8487: 
1.320     albertel 8488: sub html_encode {
                   8489:     my ($result) = @_;
                   8490: 
1.322     albertel 8491:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8492:     
                   8493:     return $result;
                   8494: }
1.1044    www      8495: 
1.317     albertel 8496: sub js_ready {
                   8497:     my ($result) = @_;
                   8498: 
1.323     albertel 8499:     $result =~ s/[\n\r]/ /xmsg;
                   8500:     $result =~ s/\\/\\\\/xmsg;
                   8501:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8502:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8503:     
                   8504:     return $result;
                   8505: }
                   8506: 
1.315     albertel 8507: sub validate_page {
                   8508:     if (  exists($env{'internal.start_page'})
1.316     albertel 8509: 	  &&     $env{'internal.start_page'} > 1) {
                   8510: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8511: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8512: 				 $ENV{'request.filename'});
1.315     albertel 8513:     }
                   8514:     if (  exists($env{'internal.end_page'})
1.316     albertel 8515: 	  &&     $env{'internal.end_page'} > 1) {
                   8516: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8517: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8518: 				 $env{'request.filename'});
1.315     albertel 8519:     }
                   8520:     if (     exists($env{'internal.start_page'})
                   8521: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8522: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8523: 				 $env{'request.filename'});
1.315     albertel 8524:     }
                   8525:     if (   ! exists($env{'internal.start_page'})
                   8526: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8527: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8528: 				 $env{'request.filename'});
1.315     albertel 8529:     }
1.306     albertel 8530: }
1.315     albertel 8531: 
1.996     www      8532: 
                   8533: sub start_scrollbox {
1.1075.2.56  raeburn  8534:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8535:     unless ($outerwidth) { $outerwidth='520px'; }
                   8536:     unless ($width) { $width='500px'; }
                   8537:     unless ($height) { $height='200px'; }
1.1075    raeburn  8538:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8539:     if ($id ne '') {
1.1075.2.42  raeburn  8540:         $table_id = ' id="table_'.$id.'"';
                   8541:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8542:     }
1.1075    raeburn  8543:     if ($bgcolor ne '') {
                   8544:         $tdcol = "background-color: $bgcolor;";
                   8545:     }
1.1075.2.42  raeburn  8546:     my $nicescroll_js;
                   8547:     if ($env{'browser.mobile'}) {
                   8548:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8549:     }
1.1075    raeburn  8550:     return <<"END";
1.1075.2.42  raeburn  8551: $nicescroll_js
                   8552: 
                   8553: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  8554: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  8555: END
1.996     www      8556: }
                   8557: 
                   8558: sub end_scrollbox {
1.1036    www      8559:     return '</div></td></tr></table>';
1.996     www      8560: }
                   8561: 
1.1075.2.42  raeburn  8562: sub nicescroll_javascript {
                   8563:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8564:     my %options;
                   8565:     if (ref($cursor) eq 'HASH') {
                   8566:         %options = %{$cursor};
                   8567:     }
                   8568:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8569:         $options{'railalign'} = 'left';
                   8570:     }
                   8571:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8572:         my $function  = &get_users_function();
                   8573:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   8574:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8575:             $options{'cursorcolor'} = '#00F';
                   8576:         }
                   8577:     }
                   8578:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8579:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   8580:             $options{'cursoropacity'}='1.0';
                   8581:         }
                   8582:     } else {
                   8583:         $options{'cursoropacity'}='1.0';
                   8584:     }
                   8585:     if ($options{'cursorfixedheight'} eq 'none') {
                   8586:         delete($options{'cursorfixedheight'});
                   8587:     } else {
                   8588:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8589:     }
                   8590:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8591:         delete($options{'railoffset'});
                   8592:     }
                   8593:     my @niceoptions;
                   8594:     while (my($key,$value) = each(%options)) {
                   8595:         if ($value =~ /^\{.+\}$/) {
                   8596:             push(@niceoptions,$key.':'.$value);
                   8597:         } else {
                   8598:             push(@niceoptions,$key.':"'.$value.'"');
                   8599:         }
                   8600:     }
                   8601:     my $nicescroll_js = '
                   8602: $(document).ready(
                   8603:       function() {
                   8604:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8605:       }
                   8606: );
                   8607: ';
                   8608:     if ($framecheck) {
                   8609:         $nicescroll_js .= '
                   8610: function expand_div(caller) {
                   8611:     if (top === self) {
                   8612:         document.getElementById("'.$id.'").style.width = "auto";
                   8613:         document.getElementById("'.$id.'").style.height = "auto";
                   8614:     } else {
                   8615:         try {
                   8616:             if (parent.frames) {
                   8617:                 if (parent.frames.length > 1) {
                   8618:                     var framesrc = parent.frames[1].location.href;
                   8619:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8620:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8621:                         document.getElementById("'.$id.'").style.width = "auto";
                   8622:                         document.getElementById("'.$id.'").style.height = "auto";
                   8623:                     }
                   8624:                 }
                   8625:             }
                   8626:         } catch (e) {
                   8627:             return;
                   8628:         }
                   8629:     }
                   8630:     return;
                   8631: }
                   8632: ';
                   8633:     }
                   8634:     if ($needjsready) {
                   8635:         $nicescroll_js = '
                   8636: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8637:     } else {
                   8638:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8639:     }
                   8640:     return $nicescroll_js;
                   8641: }
                   8642: 
1.318     albertel 8643: sub simple_error_page {
1.1075.2.49  raeburn  8644:     my ($r,$title,$msg,$args) = @_;
                   8645:     if (ref($args) eq 'HASH') {
                   8646:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8647:     } else {
                   8648:         $msg = &mt($msg);
                   8649:     }
                   8650: 
1.318     albertel 8651:     my $page =
                   8652: 	&Apache::loncommon::start_page($title).
1.1075.2.49  raeburn  8653: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8654: 	&Apache::loncommon::end_page();
                   8655:     if (ref($r)) {
                   8656: 	$r->print($page);
1.327     albertel 8657: 	return;
1.318     albertel 8658:     }
                   8659:     return $page;
                   8660: }
1.347     albertel 8661: 
                   8662: {
1.610     albertel 8663:     my @row_count;
1.961     onken    8664: 
                   8665:     sub start_data_table_count {
                   8666:         unshift(@row_count, 0);
                   8667:         return;
                   8668:     }
                   8669: 
                   8670:     sub end_data_table_count {
                   8671:         shift(@row_count);
                   8672:         return;
                   8673:     }
                   8674: 
1.347     albertel 8675:     sub start_data_table {
1.1018    raeburn  8676: 	my ($add_class,$id) = @_;
1.422     albertel 8677: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8678:         my $table_id;
                   8679:         if (defined($id)) {
                   8680:             $table_id = ' id="'.$id.'"';
                   8681:         }
1.961     onken    8682: 	&start_data_table_count();
1.1018    raeburn  8683: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8684:     }
                   8685: 
                   8686:     sub end_data_table {
1.961     onken    8687: 	&end_data_table_count();
1.389     albertel 8688: 	return '</table>'."\n";;
1.347     albertel 8689:     }
                   8690: 
                   8691:     sub start_data_table_row {
1.974     wenzelju 8692: 	my ($add_class, $id) = @_;
1.610     albertel 8693: 	$row_count[0]++;
                   8694: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8695: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8696:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8697:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8698:     }
1.471     banghart 8699:     
                   8700:     sub continue_data_table_row {
1.974     wenzelju 8701: 	my ($add_class, $id) = @_;
1.610     albertel 8702: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8703: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8704:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8705:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8706:     }
1.347     albertel 8707: 
                   8708:     sub end_data_table_row {
1.389     albertel 8709: 	return '</tr>'."\n";;
1.347     albertel 8710:     }
1.367     www      8711: 
1.421     albertel 8712:     sub start_data_table_empty_row {
1.707     bisitz   8713: #	$row_count[0]++;
1.421     albertel 8714: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8715:     }
                   8716: 
                   8717:     sub end_data_table_empty_row {
                   8718: 	return '</tr>'."\n";;
                   8719:     }
                   8720: 
1.367     www      8721:     sub start_data_table_header_row {
1.389     albertel 8722: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8723:     }
                   8724: 
                   8725:     sub end_data_table_header_row {
1.389     albertel 8726: 	return '</tr>'."\n";;
1.367     www      8727:     }
1.890     droeschl 8728: 
                   8729:     sub data_table_caption {
                   8730:         my $caption = shift;
                   8731:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8732:     }
1.347     albertel 8733: }
                   8734: 
1.548     albertel 8735: =pod
                   8736: 
                   8737: =item * &inhibit_menu_check($arg)
                   8738: 
                   8739: Checks for a inhibitmenu state and generates output to preserve it
                   8740: 
                   8741: Inputs:         $arg - can be any of
                   8742:                      - undef - in which case the return value is a string 
                   8743:                                to add  into arguments list of a uri
                   8744:                      - 'input' - in which case the return value is a HTML
                   8745:                                  <form> <input> field of type hidden to
                   8746:                                  preserve the value
                   8747:                      - a url - in which case the return value is the url with
                   8748:                                the neccesary cgi args added to preserve the
                   8749:                                inhibitmenu state
                   8750:                      - a ref to a url - no return value, but the string is
                   8751:                                         updated to include the neccessary cgi
                   8752:                                         args to preserve the inhibitmenu state
                   8753: 
                   8754: =cut
                   8755: 
                   8756: sub inhibit_menu_check {
                   8757:     my ($arg) = @_;
                   8758:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8759:     if ($arg eq 'input') {
                   8760: 	if ($env{'form.inhibitmenu'}) {
                   8761: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8762: 	} else {
                   8763: 	    return
                   8764: 	}
                   8765:     }
                   8766:     if ($env{'form.inhibitmenu'}) {
                   8767: 	if (ref($arg)) {
                   8768: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8769: 	} elsif ($arg eq '') {
                   8770: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8771: 	} else {
                   8772: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8773: 	}
                   8774:     }
                   8775:     if (!ref($arg)) {
                   8776: 	return $arg;
                   8777:     }
                   8778: }
                   8779: 
1.251     albertel 8780: ###############################################
1.182     matthew  8781: 
                   8782: =pod
                   8783: 
1.549     albertel 8784: =back
                   8785: 
                   8786: =head1 User Information Routines
                   8787: 
                   8788: =over 4
                   8789: 
1.405     albertel 8790: =item * &get_users_function()
1.182     matthew  8791: 
                   8792: Used by &bodytag to determine the current users primary role.
                   8793: Returns either 'student','coordinator','admin', or 'author'.
                   8794: 
                   8795: =cut
                   8796: 
                   8797: ###############################################
                   8798: sub get_users_function {
1.815     tempelho 8799:     my $function = 'norole';
1.818     tempelho 8800:     if ($env{'request.role'}=~/^(st)/) {
                   8801:         $function='student';
                   8802:     }
1.907     raeburn  8803:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8804:         $function='coordinator';
                   8805:     }
1.258     albertel 8806:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8807:         $function='admin';
                   8808:     }
1.826     bisitz   8809:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8810:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8811:         $function='author';
                   8812:     }
                   8813:     return $function;
1.54      www      8814: }
1.99      www      8815: 
                   8816: ###############################################
                   8817: 
1.233     raeburn  8818: =pod
                   8819: 
1.821     raeburn  8820: =item * &show_course()
                   8821: 
                   8822: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8823: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8824: 
                   8825: Inputs:
                   8826: None
                   8827: 
                   8828: Outputs:
                   8829: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8830: 
                   8831: =cut
                   8832: 
                   8833: ###############################################
                   8834: sub show_course {
                   8835:     my $course = !$env{'user.adv'};
                   8836:     if (!$env{'user.adv'}) {
                   8837:         foreach my $env (keys(%env)) {
                   8838:             next if ($env !~ m/^user\.priv\./);
                   8839:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8840:                 $course = 0;
                   8841:                 last;
                   8842:             }
                   8843:         }
                   8844:     }
                   8845:     return $course;
                   8846: }
                   8847: 
                   8848: ###############################################
                   8849: 
                   8850: =pod
                   8851: 
1.542     raeburn  8852: =item * &check_user_status()
1.274     raeburn  8853: 
                   8854: Determines current status of supplied role for a
                   8855: specific user. Roles can be active, previous or future.
                   8856: 
                   8857: Inputs: 
                   8858: user's domain, user's username, course's domain,
1.375     raeburn  8859: course's number, optional section ID.
1.274     raeburn  8860: 
                   8861: Outputs:
                   8862: role status: active, previous or future. 
                   8863: 
                   8864: =cut
                   8865: 
                   8866: sub check_user_status {
1.412     raeburn  8867:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8868:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  8869:     my @uroles = keys(%userinfo);
1.274     raeburn  8870:     my $srchstr;
                   8871:     my $active_chk = 'none';
1.412     raeburn  8872:     my $now = time;
1.274     raeburn  8873:     if (@uroles > 0) {
1.908     raeburn  8874:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8875:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8876:         } else {
1.412     raeburn  8877:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8878:         }
                   8879:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8880:             my $role_end = 0;
                   8881:             my $role_start = 0;
                   8882:             $active_chk = 'active';
1.412     raeburn  8883:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8884:                 $role_end = $1;
                   8885:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8886:                     $role_start = $1;
1.274     raeburn  8887:                 }
                   8888:             }
                   8889:             if ($role_start > 0) {
1.412     raeburn  8890:                 if ($now < $role_start) {
1.274     raeburn  8891:                     $active_chk = 'future';
                   8892:                 }
                   8893:             }
                   8894:             if ($role_end > 0) {
1.412     raeburn  8895:                 if ($now > $role_end) {
1.274     raeburn  8896:                     $active_chk = 'previous';
                   8897:                 }
                   8898:             }
                   8899:         }
                   8900:     }
                   8901:     return $active_chk;
                   8902: }
                   8903: 
                   8904: ###############################################
                   8905: 
                   8906: =pod
                   8907: 
1.405     albertel 8908: =item * &get_sections()
1.233     raeburn  8909: 
                   8910: Determines all the sections for a course including
                   8911: sections with students and sections containing other roles.
1.419     raeburn  8912: Incoming parameters: 
                   8913: 
                   8914: 1. domain
                   8915: 2. course number 
                   8916: 3. reference to array containing roles for which sections should 
                   8917: be gathered (optional).
                   8918: 4. reference to array containing status types for which sections 
                   8919: should be gathered (optional).
                   8920: 
                   8921: If the third argument is undefined, sections are gathered for any role. 
                   8922: If the fourth argument is undefined, sections are gathered for any status.
                   8923: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8924:  
1.374     raeburn  8925: Returns section hash (keys are section IDs, values are
                   8926: number of users in each section), subject to the
1.419     raeburn  8927: optional roles filter, optional status filter 
1.233     raeburn  8928: 
                   8929: =cut
                   8930: 
                   8931: ###############################################
                   8932: sub get_sections {
1.419     raeburn  8933:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8934:     if (!defined($cdom) || !defined($cnum)) {
                   8935:         my $cid =  $env{'request.course.id'};
                   8936: 
                   8937: 	return if (!defined($cid));
                   8938: 
                   8939:         $cdom = $env{'course.'.$cid.'.domain'};
                   8940:         $cnum = $env{'course.'.$cid.'.num'};
                   8941:     }
                   8942: 
                   8943:     my %sectioncount;
1.419     raeburn  8944:     my $now = time;
1.240     albertel 8945: 
1.1075.2.33  raeburn  8946:     my $check_students = 1;
                   8947:     my $only_students = 0;
                   8948:     if (ref($possible_roles) eq 'ARRAY') {
                   8949:         if (grep(/^st$/,@{$possible_roles})) {
                   8950:             if (@{$possible_roles} == 1) {
                   8951:                 $only_students = 1;
                   8952:             }
                   8953:         } else {
                   8954:             $check_students = 0;
                   8955:         }
                   8956:     }
                   8957: 
                   8958:     if ($check_students) {
1.276     albertel 8959: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8960: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8961: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8962:         my $start_index = &Apache::loncoursedata::CL_START();
                   8963:         my $end_index = &Apache::loncoursedata::CL_END();
                   8964:         my $status;
1.366     albertel 8965: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8966: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8967: 				                     $data->[$status_index],
                   8968:                                                      $data->[$start_index],
                   8969:                                                      $data->[$end_index]);
                   8970:             if ($stu_status eq 'Active') {
                   8971:                 $status = 'active';
                   8972:             } elsif ($end < $now) {
                   8973:                 $status = 'previous';
                   8974:             } elsif ($start > $now) {
                   8975:                 $status = 'future';
                   8976:             } 
                   8977: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8978:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8979:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8980: 		    $sectioncount{$section}++;
                   8981:                 }
1.240     albertel 8982: 	    }
                   8983: 	}
                   8984:     }
1.1075.2.33  raeburn  8985:     if ($only_students) {
                   8986:         return %sectioncount;
                   8987:     }
1.240     albertel 8988:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8989:     foreach my $user (sort(keys(%courseroles))) {
                   8990: 	if ($user !~ /^(\w{2})/) { next; }
                   8991: 	my ($role) = ($user =~ /^(\w{2})/);
                   8992: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  8993: 	my ($section,$status);
1.240     albertel 8994: 	if ($role eq 'cr' &&
                   8995: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   8996: 	    $section=$1;
                   8997: 	}
                   8998: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   8999: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9000:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9001:         if ($end == -1 && $start == -1) {
                   9002:             next; #deleted role
                   9003:         }
                   9004:         if (!defined($possible_status)) { 
                   9005:             $sectioncount{$section}++;
                   9006:         } else {
                   9007:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9008:                 $status = 'active';
                   9009:             } elsif ($end < $now) {
                   9010:                 $status = 'future';
                   9011:             } elsif ($start > $now) {
                   9012:                 $status = 'previous';
                   9013:             }
                   9014:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9015:                 $sectioncount{$section}++;
                   9016:             }
                   9017:         }
1.233     raeburn  9018:     }
1.366     albertel 9019:     return %sectioncount;
1.233     raeburn  9020: }
                   9021: 
1.274     raeburn  9022: ###############################################
1.294     raeburn  9023: 
                   9024: =pod
1.405     albertel 9025: 
                   9026: =item * &get_course_users()
                   9027: 
1.275     raeburn  9028: Retrieves usernames:domains for users in the specified course
                   9029: with specific role(s), and access status. 
                   9030: 
                   9031: Incoming parameters:
1.277     albertel 9032: 1. course domain
                   9033: 2. course number
                   9034: 3. access status: users must have - either active, 
1.275     raeburn  9035: previous, future, or all.
1.277     albertel 9036: 4. reference to array of permissible roles
1.288     raeburn  9037: 5. reference to array of section restrictions (optional)
                   9038: 6. reference to results object (hash of hashes).
                   9039: 7. reference to optional userdata hash
1.609     raeburn  9040: 8. reference to optional statushash
1.630     raeburn  9041: 9. flag if privileged users (except those set to unhide in
                   9042:    course settings) should be excluded    
1.609     raeburn  9043: Keys of top level results hash are roles.
1.275     raeburn  9044: Keys of inner hashes are username:domain, with 
                   9045: values set to access type.
1.288     raeburn  9046: Optional userdata hash returns an array with arguments in the 
                   9047: same order as loncoursedata::get_classlist() for student data.
                   9048: 
1.609     raeburn  9049: Optional statushash returns
                   9050: 
1.288     raeburn  9051: Entries for end, start, section and status are blank because
                   9052: of the possibility of multiple values for non-student roles.
                   9053: 
1.275     raeburn  9054: =cut
1.405     albertel 9055: 
1.275     raeburn  9056: ###############################################
1.405     albertel 9057: 
1.275     raeburn  9058: sub get_course_users {
1.630     raeburn  9059:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9060:     my %idx = ();
1.419     raeburn  9061:     my %seclists;
1.288     raeburn  9062: 
                   9063:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9064:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9065:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9066:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9067:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9068:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9069:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9070:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9071: 
1.290     albertel 9072:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9073:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9074:         my $now = time;
1.277     albertel 9075:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9076:             my $match = 0;
1.412     raeburn  9077:             my $secmatch = 0;
1.419     raeburn  9078:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9079:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9080:             if ($section eq '') {
                   9081:                 $section = 'none';
                   9082:             }
1.291     albertel 9083:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9084:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9085:                     $secmatch = 1;
                   9086:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9087:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9088:                         $secmatch = 1;
                   9089:                     }
                   9090:                 } else {  
1.419     raeburn  9091: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9092: 		        $secmatch = 1;
                   9093:                     }
1.290     albertel 9094: 		}
1.412     raeburn  9095:                 if (!$secmatch) {
                   9096:                     next;
                   9097:                 }
1.419     raeburn  9098:             }
1.275     raeburn  9099:             if (defined($$types{'active'})) {
1.288     raeburn  9100:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9101:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9102:                     $match = 1;
1.275     raeburn  9103:                 }
                   9104:             }
                   9105:             if (defined($$types{'previous'})) {
1.609     raeburn  9106:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9107:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9108:                     $match = 1;
1.275     raeburn  9109:                 }
                   9110:             }
                   9111:             if (defined($$types{'future'})) {
1.609     raeburn  9112:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9113:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9114:                     $match = 1;
1.275     raeburn  9115:                 }
                   9116:             }
1.609     raeburn  9117:             if ($match) {
                   9118:                 push(@{$seclists{$student}},$section);
                   9119:                 if (ref($userdata) eq 'HASH') {
                   9120:                     $$userdata{$student} = $$classlist{$student};
                   9121:                 }
                   9122:                 if (ref($statushash) eq 'HASH') {
                   9123:                     $statushash->{$student}{'st'}{$section} = $status;
                   9124:                 }
1.288     raeburn  9125:             }
1.275     raeburn  9126:         }
                   9127:     }
1.412     raeburn  9128:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9129:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9130:         my $now = time;
1.609     raeburn  9131:         my %displaystatus = ( previous => 'Expired',
                   9132:                               active   => 'Active',
                   9133:                               future   => 'Future',
                   9134:                             );
1.1075.2.36  raeburn  9135:         my (%nothide,@possdoms);
1.630     raeburn  9136:         if ($hidepriv) {
                   9137:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9138:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9139:                 if ($user !~ /:/) {
                   9140:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9141:                 } else {
                   9142:                     $nothide{$user} = 1;
                   9143:                 }
                   9144:             }
1.1075.2.36  raeburn  9145:             my @possdoms = ($cdom);
                   9146:             if ($coursehash{'checkforpriv'}) {
                   9147:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9148:             }
1.630     raeburn  9149:         }
1.439     raeburn  9150:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9151:             my $match = 0;
1.412     raeburn  9152:             my $secmatch = 0;
1.439     raeburn  9153:             my $status;
1.412     raeburn  9154:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9155:             $user =~ s/:$//;
1.439     raeburn  9156:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9157:             if ($end == -1 || $start == -1) {
                   9158:                 next;
                   9159:             }
                   9160:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9161:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9162:                 my ($uname,$udom) = split(/:/,$user);
                   9163:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9164:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9165:                         $secmatch = 1;
                   9166:                     } elsif ($usec eq '') {
1.420     albertel 9167:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9168:                             $secmatch = 1;
                   9169:                         }
                   9170:                     } else {
                   9171:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9172:                             $secmatch = 1;
                   9173:                         }
                   9174:                     }
                   9175:                     if (!$secmatch) {
                   9176:                         next;
                   9177:                     }
1.288     raeburn  9178:                 }
1.419     raeburn  9179:                 if ($usec eq '') {
                   9180:                     $usec = 'none';
                   9181:                 }
1.275     raeburn  9182:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9183:                     if ($hidepriv) {
1.1075.2.36  raeburn  9184:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9185:                             (!$nothide{$uname.':'.$udom})) {
                   9186:                             next;
                   9187:                         }
                   9188:                     }
1.503     raeburn  9189:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9190:                         $status = 'previous';
                   9191:                     } elsif ($start > $now) {
                   9192:                         $status = 'future';
                   9193:                     } else {
                   9194:                         $status = 'active';
                   9195:                     }
1.277     albertel 9196:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9197:                         if ($status eq $type) {
1.420     albertel 9198:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9199:                                 push(@{$$users{$role}{$user}},$type);
                   9200:                             }
1.288     raeburn  9201:                             $match = 1;
                   9202:                         }
                   9203:                     }
1.419     raeburn  9204:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9205:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9206: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9207:                         }
1.420     albertel 9208:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9209:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9210:                         }
1.609     raeburn  9211:                         if (ref($statushash) eq 'HASH') {
                   9212:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9213:                         }
1.275     raeburn  9214:                     }
                   9215:                 }
                   9216:             }
                   9217:         }
1.290     albertel 9218:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9219:             if ((defined($cdom)) && (defined($cnum))) {
                   9220:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9221:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9222:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9223:                     next if ($owner eq '');
                   9224:                     my ($ownername,$ownerdom);
                   9225:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9226:                         $ownername = $1;
                   9227:                         $ownerdom = $2;
                   9228:                     } else {
                   9229:                         $ownername = $owner;
                   9230:                         $ownerdom = $cdom;
                   9231:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9232:                     }
                   9233:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9234:                     if (defined($userdata) && 
1.609     raeburn  9235: 			!exists($$userdata{$owner})) {
                   9236: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9237:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9238:                             push(@{$seclists{$owner}},'none');
                   9239:                         }
                   9240:                         if (ref($statushash) eq 'HASH') {
                   9241:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9242:                         }
1.290     albertel 9243: 		    }
1.279     raeburn  9244:                 }
                   9245:             }
                   9246:         }
1.419     raeburn  9247:         foreach my $user (keys(%seclists)) {
                   9248:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9249:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9250:         }
1.275     raeburn  9251:     }
                   9252:     return;
                   9253: }
                   9254: 
1.288     raeburn  9255: sub get_user_info {
                   9256:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9257:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9258: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9259:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9260:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9261:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9262:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9263:     return;
                   9264: }
1.275     raeburn  9265: 
1.472     raeburn  9266: ###############################################
                   9267: 
                   9268: =pod
                   9269: 
                   9270: =item * &get_user_quota()
                   9271: 
1.1075.2.41  raeburn  9272: Retrieves quota assigned for storage of user files.
                   9273: Default is to report quota for portfolio files.
1.472     raeburn  9274: 
                   9275: Incoming parameters:
                   9276: 1. user's username
                   9277: 2. user's domain
1.1075.2.41  raeburn  9278: 3. quota name - portfolio, author, or course
                   9279:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  9280: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  9281:    course
1.472     raeburn  9282: 
                   9283: Returns:
1.1075.2.58  raeburn  9284: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9285: 2. (Optional) Type of setting: custom or default
                   9286:    (individually assigned or default for user's 
                   9287:    institutional status).
                   9288: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9289:    or student - types as defined in localenroll::inst_usertypes 
                   9290:    for user's domain, which determines default quota for user.
                   9291: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9292: 
                   9293: If a value has been stored in the user's environment, 
1.536     raeburn  9294: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  9295: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9296: 
                   9297: =cut
                   9298: 
                   9299: ###############################################
                   9300: 
                   9301: 
                   9302: sub get_user_quota {
1.1075.2.42  raeburn  9303:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9304:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9305:     if (!defined($udom)) {
                   9306:         $udom = $env{'user.domain'};
                   9307:     }
                   9308:     if (!defined($uname)) {
                   9309:         $uname = $env{'user.name'};
                   9310:     }
                   9311:     if (($udom eq '' || $uname eq '') ||
                   9312:         ($udom eq 'public') && ($uname eq 'public')) {
                   9313:         $quota = 0;
1.536     raeburn  9314:         $quotatype = 'default';
                   9315:         $defquota = 0; 
1.472     raeburn  9316:     } else {
1.536     raeburn  9317:         my $inststatus;
1.1075.2.41  raeburn  9318:         if ($quotaname eq 'course') {
                   9319:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9320:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9321:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9322:             } else {
                   9323:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9324:                 $quota = $cenv{'internal.uploadquota'};
                   9325:             }
1.536     raeburn  9326:         } else {
1.1075.2.41  raeburn  9327:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9328:                 if ($quotaname eq 'author') {
                   9329:                     $quota = $env{'environment.authorquota'};
                   9330:                 } else {
                   9331:                     $quota = $env{'environment.portfolioquota'};
                   9332:                 }
                   9333:                 $inststatus = $env{'environment.inststatus'};
                   9334:             } else {
                   9335:                 my %userenv = 
                   9336:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9337:                                          'authorquota','inststatus'],$udom,$uname);
                   9338:                 my ($tmp) = keys(%userenv);
                   9339:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9340:                     if ($quotaname eq 'author') {
                   9341:                         $quota = $userenv{'authorquota'};
                   9342:                     } else {
                   9343:                         $quota = $userenv{'portfolioquota'};
                   9344:                     }
                   9345:                     $inststatus = $userenv{'inststatus'};
                   9346:                 } else {
                   9347:                     undef(%userenv);
                   9348:                 }
                   9349:             }
                   9350:         }
                   9351:         if ($quota eq '' || wantarray) {
                   9352:             if ($quotaname eq 'course') {
                   9353:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  9354:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   9355:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  9356:                     $defquota = $domdefs{$crstype.'quota'};
                   9357:                 }
                   9358:                 if ($defquota eq '') {
                   9359:                     $defquota = 500;
                   9360:                 }
1.1075.2.41  raeburn  9361:             } else {
                   9362:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9363:             }
                   9364:             if ($quota eq '') {
                   9365:                 $quota = $defquota;
                   9366:                 $quotatype = 'default';
                   9367:             } else {
                   9368:                 $quotatype = 'custom';
                   9369:             }
1.472     raeburn  9370:         }
                   9371:     }
1.536     raeburn  9372:     if (wantarray) {
                   9373:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9374:     } else {
                   9375:         return $quota;
                   9376:     }
1.472     raeburn  9377: }
                   9378: 
                   9379: ###############################################
                   9380: 
                   9381: =pod
                   9382: 
                   9383: =item * &default_quota()
                   9384: 
1.536     raeburn  9385: Retrieves default quota assigned for storage of user portfolio files,
                   9386: given an (optional) user's institutional status.
1.472     raeburn  9387: 
                   9388: Incoming parameters:
1.1075.2.42  raeburn  9389: 
1.472     raeburn  9390: 1. domain
1.536     raeburn  9391: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9392:    status types (e.g., faculty, staff, student etc.)
                   9393:    which apply to the user for whom the default is being retrieved.
                   9394:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  9395:    default quota will be returned.
                   9396: 3.  quota name - portfolio, author, or course
                   9397:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9398: 
                   9399: Returns:
1.1075.2.42  raeburn  9400: 
1.1075.2.58  raeburn  9401: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9402: 2. (Optional) institutional type which determined the value of the
                   9403:    default quota.
1.472     raeburn  9404: 
                   9405: If a value has been stored in the domain's configuration db,
                   9406: it will return that, otherwise it returns 20 (for backwards 
                   9407: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  9408: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9409: 
1.536     raeburn  9410: If the user's status includes multiple types (e.g., staff and student),
                   9411: the largest default quota which applies to the user determines the
                   9412: default quota returned.
                   9413: 
1.472     raeburn  9414: =cut
                   9415: 
                   9416: ###############################################
                   9417: 
                   9418: 
                   9419: sub default_quota {
1.1075.2.41  raeburn  9420:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9421:     my ($defquota,$settingstatus);
                   9422:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9423:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  9424:     my $key = 'defaultquota';
                   9425:     if ($quotaname eq 'author') {
                   9426:         $key = 'authorquota';
                   9427:     }
1.622     raeburn  9428:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9429:         if ($inststatus ne '') {
1.765     raeburn  9430:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9431:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  9432:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9433:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9434:                         if ($defquota eq '') {
1.1075.2.41  raeburn  9435:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9436:                             $settingstatus = $item;
1.1075.2.41  raeburn  9437:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9438:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9439:                             $settingstatus = $item;
                   9440:                         }
                   9441:                     }
1.1075.2.41  raeburn  9442:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9443:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9444:                         if ($defquota eq '') {
                   9445:                             $defquota = $quotahash{'quotas'}{$item};
                   9446:                             $settingstatus = $item;
                   9447:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9448:                             $defquota = $quotahash{'quotas'}{$item};
                   9449:                             $settingstatus = $item;
                   9450:                         }
1.536     raeburn  9451:                     }
                   9452:                 }
                   9453:             }
                   9454:         }
                   9455:         if ($defquota eq '') {
1.1075.2.41  raeburn  9456:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9457:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9458:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9459:                 $defquota = $quotahash{'quotas'}{'default'};
                   9460:             }
1.536     raeburn  9461:             $settingstatus = 'default';
1.1075.2.42  raeburn  9462:             if ($defquota eq '') {
                   9463:                 if ($quotaname eq 'author') {
                   9464:                     $defquota = 500;
                   9465:                 }
                   9466:             }
1.536     raeburn  9467:         }
                   9468:     } else {
                   9469:         $settingstatus = 'default';
1.1075.2.41  raeburn  9470:         if ($quotaname eq 'author') {
                   9471:             $defquota = 500;
                   9472:         } else {
                   9473:             $defquota = 20;
                   9474:         }
1.536     raeburn  9475:     }
                   9476:     if (wantarray) {
                   9477:         return ($defquota,$settingstatus);
1.472     raeburn  9478:     } else {
1.536     raeburn  9479:         return $defquota;
1.472     raeburn  9480:     }
                   9481: }
                   9482: 
1.1075.2.41  raeburn  9483: ###############################################
                   9484: 
                   9485: =pod
                   9486: 
1.1075.2.42  raeburn  9487: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  9488: 
                   9489: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  9490: of existing file within authoring space will cause quota for the authoring
                   9491: space to be exceeded.
                   9492: 
                   9493: Same, if upload of a file directly to a course/community via Course Editor
                   9494: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  9495: 
1.1075.2.61  raeburn  9496: Inputs: 7 
1.1075.2.42  raeburn  9497: 1. username or coursenum
1.1075.2.41  raeburn  9498: 2. domain
1.1075.2.42  raeburn  9499: 3. context ('author' or 'course')
1.1075.2.41  raeburn  9500: 4. filename of file for which action is being requested
                   9501: 5. filesize (kB) of file
                   9502: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  9503: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  9504: 
                   9505: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   9506:          otherwise return null.
                   9507: 
1.1075.2.42  raeburn  9508: =back
                   9509: 
1.1075.2.41  raeburn  9510: =cut
                   9511: 
1.1075.2.42  raeburn  9512: sub excess_filesize_warning {
1.1075.2.59  raeburn  9513:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  9514:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  9515:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  9516:     if ($context eq 'author') {
                   9517:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9518:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9519:     } else {
                   9520:         foreach my $subdir ('docs','supplemental') {
                   9521:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9522:         }
                   9523:     }
1.1075.2.41  raeburn  9524:     $disk_quota = int($disk_quota * 1000);
                   9525:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  9526:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  9527:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  9528:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9529:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  9530:                             $disk_quota,$current_disk_usage).
                   9531:                '</p>';
                   9532:     }
                   9533:     return;
                   9534: }
                   9535: 
                   9536: ###############################################
                   9537: 
                   9538: 
1.384     raeburn  9539: sub get_secgrprole_info {
                   9540:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9541:     my %sections_count = &get_sections($cdom,$cnum);
                   9542:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9543:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9544:     my @groups = sort(keys(%curr_groups));
                   9545:     my $allroles = [];
                   9546:     my $rolehash;
                   9547:     my $accesshash = {
                   9548:                      active => 'Currently has access',
                   9549:                      future => 'Will have future access',
                   9550:                      previous => 'Previously had access',
                   9551:                   };
                   9552:     if ($needroles) {
                   9553:         $rolehash = {'all' => 'all'};
1.385     albertel 9554:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9555: 	if (&Apache::lonnet::error(%user_roles)) {
                   9556: 	    undef(%user_roles);
                   9557: 	}
                   9558:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9559:             my ($role)=split(/\:/,$item,2);
                   9560:             if ($role eq 'cr') { next; }
                   9561:             if ($role =~ /^cr/) {
                   9562:                 $$rolehash{$role} = (split('/',$role))[3];
                   9563:             } else {
                   9564:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9565:             }
                   9566:         }
                   9567:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9568:             push(@{$allroles},$key);
                   9569:         }
                   9570:         push (@{$allroles},'st');
                   9571:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9572:     }
                   9573:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9574: }
                   9575: 
1.555     raeburn  9576: sub user_picker {
1.1075.2.115  raeburn  9577:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom) = @_;
1.555     raeburn  9578:     my $currdom = $dom;
1.1075.2.114  raeburn  9579:     my @alldoms = &Apache::lonnet::all_domains();
                   9580:     if (@alldoms == 1) {
                   9581:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   9582:                                                ['directorysrch'],$alldoms[0]);
                   9583:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   9584:         my $showdom = $domdesc;
                   9585:         if ($showdom eq '') {
                   9586:             $showdom = $dom;
                   9587:         }
                   9588:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   9589:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   9590:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   9591:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   9592:             }
                   9593:         }
                   9594:     }
1.555     raeburn  9595:     my %curr_selected = (
                   9596:                         srchin => 'dom',
1.580     raeburn  9597:                         srchby => 'lastname',
1.555     raeburn  9598:                       );
                   9599:     my $srchterm;
1.625     raeburn  9600:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9601:         if ($srch->{'srchby'} ne '') {
                   9602:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9603:         }
                   9604:         if ($srch->{'srchin'} ne '') {
                   9605:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9606:         }
                   9607:         if ($srch->{'srchtype'} ne '') {
                   9608:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9609:         }
                   9610:         if ($srch->{'srchdomain'} ne '') {
                   9611:             $currdom = $srch->{'srchdomain'};
                   9612:         }
                   9613:         $srchterm = $srch->{'srchterm'};
                   9614:     }
1.1075.2.98  raeburn  9615:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  9616:                     'usr'       => 'Search criteria',
1.563     raeburn  9617:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9618:                     'uname'     => 'username',
                   9619:                     'lastname'  => 'last name',
1.555     raeburn  9620:                     'lastfirst' => 'last name, first name',
1.558     albertel 9621:                     'crs'       => 'in this course',
1.576     raeburn  9622:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9623:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9624:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9625:                     'exact'     => 'is',
                   9626:                     'contains'  => 'contains',
1.569     raeburn  9627:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  9628:                                        );
                   9629:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  9630:                     'youm'      => "You must include some text to search for.",
                   9631:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9632:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9633:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9634:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9635:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9636:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9637:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9638:                                        );
1.1075.2.98  raeburn  9639:     &html_escape(\%html_lt);
                   9640:     &js_escape(\%js_lt);
1.1075.2.115  raeburn  9641:     my $domform;
                   9642:     if ($fixeddom) {
                   9643:         $domform = &select_dom_form($currdom,'srchdomain',1,1,undef,[$currdom]);
                   9644:     } else {
                   9645:         $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   9646:     }
1.563     raeburn  9647:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9648: 
                   9649:     my @srchins = ('crs','dom','alc','instd');
                   9650: 
                   9651:     foreach my $option (@srchins) {
                   9652:         # FIXME 'alc' option unavailable until 
                   9653:         #       loncreateuser::print_user_query_page()
                   9654:         #       has been completed.
                   9655:         next if ($option eq 'alc');
1.880     raeburn  9656:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9657:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  9658:         if ($curr_selected{'srchin'} eq $option) {
                   9659:             $srchinsel .= ' 
1.1075.2.98  raeburn  9660:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  9661:         } else {
                   9662:             $srchinsel .= '
1.1075.2.98  raeburn  9663:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  9664:         }
1.555     raeburn  9665:     }
1.563     raeburn  9666:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9667: 
                   9668:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9669:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9670:         if ($curr_selected{'srchby'} eq $option) {
                   9671:             $srchbysel .= '
1.1075.2.98  raeburn  9672:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9673:         } else {
                   9674:             $srchbysel .= '
1.1075.2.98  raeburn  9675:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9676:          }
                   9677:     }
                   9678:     $srchbysel .= "\n  </select>\n";
                   9679: 
                   9680:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9681:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9682:         if ($curr_selected{'srchtype'} eq $option) {
                   9683:             $srchtypesel .= '
1.1075.2.98  raeburn  9684:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9685:         } else {
                   9686:             $srchtypesel .= '
1.1075.2.98  raeburn  9687:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9688:         }
                   9689:     }
                   9690:     $srchtypesel .= "\n  </select>\n";
                   9691: 
1.558     albertel 9692:     my ($newuserscript,$new_user_create);
1.994     raeburn  9693:     my $context_dom = $env{'request.role.domain'};
                   9694:     if ($context eq 'requestcrs') {
                   9695:         if ($env{'form.coursedom'} ne '') { 
                   9696:             $context_dom = $env{'form.coursedom'};
                   9697:         }
                   9698:     }
1.556     raeburn  9699:     if ($forcenewuser) {
1.576     raeburn  9700:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9701:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9702:                 if ($cancreate) {
                   9703:                     $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>';
                   9704:                 } else {
1.799     bisitz   9705:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9706:                     my %usertypetext = (
                   9707:                         official   => 'institutional',
                   9708:                         unofficial => 'non-institutional',
                   9709:                     );
1.799     bisitz   9710:                     $new_user_create = '<p class="LC_warning">'
                   9711:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9712:                                       .' '
                   9713:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9714:                                           ,'<a href="'.$helplink.'">','</a>')
                   9715:                                       .'</p><br />';
1.627     raeburn  9716:                 }
1.576     raeburn  9717:             }
                   9718:         }
                   9719: 
1.556     raeburn  9720:         $newuserscript = <<"ENDSCRIPT";
                   9721: 
1.570     raeburn  9722: function setSearch(createnew,callingForm) {
1.556     raeburn  9723:     if (createnew == 1) {
1.570     raeburn  9724:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9725:             if (callingForm.srchby.options[i].value == 'uname') {
                   9726:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9727:             }
                   9728:         }
1.570     raeburn  9729:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9730:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9731: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9732:             }
                   9733:         }
1.570     raeburn  9734:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9735:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9736:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9737:             }
                   9738:         }
1.570     raeburn  9739:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9740:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9741:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9742:             }
                   9743:         }
                   9744:     }
                   9745: }
                   9746: ENDSCRIPT
1.558     albertel 9747: 
1.556     raeburn  9748:     }
                   9749: 
1.555     raeburn  9750:     my $output = <<"END_BLOCK";
1.556     raeburn  9751: <script type="text/javascript">
1.824     bisitz   9752: // <![CDATA[
1.570     raeburn  9753: function validateEntry(callingForm) {
1.558     albertel 9754: 
1.556     raeburn  9755:     var checkok = 1;
1.558     albertel 9756:     var srchin;
1.570     raeburn  9757:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9758: 	if ( callingForm.srchin[i].checked ) {
                   9759: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9760: 	}
                   9761:     }
                   9762: 
1.570     raeburn  9763:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9764:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9765:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9766:     var srchterm =  callingForm.srchterm.value;
                   9767:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9768:     var msg = "";
                   9769: 
                   9770:     if (srchterm == "") {
                   9771:         checkok = 0;
1.1075.2.98  raeburn  9772:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  9773:     }
                   9774: 
1.569     raeburn  9775:     if (srchtype== 'begins') {
                   9776:         if (srchterm.length < 2) {
                   9777:             checkok = 0;
1.1075.2.98  raeburn  9778:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  9779:         }
                   9780:     }
                   9781: 
1.556     raeburn  9782:     if (srchtype== 'contains') {
                   9783:         if (srchterm.length < 3) {
                   9784:             checkok = 0;
1.1075.2.98  raeburn  9785:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  9786:         }
                   9787:     }
                   9788:     if (srchin == 'instd') {
                   9789:         if (srchdomain == '') {
                   9790:             checkok = 0;
1.1075.2.98  raeburn  9791:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  9792:         }
                   9793:     }
                   9794:     if (srchin == 'dom') {
                   9795:         if (srchdomain == '') {
                   9796:             checkok = 0;
1.1075.2.98  raeburn  9797:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  9798:         }
                   9799:     }
                   9800:     if (srchby == 'lastfirst') {
                   9801:         if (srchterm.indexOf(",") == -1) {
                   9802:             checkok = 0;
1.1075.2.98  raeburn  9803:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  9804:         }
                   9805:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9806:             checkok = 0;
1.1075.2.98  raeburn  9807:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  9808:         }
                   9809:     }
                   9810:     if (checkok == 0) {
1.1075.2.98  raeburn  9811:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  9812:         return;
                   9813:     }
                   9814:     if (checkok == 1) {
1.570     raeburn  9815:         callingForm.submit();
1.556     raeburn  9816:     }
                   9817: }
                   9818: 
                   9819: $newuserscript
                   9820: 
1.824     bisitz   9821: // ]]>
1.556     raeburn  9822: </script>
1.558     albertel 9823: 
                   9824: $new_user_create
                   9825: 
1.555     raeburn  9826: END_BLOCK
1.558     albertel 9827: 
1.876     raeburn  9828:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  9829:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  9830:                $domform.
                   9831:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  9832:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  9833:                $srchbysel.
                   9834:                $srchtypesel. 
                   9835:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9836:                $srchinsel.
                   9837:                &Apache::lonhtmlcommon::row_closure(1). 
                   9838:                &Apache::lonhtmlcommon::end_pick_box().
                   9839:                '<br />';
1.1075.2.114  raeburn  9840:     return ($output,1);
1.555     raeburn  9841: }
                   9842: 
1.612     raeburn  9843: sub user_rule_check {
1.615     raeburn  9844:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  9845:     my ($response,%inst_response);
1.612     raeburn  9846:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  9847:         if (keys(%{$usershash}) > 1) {
                   9848:             my (%by_username,%by_id,%userdoms);
                   9849:             my $checkid;
1.612     raeburn  9850:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  9851:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   9852:                     $checkid = 1;
                   9853:                 }
                   9854:             }
                   9855:             foreach my $user (keys(%{$usershash})) {
                   9856:                 my ($uname,$udom) = split(/:/,$user);
                   9857:                 if ($checkid) {
                   9858:                     if (ref($usershash->{$user}) eq 'HASH') {
                   9859:                         if ($usershash->{$user}->{'id'} ne '') {
                   9860:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   9861:                             $userdoms{$udom} = 1;
                   9862:                             if (ref($inst_results) eq 'HASH') {
                   9863:                                 $inst_results->{$uname.':'.$udom} = {};
                   9864:                             }
                   9865:                         }
                   9866:                     }
                   9867:                 } else {
                   9868:                     $by_username{$udom}{$uname} = 1;
                   9869:                     $userdoms{$udom} = 1;
                   9870:                     if (ref($inst_results) eq 'HASH') {
                   9871:                         $inst_results->{$uname.':'.$udom} = {};
                   9872:                     }
                   9873:                 }
                   9874:             }
                   9875:             foreach my $udom (keys(%userdoms)) {
                   9876:                 if (!$got_rules->{$udom}) {
                   9877:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9878:                                                              ['usercreation'],$udom);
                   9879:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   9880:                         foreach my $item ('username','id') {
                   9881:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9882:                                 $$curr_rules{$udom}{$item} =
                   9883:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   9884:                             }
                   9885:                         }
                   9886:                     }
                   9887:                     $got_rules->{$udom} = 1;
                   9888:                 }
                   9889:             }
                   9890:             if ($checkid) {
                   9891:                 foreach my $udom (keys(%by_id)) {
                   9892:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   9893:                     if ($outcome eq 'ok') {
                   9894:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   9895:                             my $uname = $by_id{$udom}{$id};
                   9896:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9897:                         }
                   9898:                         if (ref($results) eq 'HASH') {
                   9899:                             foreach my $uname (keys(%{$results})) {
                   9900:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   9901:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   9902:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   9903:                                 }
                   9904:                             }
                   9905:                         }
                   9906:                     }
1.612     raeburn  9907:                 }
1.615     raeburn  9908:             } else {
1.1075.2.99  raeburn  9909:                 foreach my $udom (keys(%by_username)) {
                   9910:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   9911:                     if ($outcome eq 'ok') {
                   9912:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   9913:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9914:                         }
                   9915:                         if (ref($results) eq 'HASH') {
                   9916:                             foreach my $uname (keys(%{$results})) {
                   9917:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   9918:                             }
                   9919:                         }
                   9920:                     }
                   9921:                 }
1.612     raeburn  9922:             }
1.1075.2.99  raeburn  9923:         } elsif (keys(%{$usershash}) == 1) {
                   9924:             my $user = (keys(%{$usershash}))[0];
                   9925:             my ($uname,$udom) = split(/:/,$user);
                   9926:             if (($udom ne '') && ($uname ne '')) {
                   9927:                 if (ref($usershash->{$user}) eq 'HASH') {
                   9928:                     if (ref($checks) eq 'HASH') {
                   9929:                         if (defined($checks->{'username'})) {
                   9930:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   9931:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   9932:                         } elsif (defined($checks->{'id'})) {
                   9933:                             if ($usershash->{$user}->{'id'} ne '') {
                   9934:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   9935:                                     &Apache::lonnet::get_instuser($udom,undef,
                   9936:                                                                   $usershash->{$user}->{'id'});
                   9937:                             } else {
                   9938:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   9939:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   9940:                             }
                   9941:                         }
                   9942:                     } else {
                   9943:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   9944:                             &Apache::lonnet::get_instuser($udom,$uname);
                   9945:                        return;
                   9946:                     }
                   9947:                     if (!$got_rules->{$udom}) {
                   9948:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9949:                                                                  ['usercreation'],$udom);
                   9950:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   9951:                             foreach my $item ('username','id') {
                   9952:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9953:                                    $$curr_rules{$udom}{$item} =
                   9954:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   9955:                                 }
                   9956:                             }
1.585     raeburn  9957:                         }
1.1075.2.99  raeburn  9958:                         $got_rules->{$udom} = 1;
1.585     raeburn  9959:                     }
                   9960:                 }
1.1075.2.99  raeburn  9961:             } else {
                   9962:                 return;
                   9963:             }
                   9964:         } else {
                   9965:             return;
                   9966:         }
                   9967:         foreach my $user (keys(%{$usershash})) {
                   9968:             my ($uname,$udom) = split(/:/,$user);
                   9969:             next if (($udom eq '') || ($uname eq ''));
                   9970:             my $id;
                   9971:             if (ref($inst_results) eq 'HASH') {
                   9972:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   9973:                     $id = $inst_results->{$user}->{'id'};
                   9974:                 }
                   9975:             }
                   9976:             if ($id eq '') {
                   9977:                 if (ref($usershash->{$user})) {
                   9978:                     $id = $usershash->{$user}->{'id'};
                   9979:                 }
1.585     raeburn  9980:             }
1.612     raeburn  9981:             foreach my $item (keys(%{$checks})) {
                   9982:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   9983:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   9984:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  9985:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   9986:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  9987:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   9988:                                 if ($rule_check{$rule}) {
                   9989:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  9990:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  9991:                                         if (ref($inst_results) eq 'HASH') {
                   9992:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   9993:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   9994:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  9995:                                                 } elsif ($item eq 'id') {
                   9996:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   9997:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   9998:                                                     }
1.615     raeburn  9999:                                                 }
1.612     raeburn  10000:                                             }
                   10001:                                         }
1.615     raeburn  10002:                                     }
                   10003:                                     last;
1.585     raeburn  10004:                                 }
                   10005:                             }
                   10006:                         }
                   10007:                     }
                   10008:                 }
                   10009:             }
                   10010:         }
                   10011:     }
1.612     raeburn  10012:     return;
                   10013: }
                   10014: 
                   10015: sub user_rule_formats {
                   10016:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10017:     my %text = ( 
                   10018:                  'username' => 'Usernames',
                   10019:                  'id'       => 'IDs',
                   10020:                );
                   10021:     my $output;
                   10022:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10023:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10024:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  10025:             $output = '<br />'.
                   10026:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10027:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10028:                       ' <ul>';
1.612     raeburn  10029:             foreach my $rule (@{$ruleorder}) {
                   10030:                 if (ref($curr_rules) eq 'ARRAY') {
                   10031:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10032:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10033:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10034:                                         $rules->{$rule}{'desc'}.'</li>';
                   10035:                         }
                   10036:                     }
                   10037:                 }
                   10038:             }
                   10039:             $output .= '</ul>';
                   10040:         }
                   10041:     }
                   10042:     return $output;
                   10043: }
                   10044: 
                   10045: sub instrule_disallow_msg {
1.615     raeburn  10046:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10047:     my $response;
                   10048:     my %text = (
                   10049:                   item   => 'username',
                   10050:                   items  => 'usernames',
                   10051:                   match  => 'matches',
                   10052:                   do     => 'does',
                   10053:                   action => 'a username',
                   10054:                   one    => 'one',
                   10055:                );
                   10056:     if ($count > 1) {
                   10057:         $text{'item'} = 'usernames';
                   10058:         $text{'match'} ='match';
                   10059:         $text{'do'} = 'do';
                   10060:         $text{'action'} = 'usernames',
                   10061:         $text{'one'} = 'ones';
                   10062:     }
                   10063:     if ($checkitem eq 'id') {
                   10064:         $text{'items'} = 'IDs';
                   10065:         $text{'item'} = 'ID';
                   10066:         $text{'action'} = 'an ID';
1.615     raeburn  10067:         if ($count > 1) {
                   10068:             $text{'item'} = 'IDs';
                   10069:             $text{'action'} = 'IDs';
                   10070:         }
1.612     raeburn  10071:     }
1.674     bisitz   10072:     $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  10073:     if ($mode eq 'upload') {
                   10074:         if ($checkitem eq 'username') {
                   10075:             $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'}.");
                   10076:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10077:             $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  10078:         }
1.669     raeburn  10079:     } elsif ($mode eq 'selfcreate') {
                   10080:         if ($checkitem eq 'id') {
                   10081:             $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.");
                   10082:         }
1.615     raeburn  10083:     } else {
                   10084:         if ($checkitem eq 'username') {
                   10085:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10086:         } elsif ($checkitem eq 'id') {
                   10087:             $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.");
                   10088:         }
1.612     raeburn  10089:     }
                   10090:     return $response;
1.585     raeburn  10091: }
                   10092: 
1.624     raeburn  10093: sub personal_data_fieldtitles {
                   10094:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10095:                         id => 'Student/Employee ID',
                   10096:                         permanentemail => 'E-mail address',
                   10097:                         lastname => 'Last Name',
                   10098:                         firstname => 'First Name',
                   10099:                         middlename => 'Middle Name',
                   10100:                         generation => 'Generation',
                   10101:                         gen => 'Generation',
1.765     raeburn  10102:                         inststatus => 'Affiliation',
1.624     raeburn  10103:                    );
                   10104:     return %fieldtitles;
                   10105: }
                   10106: 
1.642     raeburn  10107: sub sorted_inst_types {
                   10108:     my ($dom) = @_;
1.1075.2.70  raeburn  10109:     my ($usertypes,$order);
                   10110:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10111:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10112:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10113:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10114:     } else {
                   10115:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10116:     }
1.642     raeburn  10117:     my $othertitle = &mt('All users');
                   10118:     if ($env{'request.course.id'}) {
1.668     raeburn  10119:         $othertitle  = &mt('Any users');
1.642     raeburn  10120:     }
                   10121:     my @types;
                   10122:     if (ref($order) eq 'ARRAY') {
                   10123:         @types = @{$order};
                   10124:     }
                   10125:     if (@types == 0) {
                   10126:         if (ref($usertypes) eq 'HASH') {
                   10127:             @types = sort(keys(%{$usertypes}));
                   10128:         }
                   10129:     }
                   10130:     if (keys(%{$usertypes}) > 0) {
                   10131:         $othertitle = &mt('Other users');
                   10132:     }
                   10133:     return ($othertitle,$usertypes,\@types);
                   10134: }
                   10135: 
1.645     raeburn  10136: sub get_institutional_codes {
                   10137:     my ($settings,$allcourses,$LC_code) = @_;
                   10138: # Get complete list of course sections to update
                   10139:     my @currsections = ();
                   10140:     my @currxlists = ();
                   10141:     my $coursecode = $$settings{'internal.coursecode'};
                   10142: 
                   10143:     if ($$settings{'internal.sectionnums'} ne '') {
                   10144:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10145:     }
                   10146: 
                   10147:     if ($$settings{'internal.crosslistings'} ne '') {
                   10148:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10149:     }
                   10150: 
                   10151:     if (@currxlists > 0) {
                   10152:         foreach (@currxlists) {
                   10153:             if (m/^([^:]+):(\w*)$/) {
                   10154:                 unless (grep/^$1$/,@{$allcourses}) {
1.1075.2.119  raeburn  10155:                     push(@{$allcourses},$1);
1.645     raeburn  10156:                     $$LC_code{$1} = $2;
                   10157:                 }
                   10158:             }
                   10159:         }
                   10160:     }
                   10161:  
                   10162:     if (@currsections > 0) {
                   10163:         foreach (@currsections) {
                   10164:             if (m/^(\w+):(\w*)$/) {
                   10165:                 my $sec = $coursecode.$1;
                   10166:                 my $lc_sec = $2;
                   10167:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1075.2.119  raeburn  10168:                     push(@{$allcourses},$sec);
1.645     raeburn  10169:                     $$LC_code{$sec} = $lc_sec;
                   10170:                 }
                   10171:             }
                   10172:         }
                   10173:     }
                   10174:     return;
                   10175: }
                   10176: 
1.971     raeburn  10177: sub get_standard_codeitems {
                   10178:     return ('Year','Semester','Department','Number','Section');
                   10179: }
                   10180: 
1.112     bowersj2 10181: =pod
                   10182: 
1.780     raeburn  10183: =head1 Slot Helpers
                   10184: 
                   10185: =over 4
                   10186: 
                   10187: =item * sorted_slots()
                   10188: 
1.1040    raeburn  10189: Sorts an array of slot names in order of an optional sort key,
                   10190: default sort is by slot start time (earliest first). 
1.780     raeburn  10191: 
                   10192: Inputs:
                   10193: 
                   10194: =over 4
                   10195: 
                   10196: slotsarr  - Reference to array of unsorted slot names.
                   10197: 
                   10198: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10199: 
1.1040    raeburn  10200: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10201: 
1.549     albertel 10202: =back
                   10203: 
1.780     raeburn  10204: Returns:
                   10205: 
                   10206: =over 4
                   10207: 
1.1040    raeburn  10208: sorted   - An array of slot names sorted by a specified sort key 
                   10209:            (default sort key is start time of the slot).
1.780     raeburn  10210: 
                   10211: =back
                   10212: 
                   10213: =cut
                   10214: 
                   10215: 
                   10216: sub sorted_slots {
1.1040    raeburn  10217:     my ($slotsarr,$slots,$sortkey) = @_;
                   10218:     if ($sortkey eq '') {
                   10219:         $sortkey = 'starttime';
                   10220:     }
1.780     raeburn  10221:     my @sorted;
                   10222:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10223:         @sorted =
                   10224:             sort {
                   10225:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10226:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10227:                      }
                   10228:                      if (ref($slots->{$a})) { return -1;}
                   10229:                      if (ref($slots->{$b})) { return 1;}
                   10230:                      return 0;
                   10231:                  } @{$slotsarr};
                   10232:     }
                   10233:     return @sorted;
                   10234: }
                   10235: 
1.1040    raeburn  10236: =pod
                   10237: 
                   10238: =item * get_future_slots()
                   10239: 
                   10240: Inputs:
                   10241: 
                   10242: =over 4
                   10243: 
                   10244: cnum - course number
                   10245: 
                   10246: cdom - course domain
                   10247: 
                   10248: now - current UNIX time
                   10249: 
                   10250: symb - optional symb
                   10251: 
                   10252: =back
                   10253: 
                   10254: Returns:
                   10255: 
                   10256: =over 4
                   10257: 
                   10258: sorted_reservable - ref to array of student_schedulable slots currently 
                   10259:                     reservable, ordered by end date of reservation period.
                   10260: 
                   10261: reservable_now - ref to hash of student_schedulable slots currently
                   10262:                  reservable.
                   10263: 
                   10264:     Keys in inner hash are:
                   10265:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  10266:     (b) endreserve: end date of reservation period.
                   10267:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10268:         selected.
1.1040    raeburn  10269: 
                   10270: sorted_future - ref to array of student_schedulable slots reservable in
                   10271:                 the future, ordered by start date of reservation period.
                   10272: 
                   10273: future_reservable - ref to hash of student_schedulable slots reservable
                   10274:                     in the future.
                   10275: 
                   10276:     Keys in inner hash are:
                   10277:     (a) symb: either blank or symb to which slot use is restricted.
                   10278:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  10279:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10280:         selected.
1.1040    raeburn  10281: 
                   10282: =back
                   10283: 
                   10284: =cut
                   10285: 
                   10286: sub get_future_slots {
                   10287:     my ($cnum,$cdom,$now,$symb) = @_;
                   10288:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10289:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10290:     foreach my $slot (keys(%slots)) {
                   10291:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10292:         if ($symb) {
                   10293:             next if (($slots{$slot}->{'symb'} ne '') && 
                   10294:                      ($slots{$slot}->{'symb'} ne $symb));
                   10295:         }
                   10296:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10297:             ($slots{$slot}->{'endtime'} > $now)) {
                   10298:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10299:                 my $userallowed = 0;
                   10300:                 if ($slots{$slot}->{'allowedsections'}) {
                   10301:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10302:                     if (!defined($env{'request.role.sec'})
                   10303:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10304:                         $userallowed=1;
                   10305:                     } else {
                   10306:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10307:                             $userallowed=1;
                   10308:                         }
                   10309:                     }
                   10310:                     unless ($userallowed) {
                   10311:                         if (defined($env{'request.course.groups'})) {
                   10312:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10313:                             foreach my $group (@groups) {
                   10314:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10315:                                     $userallowed=1;
                   10316:                                     last;
                   10317:                                 }
                   10318:                             }
                   10319:                         }
                   10320:                     }
                   10321:                 }
                   10322:                 if ($slots{$slot}->{'allowedusers'}) {
                   10323:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10324:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10325:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10326:                         $userallowed = 1;
                   10327:                     }
                   10328:                 }
                   10329:                 next unless($userallowed);
                   10330:             }
                   10331:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10332:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10333:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  10334:             my $uniqueperiod;
                   10335:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10336:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10337:             }
1.1040    raeburn  10338:             if (($startreserve < $now) &&
                   10339:                 (!$endreserve || $endreserve > $now)) {
                   10340:                 my $lastres = $endreserve;
                   10341:                 if (!$lastres) {
                   10342:                     $lastres = $slots{$slot}->{'starttime'};
                   10343:                 }
                   10344:                 $reservable_now{$slot} = {
                   10345:                                            symb       => $symb,
1.1075.2.104  raeburn  10346:                                            endreserve => $lastres,
                   10347:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  10348:                                          };
                   10349:             } elsif (($startreserve > $now) &&
                   10350:                      (!$endreserve || $endreserve > $startreserve)) {
                   10351:                 $future_reservable{$slot} = {
                   10352:                                               symb         => $symb,
1.1075.2.104  raeburn  10353:                                               startreserve => $startreserve,
                   10354:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10355:                                             };
                   10356:             }
                   10357:         }
                   10358:     }
                   10359:     my @unsorted_reservable = keys(%reservable_now);
                   10360:     if (@unsorted_reservable > 0) {
                   10361:         @sorted_reservable = 
                   10362:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10363:     }
                   10364:     my @unsorted_future = keys(%future_reservable);
                   10365:     if (@unsorted_future > 0) {
                   10366:         @sorted_future =
                   10367:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10368:     }
                   10369:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10370: }
1.780     raeburn  10371: 
                   10372: =pod
                   10373: 
1.1057    foxr     10374: =back
                   10375: 
1.549     albertel 10376: =head1 HTTP Helpers
                   10377: 
                   10378: =over 4
                   10379: 
1.648     raeburn  10380: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10381: 
1.258     albertel 10382: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10383: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10384: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10385: 
                   10386: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10387: $possible_names is an ref to an array of form element names.  As an example:
                   10388: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10389: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10390: 
                   10391: =cut
1.1       albertel 10392: 
1.6       albertel 10393: sub get_unprocessed_cgi {
1.25      albertel 10394:   my ($query,$possible_names)= @_;
1.26      matthew  10395:   # $Apache::lonxml::debug=1;
1.356     albertel 10396:   foreach my $pair (split(/&/,$query)) {
                   10397:     my ($name, $value) = split(/=/,$pair);
1.369     www      10398:     $name = &unescape($name);
1.25      albertel 10399:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10400:       $value =~ tr/+/ /;
                   10401:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10402:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10403:     }
1.16      harris41 10404:   }
1.6       albertel 10405: }
                   10406: 
1.112     bowersj2 10407: =pod
                   10408: 
1.648     raeburn  10409: =item * &cacheheader() 
1.112     bowersj2 10410: 
                   10411: returns cache-controlling header code
                   10412: 
                   10413: =cut
                   10414: 
1.7       albertel 10415: sub cacheheader {
1.258     albertel 10416:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10417:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10418:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10419:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10420:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10421:     return $output;
1.7       albertel 10422: }
                   10423: 
1.112     bowersj2 10424: =pod
                   10425: 
1.648     raeburn  10426: =item * &no_cache($r) 
1.112     bowersj2 10427: 
                   10428: specifies header code to not have cache
                   10429: 
                   10430: =cut
                   10431: 
1.9       albertel 10432: sub no_cache {
1.216     albertel 10433:     my ($r) = @_;
                   10434:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10435: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10436:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10437:     $r->no_cache(1);
                   10438:     $r->header_out("Expires" => $date);
                   10439:     $r->header_out("Pragma" => "no-cache");
1.123     www      10440: }
                   10441: 
                   10442: sub content_type {
1.181     albertel 10443:     my ($r,$type,$charset) = @_;
1.299     foxr     10444:     if ($r) {
                   10445: 	#  Note that printout.pl calls this with undef for $r.
                   10446: 	&no_cache($r);
                   10447:     }
1.258     albertel 10448:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10449:     unless ($charset) {
                   10450: 	$charset=&Apache::lonlocal::current_encoding;
                   10451:     }
                   10452:     if ($charset) { $type.='; charset='.$charset; }
                   10453:     if ($r) {
                   10454: 	$r->content_type($type);
                   10455:     } else {
                   10456: 	print("Content-type: $type\n\n");
                   10457:     }
1.9       albertel 10458: }
1.25      albertel 10459: 
1.112     bowersj2 10460: =pod
                   10461: 
1.648     raeburn  10462: =item * &add_to_env($name,$value) 
1.112     bowersj2 10463: 
1.258     albertel 10464: adds $name to the %env hash with value
1.112     bowersj2 10465: $value, if $name already exists, the entry is converted to an array
                   10466: reference and $value is added to the array.
                   10467: 
                   10468: =cut
                   10469: 
1.25      albertel 10470: sub add_to_env {
                   10471:   my ($name,$value)=@_;
1.258     albertel 10472:   if (defined($env{$name})) {
                   10473:     if (ref($env{$name})) {
1.25      albertel 10474:       #already have multiple values
1.258     albertel 10475:       push(@{ $env{$name} },$value);
1.25      albertel 10476:     } else {
                   10477:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10478:       my $first=$env{$name};
                   10479:       undef($env{$name});
                   10480:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10481:     }
                   10482:   } else {
1.258     albertel 10483:     $env{$name}=$value;
1.25      albertel 10484:   }
1.31      albertel 10485: }
1.149     albertel 10486: 
                   10487: =pod
                   10488: 
1.648     raeburn  10489: =item * &get_env_multiple($name) 
1.149     albertel 10490: 
1.258     albertel 10491: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10492: values may be defined and end up as an array ref.
                   10493: 
                   10494: returns an array of values
                   10495: 
                   10496: =cut
                   10497: 
                   10498: sub get_env_multiple {
                   10499:     my ($name) = @_;
                   10500:     my @values;
1.258     albertel 10501:     if (defined($env{$name})) {
1.149     albertel 10502:         # exists is it an array
1.258     albertel 10503:         if (ref($env{$name})) {
                   10504:             @values=@{ $env{$name} };
1.149     albertel 10505:         } else {
1.258     albertel 10506:             $values[0]=$env{$name};
1.149     albertel 10507:         }
                   10508:     }
                   10509:     return(@values);
                   10510: }
                   10511: 
1.660     raeburn  10512: sub ask_for_embedded_content {
                   10513:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10514:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  10515:         %currsubfile,%unused,$rem);
1.1071    raeburn  10516:     my $counter = 0;
                   10517:     my $numnew = 0;
1.987     raeburn  10518:     my $numremref = 0;
                   10519:     my $numinvalid = 0;
                   10520:     my $numpathchg = 0;
                   10521:     my $numexisting = 0;
1.1071    raeburn  10522:     my $numunused = 0;
                   10523:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  10524:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10525:     my $heading = &mt('Upload embedded files');
                   10526:     my $buttontext = &mt('Upload');
                   10527: 
1.1075.2.11  raeburn  10528:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  10529:         if ($actionurl eq '/adm/dependencies') {
                   10530:             $navmap = Apache::lonnavmaps::navmap->new();
                   10531:         }
                   10532:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10533:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  10534:     }
1.1075.2.35  raeburn  10535:     if (($actionurl eq '/adm/portfolio') ||
                   10536:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10537:         my $current_path='/';
                   10538:         if ($env{'form.currentpath'}) {
                   10539:             $current_path = $env{'form.currentpath'};
                   10540:         }
                   10541:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  10542:             $udom = $cdom;
                   10543:             $uname = $cnum;
1.984     raeburn  10544:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10545:         } else {
                   10546:             $udom = $env{'user.domain'};
                   10547:             $uname = $env{'user.name'};
                   10548:             $url = '/userfiles/portfolio';
                   10549:         }
1.987     raeburn  10550:         $toplevel = $url.'/';
1.984     raeburn  10551:         $url .= $current_path;
                   10552:         $getpropath = 1;
1.987     raeburn  10553:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10554:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10555:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10556:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10557:         $toplevel = $url;
1.984     raeburn  10558:         if ($rest ne '') {
1.987     raeburn  10559:             $url .= $rest;
                   10560:         }
                   10561:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10562:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10563:             $url = $args->{'docs_url'};
                   10564:             $toplevel = $url;
1.1075.2.11  raeburn  10565:             if ($args->{'context'} eq 'paste') {
                   10566:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10567:                 ($path) =
                   10568:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10569:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10570:                 $fileloc =~ s{^/}{};
                   10571:             }
1.1071    raeburn  10572:         }
                   10573:     } elsif ($actionurl eq '/adm/dependencies') {
                   10574:         if ($env{'request.course.id'} ne '') {
                   10575:             if (ref($args) eq 'HASH') {
                   10576:                 $url = $args->{'docs_url'};
                   10577:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  10578:                 $toplevel = $url;
                   10579:                 unless ($toplevel =~ m{^/}) {
                   10580:                     $toplevel = "/$url";
                   10581:                 }
1.1075.2.11  raeburn  10582:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  10583:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10584:                     $path = $1;
                   10585:                 } else {
                   10586:                     ($path) =
                   10587:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10588:                 }
1.1075.2.79  raeburn  10589:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10590:                     $fileloc = $toplevel;
                   10591:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10592:                     my ($udom,$uname,$fname) =
                   10593:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10594:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10595:                 } else {
                   10596:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10597:                 }
1.1071    raeburn  10598:                 $fileloc =~ s{^/}{};
                   10599:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10600:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10601:             }
1.987     raeburn  10602:         }
1.1075.2.35  raeburn  10603:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10604:         $udom = $cdom;
                   10605:         $uname = $cnum;
                   10606:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10607:         $toplevel = $url;
                   10608:         $path = $url;
                   10609:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10610:         $fileloc =~ s{^/}{};
                   10611:     }
                   10612:     foreach my $file (keys(%{$allfiles})) {
                   10613:         my $embed_file;
                   10614:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10615:             $embed_file = $1;
                   10616:         } else {
                   10617:             $embed_file = $file;
                   10618:         }
1.1075.2.55  raeburn  10619:         my ($absolutepath,$cleaned_file);
                   10620:         if ($embed_file =~ m{^\w+://}) {
                   10621:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  10622:             $newfiles{$cleaned_file} = 1;
                   10623:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10624:         } else {
1.1075.2.55  raeburn  10625:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10626:             if ($embed_file =~ m{^/}) {
                   10627:                 $absolutepath = $embed_file;
                   10628:             }
1.1075.2.47  raeburn  10629:             if ($cleaned_file =~ m{/}) {
                   10630:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10631:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10632:                 my $item = $fname;
                   10633:                 if ($path ne '') {
                   10634:                     $item = $path.'/'.$fname;
                   10635:                     $subdependencies{$path}{$fname} = 1;
                   10636:                 } else {
                   10637:                     $dependencies{$item} = 1;
                   10638:                 }
                   10639:                 if ($absolutepath) {
                   10640:                     $mapping{$item} = $absolutepath;
                   10641:                 } else {
                   10642:                     $mapping{$item} = $embed_file;
                   10643:                 }
                   10644:             } else {
                   10645:                 $dependencies{$embed_file} = 1;
                   10646:                 if ($absolutepath) {
1.1075.2.47  raeburn  10647:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10648:                 } else {
1.1075.2.47  raeburn  10649:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10650:                 }
                   10651:             }
1.984     raeburn  10652:         }
                   10653:     }
1.1071    raeburn  10654:     my $dirptr = 16384;
1.984     raeburn  10655:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10656:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  10657:         if (($actionurl eq '/adm/portfolio') ||
                   10658:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  10659:             my ($sublistref,$listerror) =
                   10660:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10661:             if (ref($sublistref) eq 'ARRAY') {
                   10662:                 foreach my $line (@{$sublistref}) {
                   10663:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10664:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10665:                 }
1.984     raeburn  10666:             }
1.987     raeburn  10667:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10668:             if (opendir(my $dir,$url.'/'.$path)) {
                   10669:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10670:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10671:             }
1.1075.2.11  raeburn  10672:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10673:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10674:                   ($args->{'context'} eq 'paste')) ||
                   10675:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10676:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  10677:                 my $dir;
                   10678:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10679:                     $dir = $fileloc;
                   10680:                 } else {
                   10681:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10682:                 }
1.1071    raeburn  10683:                 if ($dir ne '') {
                   10684:                     my ($sublistref,$listerror) =
                   10685:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10686:                     if (ref($sublistref) eq 'ARRAY') {
                   10687:                         foreach my $line (@{$sublistref}) {
                   10688:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10689:                                 undef,$mtime)=split(/\&/,$line,12);
                   10690:                             unless (($testdir&$dirptr) ||
                   10691:                                     ($file_name =~ /^\.\.?$/)) {
                   10692:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10693:                             }
                   10694:                         }
                   10695:                     }
                   10696:                 }
1.984     raeburn  10697:             }
                   10698:         }
                   10699:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10700:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10701:                 my $item = $path.'/'.$file;
                   10702:                 unless ($mapping{$item} eq $item) {
                   10703:                     $pathchanges{$item} = 1;
                   10704:                 }
                   10705:                 $existing{$item} = 1;
                   10706:                 $numexisting ++;
                   10707:             } else {
                   10708:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10709:             }
                   10710:         }
1.1071    raeburn  10711:         if ($actionurl eq '/adm/dependencies') {
                   10712:             foreach my $path (keys(%currsubfile)) {
                   10713:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10714:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10715:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  10716:                              next if (($rem ne '') &&
                   10717:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10718:                                        (ref($navmap) &&
                   10719:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10720:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10721:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10722:                              $unused{$path.'/'.$file} = 1; 
                   10723:                          }
                   10724:                     }
                   10725:                 }
                   10726:             }
                   10727:         }
1.984     raeburn  10728:     }
1.987     raeburn  10729:     my %currfile;
1.1075.2.35  raeburn  10730:     if (($actionurl eq '/adm/portfolio') ||
                   10731:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10732:         my ($dirlistref,$listerror) =
                   10733:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10734:         if (ref($dirlistref) eq 'ARRAY') {
                   10735:             foreach my $line (@{$dirlistref}) {
                   10736:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10737:                 $currfile{$file_name} = 1;
                   10738:             }
1.984     raeburn  10739:         }
1.987     raeburn  10740:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10741:         if (opendir(my $dir,$url)) {
1.987     raeburn  10742:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10743:             map {$currfile{$_} = 1;} @dir_list;
                   10744:         }
1.1075.2.11  raeburn  10745:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10746:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10747:               ($args->{'context'} eq 'paste')) ||
                   10748:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10749:         if ($env{'request.course.id'} ne '') {
                   10750:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10751:             if ($dir ne '') {
                   10752:                 my ($dirlistref,$listerror) =
                   10753:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10754:                 if (ref($dirlistref) eq 'ARRAY') {
                   10755:                     foreach my $line (@{$dirlistref}) {
                   10756:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10757:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10758:                         unless (($testdir&$dirptr) ||
                   10759:                                 ($file_name =~ /^\.\.?$/)) {
                   10760:                             $currfile{$file_name} = [$size,$mtime];
                   10761:                         }
                   10762:                     }
                   10763:                 }
                   10764:             }
                   10765:         }
1.984     raeburn  10766:     }
                   10767:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10768:         if (exists($currfile{$file})) {
1.987     raeburn  10769:             unless ($mapping{$file} eq $file) {
                   10770:                 $pathchanges{$file} = 1;
                   10771:             }
                   10772:             $existing{$file} = 1;
                   10773:             $numexisting ++;
                   10774:         } else {
1.984     raeburn  10775:             $newfiles{$file} = 1;
                   10776:         }
                   10777:     }
1.1071    raeburn  10778:     foreach my $file (keys(%currfile)) {
                   10779:         unless (($file eq $filename) ||
                   10780:                 ($file eq $filename.'.bak') ||
                   10781:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  10782:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  10783:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10784:                     next if (($rem ne '') &&
                   10785:                              (($env{"httpref.$rem".$file} ne '') ||
                   10786:                               (ref($navmap) &&
                   10787:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10788:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10789:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10790:                 }
1.1075.2.11  raeburn  10791:             }
1.1071    raeburn  10792:             $unused{$file} = 1;
                   10793:         }
                   10794:     }
1.1075.2.11  raeburn  10795:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10796:         ($args->{'context'} eq 'paste')) {
                   10797:         $counter = scalar(keys(%existing));
                   10798:         $numpathchg = scalar(keys(%pathchanges));
                   10799:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  10800:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   10801:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10802:         $counter = scalar(keys(%existing));
                   10803:         $numpathchg = scalar(keys(%pathchanges));
                   10804:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  10805:     }
1.984     raeburn  10806:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10807:         if ($actionurl eq '/adm/dependencies') {
                   10808:             next if ($embed_file =~ m{^\w+://});
                   10809:         }
1.660     raeburn  10810:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10811:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  10812:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  10813:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  10814:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   10815:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  10816:         }
1.1075.2.35  raeburn  10817:         $upload_output .= '</td>';
1.1071    raeburn  10818:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  10819:             $upload_output.='<td align="right">'.
                   10820:                             '<span class="LC_info LC_fontsize_medium">'.
                   10821:                             &mt("URL points to web address").'</span>';
1.987     raeburn  10822:             $numremref++;
1.660     raeburn  10823:         } elsif ($args->{'error_on_invalid_names'}
                   10824:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  10825:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   10826:                             &mt('Invalid characters').'</span>';
1.987     raeburn  10827:             $numinvalid++;
1.660     raeburn  10828:         } else {
1.1075.2.35  raeburn  10829:             $upload_output .= '<td>'.
                   10830:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  10831:                                                      $embed_file,\%mapping,
1.1071    raeburn  10832:                                                      $allfiles,$codebase,'upload');
                   10833:             $counter ++;
                   10834:             $numnew ++;
1.987     raeburn  10835:         }
                   10836:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   10837:     }
                   10838:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  10839:         if ($actionurl eq '/adm/dependencies') {
                   10840:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   10841:             $modify_output .= &start_data_table_row().
                   10842:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   10843:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   10844:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   10845:                               '<td>'.$size.'</td>'.
                   10846:                               '<td>'.$mtime.'</td>'.
                   10847:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   10848:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   10849:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   10850:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   10851:                               &embedded_file_element('upload_embedded',$counter,
                   10852:                                                      $embed_file,\%mapping,
                   10853:                                                      $allfiles,$codebase,'modify').
                   10854:                               '</div></td>'.
                   10855:                               &end_data_table_row()."\n";
                   10856:             $counter ++;
                   10857:         } else {
                   10858:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10859:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   10860:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   10861:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  10862:                               &Apache::loncommon::end_data_table_row()."\n";
                   10863:         }
                   10864:     }
                   10865:     my $delidx = $counter;
                   10866:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   10867:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   10868:         $delete_output .= &start_data_table_row().
                   10869:                           '<td><img src="'.&icon($oldfile).'" />'.
                   10870:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   10871:                           '<td>'.$size.'</td>'.
                   10872:                           '<td>'.$mtime.'</td>'.
                   10873:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   10874:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   10875:                           &embedded_file_element('upload_embedded',$delidx,
                   10876:                                                  $oldfile,\%mapping,$allfiles,
                   10877:                                                  $codebase,'delete').'</td>'.
                   10878:                           &end_data_table_row()."\n"; 
                   10879:         $numunused ++;
                   10880:         $delidx ++;
1.987     raeburn  10881:     }
                   10882:     if ($upload_output) {
                   10883:         $upload_output = &start_data_table().
                   10884:                          $upload_output.
                   10885:                          &end_data_table()."\n";
                   10886:     }
1.1071    raeburn  10887:     if ($modify_output) {
                   10888:         $modify_output = &start_data_table().
                   10889:                          &start_data_table_header_row().
                   10890:                          '<th>'.&mt('File').'</th>'.
                   10891:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10892:                          '<th>'.&mt('Modified').'</th>'.
                   10893:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   10894:                          &end_data_table_header_row().
                   10895:                          $modify_output.
                   10896:                          &end_data_table()."\n";
                   10897:     }
                   10898:     if ($delete_output) {
                   10899:         $delete_output = &start_data_table().
                   10900:                          &start_data_table_header_row().
                   10901:                          '<th>'.&mt('File').'</th>'.
                   10902:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10903:                          '<th>'.&mt('Modified').'</th>'.
                   10904:                          '<th>'.&mt('Delete?').'</th>'.
                   10905:                          &end_data_table_header_row().
                   10906:                          $delete_output.
                   10907:                          &end_data_table()."\n";
                   10908:     }
1.987     raeburn  10909:     my $applies = 0;
                   10910:     if ($numremref) {
                   10911:         $applies ++;
                   10912:     }
                   10913:     if ($numinvalid) {
                   10914:         $applies ++;
                   10915:     }
                   10916:     if ($numexisting) {
                   10917:         $applies ++;
                   10918:     }
1.1071    raeburn  10919:     if ($counter || $numunused) {
1.987     raeburn  10920:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   10921:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  10922:                   $state.'<h3>'.$heading.'</h3>'; 
                   10923:         if ($actionurl eq '/adm/dependencies') {
                   10924:             if ($numnew) {
                   10925:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   10926:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   10927:                            $upload_output.'<br />'."\n";
                   10928:             }
                   10929:             if ($numexisting) {
                   10930:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   10931:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   10932:                            $modify_output.'<br />'."\n";
                   10933:                            $buttontext = &mt('Save changes');
                   10934:             }
                   10935:             if ($numunused) {
                   10936:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   10937:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   10938:                            $delete_output.'<br />'."\n";
                   10939:                            $buttontext = &mt('Save changes');
                   10940:             }
                   10941:         } else {
                   10942:             $output .= $upload_output.'<br />'."\n";
                   10943:         }
                   10944:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   10945:                    $counter.'" />'."\n";
                   10946:         if ($actionurl eq '/adm/dependencies') { 
                   10947:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   10948:                        $numnew.'" />'."\n";
                   10949:         } elsif ($actionurl eq '') {
1.987     raeburn  10950:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   10951:         }
                   10952:     } elsif ($applies) {
                   10953:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   10954:         if ($applies > 1) {
                   10955:             $output .=  
1.1075.2.35  raeburn  10956:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  10957:             if ($numremref) {
                   10958:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   10959:             }
                   10960:             if ($numinvalid) {
                   10961:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   10962:             }
                   10963:             if ($numexisting) {
                   10964:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   10965:             }
                   10966:             $output .= '</ul><br />';
                   10967:         } elsif ($numremref) {
                   10968:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   10969:         } elsif ($numinvalid) {
                   10970:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   10971:         } elsif ($numexisting) {
                   10972:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   10973:         }
                   10974:         $output .= $upload_output.'<br />';
                   10975:     }
                   10976:     my ($pathchange_output,$chgcount);
1.1071    raeburn  10977:     $chgcount = $counter;
1.987     raeburn  10978:     if (keys(%pathchanges) > 0) {
                   10979:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  10980:             if ($counter) {
1.987     raeburn  10981:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   10982:                                                   $embed_file,\%mapping,
1.1071    raeburn  10983:                                                   $allfiles,$codebase,'change');
1.987     raeburn  10984:             } else {
                   10985:                 $pathchange_output .= 
                   10986:                     &start_data_table_row().
                   10987:                     '<td><input type ="checkbox" name="namechange" value="'.
                   10988:                     $chgcount.'" checked="checked" /></td>'.
                   10989:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   10990:                     '<td>'.$embed_file.
                   10991:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  10992:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  10993:                     '</td>'.&end_data_table_row();
1.660     raeburn  10994:             }
1.987     raeburn  10995:             $numpathchg ++;
                   10996:             $chgcount ++;
1.660     raeburn  10997:         }
                   10998:     }
1.1075.2.35  raeburn  10999:     if (($counter) || ($numunused)) {
1.987     raeburn  11000:         if ($numpathchg) {
                   11001:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11002:                        $numpathchg.'" />'."\n";
                   11003:         }
                   11004:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11005:             ($actionurl eq '/adm/imsimport')) {
                   11006:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11007:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11008:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11009:         } elsif ($actionurl eq '/adm/dependencies') {
                   11010:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11011:         }
1.1075.2.35  raeburn  11012:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11013:     } elsif ($numpathchg) {
                   11014:         my %pathchange = ();
                   11015:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11016:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11017:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  11018:         }
1.987     raeburn  11019:     }
1.1071    raeburn  11020:     return ($output,$counter,$numpathchg);
1.987     raeburn  11021: }
                   11022: 
1.1075.2.47  raeburn  11023: =pod
                   11024: 
                   11025: =item * clean_path($name)
                   11026: 
                   11027: Performs clean-up of directories, subdirectories and filename in an
                   11028: embedded object, referenced in an HTML file which is being uploaded
                   11029: to a course or portfolio, where
                   11030: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11031: checked.
                   11032: 
                   11033: Clean-up is similar to replacements in lonnet::clean_filename()
                   11034: except each / between sub-directory and next level is preserved.
                   11035: 
                   11036: =cut
                   11037: 
                   11038: sub clean_path {
                   11039:     my ($embed_file) = @_;
                   11040:     $embed_file =~s{^/+}{};
                   11041:     my @contents;
                   11042:     if ($embed_file =~ m{/}) {
                   11043:         @contents = split(/\//,$embed_file);
                   11044:     } else {
                   11045:         @contents = ($embed_file);
                   11046:     }
                   11047:     my $lastidx = scalar(@contents)-1;
                   11048:     for (my $i=0; $i<=$lastidx; $i++) {
                   11049:         $contents[$i]=~s{\\}{/}g;
                   11050:         $contents[$i]=~s/\s+/\_/g;
                   11051:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11052:         if ($i == $lastidx) {
                   11053:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11054:         }
                   11055:     }
                   11056:     if ($lastidx > 0) {
                   11057:         return join('/',@contents);
                   11058:     } else {
                   11059:         return $contents[0];
                   11060:     }
                   11061: }
                   11062: 
1.987     raeburn  11063: sub embedded_file_element {
1.1071    raeburn  11064:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11065:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11066:                    (ref($codebase) eq 'HASH'));
                   11067:     my $output;
1.1071    raeburn  11068:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11069:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11070:     }
                   11071:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11072:                &escape($embed_file).'" />';
                   11073:     unless (($context eq 'upload_embedded') && 
                   11074:             ($mapping->{$embed_file} eq $embed_file)) {
                   11075:         $output .='
                   11076:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11077:     }
                   11078:     my $attrib;
                   11079:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11080:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11081:     }
                   11082:     $output .=
                   11083:         "\n\t\t".
                   11084:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11085:         $attrib.'" />';
                   11086:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11087:         $output .=
                   11088:             "\n\t\t".
                   11089:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11090:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11091:     }
1.987     raeburn  11092:     return $output;
1.660     raeburn  11093: }
                   11094: 
1.1071    raeburn  11095: sub get_dependency_details {
                   11096:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11097:     my ($size,$mtime,$showsize,$showmtime);
                   11098:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11099:         if ($embed_file =~ m{/}) {
                   11100:             my ($path,$fname) = split(/\//,$embed_file);
                   11101:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11102:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11103:             }
                   11104:         } else {
                   11105:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11106:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11107:             }
                   11108:         }
                   11109:         $showsize = $size/1024.0;
                   11110:         $showsize = sprintf("%.1f",$showsize);
                   11111:         if ($mtime > 0) {
                   11112:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11113:         }
                   11114:     }
                   11115:     return ($showsize,$showmtime);
                   11116: }
                   11117: 
                   11118: sub ask_embedded_js {
                   11119:     return <<"END";
                   11120: <script type="text/javascript"">
                   11121: // <![CDATA[
                   11122: function toggleBrowse(counter) {
                   11123:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11124:     var fileid = document.getElementById('embedded_item_'+counter);
                   11125:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11126:     if (chkboxid.checked == true) {
                   11127:         uploaddivid.style.display='block';
                   11128:     } else {
                   11129:         uploaddivid.style.display='none';
                   11130:         fileid.value = '';
                   11131:     }
                   11132: }
                   11133: // ]]>
                   11134: </script>
                   11135: 
                   11136: END
                   11137: }
                   11138: 
1.661     raeburn  11139: sub upload_embedded {
                   11140:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11141:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11142:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11143:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11144:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11145:         my $orig_uploaded_filename =
                   11146:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11147:         foreach my $type ('orig','ref','attrib','codebase') {
                   11148:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11149:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11150:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11151:             }
                   11152:         }
1.661     raeburn  11153:         my ($path,$fname) =
                   11154:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11155:         # no path, whole string is fname
                   11156:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11157:         $fname = &Apache::lonnet::clean_filename($fname);
                   11158:         # See if there is anything left
                   11159:         next if ($fname eq '');
                   11160: 
                   11161:         # Check if file already exists as a file or directory.
                   11162:         my ($state,$msg);
                   11163:         if ($context eq 'portfolio') {
                   11164:             my $port_path = $dirpath;
                   11165:             if ($group ne '') {
                   11166:                 $port_path = "groups/$group/$port_path";
                   11167:             }
1.987     raeburn  11168:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11169:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11170:                                               $dir_root,$port_path,$disk_quota,
                   11171:                                               $current_disk_usage,$uname,$udom);
                   11172:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11173:                 || $state eq 'file_locked') {
1.661     raeburn  11174:                 $output .= $msg;
                   11175:                 next;
                   11176:             }
                   11177:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11178:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11179:             if ($state eq 'exists') {
                   11180:                 $output .= $msg;
                   11181:                 next;
                   11182:             }
                   11183:         }
                   11184:         # Check if extension is valid
                   11185:         if (($fname =~ /\.(\w+)$/) &&
                   11186:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  11187:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11188:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11189:             next;
                   11190:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11191:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11192:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11193:             next;
                   11194:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  11195:             $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  11196:             next;
                   11197:         }
                   11198:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  11199:         my $subdir = $path;
                   11200:         $subdir =~ s{/+$}{};
1.661     raeburn  11201:         if ($context eq 'portfolio') {
1.984     raeburn  11202:             my $result;
                   11203:             if ($state eq 'existingfile') {
                   11204:                 $result=
                   11205:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  11206:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11207:             } else {
1.984     raeburn  11208:                 $result=
                   11209:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11210:                                                     $dirpath.
1.1075.2.35  raeburn  11211:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11212:                 if ($result !~ m|^/uploaded/|) {
                   11213:                     $output .= '<span class="LC_error">'
                   11214:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11215:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11216:                                .'</span><br />';
                   11217:                     next;
                   11218:                 } else {
1.987     raeburn  11219:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11220:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11221:                 }
1.661     raeburn  11222:             }
1.1075.2.35  raeburn  11223:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   11224:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11225:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11226:             my $result =
1.1075.2.35  raeburn  11227:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11228:             if ($result !~ m|^/uploaded/|) {
                   11229:                 $output .= '<span class="LC_error">'
                   11230:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11231:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11232:                            .'</span><br />';
                   11233:                     next;
                   11234:             } else {
                   11235:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11236:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  11237:                 if ($context eq 'syllabus') {
                   11238:                     &Apache::lonnet::make_public_indefinitely($result);
                   11239:                 }
1.987     raeburn  11240:             }
1.661     raeburn  11241:         } else {
                   11242: # Save the file
                   11243:             my $target = $env{'form.embedded_item_'.$i};
                   11244:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11245:             my $dest = $fullpath.$fname;
                   11246:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11247:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11248:             my $count;
                   11249:             my $filepath = $dir_root;
1.1027    raeburn  11250:             foreach my $subdir (@parts) {
                   11251:                 $filepath .= "/$subdir";
                   11252:                 if (!-e $filepath) {
1.661     raeburn  11253:                     mkdir($filepath,0770);
                   11254:                 }
                   11255:             }
                   11256:             my $fh;
                   11257:             if (!open($fh,'>'.$dest)) {
                   11258:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11259:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11260:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11261:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11262:                            '</span><br />';
                   11263:             } else {
                   11264:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11265:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11266:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11267:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11268:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11269:                               '</span><br />';
                   11270:                 } else {
1.987     raeburn  11271:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11272:                                $url.'</span>').'<br />';
                   11273:                     unless ($context eq 'testbank') {
                   11274:                         $footer .= &mt('View embedded file: [_1]',
                   11275:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11276:                     }
                   11277:                 }
                   11278:                 close($fh);
                   11279:             }
                   11280:         }
                   11281:         if ($env{'form.embedded_ref_'.$i}) {
                   11282:             $pathchange{$i} = 1;
                   11283:         }
                   11284:     }
                   11285:     if ($output) {
                   11286:         $output = '<p>'.$output.'</p>';
                   11287:     }
                   11288:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11289:     $returnflag = 'ok';
1.1071    raeburn  11290:     my $numpathchgs = scalar(keys(%pathchange));
                   11291:     if ($numpathchgs > 0) {
1.987     raeburn  11292:         if ($context eq 'portfolio') {
                   11293:             $output .= '<p>'.&mt('or').'</p>';
                   11294:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11295:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11296:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11297:             $returnflag = 'modify_orightml';
                   11298:         }
                   11299:     }
1.1071    raeburn  11300:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11301: }
                   11302: 
                   11303: sub modify_html_form {
                   11304:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11305:     my $end = 0;
                   11306:     my $modifyform;
                   11307:     if ($context eq 'upload_embedded') {
                   11308:         return unless (ref($pathchange) eq 'HASH');
                   11309:         if ($env{'form.number_embedded_items'}) {
                   11310:             $end += $env{'form.number_embedded_items'};
                   11311:         }
                   11312:         if ($env{'form.number_pathchange_items'}) {
                   11313:             $end += $env{'form.number_pathchange_items'};
                   11314:         }
                   11315:         if ($end) {
                   11316:             for (my $i=0; $i<$end; $i++) {
                   11317:                 if ($i < $env{'form.number_embedded_items'}) {
                   11318:                     next unless($pathchange->{$i});
                   11319:                 }
                   11320:                 $modifyform .=
                   11321:                     &start_data_table_row().
                   11322:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11323:                     'checked="checked" /></td>'.
                   11324:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11325:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11326:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11327:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11328:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11329:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11330:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11331:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11332:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11333:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11334:                     &end_data_table_row();
1.1071    raeburn  11335:             }
1.987     raeburn  11336:         }
                   11337:     } else {
                   11338:         $modifyform = $pathchgtable;
                   11339:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11340:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11341:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11342:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11343:         }
                   11344:     }
                   11345:     if ($modifyform) {
1.1071    raeburn  11346:         if ($actionurl eq '/adm/dependencies') {
                   11347:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11348:         }
1.987     raeburn  11349:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11350:                '<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".
                   11351:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11352:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11353:                '</ol></p>'."\n".'<p>'.
                   11354:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11355:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11356:                &start_data_table()."\n".
                   11357:                &start_data_table_header_row().
                   11358:                '<th>'.&mt('Change?').'</th>'.
                   11359:                '<th>'.&mt('Current reference').'</th>'.
                   11360:                '<th>'.&mt('Required reference').'</th>'.
                   11361:                &end_data_table_header_row()."\n".
                   11362:                $modifyform.
                   11363:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11364:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11365:                '</form>'."\n";
                   11366:     }
                   11367:     return;
                   11368: }
                   11369: 
                   11370: sub modify_html_refs {
1.1075.2.35  raeburn  11371:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11372:     my $container;
                   11373:     if ($context eq 'portfolio') {
                   11374:         $container = $env{'form.container'};
                   11375:     } elsif ($context eq 'coursedoc') {
                   11376:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11377:     } elsif ($context eq 'manage_dependencies') {
                   11378:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11379:         $container = "/$container";
1.1075.2.35  raeburn  11380:     } elsif ($context eq 'syllabus') {
                   11381:         $container = $url;
1.987     raeburn  11382:     } else {
1.1027    raeburn  11383:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11384:     }
                   11385:     my (%allfiles,%codebase,$output,$content);
                   11386:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  11387:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  11388:         if (wantarray) {
                   11389:             return ('',0,0); 
                   11390:         } else {
                   11391:             return;
                   11392:         }
                   11393:     }
                   11394:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11395:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11396:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11397:             if (wantarray) {
                   11398:                 return ('',0,0);
                   11399:             } else {
                   11400:                 return;
                   11401:             }
                   11402:         } 
1.987     raeburn  11403:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11404:         if ($content eq '-1') {
                   11405:             if (wantarray) {
                   11406:                 return ('',0,0);
                   11407:             } else {
                   11408:                 return;
                   11409:             }
                   11410:         }
1.987     raeburn  11411:     } else {
1.1071    raeburn  11412:         unless ($container =~ /^\Q$dir_root\E/) {
                   11413:             if (wantarray) {
                   11414:                 return ('',0,0);
                   11415:             } else {
                   11416:                 return;
                   11417:             }
                   11418:         } 
1.987     raeburn  11419:         if (open(my $fh,"<$container")) {
                   11420:             $content = join('', <$fh>);
                   11421:             close($fh);
                   11422:         } else {
1.1071    raeburn  11423:             if (wantarray) {
                   11424:                 return ('',0,0);
                   11425:             } else {
                   11426:                 return;
                   11427:             }
1.987     raeburn  11428:         }
                   11429:     }
                   11430:     my ($count,$codebasecount) = (0,0);
                   11431:     my $mm = new File::MMagic;
                   11432:     my $mime_type = $mm->checktype_contents($content);
                   11433:     if ($mime_type eq 'text/html') {
                   11434:         my $parse_result = 
                   11435:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11436:                                                     \%codebase,\$content);
                   11437:         if ($parse_result eq 'ok') {
                   11438:             foreach my $i (@changes) {
                   11439:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11440:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11441:                 if ($allfiles{$ref}) {
                   11442:                     my $newname =  $orig;
                   11443:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11444:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11445:                     if ($attrib_regexp =~ /:/) {
                   11446:                         $attrib_regexp =~ s/\:/|/g;
                   11447:                     }
                   11448:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11449:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11450:                         $count += $numchg;
1.1075.2.35  raeburn  11451:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  11452:                         delete($allfiles{$ref});
1.987     raeburn  11453:                     }
                   11454:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11455:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11456:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11457:                         $codebasecount ++;
                   11458:                     }
                   11459:                 }
                   11460:             }
1.1075.2.35  raeburn  11461:             my $skiprewrites;
1.987     raeburn  11462:             if ($count || $codebasecount) {
                   11463:                 my $saveresult;
1.1071    raeburn  11464:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11465:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11466:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11467:                     if ($url eq $container) {
                   11468:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11469:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11470:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11471:                                             $fname.'</span>').'</p>';
1.987     raeburn  11472:                     } else {
                   11473:                          $output = '<p class="LC_error">'.
                   11474:                                    &mt('Error: update failed for: [_1].',
                   11475:                                    '<span class="LC_filename">'.
                   11476:                                    $container.'</span>').'</p>';
                   11477:                     }
1.1075.2.35  raeburn  11478:                     if ($context eq 'syllabus') {
                   11479:                         unless ($saveresult eq 'ok') {
                   11480:                             $skiprewrites = 1;
                   11481:                         }
                   11482:                     }
1.987     raeburn  11483:                 } else {
                   11484:                     if (open(my $fh,">$container")) {
                   11485:                         print $fh $content;
                   11486:                         close($fh);
                   11487:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11488:                                   $count,'<span class="LC_filename">'.
                   11489:                                   $container.'</span>').'</p>';
1.661     raeburn  11490:                     } else {
1.987     raeburn  11491:                          $output = '<p class="LC_error">'.
                   11492:                                    &mt('Error: could not update [_1].',
                   11493:                                    '<span class="LC_filename">'.
                   11494:                                    $container.'</span>').'</p>';
1.661     raeburn  11495:                     }
                   11496:                 }
                   11497:             }
1.1075.2.35  raeburn  11498:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11499:                 my ($actionurl,$state);
                   11500:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11501:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11502:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11503:                                               \%codebase,
                   11504:                                               {'context' => 'rewrites',
                   11505:                                                'ignore_remote_references' => 1,});
                   11506:                 if (ref($mapping) eq 'HASH') {
                   11507:                     my $rewrites = 0;
                   11508:                     foreach my $key (keys(%{$mapping})) {
                   11509:                         next if ($key =~ m{^https?://});
                   11510:                         my $ref = $mapping->{$key};
                   11511:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11512:                         my $attrib;
                   11513:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11514:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11515:                         }
                   11516:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11517:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11518:                             $rewrites += $numchg;
                   11519:                         }
                   11520:                     }
                   11521:                     if ($rewrites) {
                   11522:                         my $saveresult;
                   11523:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11524:                         if ($url eq $container) {
                   11525:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11526:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11527:                                             $count,'<span class="LC_filename">'.
                   11528:                                             $fname.'</span>').'</p>';
                   11529:                         } else {
                   11530:                             $output .= '<p class="LC_error">'.
                   11531:                                        &mt('Error: could not update links in [_1].',
                   11532:                                        '<span class="LC_filename">'.
                   11533:                                        $container.'</span>').'</p>';
                   11534: 
                   11535:                         }
                   11536:                     }
                   11537:                 }
                   11538:             }
1.987     raeburn  11539:         } else {
                   11540:             &logthis('Failed to parse '.$container.
                   11541:                      ' to modify references: '.$parse_result);
1.661     raeburn  11542:         }
                   11543:     }
1.1071    raeburn  11544:     if (wantarray) {
                   11545:         return ($output,$count,$codebasecount);
                   11546:     } else {
                   11547:         return $output;
                   11548:     }
1.661     raeburn  11549: }
                   11550: 
                   11551: sub check_for_existing {
                   11552:     my ($path,$fname,$element) = @_;
                   11553:     my ($state,$msg);
                   11554:     if (-d $path.'/'.$fname) {
                   11555:         $state = 'exists';
                   11556:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11557:     } elsif (-e $path.'/'.$fname) {
                   11558:         $state = 'exists';
                   11559:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11560:     }
                   11561:     if ($state eq 'exists') {
                   11562:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11563:     }
                   11564:     return ($state,$msg);
                   11565: }
                   11566: 
                   11567: sub check_for_upload {
                   11568:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11569:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11570:     my $filesize = length($env{'form.'.$element});
                   11571:     if (!$filesize) {
                   11572:         my $msg = '<span class="LC_error">'.
                   11573:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11574:                       '<span class="LC_filename">'.$fname.'</span>',
                   11575:                       $filesize).'<br />'.
1.1007    raeburn  11576:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11577:                   '</span>';
                   11578:         return ('zero_bytes',$msg);
                   11579:     }
                   11580:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11581:     my $getpropath = 1;
1.1021    raeburn  11582:     my ($dirlistref,$listerror) =
                   11583:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11584:     my $found_file = 0;
                   11585:     my $locked_file = 0;
1.991     raeburn  11586:     my @lockers;
                   11587:     my $navmap;
                   11588:     if ($env{'request.course.id'}) {
                   11589:         $navmap = Apache::lonnavmaps::navmap->new();
                   11590:     }
1.1021    raeburn  11591:     if (ref($dirlistref) eq 'ARRAY') {
                   11592:         foreach my $line (@{$dirlistref}) {
                   11593:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11594:             if ($file_name eq $fname){
                   11595:                 $file_name = $path.$file_name;
                   11596:                 if ($group ne '') {
                   11597:                     $file_name = $group.$file_name;
                   11598:                 }
                   11599:                 $found_file = 1;
                   11600:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11601:                     foreach my $lock (@lockers) {
                   11602:                         if (ref($lock) eq 'ARRAY') {
                   11603:                             my ($symb,$crsid) = @{$lock};
                   11604:                             if ($crsid eq $env{'request.course.id'}) {
                   11605:                                 if (ref($navmap)) {
                   11606:                                     my $res = $navmap->getBySymb($symb);
                   11607:                                     foreach my $part (@{$res->parts()}) { 
                   11608:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11609:                                         unless (($slot_status == $res->RESERVED) ||
                   11610:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11611:                                             $locked_file = 1;
                   11612:                                         }
1.991     raeburn  11613:                                     }
1.1021    raeburn  11614:                                 } else {
                   11615:                                     $locked_file = 1;
1.991     raeburn  11616:                                 }
                   11617:                             } else {
                   11618:                                 $locked_file = 1;
                   11619:                             }
                   11620:                         }
1.1021    raeburn  11621:                    }
                   11622:                 } else {
                   11623:                     my @info = split(/\&/,$rest);
                   11624:                     my $currsize = $info[6]/1000;
                   11625:                     if ($currsize < $filesize) {
                   11626:                         my $extra = $filesize - $currsize;
                   11627:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  11628:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11629:                                       &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  11630:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11631:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11632:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11633:                             return ('will_exceed_quota',$msg);
                   11634:                         }
1.984     raeburn  11635:                     }
                   11636:                 }
1.661     raeburn  11637:             }
                   11638:         }
                   11639:     }
                   11640:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  11641:         my $msg = '<p class="LC_warning">'.
                   11642:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   11643:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11644:         return ('will_exceed_quota',$msg);
                   11645:     } elsif ($found_file) {
                   11646:         if ($locked_file) {
1.1075.2.69  raeburn  11647:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11648:             $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  11649:             $msg .= '</p>';
1.661     raeburn  11650:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11651:             return ('file_locked',$msg);
                   11652:         } else {
1.1075.2.69  raeburn  11653:             my $msg = '<p class="LC_error">';
1.984     raeburn  11654:             $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  11655:             $msg .= '</p>';
1.984     raeburn  11656:             return ('existingfile',$msg);
1.661     raeburn  11657:         }
                   11658:     }
                   11659: }
                   11660: 
1.987     raeburn  11661: sub check_for_traversal {
                   11662:     my ($path,$url,$toplevel) = @_;
                   11663:     my @parts=split(/\//,$path);
                   11664:     my $cleanpath;
                   11665:     my $fullpath = $url;
                   11666:     for (my $i=0;$i<@parts;$i++) {
                   11667:         next if ($parts[$i] eq '.');
                   11668:         if ($parts[$i] eq '..') {
                   11669:             $fullpath =~ s{([^/]+/)$}{};
                   11670:         } else {
                   11671:             $fullpath .= $parts[$i].'/';
                   11672:         }
                   11673:     }
                   11674:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11675:         $cleanpath = $1;
                   11676:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11677:         my $curr_toprel = $1;
                   11678:         my @parts = split(/\//,$curr_toprel);
                   11679:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11680:         my @urlparts = split(/\//,$url_toprel);
                   11681:         my $doubledots;
                   11682:         my $startdiff = -1;
                   11683:         for (my $i=0; $i<@urlparts; $i++) {
                   11684:             if ($startdiff == -1) {
                   11685:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11686:                     $startdiff = $i;
                   11687:                     $doubledots .= '../';
                   11688:                 }
                   11689:             } else {
                   11690:                 $doubledots .= '../';
                   11691:             }
                   11692:         }
                   11693:         if ($startdiff > -1) {
                   11694:             $cleanpath = $doubledots;
                   11695:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11696:                 $cleanpath .= $parts[$i].'/';
                   11697:             }
                   11698:         }
                   11699:     }
                   11700:     $cleanpath =~ s{(/)$}{};
                   11701:     return $cleanpath;
                   11702: }
1.31      albertel 11703: 
1.1053    raeburn  11704: sub is_archive_file {
                   11705:     my ($mimetype) = @_;
                   11706:     if (($mimetype eq 'application/octet-stream') ||
                   11707:         ($mimetype eq 'application/x-stuffit') ||
                   11708:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11709:         return 1;
                   11710:     }
                   11711:     return;
                   11712: }
                   11713: 
                   11714: sub decompress_form {
1.1065    raeburn  11715:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11716:     my %lt = &Apache::lonlocal::texthash (
                   11717:         this => 'This file is an archive file.',
1.1067    raeburn  11718:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11719:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11720:         youm => 'You may wish to extract its contents.',
                   11721:         extr => 'Extract contents',
1.1067    raeburn  11722:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11723:         proa => 'Process automatically?',
1.1053    raeburn  11724:         yes  => 'Yes',
                   11725:         no   => 'No',
1.1067    raeburn  11726:         fold => 'Title for folder containing movie',
                   11727:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11728:     );
1.1065    raeburn  11729:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11730:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11731:     my $info = &list_archive_contents($fileloc,\@paths);
                   11732:     if (@paths) {
                   11733:         foreach my $path (@paths) {
                   11734:             $path =~ s{^/}{};
1.1067    raeburn  11735:             if ($path =~ m{^([^/]+)/$}) {
                   11736:                 $topdir = $1;
                   11737:             }
1.1065    raeburn  11738:             if ($path =~ m{^([^/]+)/}) {
                   11739:                 $toplevel{$1} = $path;
                   11740:             } else {
                   11741:                 $toplevel{$path} = $path;
                   11742:             }
                   11743:         }
                   11744:     }
1.1067    raeburn  11745:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  11746:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11747:                         "$topdir/media/",
                   11748:                         "$topdir/media/$topdir.mp4",
                   11749:                         "$topdir/media/FirstFrame.png",
                   11750:                         "$topdir/media/player.swf",
                   11751:                         "$topdir/media/swfobject.js",
                   11752:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  11753:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  11754:                          "$topdir/$topdir.mp4",
                   11755:                          "$topdir/$topdir\_config.xml",
                   11756:                          "$topdir/$topdir\_controller.swf",
                   11757:                          "$topdir/$topdir\_embed.css",
                   11758:                          "$topdir/$topdir\_First_Frame.png",
                   11759:                          "$topdir/$topdir\_player.html",
                   11760:                          "$topdir/$topdir\_Thumbnails.png",
                   11761:                          "$topdir/playerProductInstall.swf",
                   11762:                          "$topdir/scripts/",
                   11763:                          "$topdir/scripts/config_xml.js",
                   11764:                          "$topdir/scripts/handlebars.js",
                   11765:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11766:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11767:                          "$topdir/scripts/modernizr.js",
                   11768:                          "$topdir/scripts/player-min.js",
                   11769:                          "$topdir/scripts/swfobject.js",
                   11770:                          "$topdir/skins/",
                   11771:                          "$topdir/skins/configuration_express.xml",
                   11772:                          "$topdir/skins/express_show/",
                   11773:                          "$topdir/skins/express_show/player-min.css",
                   11774:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  11775:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   11776:                          "$topdir/$topdir.mp4",
                   11777:                          "$topdir/$topdir\_config.xml",
                   11778:                          "$topdir/$topdir\_controller.swf",
                   11779:                          "$topdir/$topdir\_embed.css",
                   11780:                          "$topdir/$topdir\_First_Frame.png",
                   11781:                          "$topdir/$topdir\_player.html",
                   11782:                          "$topdir/$topdir\_Thumbnails.png",
                   11783:                          "$topdir/playerProductInstall.swf",
                   11784:                          "$topdir/scripts/",
                   11785:                          "$topdir/scripts/config_xml.js",
                   11786:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   11787:                          "$topdir/skins/",
                   11788:                          "$topdir/skins/configuration_express.xml",
                   11789:                          "$topdir/skins/express_show/",
                   11790:                          "$topdir/skins/express_show/spritesheet.min.css",
                   11791:                          "$topdir/skins/express_show/spritesheet.png",
                   11792:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  11793:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11794:         if (@diffs == 0) {
1.1075.2.59  raeburn  11795:             $is_camtasia = 6;
                   11796:         } else {
1.1075.2.81  raeburn  11797:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  11798:             if (@diffs == 0) {
                   11799:                 $is_camtasia = 8;
1.1075.2.81  raeburn  11800:             } else {
                   11801:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   11802:                 if (@diffs == 0) {
                   11803:                     $is_camtasia = 8;
                   11804:                 }
1.1075.2.59  raeburn  11805:             }
1.1067    raeburn  11806:         }
                   11807:     }
                   11808:     my $output;
                   11809:     if ($is_camtasia) {
                   11810:         $output = <<"ENDCAM";
                   11811: <script type="text/javascript" language="Javascript">
                   11812: // <![CDATA[
                   11813: 
                   11814: function camtasiaToggle() {
                   11815:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   11816:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  11817:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  11818:                 document.getElementById('camtasia_titles').style.display='block';
                   11819:             } else {
                   11820:                 document.getElementById('camtasia_titles').style.display='none';
                   11821:             }
                   11822:         }
                   11823:     }
                   11824:     return;
                   11825: }
                   11826: 
                   11827: // ]]>
                   11828: </script>
                   11829: <p>$lt{'camt'}</p>
                   11830: ENDCAM
1.1065    raeburn  11831:     } else {
1.1067    raeburn  11832:         $output = '<p>'.$lt{'this'};
                   11833:         if ($info eq '') {
                   11834:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   11835:         } else {
                   11836:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   11837:                        '<div><pre>'.$info.'</pre></div>';
                   11838:         }
1.1065    raeburn  11839:     }
1.1067    raeburn  11840:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  11841:     my $duplicates;
                   11842:     my $num = 0;
                   11843:     if (ref($dirlist) eq 'ARRAY') {
                   11844:         foreach my $item (@{$dirlist}) {
                   11845:             if (ref($item) eq 'ARRAY') {
                   11846:                 if (exists($toplevel{$item->[0]})) {
                   11847:                     $duplicates .= 
                   11848:                         &start_data_table_row().
                   11849:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11850:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   11851:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11852:                         'value="1" />'.&mt('Yes').'</label>'.
                   11853:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   11854:                         '<td>'.$item->[0].'</td>';
                   11855:                     if ($item->[2]) {
                   11856:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   11857:                     } else {
                   11858:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   11859:                     }
                   11860:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   11861:                                    '<td>'.
                   11862:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   11863:                                    '</td>'.
                   11864:                                    &end_data_table_row();
                   11865:                     $num ++;
                   11866:                 }
                   11867:             }
                   11868:         }
                   11869:     }
                   11870:     my $itemcount;
                   11871:     if (@paths > 0) {
                   11872:         $itemcount = scalar(@paths);
                   11873:     } else {
                   11874:         $itemcount = 1;
                   11875:     }
1.1067    raeburn  11876:     if ($is_camtasia) {
                   11877:         $output .= $lt{'auto'}.'<br />'.
                   11878:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  11879:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  11880:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   11881:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   11882:                    $lt{'no'}.'</label></span><br />'.
                   11883:                    '<div id="camtasia_titles" style="display:block">'.
                   11884:                    &Apache::lonhtmlcommon::start_pick_box().
                   11885:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   11886:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   11887:                    &Apache::lonhtmlcommon::row_closure().
                   11888:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   11889:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   11890:                    &Apache::lonhtmlcommon::row_closure(1).
                   11891:                    &Apache::lonhtmlcommon::end_pick_box().
                   11892:                    '</div>';
                   11893:     }
1.1065    raeburn  11894:     $output .= 
                   11895:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  11896:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   11897:         "\n";
1.1065    raeburn  11898:     if ($duplicates ne '') {
                   11899:         $output .= '<p><span class="LC_warning">'.
                   11900:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   11901:                    &start_data_table().
                   11902:                    &start_data_table_header_row().
                   11903:                    '<th>'.&mt('Overwrite?').'</th>'.
                   11904:                    '<th>'.&mt('Name').'</th>'.
                   11905:                    '<th>'.&mt('Type').'</th>'.
                   11906:                    '<th>'.&mt('Size').'</th>'.
                   11907:                    '<th>'.&mt('Last modified').'</th>'.
                   11908:                    &end_data_table_header_row().
                   11909:                    $duplicates.
                   11910:                    &end_data_table().
                   11911:                    '</p>';
                   11912:     }
1.1067    raeburn  11913:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  11914:     if (ref($hiddenelements) eq 'HASH') {
                   11915:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   11916:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   11917:         }
                   11918:     }
                   11919:     $output .= <<"END";
1.1067    raeburn  11920: <br />
1.1053    raeburn  11921: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   11922: </form>
                   11923: $noextract
                   11924: END
                   11925:     return $output;
                   11926: }
                   11927: 
1.1065    raeburn  11928: sub decompression_utility {
                   11929:     my ($program) = @_;
                   11930:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   11931:     my $location;
                   11932:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   11933:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   11934:                          '/usr/sbin/') {
                   11935:             if (-x $dir.$program) {
                   11936:                 $location = $dir.$program;
                   11937:                 last;
                   11938:             }
                   11939:         }
                   11940:     }
                   11941:     return $location;
                   11942: }
                   11943: 
                   11944: sub list_archive_contents {
                   11945:     my ($file,$pathsref) = @_;
                   11946:     my (@cmd,$output);
                   11947:     my $needsregexp;
                   11948:     if ($file =~ /\.zip$/) {
                   11949:         @cmd = (&decompression_utility('unzip'),"-l");
                   11950:         $needsregexp = 1;
                   11951:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   11952:              ($file =~ /\.tgz$/)) {
                   11953:         @cmd = (&decompression_utility('tar'),"-ztf");
                   11954:     } elsif ($file =~ /\.tar\.bz2$/) {
                   11955:         @cmd = (&decompression_utility('tar'),"-jtf");
                   11956:     } elsif ($file =~ m|\.tar$|) {
                   11957:         @cmd = (&decompression_utility('tar'),"-tf");
                   11958:     }
                   11959:     if (@cmd) {
                   11960:         undef($!);
                   11961:         undef($@);
                   11962:         if (open(my $fh,"-|", @cmd, $file)) {
                   11963:             while (my $line = <$fh>) {
                   11964:                 $output .= $line;
                   11965:                 chomp($line);
                   11966:                 my $item;
                   11967:                 if ($needsregexp) {
                   11968:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   11969:                 } else {
                   11970:                     $item = $line;
                   11971:                 }
                   11972:                 if ($item ne '') {
                   11973:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   11974:                         push(@{$pathsref},$item);
                   11975:                     } 
                   11976:                 }
                   11977:             }
                   11978:             close($fh);
                   11979:         }
                   11980:     }
                   11981:     return $output;
                   11982: }
                   11983: 
1.1053    raeburn  11984: sub decompress_uploaded_file {
                   11985:     my ($file,$dir) = @_;
                   11986:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   11987:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   11988:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   11989:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   11990:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   11991:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   11992:     my $decompressed = $env{'cgi.decompressed'};
                   11993:     &Apache::lonnet::delenv('cgi.file');
                   11994:     &Apache::lonnet::delenv('cgi.dir');
                   11995:     &Apache::lonnet::delenv('cgi.decompressed');
                   11996:     return ($decompressed,$result);
                   11997: }
                   11998: 
1.1055    raeburn  11999: sub process_decompression {
                   12000:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   12001:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  12002:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  12003:         $error = &mt('Filename not a supported archive file type.').
                   12004:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12005:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12006:     } else {
                   12007:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12008:         if ($docuhome eq 'no_host') {
                   12009:             $error = &mt('Could not determine home server for course.');
                   12010:         } else {
                   12011:             my @ids=&Apache::lonnet::current_machine_ids();
                   12012:             my $currdir = "$dir_root/$destination";
                   12013:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12014:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12015:                        "$dir_root/$destination";
                   12016:             } else {
                   12017:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12018:                        "$dir_root/$docudom/$docuname/$destination";
                   12019:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12020:                     $error = &mt('Archive file not found.');
                   12021:                 }
                   12022:             }
1.1065    raeburn  12023:             my (@to_overwrite,@to_skip);
                   12024:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12025:                 my $total = $env{'form.archive_overwrite_total'};
                   12026:                 for (my $i=0; $i<$total; $i++) {
                   12027:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12028:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12029:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12030:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12031:                     }
                   12032:                 }
                   12033:             }
                   12034:             my $numskip = scalar(@to_skip);
                   12035:             if (($numskip > 0) && 
                   12036:                 ($numskip == $env{'form.archive_itemcount'})) {
                   12037:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12038:             } elsif ($dir eq '') {
1.1055    raeburn  12039:                 $error = &mt('Directory containing archive file unavailable.');
                   12040:             } elsif (!$error) {
1.1065    raeburn  12041:                 my ($decompressed,$display);
                   12042:                 if ($numskip > 0) {
                   12043:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12044:                     mkdir("$dir/$tempdir",0755);
                   12045:                     system("mv $dir/$file $dir/$tempdir/$file");
                   12046:                     ($decompressed,$display) = 
                   12047:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   12048:                     foreach my $item (@to_skip) {
                   12049:                         if (($item ne '') && ($item !~ /\.\./)) {
                   12050:                             if (-f "$dir/$tempdir/$item") { 
                   12051:                                 unlink("$dir/$tempdir/$item");
                   12052:                             } elsif (-d "$dir/$tempdir/$item") {
                   12053:                                 system("rm -rf $dir/$tempdir/$item");
                   12054:                             }
                   12055:                         }
                   12056:                     }
                   12057:                     system("mv $dir/$tempdir/* $dir");
                   12058:                     rmdir("$dir/$tempdir");   
                   12059:                 } else {
                   12060:                     ($decompressed,$display) = 
                   12061:                         &decompress_uploaded_file($file,$dir);
                   12062:                 }
1.1055    raeburn  12063:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12064:                     $output = '<p class="LC_info">'.
                   12065:                               &mt('Files extracted successfully from archive.').
                   12066:                               '</p>'."\n";
1.1055    raeburn  12067:                     my ($warning,$result,@contents);
                   12068:                     my ($newdirlistref,$newlisterror) =
                   12069:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12070:                                                  $docuname,1);
                   12071:                     my (%is_dir,%changes,@newitems);
                   12072:                     my $dirptr = 16384;
1.1065    raeburn  12073:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12074:                         foreach my $dir_line (@{$newdirlistref}) {
                   12075:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  12076:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   12077:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  12078:                                 push(@newitems,$item);
                   12079:                                 if ($dirptr&$testdir) {
                   12080:                                     $is_dir{$item} = 1;
                   12081:                                 }
                   12082:                                 $changes{$item} = 1;
                   12083:                             }
                   12084:                         }
                   12085:                     }
                   12086:                     if (keys(%changes) > 0) {
                   12087:                         foreach my $item (sort(@newitems)) {
                   12088:                             if ($changes{$item}) {
                   12089:                                 push(@contents,$item);
                   12090:                             }
                   12091:                         }
                   12092:                     }
                   12093:                     if (@contents > 0) {
1.1067    raeburn  12094:                         my $wantform;
                   12095:                         unless ($env{'form.autoextract_camtasia'}) {
                   12096:                             $wantform = 1;
                   12097:                         }
1.1056    raeburn  12098:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12099:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12100:                                                                 $currdir,\%is_dir,
                   12101:                                                                 \%children,\%parent,
1.1056    raeburn  12102:                                                                 \@contents,\%dirorder,
                   12103:                                                                 \%titles,$wantform);
1.1055    raeburn  12104:                         if ($datatable ne '') {
                   12105:                             $output .= &archive_options_form('decompressed',$datatable,
                   12106:                                                              $count,$hiddenelem);
1.1065    raeburn  12107:                             my $startcount = 6;
1.1055    raeburn  12108:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12109:                                                            \%titles,\%children);
1.1055    raeburn  12110:                         }
1.1067    raeburn  12111:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  12112:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12113:                             my %displayed;
                   12114:                             my $total = 1;
                   12115:                             $env{'form.archive_directory'} = [];
                   12116:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12117:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12118:                                 $path =~ s{/$}{};
                   12119:                                 my $item;
                   12120:                                 if ($path ne '') {
                   12121:                                     $item = "$path/$titles{$i}";
                   12122:                                 } else {
                   12123:                                     $item = $titles{$i};
                   12124:                                 }
                   12125:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12126:                                 if ($item eq $contents[0]) {
                   12127:                                     push(@{$env{'form.archive_directory'}},$i);
                   12128:                                     $env{'form.archive_'.$i} = 'display';
                   12129:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12130:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  12131:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12132:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  12133:                                     $env{'form.archive_'.$i} = 'display';
                   12134:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12135:                                     $displayed{'web'} = $i;
                   12136:                                 } else {
1.1075.2.59  raeburn  12137:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12138:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12139:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12140:                                         push(@{$env{'form.archive_directory'}},$i);
                   12141:                                     }
                   12142:                                     $env{'form.archive_'.$i} = 'dependency';
                   12143:                                 }
                   12144:                                 $total ++;
                   12145:                             }
                   12146:                             for (my $i=1; $i<$total; $i++) {
                   12147:                                 next if ($i == $displayed{'web'});
                   12148:                                 next if ($i == $displayed{'folder'});
                   12149:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12150:                             }
                   12151:                             $env{'form.phase'} = 'decompress_cleanup';
                   12152:                             $env{'form.archivedelete'} = 1;
                   12153:                             $env{'form.archive_count'} = $total-1;
                   12154:                             $output .=
                   12155:                                 &process_extracted_files('coursedocs',$docudom,
                   12156:                                                          $docuname,$destination,
                   12157:                                                          $dir_root,$hiddenelem);
                   12158:                         }
1.1055    raeburn  12159:                     } else {
                   12160:                         $warning = &mt('No new items extracted from archive file.');
                   12161:                     }
                   12162:                 } else {
                   12163:                     $output = $display;
                   12164:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12165:                 }
                   12166:             }
                   12167:         }
                   12168:     }
                   12169:     if ($error) {
                   12170:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12171:                    $error.'</p>'."\n";
                   12172:     }
                   12173:     if ($warning) {
                   12174:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12175:     }
                   12176:     return $output;
                   12177: }
                   12178: 
                   12179: sub get_extracted {
1.1056    raeburn  12180:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12181:         $titles,$wantform) = @_;
1.1055    raeburn  12182:     my $count = 0;
                   12183:     my $depth = 0;
                   12184:     my $datatable;
1.1056    raeburn  12185:     my @hierarchy;
1.1055    raeburn  12186:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12187:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12188:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12189:     foreach my $item (@{$contents}) {
                   12190:         $count ++;
1.1056    raeburn  12191:         @{$dirorder->{$count}} = @hierarchy;
                   12192:         $titles->{$count} = $item;
1.1055    raeburn  12193:         &archive_hierarchy($depth,$count,$parent,$children);
                   12194:         if ($wantform) {
                   12195:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12196:                                        $currdir,$depth,$count);
                   12197:         }
                   12198:         if ($is_dir->{$item}) {
                   12199:             $depth ++;
1.1056    raeburn  12200:             push(@hierarchy,$count);
                   12201:             $parent->{$depth} = $count;
1.1055    raeburn  12202:             $datatable .=
                   12203:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12204:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12205:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12206:             $depth --;
1.1056    raeburn  12207:             pop(@hierarchy);
1.1055    raeburn  12208:         }
                   12209:     }
                   12210:     return ($count,$datatable);
                   12211: }
                   12212: 
                   12213: sub recurse_extracted_archive {
1.1056    raeburn  12214:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12215:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12216:     my $result='';
1.1056    raeburn  12217:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12218:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12219:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12220:         return $result;
                   12221:     }
                   12222:     my $dirptr = 16384;
                   12223:     my ($newdirlistref,$newlisterror) =
                   12224:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12225:     if (ref($newdirlistref) eq 'ARRAY') {
                   12226:         foreach my $dir_line (@{$newdirlistref}) {
                   12227:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12228:             unless ($item =~ /^\.+$/) {
                   12229:                 $$count ++;
1.1056    raeburn  12230:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12231:                 $titles->{$$count} = $item;
1.1055    raeburn  12232:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12233: 
1.1055    raeburn  12234:                 my $is_dir;
                   12235:                 if ($dirptr&$testdir) {
                   12236:                     $is_dir = 1;
                   12237:                 }
                   12238:                 if ($wantform) {
                   12239:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12240:                 }
                   12241:                 if ($is_dir) {
                   12242:                     $$depth ++;
1.1056    raeburn  12243:                     push(@{$hierarchy},$$count);
                   12244:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12245:                     $result .=
                   12246:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12247:                                                    $docuname,$depth,$count,
1.1056    raeburn  12248:                                                    $hierarchy,$dirorder,$children,
                   12249:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12250:                     $$depth --;
1.1056    raeburn  12251:                     pop(@{$hierarchy});
1.1055    raeburn  12252:                 }
                   12253:             }
                   12254:         }
                   12255:     }
                   12256:     return $result;
                   12257: }
                   12258: 
                   12259: sub archive_hierarchy {
                   12260:     my ($depth,$count,$parent,$children) =@_;
                   12261:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12262:         if (exists($parent->{$depth})) {
                   12263:              $children->{$parent->{$depth}} .= $count.':';
                   12264:         }
                   12265:     }
                   12266:     return;
                   12267: }
                   12268: 
                   12269: sub archive_row {
                   12270:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12271:     my ($name) = ($item =~ m{([^/]+)$});
                   12272:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12273:                                        'display'    => 'Add as file',
1.1055    raeburn  12274:                                        'dependency' => 'Include as dependency',
                   12275:                                        'discard'    => 'Discard',
                   12276:                                       );
                   12277:     if ($is_dir) {
1.1059    raeburn  12278:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12279:     }
1.1056    raeburn  12280:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12281:     my $offset = 0;
1.1055    raeburn  12282:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12283:         $offset ++;
1.1065    raeburn  12284:         if ($action ne 'display') {
                   12285:             $offset ++;
                   12286:         }  
1.1055    raeburn  12287:         $output .= '<td><span class="LC_nobreak">'.
                   12288:                    '<label><input type="radio" name="archive_'.$count.
                   12289:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12290:         my $text = $choices{$action};
                   12291:         if ($is_dir) {
                   12292:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12293:             if ($action eq 'display') {
1.1059    raeburn  12294:                 $text = &mt('Add as folder');
1.1055    raeburn  12295:             }
1.1056    raeburn  12296:         } else {
                   12297:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12298: 
                   12299:         }
                   12300:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12301:         if ($action eq 'dependency') {
                   12302:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12303:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12304:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12305:                        '<option value=""></option>'."\n".
                   12306:                        '</select>'."\n".
                   12307:                        '</div>';
1.1059    raeburn  12308:         } elsif ($action eq 'display') {
                   12309:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12310:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12311:                        '</div>';
1.1055    raeburn  12312:         }
1.1056    raeburn  12313:         $output .= '</td>';
1.1055    raeburn  12314:     }
                   12315:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12316:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12317:     for (my $i=0; $i<$depth; $i++) {
                   12318:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12319:     }
                   12320:     if ($is_dir) {
                   12321:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12322:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12323:     } else {
                   12324:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12325:     }
                   12326:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12327:                &end_data_table_row();
                   12328:     return $output;
                   12329: }
                   12330: 
                   12331: sub archive_options_form {
1.1065    raeburn  12332:     my ($form,$display,$count,$hiddenelem) = @_;
                   12333:     my %lt = &Apache::lonlocal::texthash(
                   12334:                perm => 'Permanently remove archive file?',
                   12335:                hows => 'How should each extracted item be incorporated in the course?',
                   12336:                cont => 'Content actions for all',
                   12337:                addf => 'Add as folder/file',
                   12338:                incd => 'Include as dependency for a displayed file',
                   12339:                disc => 'Discard',
                   12340:                no   => 'No',
                   12341:                yes  => 'Yes',
                   12342:                save => 'Save',
                   12343:     );
                   12344:     my $output = <<"END";
                   12345: <form name="$form" method="post" action="">
                   12346: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12347: <label>
                   12348:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12349: </label>
                   12350: &nbsp;
                   12351: <label>
                   12352:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12353: </span>
                   12354: </p>
                   12355: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12356: <br />$lt{'hows'}
                   12357: <div class="LC_columnSection">
                   12358:   <fieldset>
                   12359:     <legend>$lt{'cont'}</legend>
                   12360:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12361:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12362:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12363:   </fieldset>
                   12364: </div>
                   12365: END
                   12366:     return $output.
1.1055    raeburn  12367:            &start_data_table()."\n".
1.1065    raeburn  12368:            $display."\n".
1.1055    raeburn  12369:            &end_data_table()."\n".
                   12370:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12371:            $hiddenelem.
1.1065    raeburn  12372:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12373:            '</form>';
                   12374: }
                   12375: 
                   12376: sub archive_javascript {
1.1056    raeburn  12377:     my ($startcount,$numitems,$titles,$children) = @_;
                   12378:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12379:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12380:     my $scripttag = <<START;
                   12381: <script type="text/javascript">
                   12382: // <![CDATA[
                   12383: 
                   12384: function checkAll(form,prefix) {
                   12385:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12386:     for (var i=0; i < form.elements.length; i++) {
                   12387:         var id = form.elements[i].id;
                   12388:         if ((id != '') && (id != undefined)) {
                   12389:             if (idstr.test(id)) {
                   12390:                 if (form.elements[i].type == 'radio') {
                   12391:                     form.elements[i].checked = true;
1.1056    raeburn  12392:                     var nostart = i-$startcount;
1.1059    raeburn  12393:                     var offset = nostart%7;
                   12394:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12395:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12396:                 }
                   12397:             }
                   12398:         }
                   12399:     }
                   12400: }
                   12401: 
                   12402: function propagateCheck(form,count) {
                   12403:     if (count > 0) {
1.1059    raeburn  12404:         var startelement = $startcount + ((count-1) * 7);
                   12405:         for (var j=1; j<6; j++) {
                   12406:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12407:                 var item = startelement + j; 
                   12408:                 if (form.elements[item].type == 'radio') {
                   12409:                     if (form.elements[item].checked) {
                   12410:                         containerCheck(form,count,j);
                   12411:                         break;
                   12412:                     }
1.1055    raeburn  12413:                 }
                   12414:             }
                   12415:         }
                   12416:     }
                   12417: }
                   12418: 
                   12419: numitems = $numitems
1.1056    raeburn  12420: var titles = new Array(numitems);
                   12421: var parents = new Array(numitems);
1.1055    raeburn  12422: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12423:     parents[i] = new Array;
1.1055    raeburn  12424: }
1.1059    raeburn  12425: var maintitle = '$maintitle';
1.1055    raeburn  12426: 
                   12427: START
                   12428: 
1.1056    raeburn  12429:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12430:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12431:         for (my $i=0; $i<@contents; $i ++) {
                   12432:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12433:         }
                   12434:     }
                   12435: 
1.1056    raeburn  12436:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12437:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12438:     }
                   12439: 
1.1055    raeburn  12440:     $scripttag .= <<END;
                   12441: 
                   12442: function containerCheck(form,count,offset) {
                   12443:     if (count > 0) {
1.1056    raeburn  12444:         dependencyCheck(form,count,offset);
1.1059    raeburn  12445:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12446:         form.elements[item].checked = true;
                   12447:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12448:             if (parents[count].length > 0) {
                   12449:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12450:                     containerCheck(form,parents[count][j],offset);
                   12451:                 }
                   12452:             }
                   12453:         }
                   12454:     }
                   12455: }
                   12456: 
                   12457: function dependencyCheck(form,count,offset) {
                   12458:     if (count > 0) {
1.1059    raeburn  12459:         var chosen = (offset+$startcount)+7*(count-1);
                   12460:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12461:         var currtype = form.elements[depitem].type;
                   12462:         if (form.elements[chosen].value == 'dependency') {
                   12463:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12464:             form.elements[depitem].options.length = 0;
                   12465:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  12466:             for (var i=1; i<=numitems; i++) {
                   12467:                 if (i == count) {
                   12468:                     continue;
                   12469:                 }
1.1059    raeburn  12470:                 var startelement = $startcount + (i-1) * 7;
                   12471:                 for (var j=1; j<6; j++) {
                   12472:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12473:                         var item = startelement + j;
                   12474:                         if (form.elements[item].type == 'radio') {
                   12475:                             if (form.elements[item].checked) {
                   12476:                                 if (form.elements[item].value == 'display') {
                   12477:                                     var n = form.elements[depitem].options.length;
                   12478:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12479:                                 }
                   12480:                             }
                   12481:                         }
                   12482:                     }
                   12483:                 }
                   12484:             }
                   12485:         } else {
                   12486:             document.getElementById('arc_depon_'+count).style.display='none';
                   12487:             form.elements[depitem].options.length = 0;
                   12488:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12489:         }
1.1059    raeburn  12490:         titleCheck(form,count,offset);
1.1056    raeburn  12491:     }
                   12492: }
                   12493: 
                   12494: function propagateSelect(form,count,offset) {
                   12495:     if (count > 0) {
1.1065    raeburn  12496:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12497:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12498:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12499:             if (parents[count].length > 0) {
                   12500:                 for (var j=0; j<parents[count].length; j++) {
                   12501:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12502:                 }
                   12503:             }
                   12504:         }
                   12505:     }
                   12506: }
1.1056    raeburn  12507: 
                   12508: function containerSelect(form,count,offset,picked) {
                   12509:     if (count > 0) {
1.1065    raeburn  12510:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12511:         if (form.elements[item].type == 'radio') {
                   12512:             if (form.elements[item].value == 'dependency') {
                   12513:                 if (form.elements[item+1].type == 'select-one') {
                   12514:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12515:                         if (form.elements[item+1].options[i].value == picked) {
                   12516:                             form.elements[item+1].selectedIndex = i;
                   12517:                             break;
                   12518:                         }
                   12519:                     }
                   12520:                 }
                   12521:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12522:                     if (parents[count].length > 0) {
                   12523:                         for (var j=0; j<parents[count].length; j++) {
                   12524:                             containerSelect(form,parents[count][j],offset,picked);
                   12525:                         }
                   12526:                     }
                   12527:                 }
                   12528:             }
                   12529:         }
                   12530:     }
                   12531: }
                   12532: 
1.1059    raeburn  12533: function titleCheck(form,count,offset) {
                   12534:     if (count > 0) {
                   12535:         var chosen = (offset+$startcount)+7*(count-1);
                   12536:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12537:         var currtype = form.elements[depitem].type;
                   12538:         if (form.elements[chosen].value == 'display') {
                   12539:             document.getElementById('arc_title_'+count).style.display='block';
                   12540:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12541:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12542:             }
                   12543:         } else {
                   12544:             document.getElementById('arc_title_'+count).style.display='none';
                   12545:             if (currtype == 'text') { 
                   12546:                 document.getElementById('archive_title_'+count).value='';
                   12547:             }
                   12548:         }
                   12549:     }
                   12550:     return;
                   12551: }
                   12552: 
1.1055    raeburn  12553: // ]]>
                   12554: </script>
                   12555: END
                   12556:     return $scripttag;
                   12557: }
                   12558: 
                   12559: sub process_extracted_files {
1.1067    raeburn  12560:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12561:     my $numitems = $env{'form.archive_count'};
                   12562:     return unless ($numitems);
                   12563:     my @ids=&Apache::lonnet::current_machine_ids();
                   12564:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12565:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12566:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12567:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12568:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12569:         $pathtocheck = "$dir_root/$destination";
                   12570:         $dir = $dir_root;
                   12571:         $ishome = 1;
                   12572:     } else {
                   12573:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12574:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   12575:         $dir = "$dir_root/$docudom/$docuname";    
                   12576:     }
                   12577:     my $currdir = "$dir_root/$destination";
                   12578:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12579:     if ($env{'form.folderpath'}) {
                   12580:         my @items = split('&',$env{'form.folderpath'});
                   12581:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  12582:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12583:             $containers{'0'}='page';
                   12584:         } else {
                   12585:             $containers{'0'}='sequence';
                   12586:         }
1.1055    raeburn  12587:     }
                   12588:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12589:     if ($numitems) {
                   12590:         for (my $i=1; $i<=$numitems; $i++) {
                   12591:             my $path = $env{'form.archive_content_'.$i};
                   12592:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12593:                 my $item = $1;
                   12594:                 $toplevelitems{$item} = $i;
                   12595:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12596:                     $is_dir{$item} = 1;
                   12597:                 }
                   12598:             }
                   12599:         }
                   12600:     }
1.1067    raeburn  12601:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12602:     if (keys(%toplevelitems) > 0) {
                   12603:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12604:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12605:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12606:     }
1.1066    raeburn  12607:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12608:     if ($numitems) {
                   12609:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  12610:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12611:             my $path = $env{'form.archive_content_'.$i};
                   12612:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12613:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12614:                     if ($prefix ne '' && $path ne '') {
                   12615:                         if (-e $prefix.$path) {
1.1066    raeburn  12616:                             if ((@archdirs > 0) && 
                   12617:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12618:                                 $todeletedir{$prefix.$path} = 1;
                   12619:                             } else {
                   12620:                                 $todelete{$prefix.$path} = 1;
                   12621:                             }
1.1055    raeburn  12622:                         }
                   12623:                     }
                   12624:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12625:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12626:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12627:                     $docstitle = $env{'form.archive_title_'.$i};
                   12628:                     if ($docstitle eq '') {
                   12629:                         $docstitle = $title;
                   12630:                     }
1.1055    raeburn  12631:                     $outer = 0;
1.1056    raeburn  12632:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12633:                         if (@{$dirorder{$i}} > 0) {
                   12634:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12635:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12636:                                     $outer = $item;
                   12637:                                     last;
                   12638:                                 }
                   12639:                             }
                   12640:                         }
                   12641:                     }
                   12642:                     my ($errtext,$fatal) = 
                   12643:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12644:                                                '/'.$folders{$outer}.'.'.
                   12645:                                                $containers{$outer});
                   12646:                     next if ($fatal);
                   12647:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12648:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12649:                             $mapinner{$i} = time;
1.1055    raeburn  12650:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12651:                             $containers{$i} = 'sequence';
                   12652:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12653:                                       $folders{$i}.'.'.$containers{$i};
                   12654:                             my $newidx = &LONCAPA::map::getresidx();
                   12655:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12656:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12657:                             push(@LONCAPA::map::order,$newidx);
                   12658:                             my ($outtext,$errtext) =
                   12659:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12660:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12661:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12662:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12663:                             unless ($errtext) {
                   12664:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   12665:                             }
1.1055    raeburn  12666:                         }
                   12667:                     } else {
                   12668:                         if ($context eq 'coursedocs') {
                   12669:                             my $newidx=&LONCAPA::map::getresidx();
                   12670:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12671:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12672:                                       $title;
                   12673:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12674:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   12675:                             }
                   12676:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12677:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12678:                             }
                   12679:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12680:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  12681:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  12682:                                 unless ($ishome) {
                   12683:                                     my $fetch = "$newdest{$i}/$title";
                   12684:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   12685:                                     $prompttofetch{$fetch} = 1;
                   12686:                                 }
1.1055    raeburn  12687:                             }
                   12688:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12689:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12690:                             push(@LONCAPA::map::order, $newidx);
                   12691:                             my ($outtext,$errtext)=
                   12692:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12693:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12694:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  12695:                             unless ($errtext) {
                   12696:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12697:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   12698:                                 }
                   12699:                             }
1.1055    raeburn  12700:                         }
                   12701:                     }
1.1075.2.11  raeburn  12702:                 }
                   12703:             } else {
                   12704:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
                   12705:             }
                   12706:         }
                   12707:         for (my $i=1; $i<=$numitems; $i++) {
                   12708:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12709:             my $path = $env{'form.archive_content_'.$i};
                   12710:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12711:                 my ($title) = ($path =~ m{/([^/]+)$});
                   12712:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   12713:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   12714:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12715:                         my ($itemidx,$fullpath,$relpath);
                   12716:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   12717:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  12718:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  12719:                                 if ($dirorder{$i}->[$j] eq $container) {
                   12720:                                     $itemidx = $j;
1.1056    raeburn  12721:                                 }
                   12722:                             }
1.1075.2.11  raeburn  12723:                         }
                   12724:                         if ($itemidx eq '') {
                   12725:                             $itemidx =  0;
                   12726:                         }
                   12727:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   12728:                             if ($mapinner{$referrer{$i}}) {
                   12729:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   12730:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12731:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12732:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12733:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12734:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12735:                                             if (!-e $fullpath) {
                   12736:                                                 mkdir($fullpath,0755);
1.1056    raeburn  12737:                                             }
                   12738:                                         }
1.1075.2.11  raeburn  12739:                                     } else {
                   12740:                                         last;
1.1056    raeburn  12741:                                     }
1.1075.2.11  raeburn  12742:                                 }
                   12743:                             }
                   12744:                         } elsif ($newdest{$referrer{$i}}) {
                   12745:                             $fullpath = $newdest{$referrer{$i}};
                   12746:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12747:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   12748:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   12749:                                     last;
                   12750:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12751:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12752:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12753:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12754:                                         if (!-e $fullpath) {
                   12755:                                             mkdir($fullpath,0755);
1.1056    raeburn  12756:                                         }
                   12757:                                     }
1.1075.2.11  raeburn  12758:                                 } else {
                   12759:                                     last;
1.1056    raeburn  12760:                                 }
1.1075.2.11  raeburn  12761:                             }
                   12762:                         }
                   12763:                         if ($fullpath ne '') {
                   12764:                             if (-e "$prefix$path") {
                   12765:                                 system("mv $prefix$path $fullpath/$title");
                   12766:                             }
                   12767:                             if (-e "$fullpath/$title") {
                   12768:                                 my $showpath;
                   12769:                                 if ($relpath ne '') {
                   12770:                                     $showpath = "$relpath/$title";
                   12771:                                 } else {
                   12772:                                     $showpath = "/$title";
1.1056    raeburn  12773:                                 }
1.1075.2.11  raeburn  12774:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   12775:                             }
                   12776:                             unless ($ishome) {
                   12777:                                 my $fetch = "$fullpath/$title";
                   12778:                                 $fetch =~ s/^\Q$prefix$dir\E//;
                   12779:                                 $prompttofetch{$fetch} = 1;
1.1055    raeburn  12780:                             }
                   12781:                         }
                   12782:                     }
1.1075.2.11  raeburn  12783:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   12784:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   12785:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  12786:                 }
                   12787:             } else {
1.1075.2.11  raeburn  12788:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
1.1055    raeburn  12789:             }
                   12790:         }
                   12791:         if (keys(%todelete)) {
                   12792:             foreach my $key (keys(%todelete)) {
                   12793:                 unlink($key);
1.1066    raeburn  12794:             }
                   12795:         }
                   12796:         if (keys(%todeletedir)) {
                   12797:             foreach my $key (keys(%todeletedir)) {
                   12798:                 rmdir($key);
                   12799:             }
                   12800:         }
                   12801:         foreach my $dir (sort(keys(%is_dir))) {
                   12802:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   12803:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  12804:             }
                   12805:         }
1.1067    raeburn  12806:         if ($result ne '') {
                   12807:             $output .= '<ul>'."\n".
                   12808:                        $result."\n".
                   12809:                        '</ul>';
                   12810:         }
                   12811:         unless ($ishome) {
                   12812:             my $replicationfail;
                   12813:             foreach my $item (keys(%prompttofetch)) {
                   12814:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   12815:                 unless ($fetchresult eq 'ok') {
                   12816:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   12817:                 }
                   12818:             }
                   12819:             if ($replicationfail) {
                   12820:                 $output .= '<p class="LC_error">'.
                   12821:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   12822:                            $replicationfail.
                   12823:                            '</ul></p>';
                   12824:             }
                   12825:         }
1.1055    raeburn  12826:     } else {
                   12827:         $warning = &mt('No items found in archive.');
                   12828:     }
                   12829:     if ($error) {
                   12830:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12831:                    $error.'</p>'."\n";
                   12832:     }
                   12833:     if ($warning) {
                   12834:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12835:     }
                   12836:     return $output;
                   12837: }
                   12838: 
1.1066    raeburn  12839: sub cleanup_empty_dirs {
                   12840:     my ($path) = @_;
                   12841:     if (($path ne '') && (-d $path)) {
                   12842:         if (opendir(my $dirh,$path)) {
                   12843:             my @dircontents = grep(!/^\./,readdir($dirh));
                   12844:             my $numitems = 0;
                   12845:             foreach my $item (@dircontents) {
                   12846:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  12847:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  12848:                     if (-e "$path/$item") {
                   12849:                         $numitems ++;
                   12850:                     }
                   12851:                 } else {
                   12852:                     $numitems ++;
                   12853:                 }
                   12854:             }
                   12855:             if ($numitems == 0) {
                   12856:                 rmdir($path);
                   12857:             }
                   12858:             closedir($dirh);
                   12859:         }
                   12860:     }
                   12861:     return;
                   12862: }
                   12863: 
1.41      ng       12864: =pod
1.45      matthew  12865: 
1.1075.2.56  raeburn  12866: =item * &get_folder_hierarchy()
1.1068    raeburn  12867: 
                   12868: Provides hierarchy of names of folders/sub-folders containing the current
                   12869: item,
                   12870: 
                   12871: Inputs: 3
                   12872:      - $navmap - navmaps object
                   12873: 
                   12874:      - $map - url for map (either the trigger itself, or map containing
                   12875:                            the resource, which is the trigger).
                   12876: 
                   12877:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   12878: 
                   12879: Outputs: 1 @pathitems - array of folder/subfolder names.
                   12880: 
                   12881: =cut
                   12882: 
                   12883: sub get_folder_hierarchy {
                   12884:     my ($navmap,$map,$showitem) = @_;
                   12885:     my @pathitems;
                   12886:     if (ref($navmap)) {
                   12887:         my $mapres = $navmap->getResourceByUrl($map);
                   12888:         if (ref($mapres)) {
                   12889:             my $pcslist = $mapres->map_hierarchy();
                   12890:             if ($pcslist ne '') {
                   12891:                 my @pcs = split(/,/,$pcslist);
                   12892:                 foreach my $pc (@pcs) {
                   12893:                     if ($pc == 1) {
1.1075.2.38  raeburn  12894:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  12895:                     } else {
                   12896:                         my $res = $navmap->getByMapPc($pc);
                   12897:                         if (ref($res)) {
                   12898:                             my $title = $res->compTitle();
                   12899:                             $title =~ s/\W+/_/g;
                   12900:                             if ($title ne '') {
                   12901:                                 push(@pathitems,$title);
                   12902:                             }
                   12903:                         }
                   12904:                     }
                   12905:                 }
                   12906:             }
1.1071    raeburn  12907:             if ($showitem) {
                   12908:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  12909:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  12910:                 } else {
                   12911:                     my $maptitle = $mapres->compTitle();
                   12912:                     $maptitle =~ s/\W+/_/g;
                   12913:                     if ($maptitle ne '') {
                   12914:                         push(@pathitems,$maptitle);
                   12915:                     }
1.1068    raeburn  12916:                 }
                   12917:             }
                   12918:         }
                   12919:     }
                   12920:     return @pathitems;
                   12921: }
                   12922: 
                   12923: =pod
                   12924: 
1.1015    raeburn  12925: =item * &get_turnedin_filepath()
                   12926: 
                   12927: Determines path in a user's portfolio file for storage of files uploaded
                   12928: to a specific essayresponse or dropbox item.
                   12929: 
                   12930: Inputs: 3 required + 1 optional.
                   12931: $symb is symb for resource, $uname and $udom are for current user (required).
                   12932: $caller is optional (can be "submission", if routine is called when storing
                   12933: an upoaded file when "Submit Answer" button was pressed).
                   12934: 
                   12935: Returns array containing $path and $multiresp. 
                   12936: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   12937: than one file upload item.  Callers of routine should append partid as a 
                   12938: subdirectory to $path in cases where $multiresp is 1.
                   12939: 
                   12940: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   12941: 
                   12942: =cut
                   12943: 
                   12944: sub get_turnedin_filepath {
                   12945:     my ($symb,$uname,$udom,$caller) = @_;
                   12946:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   12947:     my $turnindir;
                   12948:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   12949:     $turnindir = $userhash{'turnindir'};
                   12950:     my ($path,$multiresp);
                   12951:     if ($turnindir eq '') {
                   12952:         if ($caller eq 'submission') {
                   12953:             $turnindir = &mt('turned in');
                   12954:             $turnindir =~ s/\W+/_/g;
                   12955:             my %newhash = (
                   12956:                             'turnindir' => $turnindir,
                   12957:                           );
                   12958:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   12959:         }
                   12960:     }
                   12961:     if ($turnindir ne '') {
                   12962:         $path = '/'.$turnindir.'/';
                   12963:         my ($multipart,$turnin,@pathitems);
                   12964:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12965:         if (defined($navmap)) {
                   12966:             my $mapres = $navmap->getResourceByUrl($map);
                   12967:             if (ref($mapres)) {
                   12968:                 my $pcslist = $mapres->map_hierarchy();
                   12969:                 if ($pcslist ne '') {
                   12970:                     foreach my $pc (split(/,/,$pcslist)) {
                   12971:                         my $res = $navmap->getByMapPc($pc);
                   12972:                         if (ref($res)) {
                   12973:                             my $title = $res->compTitle();
                   12974:                             $title =~ s/\W+/_/g;
                   12975:                             if ($title ne '') {
1.1075.2.48  raeburn  12976:                                 if (($pc > 1) && (length($title) > 12)) {
                   12977:                                     $title = substr($title,0,12);
                   12978:                                 }
1.1015    raeburn  12979:                                 push(@pathitems,$title);
                   12980:                             }
                   12981:                         }
                   12982:                     }
                   12983:                 }
                   12984:                 my $maptitle = $mapres->compTitle();
                   12985:                 $maptitle =~ s/\W+/_/g;
                   12986:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  12987:                     if (length($maptitle) > 12) {
                   12988:                         $maptitle = substr($maptitle,0,12);
                   12989:                     }
1.1015    raeburn  12990:                     push(@pathitems,$maptitle);
                   12991:                 }
                   12992:                 unless ($env{'request.state'} eq 'construct') {
                   12993:                     my $res = $navmap->getBySymb($symb);
                   12994:                     if (ref($res)) {
                   12995:                         my $partlist = $res->parts();
                   12996:                         my $totaluploads = 0;
                   12997:                         if (ref($partlist) eq 'ARRAY') {
                   12998:                             foreach my $part (@{$partlist}) {
                   12999:                                 my @types = $res->responseType($part);
                   13000:                                 my @ids = $res->responseIds($part);
                   13001:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13002:                                     if ($types[$i] eq 'essay') {
                   13003:                                         my $partid = $part.'_'.$ids[$i];
                   13004:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13005:                                             $totaluploads ++;
                   13006:                                         }
                   13007:                                     }
                   13008:                                 }
                   13009:                             }
                   13010:                             if ($totaluploads > 1) {
                   13011:                                 $multiresp = 1;
                   13012:                             }
                   13013:                         }
                   13014:                     }
                   13015:                 }
                   13016:             } else {
                   13017:                 return;
                   13018:             }
                   13019:         } else {
                   13020:             return;
                   13021:         }
                   13022:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13023:         $restitle =~ s/\W+/_/g;
                   13024:         if ($restitle eq '') {
                   13025:             $restitle = ($resurl =~ m{/[^/]+$});
                   13026:             if ($restitle eq '') {
                   13027:                 $restitle = time;
                   13028:             }
                   13029:         }
1.1075.2.48  raeburn  13030:         if (length($restitle) > 12) {
                   13031:             $restitle = substr($restitle,0,12);
                   13032:         }
1.1015    raeburn  13033:         push(@pathitems,$restitle);
                   13034:         $path .= join('/',@pathitems);
                   13035:     }
                   13036:     return ($path,$multiresp);
                   13037: }
                   13038: 
                   13039: =pod
                   13040: 
1.464     albertel 13041: =back
1.41      ng       13042: 
1.112     bowersj2 13043: =head1 CSV Upload/Handling functions
1.38      albertel 13044: 
1.41      ng       13045: =over 4
                   13046: 
1.648     raeburn  13047: =item * &upfile_store($r)
1.41      ng       13048: 
                   13049: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13050: needs $env{'form.upfile'}
1.41      ng       13051: returns $datatoken to be put into hidden field
                   13052: 
                   13053: =cut
1.31      albertel 13054: 
                   13055: sub upfile_store {
                   13056:     my $r=shift;
1.258     albertel 13057:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13058:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13059:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13060:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13061: 
1.258     albertel 13062:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   13063: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 13064:     {
1.158     raeburn  13065:         my $datafile = $r->dir_config('lonDaemons').
                   13066:                            '/tmp/'.$datatoken.'.tmp';
                   13067:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 13068:             print $fh $env{'form.upfile'};
1.158     raeburn  13069:             close($fh);
                   13070:         }
1.31      albertel 13071:     }
                   13072:     return $datatoken;
                   13073: }
                   13074: 
1.56      matthew  13075: =pod
                   13076: 
1.648     raeburn  13077: =item * &load_tmp_file($r)
1.41      ng       13078: 
                   13079: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 13080: needs $env{'form.datatoken'},
                   13081: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13082: 
                   13083: =cut
1.31      albertel 13084: 
                   13085: sub load_tmp_file {
                   13086:     my $r=shift;
                   13087:     my @studentdata=();
                   13088:     {
1.158     raeburn  13089:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 13090:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  13091:         if ( open(my $fh,"<$studentfile") ) {
                   13092:             @studentdata=<$fh>;
                   13093:             close($fh);
                   13094:         }
1.31      albertel 13095:     }
1.258     albertel 13096:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13097: }
                   13098: 
1.56      matthew  13099: =pod
                   13100: 
1.648     raeburn  13101: =item * &upfile_record_sep()
1.41      ng       13102: 
                   13103: Separate uploaded file into records
                   13104: returns array of records,
1.258     albertel 13105: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13106: 
                   13107: =cut
1.31      albertel 13108: 
                   13109: sub upfile_record_sep {
1.258     albertel 13110:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13111:     } else {
1.248     albertel 13112: 	my @records;
1.258     albertel 13113: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13114: 	    if ($line=~/^\s*$/) { next; }
                   13115: 	    push(@records,$line);
                   13116: 	}
                   13117: 	return @records;
1.31      albertel 13118:     }
                   13119: }
                   13120: 
1.56      matthew  13121: =pod
                   13122: 
1.648     raeburn  13123: =item * &record_sep($record)
1.41      ng       13124: 
1.258     albertel 13125: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13126: 
                   13127: =cut
                   13128: 
1.263     www      13129: sub takeleft {
                   13130:     my $index=shift;
                   13131:     return substr('0000'.$index,-4,4);
                   13132: }
                   13133: 
1.31      albertel 13134: sub record_sep {
                   13135:     my $record=shift;
                   13136:     my %components=();
1.258     albertel 13137:     if ($env{'form.upfiletype'} eq 'xml') {
                   13138:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13139:         my $i=0;
1.356     albertel 13140:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13141:             $field=~s/^(\"|\')//;
                   13142:             $field=~s/(\"|\')$//;
1.263     www      13143:             $components{&takeleft($i)}=$field;
1.31      albertel 13144:             $i++;
                   13145:         }
1.258     albertel 13146:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13147:         my $i=0;
1.356     albertel 13148:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13149:             $field=~s/^(\"|\')//;
                   13150:             $field=~s/(\"|\')$//;
1.263     www      13151:             $components{&takeleft($i)}=$field;
1.31      albertel 13152:             $i++;
                   13153:         }
                   13154:     } else {
1.561     www      13155:         my $separator=',';
1.480     banghart 13156:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13157:             $separator=';';
1.480     banghart 13158:         }
1.31      albertel 13159:         my $i=0;
1.561     www      13160: # the character we are looking for to indicate the end of a quote or a record 
                   13161:         my $looking_for=$separator;
                   13162: # do not add the characters to the fields
                   13163:         my $ignore=0;
                   13164: # we just encountered a separator (or the beginning of the record)
                   13165:         my $just_found_separator=1;
                   13166: # store the field we are working on here
                   13167:         my $field='';
                   13168: # work our way through all characters in record
                   13169:         foreach my $character ($record=~/(.)/g) {
                   13170:             if ($character eq $looking_for) {
                   13171:                if ($character ne $separator) {
                   13172: # Found the end of a quote, again looking for separator
                   13173:                   $looking_for=$separator;
                   13174:                   $ignore=1;
                   13175:                } else {
                   13176: # Found a separator, store away what we got
                   13177:                   $components{&takeleft($i)}=$field;
                   13178: 	          $i++;
                   13179:                   $just_found_separator=1;
                   13180:                   $ignore=0;
                   13181:                   $field='';
                   13182:                }
                   13183:                next;
                   13184:             }
                   13185: # single or double quotation marks after a separator indicate beginning of a quote
                   13186: # we are now looking for the end of the quote and need to ignore separators
                   13187:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13188:                $looking_for=$character;
                   13189:                next;
                   13190:             }
                   13191: # ignore would be true after we reached the end of a quote
                   13192:             if ($ignore) { next; }
                   13193:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13194:             $field.=$character;
                   13195:             $just_found_separator=0; 
1.31      albertel 13196:         }
1.561     www      13197: # catch the very last entry, since we never encountered the separator
                   13198:         $components{&takeleft($i)}=$field;
1.31      albertel 13199:     }
                   13200:     return %components;
                   13201: }
                   13202: 
1.144     matthew  13203: ######################################################
                   13204: ######################################################
                   13205: 
1.56      matthew  13206: =pod
                   13207: 
1.648     raeburn  13208: =item * &upfile_select_html()
1.41      ng       13209: 
1.144     matthew  13210: Return HTML code to select a file from the users machine and specify 
                   13211: the file type.
1.41      ng       13212: 
                   13213: =cut
                   13214: 
1.144     matthew  13215: ######################################################
                   13216: ######################################################
1.31      albertel 13217: sub upfile_select_html {
1.144     matthew  13218:     my %Types = (
                   13219:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13220:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13221:                  space => &mt('Space separated'),
                   13222:                  tab   => &mt('Tabulator separated'),
                   13223: #                 xml   => &mt('HTML/XML'),
                   13224:                  );
                   13225:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13226:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13227:     foreach my $type (sort(keys(%Types))) {
                   13228:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13229:     }
                   13230:     $Str .= "</select>\n";
                   13231:     return $Str;
1.31      albertel 13232: }
                   13233: 
1.301     albertel 13234: sub get_samples {
                   13235:     my ($records,$toget) = @_;
                   13236:     my @samples=({});
                   13237:     my $got=0;
                   13238:     foreach my $rec (@$records) {
                   13239: 	my %temp = &record_sep($rec);
                   13240: 	if (! grep(/\S/, values(%temp))) { next; }
                   13241: 	if (%temp) {
                   13242: 	    $samples[$got]=\%temp;
                   13243: 	    $got++;
                   13244: 	    if ($got == $toget) { last; }
                   13245: 	}
                   13246:     }
                   13247:     return \@samples;
                   13248: }
                   13249: 
1.144     matthew  13250: ######################################################
                   13251: ######################################################
                   13252: 
1.56      matthew  13253: =pod
                   13254: 
1.648     raeburn  13255: =item * &csv_print_samples($r,$records)
1.41      ng       13256: 
                   13257: Prints a table of sample values from each column uploaded $r is an
                   13258: Apache Request ref, $records is an arrayref from
                   13259: &Apache::loncommon::upfile_record_sep
                   13260: 
                   13261: =cut
                   13262: 
1.144     matthew  13263: ######################################################
                   13264: ######################################################
1.31      albertel 13265: sub csv_print_samples {
                   13266:     my ($r,$records) = @_;
1.662     bisitz   13267:     my $samples = &get_samples($records,5);
1.301     albertel 13268: 
1.594     raeburn  13269:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13270:               &start_data_table_header_row());
1.356     albertel 13271:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13272:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13273:     $r->print(&end_data_table_header_row());
1.301     albertel 13274:     foreach my $hash (@$samples) {
1.594     raeburn  13275: 	$r->print(&start_data_table_row());
1.356     albertel 13276: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13277: 	    $r->print('<td>');
1.356     albertel 13278: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13279: 	    $r->print('</td>');
                   13280: 	}
1.594     raeburn  13281: 	$r->print(&end_data_table_row());
1.31      albertel 13282:     }
1.594     raeburn  13283:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13284: }
                   13285: 
1.144     matthew  13286: ######################################################
                   13287: ######################################################
                   13288: 
1.56      matthew  13289: =pod
                   13290: 
1.648     raeburn  13291: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13292: 
                   13293: Prints a table to create associations between values and table columns.
1.144     matthew  13294: 
1.41      ng       13295: $r is an Apache Request ref,
                   13296: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13297: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13298: 
                   13299: =cut
                   13300: 
1.144     matthew  13301: ######################################################
                   13302: ######################################################
1.31      albertel 13303: sub csv_print_select_table {
                   13304:     my ($r,$records,$d) = @_;
1.301     albertel 13305:     my $i=0;
                   13306:     my $samples = &get_samples($records,1);
1.144     matthew  13307:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13308: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13309:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13310:               '<th>'.&mt('Column').'</th>'.
                   13311:               &end_data_table_header_row()."\n");
1.356     albertel 13312:     foreach my $array_ref (@$d) {
                   13313: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13314: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13315: 
1.875     bisitz   13316: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13317: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13318: 	$r->print('<option value="none"></option>');
1.356     albertel 13319: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13320: 	    $r->print('<option value="'.$sample.'"'.
                   13321:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13322:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13323: 	}
1.594     raeburn  13324: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13325: 	$i++;
                   13326:     }
1.594     raeburn  13327:     $r->print(&end_data_table());
1.31      albertel 13328:     $i--;
                   13329:     return $i;
                   13330: }
1.56      matthew  13331: 
1.144     matthew  13332: ######################################################
                   13333: ######################################################
                   13334: 
1.56      matthew  13335: =pod
1.31      albertel 13336: 
1.648     raeburn  13337: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13338: 
                   13339: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13340: 
                   13341: $r is an Apache Request ref,
                   13342: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13343: $d is an array of 2 element arrays (internal name, displayed name)
                   13344: 
                   13345: =cut
                   13346: 
1.144     matthew  13347: ######################################################
                   13348: ######################################################
1.31      albertel 13349: sub csv_samples_select_table {
                   13350:     my ($r,$records,$d) = @_;
                   13351:     my $i=0;
1.144     matthew  13352:     #
1.662     bisitz   13353:     my $max_samples = 5;
                   13354:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13355:     $r->print(&start_data_table().
                   13356:               &start_data_table_header_row().'<th>'.
                   13357:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13358:               &end_data_table_header_row());
1.301     albertel 13359: 
                   13360:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13361: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13362: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13363: 	foreach my $option (@$d) {
                   13364: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13365: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13366:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13367:                       $display.'</option>');
1.31      albertel 13368: 	}
                   13369: 	$r->print('</select></td><td>');
1.662     bisitz   13370: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13371: 	    if (defined($samples->[$line]{$key})) { 
                   13372: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13373: 	    }
                   13374: 	}
1.594     raeburn  13375: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13376: 	$i++;
                   13377:     }
1.594     raeburn  13378:     $r->print(&end_data_table());
1.31      albertel 13379:     $i--;
                   13380:     return($i);
1.115     matthew  13381: }
                   13382: 
1.144     matthew  13383: ######################################################
                   13384: ######################################################
                   13385: 
1.115     matthew  13386: =pod
                   13387: 
1.648     raeburn  13388: =item * &clean_excel_name($name)
1.115     matthew  13389: 
                   13390: Returns a replacement for $name which does not contain any illegal characters.
                   13391: 
                   13392: =cut
                   13393: 
1.144     matthew  13394: ######################################################
                   13395: ######################################################
1.115     matthew  13396: sub clean_excel_name {
                   13397:     my ($name) = @_;
                   13398:     $name =~ s/[:\*\?\/\\]//g;
                   13399:     if (length($name) > 31) {
                   13400:         $name = substr($name,0,31);
                   13401:     }
                   13402:     return $name;
1.25      albertel 13403: }
1.84      albertel 13404: 
1.85      albertel 13405: =pod
                   13406: 
1.648     raeburn  13407: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13408: 
                   13409: Returns either 1 or undef
                   13410: 
                   13411: 1 if the part is to be hidden, undef if it is to be shown
                   13412: 
                   13413: Arguments are:
                   13414: 
                   13415: $id the id of the part to be checked
                   13416: $symb, optional the symb of the resource to check
                   13417: $udom, optional the domain of the user to check for
                   13418: $uname, optional the username of the user to check for
                   13419: 
                   13420: =cut
1.84      albertel 13421: 
                   13422: sub check_if_partid_hidden {
                   13423:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13424:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13425: 					 $symb,$udom,$uname);
1.141     albertel 13426:     my $truth=1;
                   13427:     #if the string starts with !, then the list is the list to show not hide
                   13428:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13429:     my @hiddenlist=split(/,/,$hiddenparts);
                   13430:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13431: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13432:     }
1.141     albertel 13433:     return !$truth;
1.84      albertel 13434: }
1.127     matthew  13435: 
1.138     matthew  13436: 
                   13437: ############################################################
                   13438: ############################################################
                   13439: 
                   13440: =pod
                   13441: 
1.157     matthew  13442: =back 
                   13443: 
1.138     matthew  13444: =head1 cgi-bin script and graphing routines
                   13445: 
1.157     matthew  13446: =over 4
                   13447: 
1.648     raeburn  13448: =item * &get_cgi_id()
1.138     matthew  13449: 
                   13450: Inputs: none
                   13451: 
                   13452: Returns an id which can be used to pass environment variables
                   13453: to various cgi-bin scripts.  These environment variables will
                   13454: be removed from the users environment after a given time by
                   13455: the routine &Apache::lonnet::transfer_profile_to_env.
                   13456: 
                   13457: =cut
                   13458: 
                   13459: ############################################################
                   13460: ############################################################
1.152     albertel 13461: my $uniq=0;
1.136     matthew  13462: sub get_cgi_id {
1.154     albertel 13463:     $uniq=($uniq+1)%100000;
1.280     albertel 13464:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13465: }
                   13466: 
1.127     matthew  13467: ############################################################
                   13468: ############################################################
                   13469: 
                   13470: =pod
                   13471: 
1.648     raeburn  13472: =item * &DrawBarGraph()
1.127     matthew  13473: 
1.138     matthew  13474: Facilitates the plotting of data in a (stacked) bar graph.
                   13475: Puts plot definition data into the users environment in order for 
                   13476: graph.png to plot it.  Returns an <img> tag for the plot.
                   13477: The bars on the plot are labeled '1','2',...,'n'.
                   13478: 
                   13479: Inputs:
                   13480: 
                   13481: =over 4
                   13482: 
                   13483: =item $Title: string, the title of the plot
                   13484: 
                   13485: =item $xlabel: string, text describing the X-axis of the plot
                   13486: 
                   13487: =item $ylabel: string, text describing the Y-axis of the plot
                   13488: 
                   13489: =item $Max: scalar, the maximum Y value to use in the plot
                   13490: If $Max is < any data point, the graph will not be rendered.
                   13491: 
1.140     matthew  13492: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13493: they are plotted.  If undefined, default values will be used.
                   13494: 
1.178     matthew  13495: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13496: 
1.138     matthew  13497: =item @Values: An array of array references.  Each array reference holds data
                   13498: to be plotted in a stacked bar chart.
                   13499: 
1.239     matthew  13500: =item If the final element of @Values is a hash reference the key/value
                   13501: pairs will be added to the graph definition.
                   13502: 
1.138     matthew  13503: =back
                   13504: 
                   13505: Returns:
                   13506: 
                   13507: An <img> tag which references graph.png and the appropriate identifying
                   13508: information for the plot.
                   13509: 
1.127     matthew  13510: =cut
                   13511: 
                   13512: ############################################################
                   13513: ############################################################
1.134     matthew  13514: sub DrawBarGraph {
1.178     matthew  13515:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13516:     #
                   13517:     if (! defined($colors)) {
                   13518:         $colors = ['#33ff00', 
                   13519:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13520:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13521:                   ]; 
                   13522:     }
1.228     matthew  13523:     my $extra_settings = {};
                   13524:     if (ref($Values[-1]) eq 'HASH') {
                   13525:         $extra_settings = pop(@Values);
                   13526:     }
1.127     matthew  13527:     #
1.136     matthew  13528:     my $identifier = &get_cgi_id();
                   13529:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13530:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13531:         return '';
                   13532:     }
1.225     matthew  13533:     #
                   13534:     my @Labels;
                   13535:     if (defined($labels)) {
                   13536:         @Labels = @$labels;
                   13537:     } else {
                   13538:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1075.2.119  raeburn  13539:             push(@Labels,$i+1);
1.225     matthew  13540:         }
                   13541:     }
                   13542:     #
1.129     matthew  13543:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13544:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13545:     my %ValuesHash;
                   13546:     my $NumSets=1;
                   13547:     foreach my $array (@Values) {
                   13548:         next if (! ref($array));
1.136     matthew  13549:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13550:             join(',',@$array);
1.129     matthew  13551:     }
1.127     matthew  13552:     #
1.136     matthew  13553:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13554:     if ($NumBars < 3) {
                   13555:         $width = 120+$NumBars*32;
1.220     matthew  13556:         $xskip = 1;
1.225     matthew  13557:         $bar_width = 30;
                   13558:     } elsif ($NumBars < 5) {
                   13559:         $width = 120+$NumBars*20;
                   13560:         $xskip = 1;
                   13561:         $bar_width = 20;
1.220     matthew  13562:     } elsif ($NumBars < 10) {
1.136     matthew  13563:         $width = 120+$NumBars*15;
                   13564:         $xskip = 1;
                   13565:         $bar_width = 15;
                   13566:     } elsif ($NumBars <= 25) {
                   13567:         $width = 120+$NumBars*11;
                   13568:         $xskip = 5;
                   13569:         $bar_width = 8;
                   13570:     } elsif ($NumBars <= 50) {
                   13571:         $width = 120+$NumBars*8;
                   13572:         $xskip = 5;
                   13573:         $bar_width = 4;
                   13574:     } else {
                   13575:         $width = 120+$NumBars*8;
                   13576:         $xskip = 5;
                   13577:         $bar_width = 4;
                   13578:     }
                   13579:     #
1.137     matthew  13580:     $Max = 1 if ($Max < 1);
                   13581:     if ( int($Max) < $Max ) {
                   13582:         $Max++;
                   13583:         $Max = int($Max);
                   13584:     }
1.127     matthew  13585:     $Title  = '' if (! defined($Title));
                   13586:     $xlabel = '' if (! defined($xlabel));
                   13587:     $ylabel = '' if (! defined($ylabel));
1.369     www      13588:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13589:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13590:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13591:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13592:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13593:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13594:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13595:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13596:     $ValuesHash{$id.'.height'}   = $height;
                   13597:     $ValuesHash{$id.'.width'}    = $width;
                   13598:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13599:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13600:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13601:     #
1.228     matthew  13602:     # Deal with other parameters
                   13603:     while (my ($key,$value) = each(%$extra_settings)) {
                   13604:         $ValuesHash{$id.'.'.$key} = $value;
                   13605:     }
                   13606:     #
1.646     raeburn  13607:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13608:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13609: }
                   13610: 
                   13611: ############################################################
                   13612: ############################################################
                   13613: 
                   13614: =pod
                   13615: 
1.648     raeburn  13616: =item * &DrawXYGraph()
1.137     matthew  13617: 
1.138     matthew  13618: Facilitates the plotting of data in an XY graph.
                   13619: Puts plot definition data into the users environment in order for 
                   13620: graph.png to plot it.  Returns an <img> tag for the plot.
                   13621: 
                   13622: Inputs:
                   13623: 
                   13624: =over 4
                   13625: 
                   13626: =item $Title: string, the title of the plot
                   13627: 
                   13628: =item $xlabel: string, text describing the X-axis of the plot
                   13629: 
                   13630: =item $ylabel: string, text describing the Y-axis of the plot
                   13631: 
                   13632: =item $Max: scalar, the maximum Y value to use in the plot
                   13633: If $Max is < any data point, the graph will not be rendered.
                   13634: 
                   13635: =item $colors: Array ref containing the hex color codes for the data to be 
                   13636: plotted in.  If undefined, default values will be used.
                   13637: 
                   13638: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13639: 
                   13640: =item $Ydata: Array ref containing Array refs.  
1.185     www      13641: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13642: 
                   13643: =item %Values: hash indicating or overriding any default values which are 
                   13644: passed to graph.png.  
                   13645: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13646: 
                   13647: =back
                   13648: 
                   13649: Returns:
                   13650: 
                   13651: An <img> tag which references graph.png and the appropriate identifying
                   13652: information for the plot.
                   13653: 
1.137     matthew  13654: =cut
                   13655: 
                   13656: ############################################################
                   13657: ############################################################
                   13658: sub DrawXYGraph {
                   13659:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13660:     #
                   13661:     # Create the identifier for the graph
                   13662:     my $identifier = &get_cgi_id();
                   13663:     my $id = 'cgi.'.$identifier;
                   13664:     #
                   13665:     $Title  = '' if (! defined($Title));
                   13666:     $xlabel = '' if (! defined($xlabel));
                   13667:     $ylabel = '' if (! defined($ylabel));
                   13668:     my %ValuesHash = 
                   13669:         (
1.369     www      13670:          $id.'.title'  => &escape($Title),
                   13671:          $id.'.xlabel' => &escape($xlabel),
                   13672:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13673:          $id.'.y_max_value'=> $Max,
                   13674:          $id.'.labels'     => join(',',@$Xlabels),
                   13675:          $id.'.PlotType'   => 'XY',
                   13676:          );
                   13677:     #
                   13678:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13679:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13680:     }
                   13681:     #
                   13682:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13683:         return '';
                   13684:     }
                   13685:     my $NumSets=1;
1.138     matthew  13686:     foreach my $array (@{$Ydata}){
1.137     matthew  13687:         next if (! ref($array));
                   13688:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13689:     }
1.138     matthew  13690:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  13691:     #
                   13692:     # Deal with other parameters
                   13693:     while (my ($key,$value) = each(%Values)) {
                   13694:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  13695:     }
                   13696:     #
1.646     raeburn  13697:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  13698:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13699: }
                   13700: 
                   13701: ############################################################
                   13702: ############################################################
                   13703: 
                   13704: =pod
                   13705: 
1.648     raeburn  13706: =item * &DrawXYYGraph()
1.138     matthew  13707: 
                   13708: Facilitates the plotting of data in an XY graph with two Y axes.
                   13709: Puts plot definition data into the users environment in order for 
                   13710: graph.png to plot it.  Returns an <img> tag for the plot.
                   13711: 
                   13712: Inputs:
                   13713: 
                   13714: =over 4
                   13715: 
                   13716: =item $Title: string, the title of the plot
                   13717: 
                   13718: =item $xlabel: string, text describing the X-axis of the plot
                   13719: 
                   13720: =item $ylabel: string, text describing the Y-axis of the plot
                   13721: 
                   13722: =item $colors: Array ref containing the hex color codes for the data to be 
                   13723: plotted in.  If undefined, default values will be used.
                   13724: 
                   13725: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13726: 
                   13727: =item $Ydata1: The first data set
                   13728: 
                   13729: =item $Min1: The minimum value of the left Y-axis
                   13730: 
                   13731: =item $Max1: The maximum value of the left Y-axis
                   13732: 
                   13733: =item $Ydata2: The second data set
                   13734: 
                   13735: =item $Min2: The minimum value of the right Y-axis
                   13736: 
                   13737: =item $Max2: The maximum value of the left Y-axis
                   13738: 
                   13739: =item %Values: hash indicating or overriding any default values which are 
                   13740: passed to graph.png.  
                   13741: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13742: 
                   13743: =back
                   13744: 
                   13745: Returns:
                   13746: 
                   13747: An <img> tag which references graph.png and the appropriate identifying
                   13748: information for the plot.
1.136     matthew  13749: 
                   13750: =cut
                   13751: 
                   13752: ############################################################
                   13753: ############################################################
1.137     matthew  13754: sub DrawXYYGraph {
                   13755:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   13756:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  13757:     #
                   13758:     # Create the identifier for the graph
                   13759:     my $identifier = &get_cgi_id();
                   13760:     my $id = 'cgi.'.$identifier;
                   13761:     #
                   13762:     $Title  = '' if (! defined($Title));
                   13763:     $xlabel = '' if (! defined($xlabel));
                   13764:     $ylabel = '' if (! defined($ylabel));
                   13765:     my %ValuesHash = 
                   13766:         (
1.369     www      13767:          $id.'.title'  => &escape($Title),
                   13768:          $id.'.xlabel' => &escape($xlabel),
                   13769:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  13770:          $id.'.labels' => join(',',@$Xlabels),
                   13771:          $id.'.PlotType' => 'XY',
                   13772:          $id.'.NumSets' => 2,
1.137     matthew  13773:          $id.'.two_axes' => 1,
                   13774:          $id.'.y1_max_value' => $Max1,
                   13775:          $id.'.y1_min_value' => $Min1,
                   13776:          $id.'.y2_max_value' => $Max2,
                   13777:          $id.'.y2_min_value' => $Min2,
1.136     matthew  13778:          );
                   13779:     #
1.137     matthew  13780:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13781:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13782:     }
                   13783:     #
                   13784:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   13785:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  13786:         return '';
                   13787:     }
                   13788:     my $NumSets=1;
1.137     matthew  13789:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  13790:         next if (! ref($array));
                   13791:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  13792:     }
                   13793:     #
                   13794:     # Deal with other parameters
                   13795:     while (my ($key,$value) = each(%Values)) {
                   13796:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  13797:     }
                   13798:     #
1.646     raeburn  13799:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 13800:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  13801: }
                   13802: 
                   13803: ############################################################
                   13804: ############################################################
                   13805: 
                   13806: =pod
                   13807: 
1.157     matthew  13808: =back 
                   13809: 
1.139     matthew  13810: =head1 Statistics helper routines?  
                   13811: 
                   13812: Bad place for them but what the hell.
                   13813: 
1.157     matthew  13814: =over 4
                   13815: 
1.648     raeburn  13816: =item * &chartlink()
1.139     matthew  13817: 
                   13818: Returns a link to the chart for a specific student.  
                   13819: 
                   13820: Inputs:
                   13821: 
                   13822: =over 4
                   13823: 
                   13824: =item $linktext: The text of the link
                   13825: 
                   13826: =item $sname: The students username
                   13827: 
                   13828: =item $sdomain: The students domain
                   13829: 
                   13830: =back
                   13831: 
1.157     matthew  13832: =back
                   13833: 
1.139     matthew  13834: =cut
                   13835: 
                   13836: ############################################################
                   13837: ############################################################
                   13838: sub chartlink {
                   13839:     my ($linktext, $sname, $sdomain) = @_;
                   13840:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      13841:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 13842:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  13843:        '">'.$linktext.'</a>';
1.153     matthew  13844: }
                   13845: 
                   13846: #######################################################
                   13847: #######################################################
                   13848: 
                   13849: =pod
                   13850: 
                   13851: =head1 Course Environment Routines
1.157     matthew  13852: 
                   13853: =over 4
1.153     matthew  13854: 
1.648     raeburn  13855: =item * &restore_course_settings()
1.153     matthew  13856: 
1.648     raeburn  13857: =item * &store_course_settings()
1.153     matthew  13858: 
                   13859: Restores/Store indicated form parameters from the course environment.
                   13860: Will not overwrite existing values of the form parameters.
                   13861: 
                   13862: Inputs: 
                   13863: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   13864: 
                   13865: a hash ref describing the data to be stored.  For example:
                   13866:    
                   13867: %Save_Parameters = ('Status' => 'scalar',
                   13868:     'chartoutputmode' => 'scalar',
                   13869:     'chartoutputdata' => 'scalar',
                   13870:     'Section' => 'array',
1.373     raeburn  13871:     'Group' => 'array',
1.153     matthew  13872:     'StudentData' => 'array',
                   13873:     'Maps' => 'array');
                   13874: 
                   13875: Returns: both routines return nothing
                   13876: 
1.631     raeburn  13877: =back
                   13878: 
1.153     matthew  13879: =cut
                   13880: 
                   13881: #######################################################
                   13882: #######################################################
                   13883: sub store_course_settings {
1.496     albertel 13884:     return &store_settings($env{'request.course.id'},@_);
                   13885: }
                   13886: 
                   13887: sub store_settings {
1.153     matthew  13888:     # save to the environment
                   13889:     # appenv the same items, just to be safe
1.300     albertel 13890:     my $udom  = $env{'user.domain'};
                   13891:     my $uname = $env{'user.name'};
1.496     albertel 13892:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13893:     my %SaveHash;
                   13894:     my %AppHash;
                   13895:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 13896:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 13897:         my $envname = 'environment.'.$basename;
1.258     albertel 13898:         if (exists($env{'form.'.$setting})) {
1.153     matthew  13899:             # Save this value away
                   13900:             if ($type eq 'scalar' &&
1.258     albertel 13901:                 (! exists($env{$envname}) || 
                   13902:                  $env{$envname} ne $env{'form.'.$setting})) {
                   13903:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   13904:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  13905:             } elsif ($type eq 'array') {
                   13906:                 my $stored_form;
1.258     albertel 13907:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  13908:                     $stored_form = join(',',
                   13909:                                         map {
1.369     www      13910:                                             &escape($_);
1.258     albertel 13911:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  13912:                 } else {
                   13913:                     $stored_form = 
1.369     www      13914:                         &escape($env{'form.'.$setting});
1.153     matthew  13915:                 }
                   13916:                 # Determine if the array contents are the same.
1.258     albertel 13917:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  13918:                     $SaveHash{$basename} = $stored_form;
                   13919:                     $AppHash{$envname}   = $stored_form;
                   13920:                 }
                   13921:             }
                   13922:         }
                   13923:     }
                   13924:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 13925:                                           $udom,$uname);
1.153     matthew  13926:     if ($put_result !~ /^(ok|delayed)/) {
                   13927:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   13928:                                  'got error:'.$put_result);
                   13929:     }
                   13930:     # Make sure these settings stick around in this session, too
1.646     raeburn  13931:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  13932:     return;
                   13933: }
                   13934: 
                   13935: sub restore_course_settings {
1.499     albertel 13936:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 13937: }
                   13938: 
                   13939: sub restore_settings {
                   13940:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13941:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 13942:         next if (exists($env{'form.'.$setting}));
1.496     albertel 13943:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  13944:             '.'.$setting;
1.258     albertel 13945:         if (exists($env{$envname})) {
1.153     matthew  13946:             if ($type eq 'scalar') {
1.258     albertel 13947:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  13948:             } elsif ($type eq 'array') {
1.258     albertel 13949:                 $env{'form.'.$setting} = [ 
1.153     matthew  13950:                                            map { 
1.369     www      13951:                                                &unescape($_); 
1.258     albertel 13952:                                            } split(',',$env{$envname})
1.153     matthew  13953:                                            ];
                   13954:             }
                   13955:         }
                   13956:     }
1.127     matthew  13957: }
                   13958: 
1.618     raeburn  13959: #######################################################
                   13960: #######################################################
                   13961: 
                   13962: =pod
                   13963: 
                   13964: =head1 Domain E-mail Routines  
                   13965: 
                   13966: =over 4
                   13967: 
1.648     raeburn  13968: =item * &build_recipient_list()
1.618     raeburn  13969: 
1.1075.2.44  raeburn  13970: Build recipient lists for following types of e-mail:
1.766     raeburn  13971: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  13972: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   13973: module change checking, student/employee ID conflict checks, as
                   13974: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   13975: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  13976: 
                   13977: Inputs:
1.1075.2.44  raeburn  13978: defmail (scalar - email address of default recipient),
                   13979: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   13980: requestsmail, updatesmail, or idconflictsmail).
                   13981: 
1.619     raeburn  13982: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  13983: 
                   13984: origmail (scalar - email address of recipient from loncapa.conf,
                   13985: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  13986: 
1.655     raeburn  13987: Returns: comma separated list of addresses to which to send e-mail.
                   13988: 
                   13989: =back
1.618     raeburn  13990: 
                   13991: =cut
                   13992: 
                   13993: ############################################################
                   13994: ############################################################
                   13995: sub build_recipient_list {
1.619     raeburn  13996:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  13997:     my @recipients;
1.1075.2.122  raeburn  13998:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  13999:     my %domconfig =
1.1075.2.122  raeburn  14000:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14001:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14002:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14003:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14004:                 my @contacts = ('adminemail','supportemail');
                   14005:                 foreach my $item (@contacts) {
                   14006:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14007:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14008:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14009:                             push(@recipients,$addr);
                   14010:                         }
1.619     raeburn  14011:                     }
1.1075.2.122  raeburn  14012:                 }
                   14013:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   14014:                 if ($mailing eq 'helpdeskmail') {
                   14015:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   14016:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   14017:                         my @ok_bccs;
                   14018:                         foreach my $bcc (@bccs) {
                   14019:                             $bcc =~ s/^\s+//g;
                   14020:                             $bcc =~ s/\s+$//g;
                   14021:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14022:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14023:                                     push(@ok_bccs,$bcc);
                   14024:                                 }
                   14025:                             }
                   14026:                         }
                   14027:                         if (@ok_bccs > 0) {
                   14028:                             $allbcc = join(', ',@ok_bccs);
                   14029:                         }
                   14030:                     }
                   14031:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  14032:                 }
                   14033:             }
1.766     raeburn  14034:         } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14035:             $lastresort = $origmail;
1.618     raeburn  14036:         }
1.619     raeburn  14037:     } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14038:         $lastresort = $origmail;
                   14039:     }
                   14040: 
                   14041:     if (($mailing eq 'helpdesk') && ($lastresort ne '')) {
                   14042:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   14043:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   14044:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14045:             my %what = (
                   14046:                           perlvar => 1,
                   14047:                        );
                   14048:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   14049:             if ($primary) {
                   14050:                 my $gotaddr;
                   14051:                 my ($result,$returnhash) =
                   14052:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   14053:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   14054:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   14055:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   14056:                         $gotaddr = 1;
                   14057:                     }
                   14058:                 }
                   14059:                 unless ($gotaddr) {
                   14060:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   14061:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   14062:                     unless ($uintdom eq $intdom) {
                   14063:                         my %domconfig =
                   14064:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   14065:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   14066:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   14067:                                 my @contacts = ('adminemail','supportemail');
                   14068:                                 foreach my $item (@contacts) {
                   14069:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   14070:                                         my $addr = $domconfig{'contacts'}{$item};
                   14071:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14072:                                             push(@recipients,$addr);
                   14073:                                         }
                   14074:                                     }
                   14075:                                 }
                   14076:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   14077:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   14078:                                 }
                   14079:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   14080:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   14081:                                     my @ok_bccs;
                   14082:                                     foreach my $bcc (@bccs) {
                   14083:                                         $bcc =~ s/^\s+//g;
                   14084:                                         $bcc =~ s/\s+$//g;
                   14085:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14086:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14087:                                                 push(@ok_bccs,$bcc);
                   14088:                                             }
                   14089:                                         }
                   14090:                                     }
                   14091:                                     if (@ok_bccs > 0) {
                   14092:                                         $allbcc = join(', ',@ok_bccs);
                   14093:                                     }
                   14094:                                 }
                   14095:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   14096:                             }
                   14097:                         }
                   14098:                     }
                   14099:                 }
                   14100:             }
                   14101:         }
1.618     raeburn  14102:     }
1.688     raeburn  14103:     if (defined($defmail)) {
                   14104:         if ($defmail ne '') {
                   14105:             push(@recipients,$defmail);
                   14106:         }
1.618     raeburn  14107:     }
                   14108:     if ($otheremails) {
1.619     raeburn  14109:         my @others;
                   14110:         if ($otheremails =~ /,/) {
                   14111:             @others = split(/,/,$otheremails);
1.618     raeburn  14112:         } else {
1.619     raeburn  14113:             push(@others,$otheremails);
                   14114:         }
                   14115:         foreach my $addr (@others) {
                   14116:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14117:                 push(@recipients,$addr);
                   14118:             }
1.618     raeburn  14119:         }
                   14120:     }
1.1075.2.122  raeburn  14121:     if ($mailing eq 'helpdesk') {
                   14122:         if ((!@recipients) && ($lastresort ne '')) {
                   14123:             push(@recipients,$lastresort);
                   14124:         }
                   14125:     } elsif ($lastresort ne '') {
                   14126:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   14127:             push(@recipients,$lastresort);
                   14128:         }
                   14129:     }
                   14130:     my $recipientlist = join(',',@recipients);
                   14131:     if (wantarray) {
                   14132:         return ($recipientlist,$allbcc,$addtext);
                   14133:     } else {
                   14134:         return $recipientlist;
                   14135:     }
1.618     raeburn  14136: }
                   14137: 
1.127     matthew  14138: ############################################################
                   14139: ############################################################
1.154     albertel 14140: 
1.655     raeburn  14141: =pod
                   14142: 
                   14143: =head1 Course Catalog Routines
                   14144: 
                   14145: =over 4
                   14146: 
                   14147: =item * &gather_categories()
                   14148: 
                   14149: Converts category definitions - keys of categories hash stored in  
                   14150: coursecategories in configuration.db on the primary library server in a 
                   14151: domain - to an array.  Also generates javascript and idx hash used to 
                   14152: generate Domain Coordinator interface for editing Course Categories.
                   14153: 
                   14154: Inputs:
1.663     raeburn  14155: 
1.655     raeburn  14156: categories (reference to hash of category definitions).
1.663     raeburn  14157: 
1.655     raeburn  14158: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14159:       categories and subcategories).
1.663     raeburn  14160: 
1.655     raeburn  14161: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14162:       editing Course Categories).
1.663     raeburn  14163: 
1.655     raeburn  14164: jsarray (reference to array of categories used to create Javascript arrays for
                   14165:          Domain Coordinator interface for editing Course Categories).
                   14166: 
                   14167: Returns: nothing
                   14168: 
                   14169: Side effects: populates cats, idx and jsarray. 
                   14170: 
                   14171: =cut
                   14172: 
                   14173: sub gather_categories {
                   14174:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14175:     my %counters;
                   14176:     my $num = 0;
                   14177:     foreach my $item (keys(%{$categories})) {
                   14178:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14179:         if ($container eq '' && $depth == 0) {
                   14180:             $cats->[$depth][$categories->{$item}] = $cat;
                   14181:         } else {
                   14182:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14183:         }
                   14184:         my ($escitem,$tail) = split(/:/,$item,2);
                   14185:         if ($counters{$tail} eq '') {
                   14186:             $counters{$tail} = $num;
                   14187:             $num ++;
                   14188:         }
                   14189:         if (ref($idx) eq 'HASH') {
                   14190:             $idx->{$item} = $counters{$tail};
                   14191:         }
                   14192:         if (ref($jsarray) eq 'ARRAY') {
                   14193:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14194:         }
                   14195:     }
                   14196:     return;
                   14197: }
                   14198: 
                   14199: =pod
                   14200: 
                   14201: =item * &extract_categories()
                   14202: 
                   14203: Used to generate breadcrumb trails for course categories.
                   14204: 
                   14205: Inputs:
1.663     raeburn  14206: 
1.655     raeburn  14207: categories (reference to hash of category definitions).
1.663     raeburn  14208: 
1.655     raeburn  14209: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14210:       categories and subcategories).
1.663     raeburn  14211: 
1.655     raeburn  14212: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14213: 
1.655     raeburn  14214: allitems (reference to hash - key is category key 
                   14215:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14216: 
1.655     raeburn  14217: idx (reference to hash of counters used in Domain Coordinator interface for
                   14218:       editing Course Categories).
1.663     raeburn  14219: 
1.655     raeburn  14220: jsarray (reference to array of categories used to create Javascript arrays for
                   14221:          Domain Coordinator interface for editing Course Categories).
                   14222: 
1.665     raeburn  14223: subcats (reference to hash of arrays containing all subcategories within each 
                   14224:          category, -recursive)
                   14225: 
1.655     raeburn  14226: Returns: nothing
                   14227: 
                   14228: Side effects: populates trails and allitems hash references.
                   14229: 
                   14230: =cut
                   14231: 
                   14232: sub extract_categories {
1.665     raeburn  14233:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  14234:     if (ref($categories) eq 'HASH') {
                   14235:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14236:         if (ref($cats->[0]) eq 'ARRAY') {
                   14237:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14238:                 my $name = $cats->[0][$i];
                   14239:                 my $item = &escape($name).'::0';
                   14240:                 my $trailstr;
                   14241:                 if ($name eq 'instcode') {
                   14242:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14243:                 } elsif ($name eq 'communities') {
                   14244:                     $trailstr = &mt('Communities');
1.655     raeburn  14245:                 } else {
                   14246:                     $trailstr = $name;
                   14247:                 }
                   14248:                 if ($allitems->{$item} eq '') {
                   14249:                     push(@{$trails},$trailstr);
                   14250:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14251:                 }
                   14252:                 my @parents = ($name);
                   14253:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14254:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14255:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14256:                         if (ref($subcats) eq 'HASH') {
                   14257:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14258:                         }
                   14259:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   14260:                     }
                   14261:                 } else {
                   14262:                     if (ref($subcats) eq 'HASH') {
                   14263:                         $subcats->{$item} = [];
1.655     raeburn  14264:                     }
                   14265:                 }
                   14266:             }
                   14267:         }
                   14268:     }
                   14269:     return;
                   14270: }
                   14271: 
                   14272: =pod
                   14273: 
1.1075.2.56  raeburn  14274: =item * &recurse_categories()
1.655     raeburn  14275: 
                   14276: Recursively used to generate breadcrumb trails for course categories.
                   14277: 
                   14278: Inputs:
1.663     raeburn  14279: 
1.655     raeburn  14280: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14281:       categories and subcategories).
1.663     raeburn  14282: 
1.655     raeburn  14283: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14284: 
                   14285: category (current course category, for which breadcrumb trail is being generated).
                   14286: 
                   14287: trails (reference to array of breadcrumb trails for each category).
                   14288: 
1.655     raeburn  14289: allitems (reference to hash - key is category key
                   14290:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14291: 
1.655     raeburn  14292: parents (array containing containers directories for current category, 
                   14293:          back to top level). 
                   14294: 
                   14295: Returns: nothing
                   14296: 
                   14297: Side effects: populates trails and allitems hash references
                   14298: 
                   14299: =cut
                   14300: 
                   14301: sub recurse_categories {
1.665     raeburn  14302:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  14303:     my $shallower = $depth - 1;
                   14304:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14305:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14306:             my $name = $cats->[$depth]{$category}[$k];
                   14307:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14308:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14309:             if ($allitems->{$item} eq '') {
                   14310:                 push(@{$trails},$trailstr);
                   14311:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14312:             }
                   14313:             my $deeper = $depth+1;
                   14314:             push(@{$parents},$category);
1.665     raeburn  14315:             if (ref($subcats) eq 'HASH') {
                   14316:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14317:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14318:                     my $higher;
                   14319:                     if ($j > 0) {
                   14320:                         $higher = &escape($parents->[$j]).':'.
                   14321:                                   &escape($parents->[$j-1]).':'.$j;
                   14322:                     } else {
                   14323:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14324:                     }
                   14325:                     push(@{$subcats->{$higher}},$subcat);
                   14326:                 }
                   14327:             }
                   14328:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   14329:                                 $subcats);
1.655     raeburn  14330:             pop(@{$parents});
                   14331:         }
                   14332:     } else {
                   14333:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14334:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14335:         if ($allitems->{$item} eq '') {
                   14336:             push(@{$trails},$trailstr);
                   14337:             $allitems->{$item} = scalar(@{$trails})-1;
                   14338:         }
                   14339:     }
                   14340:     return;
                   14341: }
                   14342: 
1.663     raeburn  14343: =pod
                   14344: 
1.1075.2.56  raeburn  14345: =item * &assign_categories_table()
1.663     raeburn  14346: 
                   14347: Create a datatable for display of hierarchical categories in a domain,
                   14348: with checkboxes to allow a course to be categorized. 
                   14349: 
                   14350: Inputs:
                   14351: 
                   14352: cathash - reference to hash of categories defined for the domain (from
                   14353:           configuration.db)
                   14354: 
                   14355: currcat - scalar with an & separated list of categories assigned to a course. 
                   14356: 
1.919     raeburn  14357: type    - scalar contains course type (Course or Community).
                   14358: 
1.1075.2.117  raeburn  14359: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14360:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14361: 
1.663     raeburn  14362: Returns: $output (markup to be displayed) 
                   14363: 
                   14364: =cut
                   14365: 
                   14366: sub assign_categories_table {
1.1075.2.117  raeburn  14367:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  14368:     my $output;
                   14369:     if (ref($cathash) eq 'HASH') {
                   14370:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   14371:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   14372:         $maxdepth = scalar(@cats);
                   14373:         if (@cats > 0) {
                   14374:             my $itemcount = 0;
                   14375:             if (ref($cats[0]) eq 'ARRAY') {
                   14376:                 my @currcategories;
                   14377:                 if ($currcat ne '') {
                   14378:                     @currcategories = split('&',$currcat);
                   14379:                 }
1.919     raeburn  14380:                 my $table;
1.663     raeburn  14381:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14382:                     my $parent = $cats[0][$i];
1.919     raeburn  14383:                     next if ($parent eq 'instcode');
                   14384:                     if ($type eq 'Community') {
                   14385:                         next unless ($parent eq 'communities');
                   14386:                     } else {
                   14387:                         next if ($parent eq 'communities');
                   14388:                     }
1.663     raeburn  14389:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14390:                     my $item = &escape($parent).'::0';
                   14391:                     my $checked = '';
                   14392:                     if (@currcategories > 0) {
                   14393:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14394:                             $checked = ' checked="checked"';
1.663     raeburn  14395:                         }
                   14396:                     }
1.919     raeburn  14397:                     my $parent_title = $parent;
                   14398:                     if ($parent eq 'communities') {
                   14399:                         $parent_title = &mt('Communities');
                   14400:                     }
                   14401:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14402:                               '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14403:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  14404:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14405:                     my $depth = 1;
                   14406:                     push(@path,$parent);
1.1075.2.117  raeburn  14407:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  14408:                     pop(@path);
1.919     raeburn  14409:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14410:                     $itemcount ++;
                   14411:                 }
1.919     raeburn  14412:                 if ($itemcount) {
                   14413:                     $output = &Apache::loncommon::start_data_table().
                   14414:                               $table.
                   14415:                               &Apache::loncommon::end_data_table();
                   14416:                 }
1.663     raeburn  14417:             }
                   14418:         }
                   14419:     }
                   14420:     return $output;
                   14421: }
                   14422: 
                   14423: =pod
                   14424: 
1.1075.2.56  raeburn  14425: =item * &assign_category_rows()
1.663     raeburn  14426: 
                   14427: Create a datatable row for display of nested categories in a domain,
                   14428: with checkboxes to allow a course to be categorized,called recursively.
                   14429: 
                   14430: Inputs:
                   14431: 
                   14432: itemcount - track row number for alternating colors
                   14433: 
                   14434: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14435:       categories and subcategories.
                   14436: 
                   14437: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14438: 
                   14439: parent - parent of current category item
                   14440: 
                   14441: path - Array containing all categories back up through the hierarchy from the
                   14442:        current category to the top level.
                   14443: 
                   14444: currcategories - reference to array of current categories assigned to the course
                   14445: 
1.1075.2.117  raeburn  14446: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14447:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14448: 
1.663     raeburn  14449: Returns: $output (markup to be displayed).
                   14450: 
                   14451: =cut
                   14452: 
                   14453: sub assign_category_rows {
1.1075.2.117  raeburn  14454:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  14455:     my ($text,$name,$item,$chgstr);
                   14456:     if (ref($cats) eq 'ARRAY') {
                   14457:         my $maxdepth = scalar(@{$cats});
                   14458:         if (ref($cats->[$depth]) eq 'HASH') {
                   14459:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14460:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14461:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  14462:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14463:                 for (my $j=0; $j<$numchildren; $j++) {
                   14464:                     $name = $cats->[$depth]{$parent}[$j];
                   14465:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14466:                     my $deeper = $depth+1;
                   14467:                     my $checked = '';
                   14468:                     if (ref($currcategories) eq 'ARRAY') {
                   14469:                         if (@{$currcategories} > 0) {
                   14470:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14471:                                 $checked = ' checked="checked"';
1.663     raeburn  14472:                             }
                   14473:                         }
                   14474:                     }
1.664     raeburn  14475:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14476:                              '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14477:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  14478:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14479:                              '</td><td>';
1.663     raeburn  14480:                     if (ref($path) eq 'ARRAY') {
                   14481:                         push(@{$path},$name);
1.1075.2.117  raeburn  14482:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  14483:                         pop(@{$path});
                   14484:                     }
                   14485:                     $text .= '</td></tr>';
                   14486:                 }
                   14487:                 $text .= '</table></td>';
                   14488:             }
                   14489:         }
                   14490:     }
                   14491:     return $text;
                   14492: }
                   14493: 
1.1075.2.69  raeburn  14494: =pod
                   14495: 
                   14496: =back
                   14497: 
                   14498: =cut
                   14499: 
1.655     raeburn  14500: ############################################################
                   14501: ############################################################
                   14502: 
                   14503: 
1.443     albertel 14504: sub commit_customrole {
1.664     raeburn  14505:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14506:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14507:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14508:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14509:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14510:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14511:                  '</b><br />';
                   14512:     return $output;
                   14513: }
                   14514: 
                   14515: sub commit_standardrole {
1.1075.2.31  raeburn  14516:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14517:     my ($output,$logmsg,$linefeed);
                   14518:     if ($context eq 'auto') {
                   14519:         $linefeed = "\n";
                   14520:     } else {
                   14521:         $linefeed = "<br />\n";
                   14522:     }  
1.443     albertel 14523:     if ($three eq 'st') {
1.541     raeburn  14524:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  14525:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14526:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14527:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14528:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14529:         } else {
1.541     raeburn  14530:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14531:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14532:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14533:             if ($context eq 'auto') {
                   14534:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14535:             } else {
                   14536:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14537:                &mt('Add to classlist').': <b>ok</b>';
                   14538:             }
                   14539:             $output .= $linefeed;
1.443     albertel 14540:         }
                   14541:     } else {
                   14542:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14543:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14544:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14545:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14546:         if ($context eq 'auto') {
                   14547:             $output .= $result.$linefeed;
                   14548:         } else {
                   14549:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14550:         }
1.443     albertel 14551:     }
                   14552:     return $output;
                   14553: }
                   14554: 
                   14555: sub commit_studentrole {
1.1075.2.31  raeburn  14556:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14557:         $credits) = @_;
1.626     raeburn  14558:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  14559:     if ($context eq 'auto') {
                   14560:         $linefeed = "\n";
                   14561:     } else {
                   14562:         $linefeed = '<br />'."\n";
                   14563:     }
1.443     albertel 14564:     if (defined($one) && defined($two)) {
                   14565:         my $cid=$one.'_'.$two;
                   14566:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   14567:         my $secchange = 0;
                   14568:         my $expire_role_result;
                   14569:         my $modify_section_result;
1.628     raeburn  14570:         if ($oldsec ne '-1') { 
                   14571:             if ($oldsec ne $sec) {
1.443     albertel 14572:                 $secchange = 1;
1.628     raeburn  14573:                 my $now = time;
1.443     albertel 14574:                 my $uurl='/'.$cid;
                   14575:                 $uurl=~s/\_/\//g;
                   14576:                 if ($oldsec) {
                   14577:                     $uurl.='/'.$oldsec;
                   14578:                 }
1.626     raeburn  14579:                 $oldsecurl = $uurl;
1.628     raeburn  14580:                 $expire_role_result = 
1.652     raeburn  14581:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  14582:                 if ($env{'request.course.sec'} ne '') { 
                   14583:                     if ($expire_role_result eq 'refused') {
                   14584:                         my @roles = ('st');
                   14585:                         my @statuses = ('previous');
                   14586:                         my @roledoms = ($one);
                   14587:                         my $withsec = 1;
                   14588:                         my %roleshash = 
                   14589:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   14590:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   14591:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   14592:                             my ($oldstart,$oldend) = 
                   14593:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   14594:                             if ($oldend > 0 && $oldend <= $now) {
                   14595:                                 $expire_role_result = 'ok';
                   14596:                             }
                   14597:                         }
                   14598:                     }
                   14599:                 }
1.443     albertel 14600:                 $result = $expire_role_result;
                   14601:             }
                   14602:         }
                   14603:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  14604:             $modify_section_result = 
                   14605:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   14606:                                                            undef,undef,undef,$sec,
                   14607:                                                            $end,$start,'','',$cid,
                   14608:                                                            '',$context,$credits);
1.443     albertel 14609:             if ($modify_section_result =~ /^ok/) {
                   14610:                 if ($secchange == 1) {
1.628     raeburn  14611:                     if ($sec eq '') {
                   14612:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   14613:                     } else {
                   14614:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   14615:                     }
1.443     albertel 14616:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  14617:                     if ($sec eq '') {
                   14618:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   14619:                     } else {
                   14620:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14621:                     }
1.443     albertel 14622:                 } else {
1.628     raeburn  14623:                     if ($sec eq '') {
                   14624:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   14625:                     } else {
                   14626:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14627:                     }
1.443     albertel 14628:                 }
                   14629:             } else {
1.628     raeburn  14630:                 if ($secchange) {       
                   14631:                     $$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;
                   14632:                 } else {
                   14633:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   14634:                 }
1.443     albertel 14635:             }
                   14636:             $result = $modify_section_result;
                   14637:         } elsif ($secchange == 1) {
1.628     raeburn  14638:             if ($oldsec eq '') {
1.1075.2.20  raeburn  14639:                 $$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  14640:             } else {
                   14641:                 $$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;
                   14642:             }
1.626     raeburn  14643:             if ($expire_role_result eq 'refused') {
                   14644:                 my $newsecurl = '/'.$cid;
                   14645:                 $newsecurl =~ s/\_/\//g;
                   14646:                 if ($sec ne '') {
                   14647:                     $newsecurl.='/'.$sec;
                   14648:                 }
                   14649:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   14650:                     if ($sec eq '') {
                   14651:                         $$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;
                   14652:                     } else {
                   14653:                         $$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;
                   14654:                     }
                   14655:                 }
                   14656:             }
1.443     albertel 14657:         }
                   14658:     } else {
1.626     raeburn  14659:         $$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 14660:         $result = "error: incomplete course id\n";
                   14661:     }
                   14662:     return $result;
                   14663: }
                   14664: 
1.1075.2.25  raeburn  14665: sub show_role_extent {
                   14666:     my ($scope,$context,$role) = @_;
                   14667:     $scope =~ s{^/}{};
                   14668:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   14669:     push(@courseroles,'co');
                   14670:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   14671:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   14672:         $scope =~ s{/}{_};
                   14673:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   14674:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   14675:         my ($audom,$auname) = split(/\//,$scope);
                   14676:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   14677:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   14678:     } else {
                   14679:         $scope =~ s{/$}{};
                   14680:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   14681:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   14682:     }
                   14683: }
                   14684: 
1.443     albertel 14685: ############################################################
                   14686: ############################################################
                   14687: 
1.566     albertel 14688: sub check_clone {
1.578     raeburn  14689:     my ($args,$linefeed) = @_;
1.566     albertel 14690:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   14691:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   14692:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   14693:     my $clonemsg;
                   14694:     my $can_clone = 0;
1.944     raeburn  14695:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  14696:     if ($lctype ne 'community') {
                   14697:         $lctype = 'course';
                   14698:     }
1.566     albertel 14699:     if ($clonehome eq 'no_host') {
1.944     raeburn  14700:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14701:             $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'});
                   14702:         } else {
                   14703:             $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'});
                   14704:         }     
1.566     albertel 14705:     } else {
                   14706: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  14707:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14708:             if ($clonedesc{'type'} ne 'Community') {
                   14709:                  $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'});
                   14710:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14711:             }
                   14712:         }
1.1075.2.119  raeburn  14713: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  14714:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 14715: 	    $can_clone = 1;
                   14716: 	} else {
1.1075.2.95  raeburn  14717: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 14718: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  14719:             if ($clonehash{'cloners'} eq '') {
                   14720:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   14721:                 if ($domdefs{'canclone'}) {
                   14722:                     unless ($domdefs{'canclone'} eq 'none') {
                   14723:                         if ($domdefs{'canclone'} eq 'domain') {
                   14724:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   14725:                                 $can_clone = 1;
                   14726:                             }
                   14727:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   14728:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   14729:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   14730:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   14731:                                 $can_clone = 1;
                   14732:                             }
                   14733:                         }
                   14734:                     }
1.908     raeburn  14735:                 }
1.1075.2.95  raeburn  14736:             } else {
                   14737: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   14738:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  14739:                     $can_clone = 1;
1.1075.2.95  raeburn  14740:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  14741:                     $can_clone = 1;
1.1075.2.96  raeburn  14742:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   14743:                     $can_clone = 1;
1.1075.2.95  raeburn  14744:                 }
                   14745:                 unless ($can_clone) {
1.1075.2.96  raeburn  14746:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   14747:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  14748:                         my (%gotdomdefaults,%gotcodedefaults);
                   14749:                         foreach my $cloner (@cloners) {
                   14750:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   14751:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   14752:                                 my (%codedefaults,@code_order);
                   14753:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   14754:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   14755:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   14756:                                     }
                   14757:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   14758:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   14759:                                     }
                   14760:                                 } else {
                   14761:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   14762:                                                                             \%codedefaults,
                   14763:                                                                             \@code_order);
                   14764:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   14765:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   14766:                                 }
                   14767:                                 if (@code_order > 0) {
                   14768:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   14769:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   14770:                                                                                 $args->{'crscode'})) {
                   14771:                                         $can_clone = 1;
                   14772:                                         last;
                   14773:                                     }
                   14774:                                 }
                   14775:                             }
                   14776:                         }
                   14777:                     }
1.1075.2.96  raeburn  14778:                 }
                   14779:             }
                   14780:             unless ($can_clone) {
                   14781:                 my $ccrole = 'cc';
                   14782:                 if ($args->{'crstype'} eq 'Community') {
                   14783:                     $ccrole = 'co';
                   14784:                 }
                   14785:                 my %roleshash =
                   14786:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   14787:                                                   $args->{'ccdomain'},
                   14788:                                                   'userroles',['active'],[$ccrole],
                   14789:                                                   [$args->{'clonedomain'}]);
                   14790:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   14791:                     $can_clone = 1;
                   14792:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   14793:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   14794:                     $can_clone = 1;
1.1075.2.95  raeburn  14795:                 }
                   14796:             }
                   14797:             unless ($can_clone) {
                   14798:                 if ($args->{'crstype'} eq 'Community') {
                   14799:                     $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'});
                   14800:                 } else {
                   14801:                     $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  14802: 	        }
1.566     albertel 14803: 	    }
1.578     raeburn  14804:         }
1.566     albertel 14805:     }
                   14806:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14807: }
                   14808: 
1.444     albertel 14809: sub construct_course {
1.1075.2.119  raeburn  14810:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
                   14811:         $cnum,$category,$coderef) = @_;
1.444     albertel 14812:     my $outcome;
1.541     raeburn  14813:     my $linefeed =  '<br />'."\n";
                   14814:     if ($context eq 'auto') {
                   14815:         $linefeed = "\n";
                   14816:     }
1.566     albertel 14817: 
                   14818: #
                   14819: # Are we cloning?
                   14820: #
                   14821:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14822:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  14823: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 14824: 	if ($context ne 'auto') {
1.578     raeburn  14825:             if ($clonemsg ne '') {
                   14826: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   14827:             }
1.566     albertel 14828: 	}
                   14829: 	$outcome .= $clonemsg.$linefeed;
                   14830: 
                   14831:         if (!$can_clone) {
                   14832: 	    return (0,$outcome);
                   14833: 	}
                   14834:     }
                   14835: 
1.444     albertel 14836: #
                   14837: # Open course
                   14838: #
                   14839:     my $crstype = lc($args->{'crstype'});
                   14840:     my %cenv=();
                   14841:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   14842:                                              $args->{'cdescr'},
                   14843:                                              $args->{'curl'},
                   14844:                                              $args->{'course_home'},
                   14845:                                              $args->{'nonstandard'},
                   14846:                                              $args->{'crscode'},
                   14847:                                              $args->{'ccuname'}.':'.
                   14848:                                              $args->{'ccdomain'},
1.882     raeburn  14849:                                              $args->{'crstype'},
1.885     raeburn  14850:                                              $cnum,$context,$category);
1.444     albertel 14851: 
                   14852:     # Note: The testing routines depend on this being output; see 
                   14853:     # Utils::Course. This needs to at least be output as a comment
                   14854:     # if anyone ever decides to not show this, and Utils::Course::new
                   14855:     # will need to be suitably modified.
1.541     raeburn  14856:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  14857:     if ($$courseid =~ /^error:/) {
                   14858:         return (0,$outcome);
                   14859:     }
                   14860: 
1.444     albertel 14861: #
                   14862: # Check if created correctly
                   14863: #
1.479     albertel 14864:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 14865:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  14866:     if ($crsuhome eq 'no_host') {
                   14867:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   14868:         return (0,$outcome);
                   14869:     }
1.541     raeburn  14870:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 14871: 
1.444     albertel 14872: #
1.566     albertel 14873: # Do the cloning
                   14874: #   
                   14875:     if ($can_clone && $cloneid) {
                   14876: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   14877: 	if ($context ne 'auto') {
                   14878: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   14879: 	}
                   14880: 	$outcome .= $clonemsg.$linefeed;
                   14881: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 14882: # Copy all files
1.637     www      14883: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 14884: # Restore URL
1.566     albertel 14885: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 14886: # Restore title
1.566     albertel 14887: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  14888: # Restore creation date, creator and creation context.
                   14889:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   14890:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   14891:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 14892: # Mark as cloned
1.566     albertel 14893: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      14894: # Need to clone grading mode
                   14895:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   14896:         $cenv{'grading'}=$newenv{'grading'};
                   14897: # Do not clone these environment entries
                   14898:         &Apache::lonnet::del('environment',
                   14899:                   ['default_enrollment_start_date',
                   14900:                    'default_enrollment_end_date',
                   14901:                    'question.email',
                   14902:                    'policy.email',
                   14903:                    'comment.email',
                   14904:                    'pch.users.denied',
1.725     raeburn  14905:                    'plc.users.denied',
                   14906:                    'hidefromcat',
1.1075.2.36  raeburn  14907:                    'checkforpriv',
1.1075.2.59  raeburn  14908:                    'categories',
                   14909:                    'internal.uniquecode'],
1.638     www      14910:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  14911:         if ($args->{'textbook'}) {
                   14912:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   14913:         }
1.444     albertel 14914:     }
1.566     albertel 14915: 
1.444     albertel 14916: #
                   14917: # Set environment (will override cloned, if existing)
                   14918: #
                   14919:     my @sections = ();
                   14920:     my @xlists = ();
                   14921:     if ($args->{'crstype'}) {
                   14922:         $cenv{'type'}=$args->{'crstype'};
                   14923:     }
                   14924:     if ($args->{'crsid'}) {
                   14925:         $cenv{'courseid'}=$args->{'crsid'};
                   14926:     }
                   14927:     if ($args->{'crscode'}) {
                   14928:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   14929:     }
                   14930:     if ($args->{'crsquota'} ne '') {
                   14931:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   14932:     } else {
                   14933:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   14934:     }
                   14935:     if ($args->{'ccuname'}) {
                   14936:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   14937:                                         ':'.$args->{'ccdomain'};
                   14938:     } else {
                   14939:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   14940:     }
1.1075.2.31  raeburn  14941:     if ($args->{'defaultcredits'}) {
                   14942:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   14943:     }
1.444     albertel 14944:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   14945:     if ($args->{'crssections'}) {
                   14946:         $cenv{'internal.sectionnums'} = '';
                   14947:         if ($args->{'crssections'} =~ m/,/) {
                   14948:             @sections = split/,/,$args->{'crssections'};
                   14949:         } else {
                   14950:             $sections[0] = $args->{'crssections'};
                   14951:         }
                   14952:         if (@sections > 0) {
                   14953:             foreach my $item (@sections) {
                   14954:                 my ($sec,$gp) = split/:/,$item;
                   14955:                 my $class = $args->{'crscode'}.$sec;
                   14956:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   14957:                 $cenv{'internal.sectionnums'} .= $item.',';
                   14958:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  14959:                     push(@badclasses,$class);
1.444     albertel 14960:                 }
                   14961:             }
                   14962:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   14963:         }
                   14964:     }
                   14965: # do not hide course coordinator from staff listing, 
                   14966: # even if privileged
                   14967:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  14968: # add course coordinator's domain to domains to check for privileged users
                   14969: # if different to course domain
                   14970:     if ($$crsudom ne $args->{'ccdomain'}) {
                   14971:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   14972:     }
1.444     albertel 14973: # add crosslistings
                   14974:     if ($args->{'crsxlist'}) {
                   14975:         $cenv{'internal.crosslistings'}='';
                   14976:         if ($args->{'crsxlist'} =~ m/,/) {
                   14977:             @xlists = split/,/,$args->{'crsxlist'};
                   14978:         } else {
                   14979:             $xlists[0] = $args->{'crsxlist'};
                   14980:         }
                   14981:         if (@xlists > 0) {
                   14982:             foreach my $item (@xlists) {
                   14983:                 my ($xl,$gp) = split/:/,$item;
                   14984:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   14985:                 $cenv{'internal.crosslistings'} .= $item.',';
                   14986:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  14987:                     push(@badclasses,$xl);
1.444     albertel 14988:                 }
                   14989:             }
                   14990:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   14991:         }
                   14992:     }
                   14993:     if ($args->{'autoadds'}) {
                   14994:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   14995:     }
                   14996:     if ($args->{'autodrops'}) {
                   14997:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   14998:     }
                   14999: # check for notification of enrollment changes
                   15000:     my @notified = ();
                   15001:     if ($args->{'notify_owner'}) {
                   15002:         if ($args->{'ccuname'} ne '') {
                   15003:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15004:         }
                   15005:     }
                   15006:     if ($args->{'notify_dc'}) {
                   15007:         if ($uname ne '') { 
1.630     raeburn  15008:             push(@notified,$uname.':'.$udom);
1.444     albertel 15009:         }
                   15010:     }
                   15011:     if (@notified > 0) {
                   15012:         my $notifylist;
                   15013:         if (@notified > 1) {
                   15014:             $notifylist = join(',',@notified);
                   15015:         } else {
                   15016:             $notifylist = $notified[0];
                   15017:         }
                   15018:         $cenv{'internal.notifylist'} = $notifylist;
                   15019:     }
                   15020:     if (@badclasses > 0) {
                   15021:         my %lt=&Apache::lonlocal::texthash(
1.1075.2.119  raeburn  15022:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   15023:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   15024:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 15025:         );
1.1075.2.119  raeburn  15026:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   15027:                            &mt('That is because the user identified as the course owner ([_1]) does not have rights to access enrollment in these classes, as determined by the policies of your institution on access to official classlists',$cenv{'internal.courseowner'}).$linefeed.$lt{'itis'};
1.541     raeburn  15028:         if ($context eq 'auto') {
                   15029:             $outcome .= $badclass_msg.$linefeed;
1.1075.2.119  raeburn  15030:         } else {
1.566     albertel 15031:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1075.2.119  raeburn  15032:         }
                   15033:         foreach my $item (@badclasses) {
1.541     raeburn  15034:             if ($context eq 'auto') {
1.1075.2.119  raeburn  15035:                 $outcome .= " - $item\n";
1.541     raeburn  15036:             } else {
1.1075.2.119  raeburn  15037:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  15038:             }
1.1075.2.119  raeburn  15039:         }
                   15040:         if ($context eq 'auto') {
                   15041:             $outcome .= $linefeed;
                   15042:         } else {
                   15043:             $outcome .= "</ul><br /><br /></div>\n";
                   15044:         }
1.444     albertel 15045:     }
                   15046:     if ($args->{'no_end_date'}) {
                   15047:         $args->{'endaccess'} = 0;
                   15048:     }
                   15049:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15050:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15051:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15052:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15053:     if ($args->{'showphotos'}) {
                   15054:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15055:     }
                   15056:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15057:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15058:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15059:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15060:             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'); 
                   15061:             if ($context eq 'auto') {
                   15062:                 $outcome .= $krb_msg;
                   15063:             } else {
1.566     albertel 15064:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15065:             }
                   15066:             $outcome .= $linefeed;
1.444     albertel 15067:         }
                   15068:     }
                   15069:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15070:        if ($args->{'setpolicy'}) {
                   15071:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15072:        }
                   15073:        if ($args->{'setcontent'}) {
                   15074:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15075:        }
1.1075.2.110  raeburn  15076:        if ($args->{'setcomment'}) {
                   15077:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15078:        }
1.444     albertel 15079:     }
                   15080:     if ($args->{'reshome'}) {
                   15081: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15082: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15083:     }
                   15084: #
                   15085: # course has keyed access
                   15086: #
                   15087:     if ($args->{'setkeys'}) {
                   15088:        $cenv{'keyaccess'}='yes';
                   15089:     }
                   15090: # if specified, key authority is not course, but user
                   15091: # only active if keyaccess is yes
                   15092:     if ($args->{'keyauth'}) {
1.487     albertel 15093: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15094: 	$user = &LONCAPA::clean_username($user);
                   15095: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15096: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15097: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15098: 	}
                   15099:     }
                   15100: 
1.1075.2.59  raeburn  15101: #
                   15102: #  generate and store uniquecode (available to course requester), if course should have one.
                   15103: #
                   15104:     if ($args->{'uniquecode'}) {
                   15105:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15106:         if ($code) {
                   15107:             $cenv{'internal.uniquecode'} = $code;
                   15108:             my %crsinfo =
                   15109:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15110:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15111:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15112:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15113:             }
                   15114:             if (ref($coderef)) {
                   15115:                 $$coderef = $code;
                   15116:             }
                   15117:         }
                   15118:     }
                   15119: 
1.444     albertel 15120:     if ($args->{'disresdis'}) {
                   15121:         $cenv{'pch.roles.denied'}='st';
                   15122:     }
                   15123:     if ($args->{'disablechat'}) {
                   15124:         $cenv{'plc.roles.denied'}='st';
                   15125:     }
                   15126: 
                   15127:     # Record we've not yet viewed the Course Initialization Helper for this 
                   15128:     # course
                   15129:     $cenv{'course.helper.not.run'} = 1;
                   15130:     #
                   15131:     # Use new Randomseed
                   15132:     #
                   15133:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   15134:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   15135:     #
                   15136:     # The encryption code and receipt prefix for this course
                   15137:     #
                   15138:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   15139:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   15140:     #
                   15141:     # By default, use standard grading
                   15142:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15143: 
1.541     raeburn  15144:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15145:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15146: #
                   15147: # Open all assignments
                   15148: #
                   15149:     if ($args->{'openall'}) {
                   15150:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   15151:        my %storecontent = ($storeunder         => time,
                   15152:                            $storeunder.'.type' => 'date_start');
                   15153:        
                   15154:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  15155:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15156:    }
                   15157: #
                   15158: # Set first page
                   15159: #
                   15160:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15161: 	    || ($cloneid)) {
1.445     albertel 15162: 	use LONCAPA::map;
1.444     albertel 15163: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15164: 
                   15165: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15166:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15167: 
1.444     albertel 15168:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15169:         my $title; my $url;
                   15170:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15171: 	    $title=&mt('Syllabus');
1.444     albertel 15172:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15173:         } else {
1.963     raeburn  15174:             $title=&mt('Table of Contents');
1.444     albertel 15175:             $url='/adm/navmaps';
                   15176:         }
1.445     albertel 15177: 
                   15178:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15179: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15180: 
                   15181: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15182:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15183:     }
1.566     albertel 15184: 
                   15185:     return (1,$outcome);
1.444     albertel 15186: }
                   15187: 
1.1075.2.59  raeburn  15188: sub make_unique_code {
                   15189:     my ($cdom,$cnum) = @_;
                   15190:     # get lock on uniquecodes db
                   15191:     my $lockhash = {
                   15192:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15193:                                                   ':'.$env{'user.domain'},
                   15194:                    };
                   15195:     my $tries = 0;
                   15196:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15197:     my ($code,$error);
                   15198: 
                   15199:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15200:         $tries ++;
                   15201:         sleep 1;
                   15202:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15203:     }
                   15204:     if ($gotlock eq 'ok') {
                   15205:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15206:         my $gotcode;
                   15207:         my $attempts = 0;
                   15208:         while ((!$gotcode) && ($attempts < 100)) {
                   15209:             $code = &generate_code();
                   15210:             if (!exists($currcodes{$code})) {
                   15211:                 $gotcode = 1;
                   15212:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15213:                     $error = 'nostore';
                   15214:                 }
                   15215:             }
                   15216:             $attempts ++;
                   15217:         }
                   15218:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15219:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15220:     } else {
                   15221:         $error = 'nolock';
                   15222:     }
                   15223:     return ($code,$error);
                   15224: }
                   15225: 
                   15226: sub generate_code {
                   15227:     my $code;
                   15228:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15229:     for (my $i=0; $i<6; $i++) {
                   15230:         my $lettnum = int (rand 2);
                   15231:         my $item = '';
                   15232:         if ($lettnum) {
                   15233:             $item = $letts[int( rand(18) )];
                   15234:         } else {
                   15235:             $item = 1+int( rand(8) );
                   15236:         }
                   15237:         $code .= $item;
                   15238:     }
                   15239:     return $code;
                   15240: }
                   15241: 
1.444     albertel 15242: ############################################################
                   15243: ############################################################
                   15244: 
1.953     droeschl 15245: #SD
                   15246: # only Community and Course, or anything else?
1.378     raeburn  15247: sub course_type {
                   15248:     my ($cid) = @_;
                   15249:     if (!defined($cid)) {
                   15250:         $cid = $env{'request.course.id'};
                   15251:     }
1.404     albertel 15252:     if (defined($env{'course.'.$cid.'.type'})) {
                   15253:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15254:     } else {
                   15255:         return 'Course';
1.377     raeburn  15256:     }
                   15257: }
1.156     albertel 15258: 
1.406     raeburn  15259: sub group_term {
                   15260:     my $crstype = &course_type();
                   15261:     my %names = (
                   15262:                   'Course' => 'group',
1.865     raeburn  15263:                   'Community' => 'group',
1.406     raeburn  15264:                 );
                   15265:     return $names{$crstype};
                   15266: }
                   15267: 
1.902     raeburn  15268: sub course_types {
1.1075.2.59  raeburn  15269:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  15270:     my %typename = (
                   15271:                          official   => 'Official course',
                   15272:                          unofficial => 'Unofficial course',
                   15273:                          community  => 'Community',
1.1075.2.59  raeburn  15274:                          textbook   => 'Textbook course',
1.902     raeburn  15275:                    );
                   15276:     return (\@types,\%typename);
                   15277: }
                   15278: 
1.156     albertel 15279: sub icon {
                   15280:     my ($file)=@_;
1.505     albertel 15281:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15282:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15283:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15284:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15285: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15286: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15287: 	            $curfext.".gif") {
                   15288: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15289: 		$curfext.".gif";
                   15290: 	}
                   15291:     }
1.249     albertel 15292:     return &lonhttpdurl($iconname);
1.154     albertel 15293: } 
1.84      albertel 15294: 
1.575     albertel 15295: sub lonhttpdurl {
1.692     www      15296: #
                   15297: # Had been used for "small fry" static images on separate port 8080.
                   15298: # Modify here if lightweight http functionality desired again.
                   15299: # Currently eliminated due to increasing firewall issues.
                   15300: #
1.575     albertel 15301:     my ($url)=@_;
1.692     www      15302:     return $url;
1.215     albertel 15303: }
                   15304: 
1.213     albertel 15305: sub connection_aborted {
                   15306:     my ($r)=@_;
                   15307:     $r->print(" ");$r->rflush();
                   15308:     my $c = $r->connection;
                   15309:     return $c->aborted();
                   15310: }
                   15311: 
1.221     foxr     15312: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15313: #    strings as 'strings'.
                   15314: sub escape_single {
1.221     foxr     15315:     my ($input) = @_;
1.223     albertel 15316:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15317:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15318:     return $input;
                   15319: }
1.223     albertel 15320: 
1.222     foxr     15321: #  Same as escape_single, but escape's "'s  This 
                   15322: #  can be used for  "strings"
                   15323: sub escape_double {
                   15324:     my ($input) = @_;
                   15325:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15326:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15327:     return $input;
                   15328: }
1.223     albertel 15329:  
1.222     foxr     15330: #   Escapes the last element of a full URL.
                   15331: sub escape_url {
                   15332:     my ($url)   = @_;
1.238     raeburn  15333:     my @urlslices = split(/\//, $url,-1);
1.369     www      15334:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  15335:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15336: }
1.462     albertel 15337: 
1.820     raeburn  15338: sub compare_arrays {
                   15339:     my ($arrayref1,$arrayref2) = @_;
                   15340:     my (@difference,%count);
                   15341:     @difference = ();
                   15342:     %count = ();
                   15343:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   15344:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   15345:         foreach my $element (keys(%count)) {
                   15346:             if ($count{$element} == 1) {
                   15347:                 push(@difference,$element);
                   15348:             }
                   15349:         }
                   15350:     }
                   15351:     return @difference;
                   15352: }
                   15353: 
1.817     bisitz   15354: # -------------------------------------------------------- Initialize user login
1.462     albertel 15355: sub init_user_environment {
1.463     albertel 15356:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 15357:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   15358: 
                   15359:     my $public=($username eq 'public' && $domain eq 'public');
                   15360: 
                   15361: # See if old ID present, if so, remove
                   15362: 
1.1062    raeburn  15363:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 15364:     my $now=time;
                   15365: 
                   15366:     if ($public) {
                   15367: 	my $max_public=100;
                   15368: 	my $oldest;
                   15369: 	my $oldest_time=0;
                   15370: 	for(my $next=1;$next<=$max_public;$next++) {
                   15371: 	    if (-e $lonids."/publicuser_$next.id") {
                   15372: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   15373: 		if ($mtime<$oldest_time || !$oldest_time) {
                   15374: 		    $oldest_time=$mtime;
                   15375: 		    $oldest=$next;
                   15376: 		}
                   15377: 	    } else {
                   15378: 		$cookie="publicuser_$next";
                   15379: 		last;
                   15380: 	    }
                   15381: 	}
                   15382: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   15383:     } else {
1.463     albertel 15384: 	# if this isn't a robot, kill any existing non-robot sessions
                   15385: 	if (!$args->{'robot'}) {
                   15386: 	    opendir(DIR,$lonids);
                   15387: 	    while ($filename=readdir(DIR)) {
                   15388: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   15389: 		    unlink($lonids.'/'.$filename);
                   15390: 		}
1.462     albertel 15391: 	    }
1.463     albertel 15392: 	    closedir(DIR);
1.1075.2.84  raeburn  15393: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   15394:             my $namespace = 'nohist_courseeditor';
                   15395:             my $lockingkey = 'paste'."\0".'locked_num';
                   15396:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15397:                                                 $domain,$username);
                   15398:             if (exists($lockhash{$lockingkey})) {
                   15399:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15400:                 unless ($delresult eq 'ok') {
                   15401:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15402:                 }
                   15403:             }
1.462     albertel 15404: 	}
                   15405: # Give them a new cookie
1.463     albertel 15406: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15407: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15408: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15409:     
                   15410: # Initialize roles
                   15411: 
1.1062    raeburn  15412: 	($userroles,$firstaccenv,$timerintenv) = 
                   15413:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15414:     }
                   15415: # ------------------------------------ Check browser type and MathML capability
                   15416: 
1.1075.2.77  raeburn  15417:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15418:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15419: 
                   15420: # ------------------------------------------------------------- Get environment
                   15421: 
                   15422:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15423:     my ($tmp) = keys(%userenv);
                   15424:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15425:     } else {
                   15426: 	undef(%userenv);
                   15427:     }
                   15428:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15429: 	$form->{'interface'}=$userenv{'interface'};
                   15430:     }
                   15431:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15432: 
                   15433: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15434:     foreach my $option ('interface','localpath','localres') {
                   15435:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15436:     }
                   15437: # --------------------------------------------------------- Write first profile
                   15438: 
                   15439:     {
                   15440: 	my %initial_env = 
                   15441: 	    ("user.name"          => $username,
                   15442: 	     "user.domain"        => $domain,
                   15443: 	     "user.home"          => $authhost,
                   15444: 	     "browser.type"       => $clientbrowser,
                   15445: 	     "browser.version"    => $clientversion,
                   15446: 	     "browser.mathml"     => $clientmathml,
                   15447: 	     "browser.unicode"    => $clientunicode,
                   15448: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  15449:              "browser.mobile"     => $clientmobile,
                   15450:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  15451:              "browser.osversion"  => $clientosversion,
1.462     albertel 15452: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15453: 	     "request.course.fn"  => '',
                   15454: 	     "request.course.uri" => '',
                   15455: 	     "request.course.sec" => '',
                   15456: 	     "request.role"       => 'cm',
                   15457: 	     "request.role.adv"   => $env{'user.adv'},
                   15458: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   15459: 
                   15460:         if ($form->{'localpath'}) {
                   15461: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15462: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15463:         }
                   15464: 	
                   15465: 	if ($form->{'interface'}) {
                   15466: 	    $form->{'interface'}=~s/\W//gs;
                   15467: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15468: 	    $env{'browser.interface'}=$form->{'interface'};
                   15469: 	}
                   15470: 
1.1075.2.54  raeburn  15471:         if ($form->{'iptoken'}) {
                   15472:             my $lonhost = $r->dir_config('lonHostID');
                   15473:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15474:             $env{'user.noloadbalance'} = $lonhost;
                   15475:         }
                   15476: 
1.1075.2.120  raeburn  15477:         if ($form->{'noloadbalance'}) {
                   15478:             my @hosts = &Apache::lonnet::current_machine_ids();
                   15479:             my $hosthere = $form->{'noloadbalance'};
                   15480:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   15481:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   15482:                 $env{'user.noloadbalance'} = $hosthere;
                   15483:             }
                   15484:         }
                   15485: 
1.981     raeburn  15486:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  15487:         my %domdef;
                   15488:         unless ($domain eq 'public') {
                   15489:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   15490:         }
1.980     raeburn  15491: 
1.1075.2.7  raeburn  15492:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  15493:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  15494:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   15495:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  15496:         }
                   15497: 
1.1075.2.59  raeburn  15498:         foreach my $crstype ('official','unofficial','community','textbook') {
1.765     raeburn  15499:             $userenv{'canrequest.'.$crstype} =
                   15500:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  15501:                                                   'reload','requestcourses',
                   15502:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  15503:         }
                   15504: 
1.1075.2.14  raeburn  15505:         $userenv{'canrequest.author'} =
                   15506:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   15507:                                         'reload','requestauthor',
                   15508:                                         \%userenv,\%domdef,\%is_adv);
                   15509:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   15510:                                              $domain,$username);
                   15511:         my $reqstatus = $reqauthor{'author_status'};
                   15512:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   15513:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   15514:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   15515:                                                   $reqauthor{'author'}{'timestamp'};
                   15516:             }
                   15517:         }
                   15518: 
1.462     albertel 15519: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  15520: 
1.462     albertel 15521: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   15522: 		 &GDBM_WRCREAT(),0640)) {
                   15523: 	    &_add_to_env(\%disk_env,\%initial_env);
                   15524: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   15525: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  15526:             if (ref($firstaccenv) eq 'HASH') {
                   15527:                 &_add_to_env(\%disk_env,$firstaccenv);
                   15528:             }
                   15529:             if (ref($timerintenv) eq 'HASH') {
                   15530:                 &_add_to_env(\%disk_env,$timerintenv);
                   15531:             }
1.463     albertel 15532: 	    if (ref($args->{'extra_env'})) {
                   15533: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   15534: 	    }
1.462     albertel 15535: 	    untie(%disk_env);
                   15536: 	} else {
1.705     tempelho 15537: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   15538: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 15539: 	    return 'error: '.$!;
                   15540: 	}
                   15541:     }
                   15542:     $env{'request.role'}='cm';
                   15543:     $env{'request.role.adv'}=$env{'user.adv'};
                   15544:     $env{'browser.type'}=$clientbrowser;
                   15545: 
                   15546:     return $cookie;
                   15547: 
                   15548: }
                   15549: 
                   15550: sub _add_to_env {
                   15551:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  15552:     if (ref($env_data) eq 'HASH') {
                   15553:         while (my ($key,$value) = each(%$env_data)) {
                   15554: 	    $idf->{$prefix.$key} = $value;
                   15555: 	    $env{$prefix.$key}   = $value;
                   15556:         }
1.462     albertel 15557:     }
                   15558: }
                   15559: 
1.685     tempelho 15560: # --- Get the symbolic name of a problem and the url
                   15561: sub get_symb {
                   15562:     my ($request,$silent) = @_;
1.726     raeburn  15563:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 15564:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   15565:     if ($symb eq '') {
                   15566:         if (!$silent) {
1.1071    raeburn  15567:             if (ref($request)) { 
                   15568:                 $request->print("Unable to handle ambiguous references:$url:.");
                   15569:             }
1.685     tempelho 15570:             return ();
                   15571:         }
                   15572:     }
                   15573:     &Apache::lonenc::check_decrypt(\$symb);
                   15574:     return ($symb);
                   15575: }
                   15576: 
                   15577: # --------------------------------------------------------------Get annotation
                   15578: 
                   15579: sub get_annotation {
                   15580:     my ($symb,$enc) = @_;
                   15581: 
                   15582:     my $key = $symb;
                   15583:     if (!$enc) {
                   15584:         $key =
                   15585:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   15586:     }
                   15587:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   15588:     return $annotation{$key};
                   15589: }
                   15590: 
                   15591: sub clean_symb {
1.731     raeburn  15592:     my ($symb,$delete_enc) = @_;
1.685     tempelho 15593: 
                   15594:     &Apache::lonenc::check_decrypt(\$symb);
                   15595:     my $enc = $env{'request.enc'};
1.731     raeburn  15596:     if ($delete_enc) {
1.730     raeburn  15597:         delete($env{'request.enc'});
                   15598:     }
1.685     tempelho 15599: 
                   15600:     return ($symb,$enc);
                   15601: }
1.462     albertel 15602: 
1.1075.2.69  raeburn  15603: ############################################################
                   15604: ############################################################
                   15605: 
                   15606: =pod
                   15607: 
                   15608: =head1 Routines for building display used to search for courses
                   15609: 
                   15610: 
                   15611: =over 4
                   15612: 
                   15613: =item * &build_filters()
                   15614: 
                   15615: Create markup for a table used to set filters to use when selecting
                   15616: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   15617: and quotacheck.pl
                   15618: 
                   15619: 
                   15620: Inputs:
                   15621: 
                   15622: filterlist - anonymous array of fields to include as potential filters
                   15623: 
                   15624: crstype - course type
                   15625: 
                   15626: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   15627:               to pop-open a course selector (will contain "extra element").
                   15628: 
                   15629: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   15630: 
                   15631: filter - anonymous hash of criteria and their values
                   15632: 
                   15633: action - form action
                   15634: 
                   15635: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   15636: 
                   15637: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   15638: 
                   15639: cloneruname - username of owner of new course who wants to clone
                   15640: 
                   15641: clonerudom - domain of owner of new course who wants to clone
                   15642: 
                   15643: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   15644: 
                   15645: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   15646: 
                   15647: codedom - domain
                   15648: 
                   15649: formname - value of form element named "form".
                   15650: 
                   15651: fixeddom - domain, if fixed.
                   15652: 
                   15653: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   15654: 
                   15655: cnameelement - name of form element in form on opener page which will receive title of selected course
                   15656: 
                   15657: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   15658: 
                   15659: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   15660: 
                   15661: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   15662: 
                   15663: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   15664: 
                   15665: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   15666: 
                   15667: 
                   15668: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   15669: 
                   15670: 
                   15671: Side Effects: None
                   15672: 
                   15673: =cut
                   15674: 
                   15675: # ---------------------------------------------- search for courses based on last activity etc.
                   15676: 
                   15677: sub build_filters {
                   15678:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   15679:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   15680:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   15681:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   15682:         $clonetext,$clonewarning) = @_;
                   15683:     my ($list,$jscript);
                   15684:     my $onchange = 'javascript:updateFilters(this)';
                   15685:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   15686:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   15687:         $typeselectform,$instcodetitle);
                   15688:     if ($formname eq '') {
                   15689:         $formname = $caller;
                   15690:     }
                   15691:     foreach my $item (@{$filterlist}) {
                   15692:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   15693:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   15694:             if ($item eq 'domainfilter') {
                   15695:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   15696:             } elsif ($item eq 'coursefilter') {
                   15697:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   15698:             } elsif ($item eq 'ownerfilter') {
                   15699:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15700:             } elsif ($item eq 'ownerdomfilter') {
                   15701:                 $filter->{'ownerdomfilter'} =
                   15702:                     &LONCAPA::clean_domain($filter->{$item});
                   15703:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   15704:                                                        'ownerdomfilter',1);
                   15705:             } elsif ($item eq 'personfilter') {
                   15706:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15707:             } elsif ($item eq 'persondomfilter') {
                   15708:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   15709:                                                         'persondomfilter',1);
                   15710:             } else {
                   15711:                 $filter->{$item} =~ s/\W//g;
                   15712:             }
                   15713:             if (!$filter->{$item}) {
                   15714:                 $filter->{$item} = '';
                   15715:             }
                   15716:         }
                   15717:         if ($item eq 'domainfilter') {
                   15718:             my $allow_blank = 1;
                   15719:             if ($formname eq 'portform') {
                   15720:                 $allow_blank=0;
                   15721:             } elsif ($formname eq 'studentform') {
                   15722:                 $allow_blank=0;
                   15723:             }
                   15724:             if ($fixeddom) {
                   15725:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   15726:                                     ' value="'.$codedom.'" />'.
                   15727:                                     &Apache::lonnet::domain($codedom,'description');
                   15728:             } else {
                   15729:                 $domainselectform = &select_dom_form($filter->{$item},
                   15730:                                                      'domainfilter',
                   15731:                                                       $allow_blank,'',$onchange);
                   15732:             }
                   15733:         } else {
                   15734:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   15735:         }
                   15736:     }
                   15737: 
                   15738:     # last course activity filter and selection
                   15739:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   15740: 
                   15741:     # course created filter and selection
                   15742:     if (exists($filter->{'createdfilter'})) {
                   15743:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   15744:     }
                   15745: 
                   15746:     my %lt = &Apache::lonlocal::texthash(
                   15747:                 'cac' => "$crstype Activity",
                   15748:                 'ccr' => "$crstype Created",
                   15749:                 'cde' => "$crstype Title",
                   15750:                 'cdo' => "$crstype Domain",
                   15751:                 'ins' => 'Institutional Code',
                   15752:                 'inc' => 'Institutional Categorization',
                   15753:                 'cow' => "$crstype Owner/Co-owner",
                   15754:                 'cop' => "$crstype Personnel Includes",
                   15755:                 'cog' => 'Type',
                   15756:              );
                   15757: 
                   15758:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15759:         my $typeval = 'Course';
                   15760:         if ($crstype eq 'Community') {
                   15761:             $typeval = 'Community';
                   15762:         }
                   15763:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   15764:     } else {
                   15765:         $typeselectform =  '<select name="type" size="1"';
                   15766:         if ($onchange) {
                   15767:             $typeselectform .= ' onchange="'.$onchange.'"';
                   15768:         }
                   15769:         $typeselectform .= '>'."\n";
                   15770:         foreach my $posstype ('Course','Community') {
                   15771:             $typeselectform.='<option value="'.$posstype.'"'.
                   15772:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   15773:         }
                   15774:         $typeselectform.="</select>";
                   15775:     }
                   15776: 
                   15777:     my ($cloneableonlyform,$cloneabletitle);
                   15778:     if (exists($filter->{'cloneableonly'})) {
                   15779:         my $cloneableon = '';
                   15780:         my $cloneableoff = ' checked="checked"';
                   15781:         if ($filter->{'cloneableonly'}) {
                   15782:             $cloneableon = $cloneableoff;
                   15783:             $cloneableoff = '';
                   15784:         }
                   15785:         $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>';
                   15786:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  15787:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  15788:         } else {
                   15789:             $cloneabletitle = &mt('Cloneable by you');
                   15790:         }
                   15791:     }
                   15792:     my $officialjs;
                   15793:     if ($crstype eq 'Course') {
                   15794:         if (exists($filter->{'instcodefilter'})) {
                   15795: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   15796: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   15797:             if ($codedom) {
                   15798:                 $officialjs = 1;
                   15799:                 ($instcodeform,$jscript,$$numtitlesref) =
                   15800:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   15801:                                                                   $officialjs,$codetitlesref);
                   15802:                 if ($jscript) {
                   15803:                     $jscript = '<script type="text/javascript">'."\n".
                   15804:                                '// <![CDATA['."\n".
                   15805:                                $jscript."\n".
                   15806:                                '// ]]>'."\n".
                   15807:                                '</script>'."\n";
                   15808:                 }
                   15809:             }
                   15810:             if ($instcodeform eq '') {
                   15811:                 $instcodeform =
                   15812:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   15813:                     $list->{'instcodefilter'}.'" />';
                   15814:                 $instcodetitle = $lt{'ins'};
                   15815:             } else {
                   15816:                 $instcodetitle = $lt{'inc'};
                   15817:             }
                   15818:             if ($fixeddom) {
                   15819:                 $instcodetitle .= '<br />('.$codedom.')';
                   15820:             }
                   15821:         }
                   15822:     }
                   15823:     my $output = qq|
                   15824: <form method="post" name="filterpicker" action="$action">
                   15825: <input type="hidden" name="form" value="$formname" />
                   15826: |;
                   15827:     if ($formname eq 'modifycourse') {
                   15828:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   15829:                    '<input type="hidden" name="prevphase" value="'.
                   15830:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  15831:     } elsif ($formname eq 'quotacheck') {
                   15832:         $output .= qq|
                   15833: <input type="hidden" name="sortby" value="" />
                   15834: <input type="hidden" name="sortorder" value="" />
                   15835: |;
                   15836:     } else {
1.1075.2.69  raeburn  15837:         my $name_input;
                   15838:         if ($cnameelement ne '') {
                   15839:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   15840:                           $cnameelement.'" />';
                   15841:         }
                   15842:         $output .= qq|
                   15843: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   15844: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   15845: $name_input
                   15846: $roleelement
                   15847: $multelement
                   15848: $typeelement
                   15849: |;
                   15850:         if ($formname eq 'portform') {
                   15851:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   15852:         }
                   15853:     }
                   15854:     if ($fixeddom) {
                   15855:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   15856:     }
                   15857:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   15858:     if ($sincefilterform) {
                   15859:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   15860:                   .$sincefilterform
                   15861:                   .&Apache::lonhtmlcommon::row_closure();
                   15862:     }
                   15863:     if ($createdfilterform) {
                   15864:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   15865:                   .$createdfilterform
                   15866:                   .&Apache::lonhtmlcommon::row_closure();
                   15867:     }
                   15868:     if ($domainselectform) {
                   15869:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   15870:                   .$domainselectform
                   15871:                   .&Apache::lonhtmlcommon::row_closure();
                   15872:     }
                   15873:     if ($typeselectform) {
                   15874:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15875:             $output .= $typeselectform;
                   15876:         } else {
                   15877:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   15878:                       .$typeselectform
                   15879:                       .&Apache::lonhtmlcommon::row_closure();
                   15880:         }
                   15881:     }
                   15882:     if ($instcodeform) {
                   15883:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   15884:                   .$instcodeform
                   15885:                   .&Apache::lonhtmlcommon::row_closure();
                   15886:     }
                   15887:     if (exists($filter->{'ownerfilter'})) {
                   15888:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   15889:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15890:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   15891:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15892:                    $ownerdomselectform.'</td></tr></table>'.
                   15893:                    &Apache::lonhtmlcommon::row_closure();
                   15894:     }
                   15895:     if (exists($filter->{'personfilter'})) {
                   15896:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   15897:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15898:                    '<input type="text" name="personfilter" size="20" value="'.
                   15899:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15900:                    $persondomselectform.'</td></tr></table>'.
                   15901:                    &Apache::lonhtmlcommon::row_closure();
                   15902:     }
                   15903:     if (exists($filter->{'coursefilter'})) {
                   15904:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   15905:                   .'<input type="text" name="coursefilter" size="25" value="'
                   15906:                   .$list->{'coursefilter'}.'" />'
                   15907:                   .&Apache::lonhtmlcommon::row_closure();
                   15908:     }
                   15909:     if ($cloneableonlyform) {
                   15910:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   15911:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   15912:     }
                   15913:     if (exists($filter->{'descriptfilter'})) {
                   15914:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   15915:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   15916:                   .$list->{'descriptfilter'}.'" />'
                   15917:                   .&Apache::lonhtmlcommon::row_closure(1);
                   15918:     }
                   15919:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   15920:                '<input type="hidden" name="updater" value="" />'."\n".
                   15921:                '<input type="submit" name="gosearch" value="'.
                   15922:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   15923:     return $jscript.$clonewarning.$output;
                   15924: }
                   15925: 
                   15926: =pod
                   15927: 
                   15928: =item * &timebased_select_form()
                   15929: 
                   15930: Create markup for a dropdown list used to select a time-based
                   15931: filter e.g., Course Activity, Course Created, when searching for courses
                   15932: or communities
                   15933: 
                   15934: Inputs:
                   15935: 
                   15936: item - name of form element (sincefilter or createdfilter)
                   15937: 
                   15938: filter - anonymous hash of criteria and their values
                   15939: 
                   15940: Returns: HTML for a select box contained a blank, then six time selections,
                   15941:          with value set in incoming form variables currently selected.
                   15942: 
                   15943: Side Effects: None
                   15944: 
                   15945: =cut
                   15946: 
                   15947: sub timebased_select_form {
                   15948:     my ($item,$filter) = @_;
                   15949:     if (ref($filter) eq 'HASH') {
                   15950:         $filter->{$item} =~ s/[^\d-]//g;
                   15951:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   15952:         return &select_form(
                   15953:                             $filter->{$item},
                   15954:                             $item,
                   15955:                             {      '-1' => '',
                   15956:                                 '86400' => &mt('today'),
                   15957:                                '604800' => &mt('last week'),
                   15958:                               '2592000' => &mt('last month'),
                   15959:                               '7776000' => &mt('last three months'),
                   15960:                              '15552000' => &mt('last six months'),
                   15961:                              '31104000' => &mt('last year'),
                   15962:                     'select_form_order' =>
                   15963:                            ['-1','86400','604800','2592000','7776000',
                   15964:                             '15552000','31104000']});
                   15965:     }
                   15966: }
                   15967: 
                   15968: =pod
                   15969: 
                   15970: =item * &js_changer()
                   15971: 
                   15972: Create script tag containing Javascript used to submit course search form
                   15973: when course type or domain is changed, and also to hide 'Searching ...' on
                   15974: page load completion for page showing search result.
                   15975: 
                   15976: Inputs: None
                   15977: 
                   15978: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   15979: 
                   15980: Side Effects: None
                   15981: 
                   15982: =cut
                   15983: 
                   15984: sub js_changer {
                   15985:     return <<ENDJS;
                   15986: <script type="text/javascript">
                   15987: // <![CDATA[
                   15988: function updateFilters(caller) {
                   15989:     if (typeof(caller) != "undefined") {
                   15990:         document.filterpicker.updater.value = caller.name;
                   15991:     }
                   15992:     document.filterpicker.submit();
                   15993: }
                   15994: 
                   15995: function hideSearching() {
                   15996:     if (document.getElementById('searching')) {
                   15997:         document.getElementById('searching').style.display = 'none';
                   15998:     }
                   15999:     return;
                   16000: }
                   16001: 
                   16002: // ]]>
                   16003: </script>
                   16004: 
                   16005: ENDJS
                   16006: }
                   16007: 
                   16008: =pod
                   16009: 
                   16010: =item * &search_courses()
                   16011: 
                   16012: Process selected filters form course search form and pass to lonnet::courseiddump
                   16013: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16014: 
                   16015: Inputs:
                   16016: 
                   16017: dom - domain being searched
                   16018: 
                   16019: type - course type ('Course' or 'Community' or '.' if any).
                   16020: 
                   16021: filter - anonymous hash of criteria and their values
                   16022: 
                   16023: numtitles - for institutional codes - number of categories
                   16024: 
                   16025: cloneruname - optional username of new course owner
                   16026: 
                   16027: clonerudom - optional domain of new course owner
                   16028: 
1.1075.2.95  raeburn  16029: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  16030:             (used when DC is using course creation form)
                   16031: 
                   16032: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16033: 
1.1075.2.95  raeburn  16034: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16035:            (and so can clone automatically)
                   16036: 
                   16037: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16038: 
                   16039: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   16040:               courses to clone
1.1075.2.69  raeburn  16041: 
                   16042: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16043: 
                   16044: 
                   16045: Side Effects: None
                   16046: 
                   16047: =cut
                   16048: 
                   16049: 
                   16050: sub search_courses {
1.1075.2.95  raeburn  16051:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   16052:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  16053:     my (%courses,%showcourses,$cloner);
                   16054:     if (($filter->{'ownerfilter'} ne '') ||
                   16055:         ($filter->{'ownerdomfilter'} ne '')) {
                   16056:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   16057:                                        $filter->{'ownerdomfilter'};
                   16058:     }
                   16059:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   16060:         if (!$filter->{$item}) {
                   16061:             $filter->{$item}='.';
                   16062:         }
                   16063:     }
                   16064:     my $now = time;
                   16065:     my $timefilter =
                   16066:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   16067:     my ($createdbefore,$createdafter);
                   16068:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   16069:         $createdbefore = $now;
                   16070:         $createdafter = $now-$filter->{'createdfilter'};
                   16071:     }
                   16072:     my ($instcodefilter,$regexpok);
                   16073:     if ($numtitles) {
                   16074:         if ($env{'form.official'} eq 'on') {
                   16075:             $instcodefilter =
                   16076:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16077:             $regexpok = 1;
                   16078:         } elsif ($env{'form.official'} eq 'off') {
                   16079:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16080:             unless ($instcodefilter eq '') {
                   16081:                 $regexpok = -1;
                   16082:             }
                   16083:         }
                   16084:     } else {
                   16085:         $instcodefilter = $filter->{'instcodefilter'};
                   16086:     }
                   16087:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   16088:     if ($type eq '') { $type = '.'; }
                   16089: 
                   16090:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   16091:         $cloner = $cloneruname.':'.$clonerudom;
                   16092:     }
                   16093:     %courses = &Apache::lonnet::courseiddump($dom,
                   16094:                                              $filter->{'descriptfilter'},
                   16095:                                              $timefilter,
                   16096:                                              $instcodefilter,
                   16097:                                              $filter->{'combownerfilter'},
                   16098:                                              $filter->{'coursefilter'},
                   16099:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  16100:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  16101:                                              $filter->{'cloneableonly'},
                   16102:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  16103:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  16104:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   16105:         my $ccrole;
                   16106:         if ($type eq 'Community') {
                   16107:             $ccrole = 'co';
                   16108:         } else {
                   16109:             $ccrole = 'cc';
                   16110:         }
                   16111:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   16112:                                                      $filter->{'persondomfilter'},
                   16113:                                                      'userroles',undef,
                   16114:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   16115:                                                      $dom);
                   16116:         foreach my $role (keys(%rolehash)) {
                   16117:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   16118:             my $cid = $cdom.'_'.$cnum;
                   16119:             if (exists($courses{$cid})) {
                   16120:                 if (ref($courses{$cid}) eq 'HASH') {
                   16121:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   16122:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1075.2.119  raeburn  16123:                             push(@{$courses{$cid}{roles}},$courserole);
1.1075.2.69  raeburn  16124:                         }
                   16125:                     } else {
                   16126:                         $courses{$cid}{roles} = [$courserole];
                   16127:                     }
                   16128:                     $showcourses{$cid} = $courses{$cid};
                   16129:                 }
                   16130:             }
                   16131:         }
                   16132:         %courses = %showcourses;
                   16133:     }
                   16134:     return %courses;
                   16135: }
                   16136: 
                   16137: =pod
                   16138: 
                   16139: =back
                   16140: 
1.1075.2.88  raeburn  16141: =head1 Routines for version requirements for current course.
                   16142: 
                   16143: =over 4
                   16144: 
                   16145: =item * &check_release_required()
                   16146: 
                   16147: Compares required LON-CAPA version with version on server, and
                   16148: if required version is newer looks for a server with the required version.
                   16149: 
                   16150: Looks first at servers in user's owen domain; if none suitable, looks at
                   16151: servers in course's domain are permitted to host sessions for user's domain.
                   16152: 
                   16153: Inputs:
                   16154: 
                   16155: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16156: 
                   16157: $courseid - Course ID of current course
                   16158: 
                   16159: $rolecode - User's current role in course (for switchserver query string).
                   16160: 
                   16161: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16162: 
                   16163: 
                   16164: Returns:
                   16165: 
                   16166: $switchserver - query string tp append to /adm/switchserver call (if
                   16167:                 current server's LON-CAPA version is too old.
                   16168: 
                   16169: $warning - Message is displayed if no suitable server could be found.
                   16170: 
                   16171: =cut
                   16172: 
                   16173: sub check_release_required {
                   16174:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16175:     my ($switchserver,$warning);
                   16176:     if ($required ne '') {
                   16177:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16178:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16179:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16180:             my $otherserver;
                   16181:             if (($major eq '' && $minor eq '') ||
                   16182:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16183:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16184:                 my $switchlcrev =
                   16185:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16186:                                                            $userdomserver);
                   16187:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16188:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16189:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16190:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16191:                     if ($cdom ne $env{'user.domain'}) {
                   16192:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16193:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16194:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16195:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16196:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16197:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16198:                         my $canhost =
                   16199:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16200:                                                               $coursedomserver,
                   16201:                                                               $remoterev,
                   16202:                                                               $udomdefaults{'remotesessions'},
                   16203:                                                               $defdomdefaults{'hostedsessions'});
                   16204: 
                   16205:                         if ($canhost) {
                   16206:                             $otherserver = $coursedomserver;
                   16207:                         } else {
                   16208:                             $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.");
                   16209:                         }
                   16210:                     } else {
                   16211:                         $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).");
                   16212:                     }
                   16213:                 } else {
                   16214:                     $otherserver = $userdomserver;
                   16215:                 }
                   16216:             }
                   16217:             if ($otherserver ne '') {
                   16218:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16219:             }
                   16220:         }
                   16221:     }
                   16222:     return ($switchserver,$warning);
                   16223: }
                   16224: 
                   16225: =pod
                   16226: 
                   16227: =item * &check_release_result()
                   16228: 
                   16229: Inputs:
                   16230: 
                   16231: $switchwarning - Warning message if no suitable server found to host session.
                   16232: 
                   16233: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16234:                 and current role.
                   16235: 
                   16236: Returns: HTML to display with information about requirement to switch server.
                   16237:          Either displaying warning with link to Roles/Courses screen or
                   16238:          display link to switchserver.
                   16239: 
1.1075.2.69  raeburn  16240: =cut
                   16241: 
1.1075.2.88  raeburn  16242: sub check_release_result {
                   16243:     my ($switchwarning,$switchserver) = @_;
                   16244:     my $output = &start_page('Selected course unavailable on this server').
                   16245:                  '<p class="LC_warning">';
                   16246:     if ($switchwarning) {
                   16247:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16248:         if (&show_course()) {
                   16249:             $output .= &mt('Display courses');
                   16250:         } else {
                   16251:             $output .= &mt('Display roles');
                   16252:         }
                   16253:         $output .= '</a>';
                   16254:     } elsif ($switchserver) {
                   16255:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16256:                    '<br />'.
                   16257:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16258:                    &mt('Switch Server').
                   16259:                    '</a>';
                   16260:     }
                   16261:     $output .= '</p>'.&end_page();
                   16262:     return $output;
                   16263: }
                   16264: 
                   16265: =pod
                   16266: 
                   16267: =item * &needs_coursereinit()
                   16268: 
                   16269: Determine if course contents stored for user's session needs to be
                   16270: refreshed, because content has changed since "Big Hash" last tied.
                   16271: 
                   16272: Check for change is made if time last checked is more than 10 minutes ago
                   16273: (by default).
                   16274: 
                   16275: Inputs:
                   16276: 
                   16277: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16278: 
                   16279: $interval (optional) - Time which may elapse (in s) between last check for content
                   16280:                        change in current course. (default: 600 s).
                   16281: 
                   16282: Returns: an array; first element is:
                   16283: 
                   16284: =over 4
                   16285: 
                   16286: 'switch' - if content updates mean user's session
                   16287:            needs to be switched to a server running a newer LON-CAPA version
                   16288: 
                   16289: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16290:            on current server hosting user's session
                   16291: 
                   16292: ''       - if no action required.
                   16293: 
                   16294: =back
                   16295: 
                   16296: If first item element is 'switch':
                   16297: 
                   16298: second item is $switchwarning - Warning message if no suitable server found to host session.
                   16299: 
                   16300: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16301:                               and current role.
                   16302: 
                   16303: otherwise: no other elements returned.
                   16304: 
                   16305: =back
                   16306: 
                   16307: =cut
                   16308: 
                   16309: sub needs_coursereinit {
                   16310:     my ($loncaparev,$interval) = @_;
                   16311:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16312:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16313:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16314:     my $now = time;
                   16315:     if ($interval eq '') {
                   16316:         $interval = 600;
                   16317:     }
                   16318:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16319:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16320:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   16321:         if ($lastchange > $env{'request.course.tied'}) {
                   16322:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16323:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16324:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16325:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16326:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16327:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16328:                     my ($switchserver,$switchwarning) =
                   16329:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   16330:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   16331:                     if ($switchwarning ne '' || $switchserver ne '') {
                   16332:                         return ('switch',$switchwarning,$switchserver);
                   16333:                     }
                   16334:                 }
                   16335:             }
                   16336:             return ('update');
                   16337:         }
                   16338:     }
                   16339:     return ();
                   16340: }
1.1075.2.69  raeburn  16341: 
1.1075.2.11  raeburn  16342: sub update_content_constraints {
                   16343:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16344:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16345:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   16346:     my %checkresponsetypes;
                   16347:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   16348:         my ($item,$name,$value) = split(/:/,$key);
                   16349:         if ($item eq 'resourcetag') {
                   16350:             if ($name eq 'responsetype') {
                   16351:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   16352:             }
                   16353:         }
                   16354:     }
                   16355:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16356:     if (defined($navmap)) {
                   16357:         my %allresponses;
                   16358:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   16359:             my %responses = $res->responseTypes();
                   16360:             foreach my $key (keys(%responses)) {
                   16361:                 next unless(exists($checkresponsetypes{$key}));
                   16362:                 $allresponses{$key} += $responses{$key};
                   16363:             }
                   16364:         }
                   16365:         foreach my $key (keys(%allresponses)) {
                   16366:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   16367:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   16368:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   16369:             }
                   16370:         }
                   16371:         undef($navmap);
                   16372:     }
                   16373:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   16374:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   16375:     }
                   16376:     return;
                   16377: }
                   16378: 
1.1075.2.27  raeburn  16379: sub allmaps_incourse {
                   16380:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16381:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   16382:         $cid = $env{'request.course.id'};
                   16383:         $cdom = $env{'course.'.$cid.'.domain'};
                   16384:         $cnum = $env{'course.'.$cid.'.num'};
                   16385:         $chome = $env{'course.'.$cid.'.home'};
                   16386:     }
                   16387:     my %allmaps = ();
                   16388:     my $lastchange =
                   16389:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16390:     if ($lastchange > $env{'request.course.tied'}) {
                   16391:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   16392:         unless ($ferr) {
                   16393:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   16394:         }
                   16395:     }
                   16396:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16397:     if (defined($navmap)) {
                   16398:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   16399:             $allmaps{$res->src()} = 1;
                   16400:         }
                   16401:     }
                   16402:     return \%allmaps;
                   16403: }
                   16404: 
1.1075.2.11  raeburn  16405: sub parse_supplemental_title {
                   16406:     my ($title) = @_;
                   16407: 
                   16408:     my ($foldertitle,$renametitle);
                   16409:     if ($title =~ /&amp;&amp;&amp;/) {
                   16410:         $title = &HTML::Entites::decode($title);
                   16411:     }
                   16412:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   16413:         $renametitle=$4;
                   16414:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16415:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16416:         my $name =  &plainname($uname,$udom);
                   16417:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16418:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16419:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16420:             $name.': <br />'.$foldertitle;
                   16421:     }
                   16422:     if (wantarray) {
                   16423:         return ($title,$foldertitle,$renametitle);
                   16424:     }
                   16425:     return $title;
                   16426: }
                   16427: 
1.1075.2.43  raeburn  16428: sub recurse_supplemental {
                   16429:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16430:     if ($suppmap) {
                   16431:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16432:         if ($fatal) {
                   16433:             $errors ++;
                   16434:         } else {
                   16435:             if ($#LONCAPA::map::resources > 0) {
                   16436:                 foreach my $res (@LONCAPA::map::resources) {
                   16437:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16438:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  16439:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16440:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  16441:                         } else {
                   16442:                             $numfiles ++;
                   16443:                         }
                   16444:                     }
                   16445:                 }
                   16446:             }
                   16447:         }
                   16448:     }
                   16449:     return ($numfiles,$errors);
                   16450: }
                   16451: 
1.1075.2.18  raeburn  16452: sub symb_to_docspath {
1.1075.2.119  raeburn  16453:     my ($symb,$navmapref) = @_;
                   16454:     return unless ($symb && ref($navmapref));
1.1075.2.18  raeburn  16455:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16456:     if ($resurl=~/\.(sequence|page)$/) {
                   16457:         $mapurl=$resurl;
                   16458:     } elsif ($resurl eq 'adm/navmaps') {
                   16459:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16460:     }
                   16461:     my $mapresobj;
1.1075.2.119  raeburn  16462:     unless (ref($$navmapref)) {
                   16463:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   16464:     }
                   16465:     if (ref($$navmapref)) {
                   16466:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1075.2.18  raeburn  16467:     }
                   16468:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16469:     my $type=$2;
                   16470:     my $path;
                   16471:     if (ref($mapresobj)) {
                   16472:         my $pcslist = $mapresobj->map_hierarchy();
                   16473:         if ($pcslist ne '') {
                   16474:             foreach my $pc (split(/,/,$pcslist)) {
                   16475:                 next if ($pc <= 1);
1.1075.2.119  raeburn  16476:                 my $res = $$navmapref->getByMapPc($pc);
1.1075.2.18  raeburn  16477:                 if (ref($res)) {
                   16478:                     my $thisurl = $res->src();
                   16479:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16480:                     my $thistitle = $res->title();
                   16481:                     $path .= '&'.
                   16482:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  16483:                              &escape($thistitle).
1.1075.2.18  raeburn  16484:                              ':'.$res->randompick().
                   16485:                              ':'.$res->randomout().
                   16486:                              ':'.$res->encrypted().
                   16487:                              ':'.$res->randomorder().
                   16488:                              ':'.$res->is_page();
                   16489:                 }
                   16490:             }
                   16491:         }
                   16492:         $path =~ s/^\&//;
                   16493:         my $maptitle = $mapresobj->title();
                   16494:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16495:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16496:         }
                   16497:         $path .= (($path ne '')? '&' : '').
                   16498:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16499:                  &escape($maptitle).
1.1075.2.18  raeburn  16500:                  ':'.$mapresobj->randompick().
                   16501:                  ':'.$mapresobj->randomout().
                   16502:                  ':'.$mapresobj->encrypted().
                   16503:                  ':'.$mapresobj->randomorder().
                   16504:                  ':'.$mapresobj->is_page();
                   16505:     } else {
                   16506:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   16507:         my $ispage = (($type eq 'page')? 1 : '');
                   16508:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16509:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16510:         }
                   16511:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16512:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  16513:     }
                   16514:     unless ($mapurl eq 'default') {
                   16515:         $path = 'default&'.
1.1075.2.46  raeburn  16516:                 &escape('Main Content').
1.1075.2.18  raeburn  16517:                 ':::::&'.$path;
                   16518:     }
                   16519:     return $path;
                   16520: }
                   16521: 
1.1075.2.14  raeburn  16522: sub captcha_display {
                   16523:     my ($context,$lonhost) = @_;
                   16524:     my ($output,$error);
1.1075.2.107  raeburn  16525:     my ($captcha,$pubkey,$privkey,$version) =
                   16526:         &get_captcha_config($context,$lonhost);
1.1075.2.14  raeburn  16527:     if ($captcha eq 'original') {
                   16528:         $output = &create_captcha();
                   16529:         unless ($output) {
                   16530:             $error = 'captcha';
                   16531:         }
                   16532:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  16533:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  16534:         unless ($output) {
                   16535:             $error = 'recaptcha';
                   16536:         }
                   16537:     }
1.1075.2.107  raeburn  16538:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  16539: }
                   16540: 
                   16541: sub captcha_response {
                   16542:     my ($context,$lonhost) = @_;
                   16543:     my ($captcha_chk,$captcha_error);
1.1075.2.109  raeburn  16544:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
1.1075.2.14  raeburn  16545:     if ($captcha eq 'original') {
                   16546:         ($captcha_chk,$captcha_error) = &check_captcha();
                   16547:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  16548:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  16549:     } else {
                   16550:         $captcha_chk = 1;
                   16551:     }
                   16552:     return ($captcha_chk,$captcha_error);
                   16553: }
                   16554: 
                   16555: sub get_captcha_config {
                   16556:     my ($context,$lonhost) = @_;
1.1075.2.107  raeburn  16557:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  16558:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   16559:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   16560:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16561:     if ($context eq 'usercreation') {
                   16562:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   16563:         if (ref($domconfig{$context}) eq 'HASH') {
                   16564:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   16565:             if (ref($hashtocheck) eq 'HASH') {
                   16566:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   16567:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   16568:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   16569:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   16570:                     }
                   16571:                     if ($privkey && $pubkey) {
                   16572:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  16573:                         $version = $hashtocheck->{'recaptchaversion'};
                   16574:                         if ($version ne '2') {
                   16575:                             $version = 1;
                   16576:                         }
1.1075.2.14  raeburn  16577:                     } else {
                   16578:                         $captcha = 'original';
                   16579:                     }
                   16580:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   16581:                     $captcha = 'original';
                   16582:                 }
                   16583:             }
                   16584:         } else {
                   16585:             $captcha = 'captcha';
                   16586:         }
                   16587:     } elsif ($context eq 'login') {
                   16588:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   16589:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   16590:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   16591:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   16592:             if ($privkey && $pubkey) {
                   16593:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  16594:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   16595:                 if ($version ne '2') {
                   16596:                     $version = 1;
                   16597:                 }
1.1075.2.14  raeburn  16598:             } else {
                   16599:                 $captcha = 'original';
                   16600:             }
                   16601:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   16602:             $captcha = 'original';
                   16603:         }
                   16604:     }
1.1075.2.107  raeburn  16605:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  16606: }
                   16607: 
                   16608: sub create_captcha {
                   16609:     my %captcha_params = &captcha_settings();
                   16610:     my ($output,$maxtries,$tries) = ('',10,0);
                   16611:     while ($tries < $maxtries) {
                   16612:         $tries ++;
                   16613:         my $captcha = Authen::Captcha->new (
                   16614:                                            output_folder => $captcha_params{'output_dir'},
                   16615:                                            data_folder   => $captcha_params{'db_dir'},
                   16616:                                           );
                   16617:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   16618: 
                   16619:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   16620:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   16621:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.66  raeburn  16622:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   16623:                       '<br />'.
                   16624:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  16625:             last;
                   16626:         }
                   16627:     }
                   16628:     return $output;
                   16629: }
                   16630: 
                   16631: sub captcha_settings {
                   16632:     my %captcha_params = (
                   16633:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   16634:                            www_output_dir => "/captchaspool",
                   16635:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   16636:                            numchars       => '5',
                   16637:                          );
                   16638:     return %captcha_params;
                   16639: }
                   16640: 
                   16641: sub check_captcha {
                   16642:     my ($captcha_chk,$captcha_error);
                   16643:     my $code = $env{'form.code'};
                   16644:     my $md5sum = $env{'form.crypt'};
                   16645:     my %captcha_params = &captcha_settings();
                   16646:     my $captcha = Authen::Captcha->new(
                   16647:                       output_folder => $captcha_params{'output_dir'},
                   16648:                       data_folder   => $captcha_params{'db_dir'},
                   16649:                   );
1.1075.2.26  raeburn  16650:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  16651:     my %captcha_hash = (
                   16652:                         0       => 'Code not checked (file error)',
                   16653:                        -1      => 'Failed: code expired',
                   16654:                        -2      => 'Failed: invalid code (not in database)',
                   16655:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   16656:     );
                   16657:     if ($captcha_chk != 1) {
                   16658:         $captcha_error = $captcha_hash{$captcha_chk}
                   16659:     }
                   16660:     return ($captcha_chk,$captcha_error);
                   16661: }
                   16662: 
                   16663: sub create_recaptcha {
1.1075.2.107  raeburn  16664:     my ($pubkey,$version) = @_;
                   16665:     if ($version >= 2) {
                   16666:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   16667:     } else {
                   16668:         my $use_ssl;
                   16669:         if ($ENV{'SERVER_PORT'} == 443) {
                   16670:             $use_ssl = 1;
                   16671:         }
                   16672:         my $captcha = Captcha::reCAPTCHA->new;
                   16673:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   16674:                $captcha->get_html($pubkey,undef,$use_ssl).
                   16675:                &mt('If the text is hard to read, [_1] will replace them.',
                   16676:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   16677:                '<br /><br />';
                   16678:      }
1.1075.2.14  raeburn  16679: }
                   16680: 
                   16681: sub check_recaptcha {
1.1075.2.107  raeburn  16682:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  16683:     my $captcha_chk;
1.1075.2.107  raeburn  16684:     if ($version >= 2) {
                   16685:         my $ua = LWP::UserAgent->new;
                   16686:         $ua->timeout(10);
                   16687:         my %info = (
                   16688:                      secret   => $privkey,
                   16689:                      response => $env{'form.g-recaptcha-response'},
                   16690:                      remoteip => $ENV{'REMOTE_ADDR'},
                   16691:                    );
                   16692:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   16693:         if ($response->is_success)  {
                   16694:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   16695:             if (ref($data) eq 'HASH') {
                   16696:                 if ($data->{'success'}) {
                   16697:                     $captcha_chk = 1;
                   16698:                 }
                   16699:             }
                   16700:         }
                   16701:     } else {
                   16702:         my $captcha = Captcha::reCAPTCHA->new;
                   16703:         my $captcha_result =
                   16704:             $captcha->check_answer(
                   16705:                                     $privkey,
                   16706:                                     $ENV{'REMOTE_ADDR'},
                   16707:                                     $env{'form.recaptcha_challenge_field'},
                   16708:                                     $env{'form.recaptcha_response_field'},
                   16709:                                   );
                   16710:         if ($captcha_result->{is_valid}) {
                   16711:             $captcha_chk = 1;
                   16712:         }
1.1075.2.14  raeburn  16713:     }
                   16714:     return $captcha_chk;
                   16715: }
                   16716: 
1.1075.2.64  raeburn  16717: sub emailusername_info {
1.1075.2.103  raeburn  16718:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  16719:     my %titles = &Apache::lonlocal::texthash (
                   16720:                      lastname      => 'Last Name',
                   16721:                      firstname     => 'First Name',
                   16722:                      institution   => 'School/college/university',
                   16723:                      location      => "School's city, state/province, country",
                   16724:                      web           => "School's web address",
                   16725:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  16726:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  16727:                  );
                   16728:     return (\@fields,\%titles);
                   16729: }
                   16730: 
1.1075.2.56  raeburn  16731: sub cleanup_html {
                   16732:     my ($incoming) = @_;
                   16733:     my $outgoing;
                   16734:     if ($incoming ne '') {
                   16735:         $outgoing = $incoming;
                   16736:         $outgoing =~ s/;/&#059;/g;
                   16737:         $outgoing =~ s/\#/&#035;/g;
                   16738:         $outgoing =~ s/\&/&#038;/g;
                   16739:         $outgoing =~ s/</&#060;/g;
                   16740:         $outgoing =~ s/>/&#062;/g;
                   16741:         $outgoing =~ s/\(/&#040/g;
                   16742:         $outgoing =~ s/\)/&#041;/g;
                   16743:         $outgoing =~ s/"/&#034;/g;
                   16744:         $outgoing =~ s/'/&#039;/g;
                   16745:         $outgoing =~ s/\$/&#036;/g;
                   16746:         $outgoing =~ s{/}{&#047;}g;
                   16747:         $outgoing =~ s/=/&#061;/g;
                   16748:         $outgoing =~ s/\\/&#092;/g
                   16749:     }
                   16750:     return $outgoing;
                   16751: }
                   16752: 
1.1075.2.74  raeburn  16753: # Checks for critical messages and returns a redirect url if one exists.
                   16754: # $interval indicates how often to check for messages.
                   16755: sub critical_redirect {
                   16756:     my ($interval) = @_;
                   16757:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   16758:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   16759:                                         $env{'user.name'});
                   16760:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   16761:         my $redirecturl;
                   16762:         if ($what[0]) {
                   16763:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   16764:                 $redirecturl='/adm/email?critical=display';
                   16765:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   16766:                 return (1, $url);
                   16767:             }
                   16768:         }
                   16769:     }
                   16770:     return ();
                   16771: }
                   16772: 
1.1075.2.64  raeburn  16773: # Use:
                   16774: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   16775: #
                   16776: ##################################################
                   16777: #          password associated functions         #
                   16778: ##################################################
                   16779: sub des_keys {
                   16780:     # Make a new key for DES encryption.
                   16781:     # Each key has two parts which are returned separately.
                   16782:     # Please note:  Each key must be passed through the &hex function
                   16783:     # before it is output to the web browser.  The hex versions cannot
                   16784:     # be used to decrypt.
                   16785:     my @hexstr=('0','1','2','3','4','5','6','7',
                   16786:                 '8','9','a','b','c','d','e','f');
                   16787:     my $lkey='';
                   16788:     for (0..7) {
                   16789:         $lkey.=$hexstr[rand(15)];
                   16790:     }
                   16791:     my $ukey='';
                   16792:     for (0..7) {
                   16793:         $ukey.=$hexstr[rand(15)];
                   16794:     }
                   16795:     return ($lkey,$ukey);
                   16796: }
                   16797: 
                   16798: sub des_decrypt {
                   16799:     my ($key,$cyphertext) = @_;
                   16800:     my $keybin=pack("H16",$key);
                   16801:     my $cypher;
                   16802:     if ($Crypt::DES::VERSION>=2.03) {
                   16803:         $cypher=new Crypt::DES $keybin;
                   16804:     } else {
                   16805:         $cypher=new DES $keybin;
                   16806:     }
1.1075.2.106  raeburn  16807:     my $plaintext='';
                   16808:     my $cypherlength = length($cyphertext);
                   16809:     my $numchunks = int($cypherlength/32);
                   16810:     for (my $j=0; $j<$numchunks; $j++) {
                   16811:         my $start = $j*32;
                   16812:         my $cypherblock = substr($cyphertext,$start,32);
                   16813:         my $chunk =
                   16814:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   16815:         $chunk .=
                   16816:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   16817:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   16818:         $plaintext .= $chunk;
                   16819:     }
1.1075.2.64  raeburn  16820:     return $plaintext;
                   16821: }
                   16822: 
1.112     bowersj2 16823: 1;
                   16824: __END__;
1.41      ng       16825: 

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