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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1241  ! raeburn     4: # $Id: loncommon.pm,v 1.1240 2016/04/05 02:02:27 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1108    raeburn    70: use Apache::lonuserutils();
1.1110    raeburn    71: use Apache::lonuserstate();
1.1182    raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    74: use DateTime::TimeZone;
1.1241  ! raeburn    75: use DateTime::Locale;
1.1220    raeburn    76: use Encode();
1.1091    foxr       77: use Text::Aspell;
1.1094    raeburn    78: use Authen::Captcha;
                     79: use Captcha::reCAPTCHA;
1.1234    raeburn    80: use JSON::DWIW;
                     81: use LWP::UserAgent;
1.1174    raeburn    82: use Crypt::DES;
                     83: use DynaLoader; # for Crypt::DES version
1.1223    musolffc   84: use MIME::Lite;
                     85: use MIME::Types;
1.117     www        86: 
1.517     raeburn    87: # ---------------------------------------------- Designs
                     88: use vars qw(%defaultdesign);
                     89: 
1.22      www        90: my $readit;
                     91: 
1.517     raeburn    92: 
1.157     matthew    93: ##
                     94: ## Global Variables
                     95: ##
1.46      matthew    96: 
1.643     foxr       97: 
                     98: # ----------------------------------------------- SSI with retries:
                     99: #
                    100: 
                    101: =pod
                    102: 
1.648     raeburn   103: =head1 Server Side include with retries:
1.643     foxr      104: 
                    105: =over 4
                    106: 
1.648     raeburn   107: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      108: 
                    109: Performs an ssi with some number of retries.  Retries continue either
                    110: until the result is ok or until the retry count supplied by the
                    111: caller is exhausted.  
                    112: 
                    113: Inputs:
1.648     raeburn   114: 
                    115: =over 4
                    116: 
1.643     foxr      117: resource   - Identifies the resource to insert.
1.648     raeburn   118: 
1.643     foxr      119: retries    - Count of the number of retries allowed.
1.648     raeburn   120: 
1.643     foxr      121: form       - Hash that identifies the rendering options.
                    122: 
1.648     raeburn   123: =back
                    124: 
                    125: Returns:
                    126: 
                    127: =over 4
                    128: 
1.643     foxr      129: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   130: 
1.643     foxr      131: response   - The response from the last attempt (which may or may not have been successful.
                    132: 
1.648     raeburn   133: =back
                    134: 
                    135: =back
                    136: 
1.643     foxr      137: =cut
                    138: 
                    139: sub ssi_with_retries {
                    140:     my ($resource, $retries, %form) = @_;
                    141: 
                    142: 
                    143:     my $ok = 0;			# True if we got a good response.
                    144:     my $content;
                    145:     my $response;
                    146: 
                    147:     # Try to get the ssi done. within the retries count:
                    148: 
                    149:     do {
                    150: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    151: 	$ok      = $response->is_success;
1.650     www       152:         if (!$ok) {
                    153:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    154:         }
1.643     foxr      155: 	$retries--;
                    156:     } while (!$ok && ($retries > 0));
                    157: 
                    158:     if (!$ok) {
                    159: 	$content = '';		# On error return an empty content.
                    160:     }
                    161:     return ($content, $response);
                    162: 
                    163: }
                    164: 
                    165: 
                    166: 
1.20      www       167: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  168: my %language;
1.124     www       169: my %supported_language;
1.1088    foxr      170: my %supported_codes;
1.1048    foxr      171: my %latex_language;		# For choosing hyphenation in <transl..>
                    172: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  173: my %cprtag;
1.192     taceyjo1  174: my %scprtag;
1.351     www       175: my %fe; my %fd; my %fm;
1.41      ng        176: my %category_extensions;
1.12      harris41  177: 
1.46      matthew   178: # ---------------------------------------------- Thesaurus variables
1.144     matthew   179: #
                    180: # %Keywords:
                    181: #      A hash used by &keyword to determine if a word is considered a keyword.
                    182: # $thesaurus_db_file 
                    183: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   184: 
                    185: my %Keywords;
                    186: my $thesaurus_db_file;
                    187: 
1.144     matthew   188: #
                    189: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    190: # thesaurus.tab, and filecategories.tab.
                    191: #
1.18      www       192: BEGIN {
1.46      matthew   193:     # Variable initialization
                    194:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    195:     #
1.22      www       196:     unless ($readit) {
1.12      harris41  197: # ------------------------------------------------------------------- languages
                    198:     {
1.158     raeburn   199:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    200:                                    '/language.tab';
                    201:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  202:             while (my $line = <$fh>) {
                    203:                 next if ($line=~/^\#/);
                    204:                 chomp($line);
1.1088    foxr      205:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   206:                 $language{$key}=$val.' - '.$enc;
                    207:                 if ($sup) {
                    208:                     $supported_language{$key}=$sup;
1.1088    foxr      209: 		    $supported_codes{$key}   = $code;
1.158     raeburn   210:                 }
1.1048    foxr      211: 		if ($latex) {
                    212: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      213: 		    $latex_language{$code} = $latex;
1.1048    foxr      214: 		}
1.158     raeburn   215:             }
                    216:             close($fh);
                    217:         }
1.12      harris41  218:     }
                    219: # ------------------------------------------------------------------ copyrights
                    220:     {
1.158     raeburn   221:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    222:                                   '/copyright.tab';
                    223:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  224:             while (my $line = <$fh>) {
                    225:                 next if ($line=~/^\#/);
                    226:                 chomp($line);
                    227:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   228:                 $cprtag{$key}=$val;
                    229:             }
                    230:             close($fh);
                    231:         }
1.12      harris41  232:     }
1.351     www       233: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  234:     {
                    235:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    236:                                   '/source_copyright.tab';
                    237:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  238:             while (my $line = <$fh>) {
                    239:                 next if ($line =~ /^\#/);
                    240:                 chomp($line);
                    241:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  242:                 $scprtag{$key}=$val;
                    243:             }
                    244:             close($fh);
                    245:         }
                    246:     }
1.63      www       247: 
1.517     raeburn   248: # -------------------------------------------------------------- default domain designs
1.63      www       249:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   250:     my $designfile = $designdir.'/default.tab';
                    251:     if ( open (my $fh,"<$designfile") ) {
                    252:         while (my $line = <$fh>) {
                    253:             next if ($line =~ /^\#/);
                    254:             chomp($line);
                    255:             my ($key,$val)=(split(/\=/,$line));
                    256:             if ($val) { $defaultdesign{$key}=$val; }
                    257:         }
                    258:         close($fh);
1.63      www       259:     }
                    260: 
1.15      harris41  261: # ------------------------------------------------------------- file categories
                    262:     {
1.158     raeburn   263:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    264:                                   '/filecategories.tab';
                    265:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  266: 	    while (my $line = <$fh>) {
                    267: 		next if ($line =~ /^\#/);
                    268: 		chomp($line);
                    269:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.158     raeburn   270:                 push @{$category_extensions{lc($category)}},$extension;
                    271:             }
                    272:             close($fh);
                    273:         }
                    274: 
1.15      harris41  275:     }
1.12      harris41  276: # ------------------------------------------------------------------ file types
                    277:     {
1.158     raeburn   278:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    279:                '/filetypes.tab';
                    280:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  281:             while (my $line = <$fh>) {
                    282: 		next if ($line =~ /^\#/);
                    283: 		chomp($line);
                    284:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   285:                 if ($descr ne '') {
                    286:                     $fe{$ending}=lc($emb);
                    287:                     $fd{$ending}=$descr;
1.351     www       288:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   289:                 }
                    290:             }
                    291:             close($fh);
                    292:         }
1.12      harris41  293:     }
1.22      www       294:     &Apache::lonnet::logthis(
1.705     tempelho  295:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       296:     $readit=1;
1.46      matthew   297:     }  # end of unless($readit) 
1.32      matthew   298:     
                    299: }
1.112     bowersj2  300: 
1.42      matthew   301: ###############################################################
                    302: ##           HTML and Javascript Helper Functions            ##
                    303: ###############################################################
                    304: 
                    305: =pod 
                    306: 
1.112     bowersj2  307: =head1 HTML and Javascript Functions
1.42      matthew   308: 
1.112     bowersj2  309: =over 4
                    310: 
1.648     raeburn   311: =item * &browser_and_searcher_javascript()
1.112     bowersj2  312: 
                    313: X<browsing, javascript>X<searching, javascript>Returns a string
                    314: containing javascript with two functions, C<openbrowser> and
                    315: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    316: tags.
1.42      matthew   317: 
1.648     raeburn   318: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   319: 
                    320: inputs: formname, elementname, only, omit
                    321: 
                    322: formname and elementname indicate the name of the html form and name of
                    323: the element that the results of the browsing selection are to be placed in. 
                    324: 
                    325: Specifying 'only' will restrict the browser to displaying only files
1.185     www       326: with the given extension.  Can be a comma separated list.
1.42      matthew   327: 
                    328: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       329: with the given extension.  Can be a comma separated list.
1.42      matthew   330: 
1.648     raeburn   331: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   332: 
                    333: Inputs: formname, elementname
                    334: 
                    335: formname and elementname specify the name of the html form and the name
                    336: of the element the selection from the search results will be placed in.
1.542     raeburn   337: 
1.42      matthew   338: =cut
                    339: 
                    340: sub browser_and_searcher_javascript {
1.199     albertel  341:     my ($mode)=@_;
                    342:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  343:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   344:     return <<END;
1.219     albertel  345: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   346:     var editbrowser = null;
1.135     albertel  347:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       348:         var url = '$resurl/?';
1.42      matthew   349:         if (editbrowser == null) {
                    350:             url += 'launch=1&';
                    351:         }
                    352:         url += 'catalogmode=interactive&';
1.199     albertel  353:         url += 'mode=$mode&';
1.611     albertel  354:         url += 'inhibitmenu=yes&';
1.42      matthew   355:         url += 'form=' + formname + '&';
                    356:         if (only != null) {
                    357:             url += 'only=' + only + '&';
1.217     albertel  358:         } else {
                    359:             url += 'only=&';
                    360: 	}
1.42      matthew   361:         if (omit != null) {
                    362:             url += 'omit=' + omit + '&';
1.217     albertel  363:         } else {
                    364:             url += 'omit=&';
                    365: 	}
1.135     albertel  366:         if (titleelement != null) {
                    367:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  368:         } else {
                    369: 	    url += 'titleelement=&';
                    370: 	}
1.42      matthew   371:         url += 'element=' + elementname + '';
                    372:         var title = 'Browser';
1.435     albertel  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   374:         options += ',width=700,height=600';
                    375:         editbrowser = open(url,title,options,'1');
                    376:         editbrowser.focus();
                    377:     }
                    378:     var editsearcher;
1.135     albertel  379:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   380:         var url = '/adm/searchcat?';
                    381:         if (editsearcher == null) {
                    382:             url += 'launch=1&';
                    383:         }
                    384:         url += 'catalogmode=interactive&';
1.199     albertel  385:         url += 'mode=$mode&';
1.42      matthew   386:         url += 'form=' + formname + '&';
1.135     albertel  387:         if (titleelement != null) {
                    388:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  389:         } else {
                    390: 	    url += 'titleelement=&';
                    391: 	}
1.42      matthew   392:         url += 'element=' + elementname + '';
                    393:         var title = 'Search';
1.435     albertel  394:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   395:         options += ',width=700,height=600';
                    396:         editsearcher = open(url,title,options,'1');
                    397:         editsearcher.focus();
                    398:     }
1.219     albertel  399: // END LON-CAPA Internal -->
1.42      matthew   400: END
1.170     www       401: }
                    402: 
                    403: sub lastresurl {
1.258     albertel  404:     if ($env{'environment.lastresurl'}) {
                    405: 	return $env{'environment.lastresurl'}
1.170     www       406:     } else {
                    407: 	return '/res';
                    408:     }
                    409: }
                    410: 
                    411: sub storeresurl {
                    412:     my $resurl=&Apache::lonnet::clutter(shift);
                    413:     unless ($resurl=~/^\/res/) { return 0; }
                    414:     $resurl=~s/\/$//;
                    415:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   416:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       417:     return 1;
1.42      matthew   418: }
                    419: 
1.74      www       420: sub studentbrowser_javascript {
1.111     www       421:    unless (
1.258     albertel  422:             (($env{'request.course.id'}) && 
1.302     albertel  423:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    424: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    425: 					  '/'.$env{'request.course.sec'})
                    426: 	      ))
1.258     albertel  427:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       428:           ) { return ''; }  
1.74      www       429:    return (<<'ENDSTDBRW');
1.776     bisitz    430: <script type="text/javascript" language="Javascript">
1.824     bisitz    431: // <![CDATA[
1.74      www       432:     var stdeditbrowser;
1.999     www       433:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       434:         var url = '/adm/pickstudent?';
                    435:         var filter;
1.558     albertel  436: 	if (!ignorefilter) {
                    437: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    438: 	}
1.74      www       439:         if (filter != null) {
                    440:            if (filter != '') {
                    441:                url += 'filter='+filter+'&';
                    442: 	   }
                    443:         }
                    444:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       445:                                     '&udomelement='+udom+
                    446:                                     '&clicker='+clicker;
1.111     www       447: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   448:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       449:         var title = 'Student_Browser';
1.74      www       450:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    451:         options += ',width=700,height=600';
                    452:         stdeditbrowser = open(url,title,options,'1');
                    453:         stdeditbrowser.focus();
                    454:     }
1.824     bisitz    455: // ]]>
1.74      www       456: </script>
                    457: ENDSTDBRW
                    458: }
1.42      matthew   459: 
1.1003    www       460: sub resourcebrowser_javascript {
                    461:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       462:    return (<<'ENDRESBRW');
1.1003    www       463: <script type="text/javascript" language="Javascript">
                    464: // <![CDATA[
                    465:     var reseditbrowser;
1.1004    www       466:     function openresbrowser(formname,reslink) {
1.1005    www       467:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       468:         var title = 'Resource_Browser';
                    469:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       470:         options += ',width=700,height=500';
1.1004    www       471:         reseditbrowser = open(url,title,options,'1');
                    472:         reseditbrowser.focus();
1.1003    www       473:     }
                    474: // ]]>
                    475: </script>
1.1004    www       476: ENDRESBRW
1.1003    www       477: }
                    478: 
1.74      www       479: sub selectstudent_link {
1.999     www       480:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    481:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    482:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    483:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  484:    if ($env{'request.course.id'}) {  
1.302     albertel  485:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    486: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    487: 					'/'.$env{'request.course.sec'})) {
1.111     www       488: 	   return '';
                    489:        }
1.999     www       490:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   491:        if ($courseadvonly)  {
                    492:            $callargs .= ",'',1,1";
                    493:        }
                    494:        return '<span class="LC_nobreak">'.
                    495:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    496:               &mt('Select User').'</a></span>';
1.74      www       497:    }
1.258     albertel  498:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       499:        $callargs .= ",'',1"; 
1.793     raeburn   500:        return '<span class="LC_nobreak">'.
                    501:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    502:               &mt('Select User').'</a></span>';
1.111     www       503:    }
                    504:    return '';
1.91      www       505: }
                    506: 
1.1004    www       507: sub selectresource_link {
                    508:    my ($form,$reslink,$arg)=@_;
                    509:    
                    510:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    511:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    512:    unless ($env{'request.course.id'}) { return $arg; }
                    513:    return '<span class="LC_nobreak">'.
                    514:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    515:               $arg.'</a></span>';
                    516: }
                    517: 
                    518: 
                    519: 
1.653     raeburn   520: sub authorbrowser_javascript {
                    521:     return <<"ENDAUTHORBRW";
1.776     bisitz    522: <script type="text/javascript" language="JavaScript">
1.824     bisitz    523: // <![CDATA[
1.653     raeburn   524: var stdeditbrowser;
                    525: 
                    526: function openauthorbrowser(formname,udom) {
                    527:     var url = '/adm/pickauthor?';
                    528:     url += 'form='+formname+'&roledom='+udom;
                    529:     var title = 'Author_Browser';
                    530:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    531:     options += ',width=700,height=600';
                    532:     stdeditbrowser = open(url,title,options,'1');
                    533:     stdeditbrowser.focus();
                    534: }
                    535: 
1.824     bisitz    536: // ]]>
1.653     raeburn   537: </script>
                    538: ENDAUTHORBRW
                    539: }
                    540: 
1.91      www       541: sub coursebrowser_javascript {
1.1116    raeburn   542:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   543:         $credits_element,$instcode) = @_;
1.932     raeburn   544:     my $wintitle = 'Course_Browser';
1.931     raeburn   545:     if ($crstype eq 'Community') {
1.932     raeburn   546:         $wintitle = 'Community_Browser';
1.909     raeburn   547:     }
1.876     raeburn   548:     my $id_functions = &javascript_index_functions();
                    549:     my $output = '
1.776     bisitz    550: <script type="text/javascript" language="JavaScript">
1.824     bisitz    551: // <![CDATA[
1.468     raeburn   552:     var stdeditbrowser;'."\n";
1.876     raeburn   553: 
                    554:     $output .= <<"ENDSTDBRW";
1.909     raeburn   555:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       556:         var url = '/adm/pickcourse?';
1.895     raeburn   557:         var formid = getFormIdByName(formname);
1.876     raeburn   558:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  559:         if (domainfilter != null) {
                    560:            if (domainfilter != '') {
                    561:                url += 'domainfilter='+domainfilter+'&';
                    562: 	   }
                    563:         }
1.91      www       564:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  565: 	                            '&cdomelement='+udom+
                    566:                                     '&cnameelement='+desc;
1.468     raeburn   567:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   568:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   569:                 url += '&roleelement='+extra_element;
                    570:                 if (domainfilter == null || domainfilter == '') {
                    571:                     url += '&domainfilter='+extra_element;
                    572:                 }
1.234     raeburn   573:             }
1.468     raeburn   574:             else {
                    575:                 if (formname == 'portform') {
                    576:                     url += '&setroles='+extra_element;
1.800     raeburn   577:                 } else {
                    578:                     if (formname == 'rules') {
                    579:                         url += '&fixeddom='+extra_element; 
                    580:                     }
1.468     raeburn   581:                 }
                    582:             }     
1.230     raeburn   583:         }
1.909     raeburn   584:         if (type != null && type != '') {
                    585:             url += '&type='+type;
                    586:         }
                    587:         if (type_elem != null && type_elem != '') {
                    588:             url += '&typeelement='+type_elem;
                    589:         }
1.872     raeburn   590:         if (formname == 'ccrs') {
                    591:             var ownername = document.forms[formid].ccuname.value;
                    592:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   593:             url += '&cloner='+ownername+':'+ownerdom;
                    594:             if (type == 'Course') {
                    595:                 url += '&crscode='+document.forms[formid].crscode.value;
                    596:             }
1.1221    raeburn   597:         }
                    598:         if (formname == 'requestcrs') {
                    599:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   600:         }
1.293     raeburn   601:         if (multflag !=null && multflag != '') {
                    602:             url += '&multiple='+multflag;
                    603:         }
1.909     raeburn   604:         var title = '$wintitle';
1.91      www       605:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    606:         options += ',width=700,height=600';
                    607:         stdeditbrowser = open(url,title,options,'1');
                    608:         stdeditbrowser.focus();
                    609:     }
1.876     raeburn   610: $id_functions
                    611: ENDSTDBRW
1.1116    raeburn   612:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    613:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    614:                                       $credits_element);
1.876     raeburn   615:     }
                    616:     $output .= '
                    617: // ]]>
                    618: </script>';
                    619:     return $output;
                    620: }
                    621: 
                    622: sub javascript_index_functions {
                    623:     return <<"ENDJS";
                    624: 
                    625: function getFormIdByName(formname) {
                    626:     for (var i=0;i<document.forms.length;i++) {
                    627:         if (document.forms[i].name == formname) {
                    628:             return i;
                    629:         }
                    630:     }
                    631:     return -1;
                    632: }
                    633: 
                    634: function getIndexByName(formid,item) {
                    635:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    636:         if (document.forms[formid].elements[i].name == item) {
                    637:             return i;
                    638:         }
                    639:     }
                    640:     return -1;
                    641: }
1.468     raeburn   642: 
1.876     raeburn   643: function getDomainFromSelectbox(formname,udom) {
                    644:     var userdom;
                    645:     var formid = getFormIdByName(formname);
                    646:     if (formid > -1) {
                    647:         var domid = getIndexByName(formid,udom);
                    648:         if (domid > -1) {
                    649:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    650:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    651:             }
                    652:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    653:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   654:             }
                    655:         }
                    656:     }
1.876     raeburn   657:     return userdom;
                    658: }
                    659: 
                    660: ENDJS
1.468     raeburn   661: 
1.876     raeburn   662: }
                    663: 
1.1017    raeburn   664: sub javascript_array_indexof {
1.1018    raeburn   665:     return <<ENDJS;
1.1017    raeburn   666: <script type="text/javascript" language="JavaScript">
                    667: // <![CDATA[
                    668: 
                    669: if (!Array.prototype.indexOf) {
                    670:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    671:         "use strict";
                    672:         if (this === void 0 || this === null) {
                    673:             throw new TypeError();
                    674:         }
                    675:         var t = Object(this);
                    676:         var len = t.length >>> 0;
                    677:         if (len === 0) {
                    678:             return -1;
                    679:         }
                    680:         var n = 0;
                    681:         if (arguments.length > 0) {
                    682:             n = Number(arguments[1]);
1.1088    foxr      683:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   684:                 n = 0;
                    685:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    686:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    687:             }
                    688:         }
                    689:         if (n >= len) {
                    690:             return -1;
                    691:         }
                    692:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    693:         for (; k < len; k++) {
                    694:             if (k in t && t[k] === searchElement) {
                    695:                 return k;
                    696:             }
                    697:         }
                    698:         return -1;
                    699:     }
                    700: }
                    701: 
                    702: // ]]>
                    703: </script>
                    704: 
                    705: ENDJS
                    706: 
                    707: }
                    708: 
1.876     raeburn   709: sub userbrowser_javascript {
                    710:     my $id_functions = &javascript_index_functions();
                    711:     return <<"ENDUSERBRW";
                    712: 
1.888     raeburn   713: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   714:     var url = '/adm/pickuser?';
                    715:     var userdom = getDomainFromSelectbox(formname,udom);
                    716:     if (userdom != null) {
                    717:        if (userdom != '') {
                    718:            url += 'srchdom='+userdom+'&';
                    719:        }
                    720:     }
                    721:     url += 'form=' + formname + '&unameelement='+uname+
                    722:                                 '&udomelement='+udom+
                    723:                                 '&ulastelement='+ulast+
                    724:                                 '&ufirstelement='+ufirst+
                    725:                                 '&uemailelement='+uemail+
1.881     raeburn   726:                                 '&hideudomelement='+hideudom+
                    727:                                 '&coursedom='+crsdom;
1.888     raeburn   728:     if ((caller != null) && (caller != undefined)) {
                    729:         url += '&caller='+caller;
                    730:     }
1.876     raeburn   731:     var title = 'User_Browser';
                    732:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    733:     options += ',width=700,height=600';
                    734:     var stdeditbrowser = open(url,title,options,'1');
                    735:     stdeditbrowser.focus();
                    736: }
                    737: 
1.888     raeburn   738: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   739:     var formid = getFormIdByName(formname);
                    740:     if (formid > -1) {
1.888     raeburn   741:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   742:         var domid = getIndexByName(formid,udom);
                    743:         var hidedomid = getIndexByName(formid,origdom);
                    744:         if (hidedomid > -1) {
                    745:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   746:             var unameval = document.forms[formid].elements[unameid].value;
                    747:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    748:                 if (domid > -1) {
                    749:                     var slct = document.forms[formid].elements[domid];
                    750:                     if (slct.type == 'select-one') {
                    751:                         var i;
                    752:                         for (i=0;i<slct.length;i++) {
                    753:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    754:                         }
                    755:                     }
                    756:                     if (slct.type == 'hidden') {
                    757:                         slct.value = fixeddom;
1.876     raeburn   758:                     }
                    759:                 }
1.468     raeburn   760:             }
                    761:         }
                    762:     }
1.876     raeburn   763:     return;
                    764: }
                    765: 
                    766: $id_functions
                    767: ENDUSERBRW
1.468     raeburn   768: }
                    769: 
                    770: sub setsec_javascript {
1.1116    raeburn   771:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   772:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    773:         $communityrolestr);
                    774:     if ($role_element ne '') {
                    775:         my @allroles = ('st','ta','ep','in','ad');
                    776:         foreach my $crstype ('Course','Community') {
                    777:             if ($crstype eq 'Community') {
                    778:                 foreach my $role (@allroles) {
                    779:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    780:                 }
                    781:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    782:             } else {
                    783:                 foreach my $role (@allroles) {
                    784:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    785:                 }
                    786:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    787:             }
                    788:         }
                    789:         $rolestr = '"'.join('","',@allroles).'"';
                    790:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    791:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    792:     }
1.468     raeburn   793:     my $setsections = qq|
                    794: function setSect(sectionlist) {
1.629     raeburn   795:     var sectionsArray = new Array();
                    796:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    797:         sectionsArray = sectionlist.split(",");
                    798:     }
1.468     raeburn   799:     var numSections = sectionsArray.length;
                    800:     document.$formname.$sec_element.length = 0;
                    801:     if (numSections == 0) {
                    802:         document.$formname.$sec_element.multiple=false;
                    803:         document.$formname.$sec_element.size=1;
                    804:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    805:     } else {
                    806:         if (numSections == 1) {
                    807:             document.$formname.$sec_element.multiple=false;
                    808:             document.$formname.$sec_element.size=1;
                    809:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    810:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    811:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    812:         } else {
                    813:             for (var i=0; i<numSections; i++) {
                    814:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    815:             }
                    816:             document.$formname.$sec_element.multiple=true
                    817:             if (numSections < 3) {
                    818:                 document.$formname.$sec_element.size=numSections;
                    819:             } else {
                    820:                 document.$formname.$sec_element.size=3;
                    821:             }
                    822:             document.$formname.$sec_element.options[0].selected = false
                    823:         }
                    824:     }
1.91      www       825: }
1.905     raeburn   826: 
                    827: function setRole(crstype) {
1.468     raeburn   828: |;
1.905     raeburn   829:     if ($role_element eq '') {
                    830:         $setsections .= '    return;
                    831: }
                    832: ';
                    833:     } else {
                    834:         $setsections .= qq|
                    835:     var elementLength = document.$formname.$role_element.length;
                    836:     var allroles = Array($rolestr);
                    837:     var courserolenames = Array($courserolestr);
                    838:     var communityrolenames = Array($communityrolestr);
                    839:     if (elementLength != undefined) {
                    840:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    841:             if (crstype == 'Course') {
                    842:                 return;
                    843:             } else {
                    844:                 allroles[5] = 'co';
                    845:                 for (var i=0; i<6; i++) {
                    846:                     document.$formname.$role_element.options[i].value = allroles[i];
                    847:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    848:                 }
                    849:             }
                    850:         } else {
                    851:             if (crstype == 'Community') {
                    852:                 return;
                    853:             } else {
                    854:                 allroles[5] = 'cc';
                    855:                 for (var i=0; i<6; i++) {
                    856:                     document.$formname.$role_element.options[i].value = allroles[i];
                    857:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    858:                 }
                    859:             }
                    860:         }
                    861:     }
                    862:     return;
                    863: }
                    864: |;
                    865:     }
1.1116    raeburn   866:     if ($credits_element) {
                    867:         $setsections .= qq|
                    868: function setCredits(defaultcredits) {
                    869:     document.$formname.$credits_element.value = defaultcredits;
                    870:     return;
                    871: }
                    872: |;
                    873:     }
1.468     raeburn   874:     return $setsections;
                    875: }
                    876: 
1.91      www       877: sub selectcourse_link {
1.909     raeburn   878:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    879:        $typeelement) = @_;
                    880:    my $type = $selecttype;
1.871     raeburn   881:    my $linktext = &mt('Select Course');
                    882:    if ($selecttype eq 'Community') {
1.909     raeburn   883:        $linktext = &mt('Select Community');
1.1239    raeburn   884:    } elsif ($selecttype eq 'Placement') {
                    885:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   886:    } elsif ($selecttype eq 'Course/Community') {
                    887:        $linktext = &mt('Select Course/Community');
1.909     raeburn   888:        $type = '';
1.1019    raeburn   889:    } elsif ($selecttype eq 'Select') {
                    890:        $linktext = &mt('Select');
                    891:        $type = '';
1.871     raeburn   892:    }
1.787     bisitz    893:    return '<span class="LC_nobreak">'
                    894:          ."<a href='"
                    895:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    896:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   897:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   898:          ."'>".$linktext.'</a>'
1.787     bisitz    899:          .'</span>';
1.74      www       900: }
1.42      matthew   901: 
1.653     raeburn   902: sub selectauthor_link {
                    903:    my ($form,$udom)=@_;
                    904:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    905:           &mt('Select Author').'</a>';
                    906: }
                    907: 
1.876     raeburn   908: sub selectuser_link {
1.881     raeburn   909:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   910:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   911:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   912:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   913:            ');">'.$linktext.'</a>';
1.876     raeburn   914: }
                    915: 
1.273     raeburn   916: sub check_uncheck_jscript {
                    917:     my $jscript = <<"ENDSCRT";
                    918: function checkAll(field) {
                    919:     if (field.length > 0) {
                    920:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   921:             if (!field[i].disabled) { 
                    922:                 field[i].checked = true;
                    923:             }
1.273     raeburn   924:         }
                    925:     } else {
1.1093    raeburn   926:         if (!field.disabled) { 
                    927:             field.checked = true;
                    928:         }
1.273     raeburn   929:     }
                    930: }
                    931:  
                    932: function uncheckAll(field) {
                    933:     if (field.length > 0) {
                    934:         for (i = 0; i < field.length; i++) {
                    935:             field[i].checked = false ;
1.543     albertel  936:         }
                    937:     } else {
1.273     raeburn   938:         field.checked = false ;
                    939:     }
                    940: }
                    941: ENDSCRT
                    942:     return $jscript;
                    943: }
                    944: 
1.656     www       945: sub select_timezone {
1.659     raeburn   946:    my ($name,$selected,$onchange,$includeempty)=@_;
                    947:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    948:    if ($includeempty) {
                    949:        $output .= '<option value=""';
                    950:        if (($selected eq '') || ($selected eq 'local')) {
                    951:            $output .= ' selected="selected" ';
                    952:        }
                    953:        $output .= '> </option>';
                    954:    }
1.657     raeburn   955:    my @timezones = DateTime::TimeZone->all_names;
                    956:    foreach my $tzone (@timezones) {
                    957:        $output.= '<option value="'.$tzone.'"';
                    958:        if ($tzone eq $selected) {
                    959:            $output.=' selected="selected"';
                    960:        }
                    961:        $output.=">$tzone</option>\n";
1.656     www       962:    }
                    963:    $output.="</select>";
                    964:    return $output;
                    965: }
1.273     raeburn   966: 
1.687     raeburn   967: sub select_datelocale {
                    968:     my ($name,$selected,$onchange,$includeempty)=@_;
                    969:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    970:     if ($includeempty) {
                    971:         $output .= '<option value=""';
                    972:         if ($selected eq '') {
                    973:             $output .= ' selected="selected" ';
                    974:         }
                    975:         $output .= '> </option>';
                    976:     }
1.1241  ! raeburn   977:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   978:     my (@possibles,%locale_names);
1.1241  ! raeburn   979:     my @locales = DateTime::Locale->ids();
        !           980:     foreach my $id (@locales) {
        !           981:         if ($id ne '') {
        !           982:             my ($en_terr,$native_terr);
        !           983:             my $loc = DateTime::Locale->load($id);
        !           984:             if (ref($loc)) {
        !           985:                 $en_terr = $loc->name();
        !           986:                 $native_terr = $loc->native_name();
1.687     raeburn   987:                 if (grep(/^en$/,@languages) || !@languages) {
                    988:                     if ($en_terr ne '') {
                    989:                         $locale_names{$id} = '('.$en_terr.')';
                    990:                     } elsif ($native_terr ne '') {
                    991:                         $locale_names{$id} = $native_terr;
                    992:                     }
                    993:                 } else {
                    994:                     if ($native_terr ne '') {
                    995:                         $locale_names{$id} = $native_terr.' ';
                    996:                     } elsif ($en_terr ne '') {
                    997:                         $locale_names{$id} = '('.$en_terr.')';
                    998:                     }
                    999:                 }
1.1220    raeburn  1000:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241  ! raeburn  1001:                 push(@possibles,$id);
        !          1002:             } 
1.687     raeburn  1003:         }
                   1004:     }
                   1005:     foreach my $item (sort(@possibles)) {
                   1006:         $output.= '<option value="'.$item.'"';
                   1007:         if ($item eq $selected) {
                   1008:             $output.=' selected="selected"';
                   1009:         }
                   1010:         $output.=">$item";
                   1011:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1012:             $output.='  '.$locale_names{$item};
1.687     raeburn  1013:         }
                   1014:         $output.="</option>\n";
                   1015:     }
                   1016:     $output.="</select>";
                   1017:     return $output;
                   1018: }
                   1019: 
1.792     raeburn  1020: sub select_language {
                   1021:     my ($name,$selected,$includeempty) = @_;
                   1022:     my %langchoices;
                   1023:     if ($includeempty) {
1.1117    raeburn  1024:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1025:     }
                   1026:     foreach my $id (&languageids()) {
                   1027:         my $code = &supportedlanguagecode($id);
                   1028:         if ($code) {
                   1029:             $langchoices{$code} = &plainlanguagedescription($id);
                   1030:         }
                   1031:     }
1.1117    raeburn  1032:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.970     raeburn  1033:     return &select_form($selected,$name,\%langchoices);
1.792     raeburn  1034: }
                   1035: 
1.42      matthew  1036: =pod
1.36      matthew  1037: 
1.1088    foxr     1038: 
                   1039: =item * &list_languages()
                   1040: 
                   1041: Returns an array reference that is suitable for use in language prompters.
                   1042: Each array element is itself a two element array.  The first element
                   1043: is the language code.  The second element a descsriptiuon of the 
                   1044: language itself.  This is suitable for use in e.g.
                   1045: &Apache::edit::select_arg (once dereferenced that is).
                   1046: 
                   1047: =cut 
                   1048: 
                   1049: sub list_languages {
                   1050:     my @lang_choices;
                   1051: 
                   1052:     foreach my $id (&languageids()) {
                   1053: 	my $code = &supportedlanguagecode($id);
                   1054: 	if ($code) {
                   1055: 	    my $selector    = $supported_codes{$id};
                   1056: 	    my $description = &plainlanguagedescription($id);
                   1057: 	    push (@lang_choices, [$selector, $description]);
                   1058: 	}
                   1059:     }
                   1060:     return \@lang_choices;
                   1061: }
                   1062: 
                   1063: =pod
                   1064: 
1.648     raeburn  1065: =item * &linked_select_forms(...)
1.36      matthew  1066: 
                   1067: linked_select_forms returns a string containing a <script></script> block
                   1068: and html for two <select> menus.  The select menus will be linked in that
                   1069: changing the value of the first menu will result in new values being placed
                   1070: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1071: order unless a defined order is provided.
1.36      matthew  1072: 
                   1073: linked_select_forms takes the following ordered inputs:
                   1074: 
                   1075: =over 4
                   1076: 
1.112     bowersj2 1077: =item * $formname, the name of the <form> tag
1.36      matthew  1078: 
1.112     bowersj2 1079: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1080: 
1.112     bowersj2 1081: =item * $firstdefault, the default value for the first menu
1.36      matthew  1082: 
1.112     bowersj2 1083: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1084: 
1.112     bowersj2 1085: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1086: 
1.112     bowersj2 1087: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1088: 
1.609     raeburn  1089: =item * $menuorder, the order of values in the first menu
                   1090: 
1.1115    raeburn  1091: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1092:         event for the first <select> tag
                   1093: 
                   1094: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1095:         event for the second <select> tag
                   1096: 
1.41      ng       1097: =back 
                   1098: 
1.36      matthew  1099: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1100: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1101: values for the first select menu.  The text that coincides with the 
1.41      ng       1102: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1103: and text for the second menu are given in the hash pointed to by 
                   1104: $menu{$choice1}->{'select2'}.  
                   1105: 
1.112     bowersj2 1106:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1107:                        default => "B3",
                   1108:                        select2 => { 
                   1109:                            B1 => "Choice B1",
                   1110:                            B2 => "Choice B2",
                   1111:                            B3 => "Choice B3",
                   1112:                            B4 => "Choice B4"
1.609     raeburn  1113:                            },
                   1114:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1115:                    },
                   1116:                A2 => { text =>"Choice A2" ,
                   1117:                        default => "C2",
                   1118:                        select2 => { 
                   1119:                            C1 => "Choice C1",
                   1120:                            C2 => "Choice C2",
                   1121:                            C3 => "Choice C3"
1.609     raeburn  1122:                            },
                   1123:                        order => ['C2','C1','C3'],
1.112     bowersj2 1124:                    },
                   1125:                A3 => { text =>"Choice A3" ,
                   1126:                        default => "D6",
                   1127:                        select2 => { 
                   1128:                            D1 => "Choice D1",
                   1129:                            D2 => "Choice D2",
                   1130:                            D3 => "Choice D3",
                   1131:                            D4 => "Choice D4",
                   1132:                            D5 => "Choice D5",
                   1133:                            D6 => "Choice D6",
                   1134:                            D7 => "Choice D7"
1.609     raeburn  1135:                            },
                   1136:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1137:                    }
                   1138:                );
1.36      matthew  1139: 
                   1140: =cut
                   1141: 
                   1142: sub linked_select_forms {
                   1143:     my ($formname,
                   1144:         $middletext,
                   1145:         $firstdefault,
                   1146:         $firstselectname,
                   1147:         $secondselectname, 
1.609     raeburn  1148:         $hashref,
                   1149:         $menuorder,
1.1115    raeburn  1150:         $onchangefirst,
                   1151:         $onchangesecond
1.36      matthew  1152:         ) = @_;
                   1153:     my $second = "document.$formname.$secondselectname";
                   1154:     my $first = "document.$formname.$firstselectname";
                   1155:     # output the javascript to do the changing
                   1156:     my $result = '';
1.776     bisitz   1157:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1158:     $result.="// <![CDATA[\n";
1.36      matthew  1159:     $result.="var select2data = new Object();\n";
                   1160:     $" = '","';
                   1161:     my $debug = '';
                   1162:     foreach my $s1 (sort(keys(%$hashref))) {
                   1163:         $result.="select2data.d_$s1 = new Object();\n";        
                   1164:         $result.="select2data.d_$s1.def = new String('".
                   1165:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1166:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1167:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1168:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1169:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1170:         }
1.36      matthew  1171:         $result.="\"@s2values\");\n";
                   1172:         $result.="select2data.d_$s1.texts = new Array(";        
                   1173:         my @s2texts;
                   1174:         foreach my $value (@s2values) {
                   1175:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                   1176:         }
                   1177:         $result.="\"@s2texts\");\n";
                   1178:     }
                   1179:     $"=' ';
                   1180:     $result.= <<"END";
                   1181: 
                   1182: function select1_changed() {
                   1183:     // Determine new choice
                   1184:     var newvalue = "d_" + $first.value;
                   1185:     // update select2
                   1186:     var values     = select2data[newvalue].values;
                   1187:     var texts      = select2data[newvalue].texts;
                   1188:     var select2def = select2data[newvalue].def;
                   1189:     var i;
                   1190:     // out with the old
                   1191:     for (i = 0; i < $second.options.length; i++) {
                   1192:         $second.options[i] = null;
                   1193:     }
                   1194:     // in with the nuclear
                   1195:     for (i=0;i<values.length; i++) {
                   1196:         $second.options[i] = new Option(values[i]);
1.143     matthew  1197:         $second.options[i].value = values[i];
1.36      matthew  1198:         $second.options[i].text = texts[i];
                   1199:         if (values[i] == select2def) {
                   1200:             $second.options[i].selected = true;
                   1201:         }
                   1202:     }
                   1203: }
1.824     bisitz   1204: // ]]>
1.36      matthew  1205: </script>
                   1206: END
                   1207:     # output the initial values for the selection lists
1.1115    raeburn  1208:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1209:     my @order = sort(keys(%{$hashref}));
                   1210:     if (ref($menuorder) eq 'ARRAY') {
                   1211:         @order = @{$menuorder};
                   1212:     }
                   1213:     foreach my $value (@order) {
1.36      matthew  1214:         $result.="    <option value=\"$value\" ";
1.253     albertel 1215:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1216:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1217:     }
                   1218:     $result .= "</select>\n";
                   1219:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1220:     $result .= $middletext;
1.1115    raeburn  1221:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1222:     if ($onchangesecond) {
                   1223:         $result .= ' onchange="'.$onchangesecond.'"';
                   1224:     }
                   1225:     $result .= ">\n";
1.36      matthew  1226:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1227:     
                   1228:     my @secondorder = sort(keys(%select2));
                   1229:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1230:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1231:     }
                   1232:     foreach my $value (@secondorder) {
1.36      matthew  1233:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1234:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1235:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1236:     }
                   1237:     $result .= "</select>\n";
                   1238:     #    return $debug;
                   1239:     return $result;
                   1240: }   #  end of sub linked_select_forms {
                   1241: 
1.45      matthew  1242: =pod
1.44      bowersj2 1243: 
1.973     raeburn  1244: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1245: 
1.112     bowersj2 1246: Returns a string corresponding to an HTML link to the given help
                   1247: $topic, where $topic corresponds to the name of a .tex file in
                   1248: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1249: spaces. 
                   1250: 
                   1251: $text will optionally be linked to the same topic, allowing you to
                   1252: link text in addition to the graphic. If you do not want to link
                   1253: text, but wish to specify one of the later parameters, pass an
                   1254: empty string. 
                   1255: 
                   1256: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1257: the link will not open a new window. If false, the link will open
                   1258: a new window using Javascript. (Default is false.) 
                   1259: 
                   1260: $width and $height are optional numerical parameters that will
                   1261: override the width and height of the popped up window, which may
1.973     raeburn  1262: be useful for certain help topics with big pictures included.
                   1263: 
                   1264: $imgid is the id of the img tag used for the help icon. This may be
                   1265: used in a javascript call to switch the image src.  See 
                   1266: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1267: 
                   1268: =cut
                   1269: 
                   1270: sub help_open_topic {
1.973     raeburn  1271:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1272:     $text = "" if (not defined $text);
1.44      bowersj2 1273:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1274:     $width = 500 if (not defined $width);
1.44      bowersj2 1275:     $height = 400 if (not defined $height);
                   1276:     my $filename = $topic;
                   1277:     $filename =~ s/ /_/g;
                   1278: 
1.48      bowersj2 1279:     my $template = "";
                   1280:     my $link;
1.572     banghart 1281:     
1.159     www      1282:     $topic=~s/\W/\_/g;
1.44      bowersj2 1283: 
1.572     banghart 1284:     if (!$stayOnPage) {
1.1033    www      1285: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1286:     } elsif ($stayOnPage eq 'popup') {
                   1287:         $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 1288:     } else {
1.48      bowersj2 1289: 	$link = "/adm/help/${filename}.hlp";
                   1290:     }
                   1291: 
                   1292:     # Add the text
1.755     neumanie 1293:     if ($text ne "") {	
1.763     bisitz   1294: 	$template.='<span class="LC_help_open_topic">'
                   1295:                   .'<a target="_top" href="'.$link.'">'
                   1296:                   .$text.'</a>';
1.48      bowersj2 1297:     }
                   1298: 
1.763     bisitz   1299:     # (Always) Add the graphic
1.179     matthew  1300:     my $title = &mt('Online Help');
1.667     raeburn  1301:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1302:     if ($imgid ne '') {
                   1303:         $imgid = ' id="'.$imgid.'"';
                   1304:     }
1.763     bisitz   1305:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1306:               .'<img src="'.$helpicon.'" border="0"'
                   1307:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1308:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1309:               .' /></a>';
                   1310:     if ($text ne "") {	
                   1311:         $template.='</span>';
                   1312:     }
1.44      bowersj2 1313:     return $template;
                   1314: 
1.106     bowersj2 1315: }
                   1316: 
                   1317: # This is a quicky function for Latex cheatsheet editing, since it 
                   1318: # appears in at least four places
                   1319: sub helpLatexCheatsheet {
1.1037    www      1320:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1321:     my $out;
1.106     bowersj2 1322:     my $addOther = '';
1.732     raeburn  1323:     if ($topic) {
1.1037    www      1324: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1325:     }
                   1326:     $out = '<span>' # Start cheatsheet
                   1327: 	  .$addOther
                   1328:           .'<span>'
1.1037    www      1329: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1330: 	  .'</span> <span>'
1.1037    www      1331: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1332: 	  .'</span>';
1.732     raeburn  1333:     unless ($not_author) {
1.1186    kruse    1334:         $out .= '<span>'
                   1335:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1336:                .'</span> <span>'
                   1337:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1338: 	       .'</span>';
1.732     raeburn  1339:     }
1.763     bisitz   1340:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1341:     return $out;
1.172     www      1342: }
                   1343: 
1.430     albertel 1344: sub general_help {
                   1345:     my $helptopic='Student_Intro';
                   1346:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1347: 	$helptopic='Authoring_Intro';
1.907     raeburn  1348:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1349: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1350:     } elsif ($env{'request.role'}=~/^dc/) {
                   1351:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1352:     }
                   1353:     return $helptopic;
                   1354: }
                   1355: 
                   1356: sub update_help_link {
                   1357:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1358:     my $origurl = $ENV{'REQUEST_URI'};
                   1359:     $origurl=~s|^/~|/priv/|;
                   1360:     my $timestamp = time;
                   1361:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1362:         $$datum = &escape($$datum);
                   1363:     }
                   1364: 
                   1365:     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";
                   1366:     my $output .= <<"ENDOUTPUT";
                   1367: <script type="text/javascript">
1.824     bisitz   1368: // <![CDATA[
1.430     albertel 1369: banner_link = '$banner_link';
1.824     bisitz   1370: // ]]>
1.430     albertel 1371: </script>
                   1372: ENDOUTPUT
                   1373:     return $output;
                   1374: }
                   1375: 
                   1376: # now just updates the help link and generates a blue icon
1.193     raeburn  1377: sub help_open_menu {
1.430     albertel 1378:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1379: 	= @_;    
1.949     droeschl 1380:     $stayOnPage = 1;
1.430     albertel 1381:     my $output;
                   1382:     if ($component_help) {
                   1383: 	if (!$text) {
                   1384: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1385: 				       $width,$height);
                   1386: 	} else {
                   1387: 	    my $help_text;
                   1388: 	    $help_text=&unescape($topic);
                   1389: 	    $output='<table><tr><td>'.
                   1390: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1391: 				 $width,$height).'</td></tr></table>';
                   1392: 	}
                   1393:     }
                   1394:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1395:     return $output.$banner_link;
                   1396: }
                   1397: 
                   1398: sub top_nav_help {
                   1399:     my ($text) = @_;
1.436     albertel 1400:     $text = &mt($text);
1.949     droeschl 1401:     my $stay_on_page = 1;
                   1402: 
1.1168    raeburn  1403:     my ($link,$banner_link);
                   1404:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1405:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1406: 	                         : "javascript:helpMenu('open')";
                   1407:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1408:     }
1.201     raeburn  1409:     my $title = &mt('Get help');
1.1168    raeburn  1410:     if ($link) {
                   1411:         return <<"END";
1.436     albertel 1412: $banner_link
1.1159    raeburn  1413: <a href="$link" title="$title">$text</a>
1.436     albertel 1414: END
1.1168    raeburn  1415:     } else {
                   1416:         return '&nbsp;'.$text.'&nbsp;';
                   1417:     }
1.436     albertel 1418: }
                   1419: 
                   1420: sub help_menu_js {
1.1154    raeburn  1421:     my ($httphost) = @_;
1.949     droeschl 1422:     my $stayOnPage = 1;
1.436     albertel 1423:     my $width = 620;
                   1424:     my $height = 600;
1.430     albertel 1425:     my $helptopic=&general_help();
1.1154    raeburn  1426:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1427:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1428:     my $start_page =
                   1429:         &Apache::loncommon::start_page('Help Menu', undef,
                   1430: 				       {'frameset'    => 1,
                   1431: 					'js_ready'    => 1,
1.1154    raeburn  1432:                                         'use_absolute' => $httphost,
1.331     albertel 1433: 					'add_entries' => {
1.1168    raeburn  1434: 					    'border' => '0', 
1.579     raeburn  1435: 					    'rows'   => "110,*",},});
1.331     albertel 1436:     my $end_page =
                   1437:         &Apache::loncommon::end_page({'frameset' => 1,
                   1438: 				      'js_ready' => 1,});
                   1439: 
1.436     albertel 1440:     my $template .= <<"ENDTEMPLATE";
                   1441: <script type="text/javascript">
1.877     bisitz   1442: // <![CDATA[
1.253     albertel 1443: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1444: var banner_link = '';
1.243     raeburn  1445: function helpMenu(target) {
                   1446:     var caller = this;
                   1447:     if (target == 'open') {
                   1448:         var newWindow = null;
                   1449:         try {
1.262     albertel 1450:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1451:         }
                   1452:         catch(error) {
                   1453:             writeHelp(caller);
                   1454:             return;
                   1455:         }
                   1456:         if (newWindow) {
                   1457:             caller = newWindow;
                   1458:         }
1.193     raeburn  1459:     }
1.243     raeburn  1460:     writeHelp(caller);
                   1461:     return;
                   1462: }
                   1463: function writeHelp(caller) {
1.1168    raeburn  1464:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1465:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1466:     caller.document.close();
                   1467:     caller.focus();
1.193     raeburn  1468: }
1.877     bisitz   1469: // END LON-CAPA Internal -->
1.253     albertel 1470: // ]]>
1.436     albertel 1471: </script>
1.193     raeburn  1472: ENDTEMPLATE
                   1473:     return $template;
                   1474: }
                   1475: 
1.172     www      1476: sub help_open_bug {
                   1477:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1478:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1479:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1480:     $text = "" if (not defined $text);
                   1481: 	$stayOnPage=1;
1.184     albertel 1482:     $width = 600 if (not defined $width);
                   1483:     $height = 600 if (not defined $height);
1.172     www      1484: 
                   1485:     $topic=~s/\W+/\+/g;
                   1486:     my $link='';
                   1487:     my $template='';
1.379     albertel 1488:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1489: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1490:     if (!$stayOnPage)
                   1491:     {
                   1492: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1493:     }
                   1494:     else
                   1495:     {
                   1496: 	$link = $url;
                   1497:     }
                   1498:     # Add the text
                   1499:     if ($text ne "")
                   1500:     {
                   1501: 	$template .= 
                   1502:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1503:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1504:     }
                   1505: 
                   1506:     # Add the graphic
1.179     matthew  1507:     my $title = &mt('Report a Bug');
1.215     albertel 1508:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1509:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1510:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1511: ENDTEMPLATE
                   1512:     if ($text ne '') { $template.='</td></tr></table>' };
                   1513:     return $template;
                   1514: 
                   1515: }
                   1516: 
                   1517: sub help_open_faq {
                   1518:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1519:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1520:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1521:     $text = "" if (not defined $text);
                   1522: 	$stayOnPage=1;
                   1523:     $width = 350 if (not defined $width);
                   1524:     $height = 400 if (not defined $height);
                   1525: 
                   1526:     $topic=~s/\W+/\+/g;
                   1527:     my $link='';
                   1528:     my $template='';
                   1529:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1530:     if (!$stayOnPage)
                   1531:     {
                   1532: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1533:     }
                   1534:     else
                   1535:     {
                   1536: 	$link = $url;
                   1537:     }
                   1538: 
                   1539:     # Add the text
                   1540:     if ($text ne "")
                   1541:     {
                   1542: 	$template .= 
1.173     www      1543:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1544:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1545:     }
                   1546: 
                   1547:     # Add the graphic
1.179     matthew  1548:     my $title = &mt('View the FAQ');
1.215     albertel 1549:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1550:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1551:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1552: ENDTEMPLATE
                   1553:     if ($text ne '') { $template.='</td></tr></table>' };
                   1554:     return $template;
                   1555: 
1.44      bowersj2 1556: }
1.37      matthew  1557: 
1.180     matthew  1558: ###############################################################
                   1559: ###############################################################
                   1560: 
1.45      matthew  1561: =pod
                   1562: 
1.648     raeburn  1563: =item * &change_content_javascript():
1.256     matthew  1564: 
                   1565: This and the next function allow you to create small sections of an
                   1566: otherwise static HTML page that you can update on the fly with
                   1567: Javascript, even in Netscape 4.
                   1568: 
                   1569: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1570: must be written to the HTML page once. It will prove the Javascript
                   1571: function "change(name, content)". Calling the change function with the
                   1572: name of the section 
                   1573: you want to update, matching the name passed to C<changable_area>, and
                   1574: the new content you want to put in there, will put the content into
                   1575: that area.
                   1576: 
                   1577: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1578: to contain room for the original contents. You need to "make space"
                   1579: for whatever changes you wish to make, and be B<sure> to check your
                   1580: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1581: it's adequate for updating a one-line status display, but little more.
                   1582: This script will set the space to 100% width, so you only need to
                   1583: worry about height in Netscape 4.
                   1584: 
                   1585: Modern browsers are much less limiting, and if you can commit to the
                   1586: user not using Netscape 4, this feature may be used freely with
                   1587: pretty much any HTML.
                   1588: 
                   1589: =cut
                   1590: 
                   1591: sub change_content_javascript {
                   1592:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1593:     if ($env{'browser.type'} eq 'netscape' &&
                   1594: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1595: 	return (<<NETSCAPE4);
                   1596: 	function change(name, content) {
                   1597: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1598: 	    doc.open();
                   1599: 	    doc.write(content);
                   1600: 	    doc.close();
                   1601: 	}
                   1602: NETSCAPE4
                   1603:     } else {
                   1604: 	# Otherwise, we need to use semi-standards-compliant code
                   1605: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1606: 	# is really scary, and every useful browser supports it
                   1607: 	return (<<DOMBASED);
                   1608: 	function change(name, content) {
                   1609: 	    element = document.getElementById(name);
                   1610: 	    element.innerHTML = content;
                   1611: 	}
                   1612: DOMBASED
                   1613:     }
                   1614: }
                   1615: 
                   1616: =pod
                   1617: 
1.648     raeburn  1618: =item * &changable_area($name,$origContent):
1.256     matthew  1619: 
                   1620: This provides a "changable area" that can be modified on the fly via
                   1621: the Javascript code provided in C<change_content_javascript>. $name is
                   1622: the name you will use to reference the area later; do not repeat the
                   1623: same name on a given HTML page more then once. $origContent is what
                   1624: the area will originally contain, which can be left blank.
                   1625: 
                   1626: =cut
                   1627: 
                   1628: sub changable_area {
                   1629:     my ($name, $origContent) = @_;
                   1630: 
1.258     albertel 1631:     if ($env{'browser.type'} eq 'netscape' &&
                   1632: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1633: 	# If this is netscape 4, we need to use the Layer tag
                   1634: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1635:     } else {
                   1636: 	return "<span id='$name'>$origContent</span>";
                   1637:     }
                   1638: }
                   1639: 
                   1640: =pod
                   1641: 
1.648     raeburn  1642: =item * &viewport_geometry_js 
1.590     raeburn  1643: 
                   1644: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1645: 
                   1646: =cut
                   1647: 
                   1648: 
                   1649: sub viewport_geometry_js { 
                   1650:     return <<"GEOMETRY";
                   1651: var Geometry = {};
                   1652: function init_geometry() {
                   1653:     if (Geometry.init) { return };
                   1654:     Geometry.init=1;
                   1655:     if (window.innerHeight) {
                   1656:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1657:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1658:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1659:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1660:     }
                   1661:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1662:         Geometry.getViewportHeight =
                   1663:             function() { return document.documentElement.clientHeight; };
                   1664:         Geometry.getViewportWidth =
                   1665:             function() { return document.documentElement.clientWidth; };
                   1666: 
                   1667:         Geometry.getHorizontalScroll =
                   1668:             function() { return document.documentElement.scrollLeft; };
                   1669:         Geometry.getVerticalScroll =
                   1670:             function() { return document.documentElement.scrollTop; };
                   1671:     }
                   1672:     else if (document.body.clientHeight) {
                   1673:         Geometry.getViewportHeight =
                   1674:             function() { return document.body.clientHeight; };
                   1675:         Geometry.getViewportWidth =
                   1676:             function() { return document.body.clientWidth; };
                   1677:         Geometry.getHorizontalScroll =
                   1678:             function() { return document.body.scrollLeft; };
                   1679:         Geometry.getVerticalScroll =
                   1680:             function() { return document.body.scrollTop; };
                   1681:     }
                   1682: }
                   1683: 
                   1684: GEOMETRY
                   1685: }
                   1686: 
                   1687: =pod
                   1688: 
1.648     raeburn  1689: =item * &viewport_size_js()
1.590     raeburn  1690: 
                   1691: 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. 
                   1692: 
                   1693: =cut
                   1694: 
                   1695: sub viewport_size_js {
                   1696:     my $geometry = &viewport_geometry_js();
                   1697:     return <<"DIMS";
                   1698: 
                   1699: $geometry
                   1700: 
                   1701: function getViewportDims(width,height) {
                   1702:     init_geometry();
                   1703:     width.value = Geometry.getViewportWidth();
                   1704:     height.value = Geometry.getViewportHeight();
                   1705:     return;
                   1706: }
                   1707: 
                   1708: DIMS
                   1709: }
                   1710: 
                   1711: =pod
                   1712: 
1.648     raeburn  1713: =item * &resize_textarea_js()
1.565     albertel 1714: 
                   1715: emits the needed javascript to resize a textarea to be as big as possible
                   1716: 
                   1717: creates a function resize_textrea that takes two IDs first should be
                   1718: the id of the element to resize, second should be the id of a div that
                   1719: surrounds everything that comes after the textarea, this routine needs
                   1720: to be attached to the <body> for the onload and onresize events.
                   1721: 
1.648     raeburn  1722: =back
1.565     albertel 1723: 
                   1724: =cut
                   1725: 
                   1726: sub resize_textarea_js {
1.590     raeburn  1727:     my $geometry = &viewport_geometry_js();
1.565     albertel 1728:     return <<"RESIZE";
                   1729:     <script type="text/javascript">
1.824     bisitz   1730: // <![CDATA[
1.590     raeburn  1731: $geometry
1.565     albertel 1732: 
1.588     albertel 1733: function getX(element) {
                   1734:     var x = 0;
                   1735:     while (element) {
                   1736: 	x += element.offsetLeft;
                   1737: 	element = element.offsetParent;
                   1738:     }
                   1739:     return x;
                   1740: }
                   1741: function getY(element) {
                   1742:     var y = 0;
                   1743:     while (element) {
                   1744: 	y += element.offsetTop;
                   1745: 	element = element.offsetParent;
                   1746:     }
                   1747:     return y;
                   1748: }
                   1749: 
                   1750: 
1.565     albertel 1751: function resize_textarea(textarea_id,bottom_id) {
                   1752:     init_geometry();
                   1753:     var textarea        = document.getElementById(textarea_id);
                   1754:     //alert(textarea);
                   1755: 
1.588     albertel 1756:     var textarea_top    = getY(textarea);
1.565     albertel 1757:     var textarea_height = textarea.offsetHeight;
                   1758:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1759:     var bottom_top      = getY(bottom);
1.565     albertel 1760:     var bottom_height   = bottom.offsetHeight;
                   1761:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1762:     var fudge           = 23;
1.565     albertel 1763:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1764:     if (new_height < 300) {
                   1765: 	new_height = 300;
                   1766:     }
                   1767:     textarea.style.height=new_height+'px';
                   1768: }
1.824     bisitz   1769: // ]]>
1.565     albertel 1770: </script>
                   1771: RESIZE
                   1772: 
                   1773: }
                   1774: 
1.1205    golterma 1775: sub colorfuleditor_js {
                   1776:     return <<"COLORFULEDIT"
                   1777: <script type="text/javascript">
                   1778: // <![CDATA[>
                   1779:     function fold_box(curDepth, lastresource){
                   1780: 
                   1781:     // we need a list because there can be several blocks you need to fold in one tag
                   1782:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1783:     // but there is only one folding button per tag
                   1784:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1785: 
                   1786:         if(block.item(0).style.display == 'none'){
                   1787: 
                   1788:             foldbutton.value = '@{[&mt("Hide")]}';
                   1789:             for (i = 0; i < block.length; i++){
                   1790:                 block.item(i).style.display = '';
                   1791:             }
                   1792:         }else{
                   1793: 
                   1794:             foldbutton.value = '@{[&mt("Show")]}';
                   1795:             for (i = 0; i < block.length; i++){
                   1796:                 // block.item(i).style.visibility = 'collapse';
                   1797:                 block.item(i).style.display = 'none';
                   1798:             }
                   1799:         };
                   1800:         saveState(lastresource);
                   1801:     }
                   1802: 
                   1803:     function saveState (lastresource) {
                   1804: 
                   1805:         var tag_list = getTagList();
                   1806:         if(tag_list != null){
                   1807:             var timestamp = new Date().getTime();
                   1808:             var key = lastresource;
                   1809: 
                   1810:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1811:             // starting with timestamp
                   1812:             var value = timestamp+';';
                   1813: 
                   1814:             // building the list of key-value pairs
                   1815:             for(var i = 0; i < tag_list.length; i++){
                   1816:                 value += tag_list[i]+',';
                   1817:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1818:             }
                   1819: 
                   1820:             // only iterate whole storage if nothing to override
                   1821:             if(localStorage.getItem(key) == null){        
                   1822: 
                   1823:                 // prevent storage from growing large
                   1824:                 if(localStorage.length > 50){
                   1825:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1826:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1827:                     var oldest_key;
                   1828:                     
                   1829:                     for(var i = 1; i < localStorage.length; i++){
                   1830:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1831:                             oldest_key = localStorage.key(i);
                   1832:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1833:                         }
                   1834:                     }
                   1835:                     localStorage.removeItem(oldest_key);
                   1836:                 }
                   1837:             }
                   1838:             localStorage.setItem(key,value);
                   1839:         }
                   1840:     }
                   1841: 
                   1842:     // restore folding status of blocks (on page load)
                   1843:     function restoreState (lastresource) {
                   1844:         if(localStorage.getItem(lastresource) != null){
                   1845:             var key = lastresource;
                   1846:             var value = localStorage.getItem(key);
                   1847:             var regex_delTimestamp = /^\d+;/;
                   1848: 
                   1849:             value.replace(regex_delTimestamp, '');
                   1850: 
                   1851:             var valueArr = value.split(';');
                   1852:             var pairs;
                   1853:             var elements;
                   1854:             for (var i = 0; i < valueArr.length; i++){
                   1855:                 pairs = valueArr[i].split(',');
                   1856:                 elements = document.getElementsByName(pairs[0]);
                   1857: 
                   1858:                 for (var j = 0; j < elements.length; j++){  
                   1859:                     elements[j].style.display = pairs[1];
                   1860:                     if (pairs[1] == "none"){
                   1861:                         var regex_id = /([_\\d]+)\$/;
                   1862:                         regex_id.exec(pairs[0]);
                   1863:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1864:                     }
                   1865:                 }
                   1866:             }
                   1867:         }
                   1868:     }
                   1869: 
                   1870:     function getTagList () {
                   1871:         
                   1872:         var stringToSearch = document.lonhomework.innerHTML;
                   1873: 
                   1874:         var ret = new Array();
                   1875:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1876:         var tag_list = stringToSearch.match(regex_findBlock);
                   1877: 
                   1878:         if(tag_list != null){
                   1879:             for(var i = 0; i < tag_list.length; i++){            
                   1880:                 ret.push(tag_list[i].replace(/"/, ''));
                   1881:             }
                   1882:         }
                   1883:         return ret;
                   1884:     }
                   1885: 
                   1886:     function saveScrollPosition (resource) {
                   1887:         var tag_list = getTagList();
                   1888: 
                   1889:         // we dont always want to jump to the first block
                   1890:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1891:         if(\$(window).scrollTop() > 170){
                   1892:             if(tag_list != null){
                   1893:                 var result;
                   1894:                 for(var i = 0; i < tag_list.length; i++){
                   1895:                     if(isElementInViewport(tag_list[i])){
                   1896:                         result += tag_list[i]+';';
                   1897:                     }
                   1898:                 }
                   1899:                 sessionStorage.setItem('anchor_'+resource, result);
                   1900:             }
                   1901:         } else {
                   1902:             // we dont need to save zero, just delete the item to leave everything tidy
                   1903:             sessionStorage.removeItem('anchor_'+resource);
                   1904:         }
                   1905:     }
                   1906: 
                   1907:     function restoreScrollPosition(resource){
                   1908: 
                   1909:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1910:         if(elem != null){
                   1911:             var tag_list = elem.split(';');
                   1912:             var elem_list;
                   1913: 
                   1914:             for(var i = 0; i < tag_list.length; i++){
                   1915:                 elem_list = document.getElementsByName(tag_list[i]);
                   1916:                 
                   1917:                 if(elem_list.length > 0){
                   1918:                     elem = elem_list[0];
                   1919:                     break;
                   1920:                 }
                   1921:             }
                   1922:             elem.scrollIntoView();
                   1923:         }
                   1924:     }
                   1925: 
                   1926:     function isElementInViewport(el) {
                   1927: 
                   1928:         // change to last element instead of first
                   1929:         var elem = document.getElementsByName(el);
                   1930:         var rect = elem[0].getBoundingClientRect();
                   1931: 
                   1932:         return (
                   1933:             rect.top >= 0 &&
                   1934:             rect.left >= 0 &&
                   1935:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1936:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1937:         );
                   1938:     }
                   1939:     
                   1940:     function autosize(depth){
                   1941:         var cmInst = window['cm'+depth];
                   1942:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1943: 
                   1944:         // is fixed size, switching to dynamic
                   1945:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1946:             cmInst.setSize("","auto");
                   1947:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1948:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1949: 
                   1950:         // is dynamic size, switching to fixed
                   1951:         } else {
                   1952:             cmInst.setSize("","300px");
                   1953:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1954:             sessionStorage.removeItem("autosized_"+depth);
                   1955:         }
                   1956:     }
                   1957: 
                   1958: 
                   1959: 
                   1960: // ]]>
                   1961: </script>
                   1962: COLORFULEDIT
                   1963: }
                   1964: 
                   1965: sub xmleditor_js {
                   1966:     return <<XMLEDIT
                   1967: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1968: <script type="text/javascript">
                   1969: // <![CDATA[>
                   1970: 
                   1971:     function saveScrollPosition (resource) {
                   1972: 
                   1973:         var scrollPos = \$(window).scrollTop();
                   1974:         sessionStorage.setItem(resource,scrollPos);
                   1975:     }
                   1976: 
                   1977:     function restoreScrollPosition(resource){
                   1978: 
                   1979:         var scrollPos = sessionStorage.getItem(resource);
                   1980:         \$(window).scrollTop(scrollPos);
                   1981:     }
                   1982: 
                   1983:     // unless internet explorer
                   1984:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1985: 
                   1986:         \$(document).ready(function() {
                   1987:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1988:         });
                   1989:     }
                   1990: 
                   1991:     // inserts text at cursor position into codemirror (xml editor only)
                   1992:     function insertText(text){
                   1993:         cm.focus();
                   1994:         var curPos = cm.getCursor();
                   1995:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   1996:     }
                   1997: // ]]>
                   1998: </script>
                   1999: XMLEDIT
                   2000: }
                   2001: 
                   2002: sub insert_folding_button {
                   2003:     my $curDepth = $Apache::lonxml::curdepth;
                   2004:     my $lastresource = $env{'request.ambiguous'};
                   2005: 
                   2006:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2007:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2008: }
                   2009: 
1.565     albertel 2010: =pod
                   2011: 
1.256     matthew  2012: =head1 Excel and CSV file utility routines
                   2013: 
                   2014: =cut
                   2015: 
                   2016: ###############################################################
                   2017: ###############################################################
                   2018: 
                   2019: =pod
                   2020: 
1.1162    raeburn  2021: =over 4
                   2022: 
1.648     raeburn  2023: =item * &csv_translate($text) 
1.37      matthew  2024: 
1.185     www      2025: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2026: format.
                   2027: 
                   2028: =cut
                   2029: 
1.180     matthew  2030: ###############################################################
                   2031: ###############################################################
1.37      matthew  2032: sub csv_translate {
                   2033:     my $text = shift;
                   2034:     $text =~ s/\"/\"\"/g;
1.209     albertel 2035:     $text =~ s/\n/ /g;
1.37      matthew  2036:     return $text;
                   2037: }
1.180     matthew  2038: 
                   2039: ###############################################################
                   2040: ###############################################################
                   2041: 
                   2042: =pod
                   2043: 
1.648     raeburn  2044: =item * &define_excel_formats()
1.180     matthew  2045: 
                   2046: Define some commonly used Excel cell formats.
                   2047: 
                   2048: Currently supported formats:
                   2049: 
                   2050: =over 4
                   2051: 
                   2052: =item header
                   2053: 
                   2054: =item bold
                   2055: 
                   2056: =item h1
                   2057: 
                   2058: =item h2
                   2059: 
                   2060: =item h3
                   2061: 
1.256     matthew  2062: =item h4
                   2063: 
                   2064: =item i
                   2065: 
1.180     matthew  2066: =item date
                   2067: 
                   2068: =back
                   2069: 
                   2070: Inputs: $workbook
                   2071: 
                   2072: Returns: $format, a hash reference.
                   2073: 
1.1057    foxr     2074: 
1.180     matthew  2075: =cut
                   2076: 
                   2077: ###############################################################
                   2078: ###############################################################
                   2079: sub define_excel_formats {
                   2080:     my ($workbook) = @_;
                   2081:     my $format;
                   2082:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2083:                                                 bottom    => 1,
                   2084:                                                 align     => 'center');
                   2085:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2086:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2087:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2088:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2089:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2090:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2091:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2092:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2093:     return $format;
                   2094: }
                   2095: 
                   2096: ###############################################################
                   2097: ###############################################################
1.113     bowersj2 2098: 
                   2099: =pod
                   2100: 
1.648     raeburn  2101: =item * &create_workbook()
1.255     matthew  2102: 
                   2103: Create an Excel worksheet.  If it fails, output message on the
                   2104: request object and return undefs.
                   2105: 
                   2106: Inputs: Apache request object
                   2107: 
                   2108: Returns (undef) on failure, 
                   2109:     Excel worksheet object, scalar with filename, and formats 
                   2110:     from &Apache::loncommon::define_excel_formats on success
                   2111: 
                   2112: =cut
                   2113: 
                   2114: ###############################################################
                   2115: ###############################################################
                   2116: sub create_workbook {
                   2117:     my ($r) = @_;
                   2118:         #
                   2119:     # Create the excel spreadsheet
                   2120:     my $filename = '/prtspool/'.
1.258     albertel 2121:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2122:         time.'_'.rand(1000000000).'.xls';
                   2123:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2124:     if (! defined($workbook)) {
                   2125:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2126:         $r->print(
                   2127:             '<p class="LC_error">'
                   2128:            .&mt('Problems occurred in creating the new Excel file.')
                   2129:            .' '.&mt('This error has been logged.')
                   2130:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2131:            .'</p>'
                   2132:         );
1.255     matthew  2133:         return (undef);
                   2134:     }
                   2135:     #
1.1014    foxr     2136:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2137:     #
                   2138:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2139:     return ($workbook,$filename,$format);
                   2140: }
                   2141: 
                   2142: ###############################################################
                   2143: ###############################################################
                   2144: 
                   2145: =pod
                   2146: 
1.648     raeburn  2147: =item * &create_text_file()
1.113     bowersj2 2148: 
1.542     raeburn  2149: Create a file to write to and eventually make available to the user.
1.256     matthew  2150: If file creation fails, outputs an error message on the request object and 
                   2151: return undefs.
1.113     bowersj2 2152: 
1.256     matthew  2153: Inputs: Apache request object, and file suffix
1.113     bowersj2 2154: 
1.256     matthew  2155: Returns (undef) on failure, 
                   2156:     Filehandle and filename on success.
1.113     bowersj2 2157: 
                   2158: =cut
                   2159: 
1.256     matthew  2160: ###############################################################
                   2161: ###############################################################
                   2162: sub create_text_file {
                   2163:     my ($r,$suffix) = @_;
                   2164:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2165:     my $fh;
                   2166:     my $filename = '/prtspool/'.
1.258     albertel 2167:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2168:         time.'_'.rand(1000000000).'.'.$suffix;
                   2169:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2170:     if (! defined($fh)) {
                   2171:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2172:         $r->print(
                   2173:             '<p class="LC_error">'
                   2174:            .&mt('Problems occurred in creating the output file.')
                   2175:            .' '.&mt('This error has been logged.')
                   2176:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2177:            .'</p>'
                   2178:         );
1.113     bowersj2 2179:     }
1.256     matthew  2180:     return ($fh,$filename)
1.113     bowersj2 2181: }
                   2182: 
                   2183: 
1.256     matthew  2184: =pod 
1.113     bowersj2 2185: 
                   2186: =back
                   2187: 
                   2188: =cut
1.37      matthew  2189: 
                   2190: ###############################################################
1.33      matthew  2191: ##        Home server <option> list generating code          ##
                   2192: ###############################################################
1.35      matthew  2193: 
1.169     www      2194: # ------------------------------------------
                   2195: 
                   2196: sub domain_select {
                   2197:     my ($name,$value,$multiple)=@_;
                   2198:     my %domains=map { 
1.514     albertel 2199: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2200:     } &Apache::lonnet::all_domains();
1.169     www      2201:     if ($multiple) {
                   2202: 	$domains{''}=&mt('Any domain');
1.550     albertel 2203: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2204: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2205:     } else {
1.550     albertel 2206: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2207: 	return &select_form($name,$value,\%domains);
1.169     www      2208:     }
                   2209: }
                   2210: 
1.282     albertel 2211: #-------------------------------------------
                   2212: 
                   2213: =pod
                   2214: 
1.519     raeburn  2215: =head1 Routines for form select boxes
                   2216: 
                   2217: =over 4
                   2218: 
1.648     raeburn  2219: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2220: 
                   2221: Returns a string containing a <select> element int multiple mode
                   2222: 
                   2223: 
                   2224: Args:
                   2225:   $name - name of the <select> element
1.506     raeburn  2226:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2227:   $size - number of rows long the select element is
1.283     albertel 2228:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2229:           (shown text should already have been &mt())
1.506     raeburn  2230:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2231: 
1.282     albertel 2232: =cut
                   2233: 
                   2234: #-------------------------------------------
1.169     www      2235: sub multiple_select_form {
1.284     albertel 2236:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2237:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2238:     my $output='';
1.191     matthew  2239:     if (! defined($size)) {
                   2240:         $size = 4;
1.283     albertel 2241:         if (scalar(keys(%$hash))<4) {
                   2242:             $size = scalar(keys(%$hash));
1.191     matthew  2243:         }
                   2244:     }
1.734     bisitz   2245:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2246:     my @order;
1.506     raeburn  2247:     if (ref($order) eq 'ARRAY')  {
                   2248:         @order = @{$order};
                   2249:     } else {
                   2250:         @order = sort(keys(%$hash));
1.501     banghart 2251:     }
                   2252:     if (exists($$hash{'select_form_order'})) {
                   2253:         @order = @{$$hash{'select_form_order'}};
                   2254:     }
                   2255:         
1.284     albertel 2256:     foreach my $key (@order) {
1.356     albertel 2257:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2258:         $output.='selected="selected" ' if ($selected{$key});
                   2259:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2260:     }
                   2261:     $output.="</select>\n";
                   2262:     return $output;
                   2263: }
                   2264: 
1.88      www      2265: #-------------------------------------------
                   2266: 
                   2267: =pod
                   2268: 
1.970     raeburn  2269: =item * &select_form($defdom,$name,$hashref,$onchange)
1.88      www      2270: 
                   2271: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2272: allow a user to select options from a ref to a hash containing:
                   2273: option_name => displayed text. An optional $onchange can include
                   2274: a javascript onchange item, e.g., onchange="this.form.submit();"  
                   2275: 
1.88      www      2276: See lonrights.pm for an example invocation and use.
                   2277: 
                   2278: =cut
                   2279: 
                   2280: #-------------------------------------------
                   2281: sub select_form {
1.1228    raeburn  2282:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2283:     return unless (ref($hashref) eq 'HASH');
                   2284:     if ($onchange) {
                   2285:         $onchange = ' onchange="'.$onchange.'"';
                   2286:     }
1.1228    raeburn  2287:     my $disabled;
                   2288:     if ($readonly) {
                   2289:         $disabled = ' disabled="disabled"';
                   2290:     }
                   2291:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2292:     my @keys;
1.970     raeburn  2293:     if (exists($hashref->{'select_form_order'})) {
                   2294: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2295:     } else {
1.970     raeburn  2296: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2297:     }
1.356     albertel 2298:     foreach my $key (@keys) {
                   2299:         $selectform.=
                   2300: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2301:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2302:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2303:     }
                   2304:     $selectform.="</select>";
                   2305:     return $selectform;
                   2306: }
                   2307: 
1.475     www      2308: # For display filters
                   2309: 
                   2310: sub display_filter {
1.1074    raeburn  2311:     my ($context) = @_;
1.475     www      2312:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2313:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2314:     my $phraseinput = 'hidden';
                   2315:     my $includeinput = 'hidden';
                   2316:     my ($checked,$includetypestext);
                   2317:     if ($env{'form.displayfilter'} eq 'containing') {
                   2318:         $phraseinput = 'text'; 
                   2319:         if ($context eq 'parmslog') {
                   2320:             $includeinput = 'checkbox';
                   2321:             if ($env{'form.includetypes'}) {
                   2322:                 $checked = ' checked="checked"';
                   2323:             }
                   2324:             $includetypestext = &mt('Include parameter types');
                   2325:         }
                   2326:     } else {
                   2327:         $includetypestext = '&nbsp;';
                   2328:     }
                   2329:     my ($additional,$secondid,$thirdid);
                   2330:     if ($context eq 'parmslog') {
                   2331:         $additional = 
                   2332:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2333:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2334:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2335:             '</label>';
                   2336:         $secondid = 'includetypes';
                   2337:         $thirdid = 'includetypestext';
                   2338:     }
                   2339:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2340:                                                     '$secondid','$thirdid')";
                   2341:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2342: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2343: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2344: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2345:            &mt('Filter: [_1]',
1.477     www      2346: 	   &select_form($env{'form.displayfilter'},
                   2347: 			'displayfilter',
1.970     raeburn  2348: 			{'currentfolder' => 'Current folder/page',
1.477     www      2349: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2350: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2351: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2352:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2353:                          '" />'.$additional;
                   2354: }
                   2355: 
                   2356: sub display_filter_js {
                   2357:     my $includetext = &mt('Include parameter types');
                   2358:     return <<"ENDJS";
                   2359:   
                   2360: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2361:     var firstType = 'hidden';
                   2362:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2363:         firstType = 'text';
                   2364:     }
                   2365:     firstObject = document.getElementById(firstid);
                   2366:     if (typeof(firstObject) == 'object') {
                   2367:         if (firstObject.type != firstType) {
                   2368:             changeInputType(firstObject,firstType);
                   2369:         }
                   2370:     }
                   2371:     if (context == 'parmslog') {
                   2372:         var secondType = 'hidden';
                   2373:         if (firstType == 'text') {
                   2374:             secondType = 'checkbox';
                   2375:         }
                   2376:         secondObject = document.getElementById(secondid);  
                   2377:         if (typeof(secondObject) == 'object') {
                   2378:             if (secondObject.type != secondType) {
                   2379:                 changeInputType(secondObject,secondType);
                   2380:             }
                   2381:         }
                   2382:         var textItem = document.getElementById(thirdid);
                   2383:         var currtext = textItem.innerHTML;
                   2384:         var newtext;
                   2385:         if (firstType == 'text') {
                   2386:             newtext = '$includetext';
                   2387:         } else {
                   2388:             newtext = '&nbsp;';
                   2389:         }
                   2390:         if (currtext != newtext) {
                   2391:             textItem.innerHTML = newtext;
                   2392:         }
                   2393:     }
                   2394:     return;
                   2395: }
                   2396: 
                   2397: function changeInputType(oldObject,newType) {
                   2398:     var newObject = document.createElement('input');
                   2399:     newObject.type = newType;
                   2400:     if (oldObject.size) {
                   2401:         newObject.size = oldObject.size;
                   2402:     }
                   2403:     if (oldObject.value) {
                   2404:         newObject.value = oldObject.value;
                   2405:     }
                   2406:     if (oldObject.name) {
                   2407:         newObject.name = oldObject.name;
                   2408:     }
                   2409:     if (oldObject.id) {
                   2410:         newObject.id = oldObject.id;
                   2411:     }
                   2412:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2413:     return;
                   2414: }
                   2415: 
                   2416: ENDJS
1.475     www      2417: }
                   2418: 
1.167     www      2419: sub gradeleveldescription {
                   2420:     my $gradelevel=shift;
                   2421:     my %gradelevels=(0 => 'Not specified',
                   2422: 		     1 => 'Grade 1',
                   2423: 		     2 => 'Grade 2',
                   2424: 		     3 => 'Grade 3',
                   2425: 		     4 => 'Grade 4',
                   2426: 		     5 => 'Grade 5',
                   2427: 		     6 => 'Grade 6',
                   2428: 		     7 => 'Grade 7',
                   2429: 		     8 => 'Grade 8',
                   2430: 		     9 => 'Grade 9',
                   2431: 		     10 => 'Grade 10',
                   2432: 		     11 => 'Grade 11',
                   2433: 		     12 => 'Grade 12',
                   2434: 		     13 => 'Grade 13',
                   2435: 		     14 => '100 Level',
                   2436: 		     15 => '200 Level',
                   2437: 		     16 => '300 Level',
                   2438: 		     17 => '400 Level',
                   2439: 		     18 => 'Graduate Level');
                   2440:     return &mt($gradelevels{$gradelevel});
                   2441: }
                   2442: 
1.163     www      2443: sub select_level_form {
                   2444:     my ($deflevel,$name)=@_;
                   2445:     unless ($deflevel) { $deflevel=0; }
1.167     www      2446:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2447:     for (my $i=0; $i<=18; $i++) {
                   2448:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2449:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2450:                 ">".&gradeleveldescription($i)."</option>\n";
                   2451:     }
                   2452:     $selectform.="</select>";
                   2453:     return $selectform;
1.163     www      2454: }
1.167     www      2455: 
1.35      matthew  2456: #-------------------------------------------
                   2457: 
1.45      matthew  2458: =pod
                   2459: 
1.1121    raeburn  2460: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
1.35      matthew  2461: 
                   2462: Returns a string containing a <select name='$name' size='1'> form to 
                   2463: allow a user to select the domain to preform an operation in.  
                   2464: See loncreateuser.pm for an example invocation and use.
                   2465: 
1.90      www      2466: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2467: selected");
                   2468: 
1.743     raeburn  2469: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2470: 
1.910     raeburn  2471: 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.
                   2472: 
1.1121    raeburn  2473: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2474: 
                   2475: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2476: 
1.35      matthew  2477: =cut
                   2478: 
                   2479: #-------------------------------------------
1.34      matthew  2480: sub select_dom_form {
1.1121    raeburn  2481:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
1.872     raeburn  2482:     if ($onchange) {
1.874     raeburn  2483:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2484:     }
1.1121    raeburn  2485:     my (@domains,%exclude);
1.910     raeburn  2486:     if (ref($incdoms) eq 'ARRAY') {
                   2487:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2488:     } else {
                   2489:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2490:     }
1.90      www      2491:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2492:     if (ref($excdoms) eq 'ARRAY') {
                   2493:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2494:     }
1.743     raeburn  2495:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.356     albertel 2496:     foreach my $dom (@domains) {
1.1121    raeburn  2497:         next if ($exclude{$dom});
1.356     albertel 2498:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2499:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2500:         if ($showdomdesc) {
                   2501:             if ($dom ne '') {
                   2502:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2503:                 if ($domdesc ne '') {
                   2504:                     $selectdomain .= ' ('.$domdesc.')';
                   2505:                 }
                   2506:             } 
                   2507:         }
                   2508:         $selectdomain .= "</option>\n";
1.34      matthew  2509:     }
                   2510:     $selectdomain.="</select>";
                   2511:     return $selectdomain;
                   2512: }
                   2513: 
1.35      matthew  2514: #-------------------------------------------
                   2515: 
1.45      matthew  2516: =pod
                   2517: 
1.648     raeburn  2518: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2519: 
1.586     raeburn  2520: input: 4 arguments (two required, two optional) - 
                   2521:     $domain - domain of new user
                   2522:     $name - name of form element
                   2523:     $default - Value of 'default' causes a default item to be first 
                   2524:                             option, and selected by default. 
                   2525:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2526:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2527: output: returns 2 items: 
1.586     raeburn  2528: (a) form element which contains either:
                   2529:    (i) <select name="$name">
                   2530:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2531:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2532:        </select>
                   2533:        form item if there are multiple library servers in $domain, or
                   2534:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2535:        if there is only one library server in $domain.
                   2536: 
                   2537: (b) number of library servers found.
                   2538: 
                   2539: See loncreateuser.pm for example of use.
1.35      matthew  2540: 
                   2541: =cut
                   2542: 
                   2543: #-------------------------------------------
1.586     raeburn  2544: sub home_server_form_item {
                   2545:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2546:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2547:     my $result;
                   2548:     my $numlib = keys(%servers);
                   2549:     if ($numlib > 1) {
                   2550:         $result .= '<select name="'.$name.'" />'."\n";
                   2551:         if ($default) {
1.804     bisitz   2552:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2553:                        '</option>'."\n";
                   2554:         }
                   2555:         foreach my $hostid (sort(keys(%servers))) {
                   2556:             $result.= '<option value="'.$hostid.'">'.
                   2557: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2558:         }
                   2559:         $result .= '</select>'."\n";
                   2560:     } elsif ($numlib == 1) {
                   2561:         my $hostid;
                   2562:         foreach my $item (keys(%servers)) {
                   2563:             $hostid = $item;
                   2564:         }
                   2565:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2566:                    $hostid.'" />';
                   2567:                    if (!$hide) {
                   2568:                        $result .= $hostid.' '.$servers{$hostid};
                   2569:                    }
                   2570:                    $result .= "\n";
                   2571:     } elsif ($default) {
                   2572:         $result .= '<input type="hidden" name="'.$name.
                   2573:                    '" value="default" />';
                   2574:                    if (!$hide) {
                   2575:                        $result .= &mt('default');
                   2576:                    }
                   2577:                    $result .= "\n";
1.33      matthew  2578:     }
1.586     raeburn  2579:     return ($result,$numlib);
1.33      matthew  2580: }
1.112     bowersj2 2581: 
                   2582: =pod
                   2583: 
1.534     albertel 2584: =back 
                   2585: 
1.112     bowersj2 2586: =cut
1.87      matthew  2587: 
                   2588: ###############################################################
1.112     bowersj2 2589: ##                  Decoding User Agent                      ##
1.87      matthew  2590: ###############################################################
                   2591: 
                   2592: =pod
                   2593: 
1.112     bowersj2 2594: =head1 Decoding the User Agent
                   2595: 
                   2596: =over 4
                   2597: 
                   2598: =item * &decode_user_agent()
1.87      matthew  2599: 
                   2600: Inputs: $r
                   2601: 
                   2602: Outputs:
                   2603: 
                   2604: =over 4
                   2605: 
1.112     bowersj2 2606: =item * $httpbrowser
1.87      matthew  2607: 
1.112     bowersj2 2608: =item * $clientbrowser
1.87      matthew  2609: 
1.112     bowersj2 2610: =item * $clientversion
1.87      matthew  2611: 
1.112     bowersj2 2612: =item * $clientmathml
1.87      matthew  2613: 
1.112     bowersj2 2614: =item * $clientunicode
1.87      matthew  2615: 
1.112     bowersj2 2616: =item * $clientos
1.87      matthew  2617: 
1.1137    raeburn  2618: =item * $clientmobile
                   2619: 
1.1141    raeburn  2620: =item * $clientinfo
                   2621: 
1.1194    raeburn  2622: =item * $clientosversion
                   2623: 
1.87      matthew  2624: =back
                   2625: 
1.157     matthew  2626: =back 
                   2627: 
1.87      matthew  2628: =cut
                   2629: 
                   2630: ###############################################################
                   2631: ###############################################################
                   2632: sub decode_user_agent {
1.247     albertel 2633:     my ($r)=@_;
1.87      matthew  2634:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2635:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2636:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2637:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2638:     my $clientbrowser='unknown';
                   2639:     my $clientversion='0';
                   2640:     my $clientmathml='';
                   2641:     my $clientunicode='0';
1.1137    raeburn  2642:     my $clientmobile=0;
1.1194    raeburn  2643:     my $clientosversion='';
1.87      matthew  2644:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2645:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2646: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2647: 	    $clientbrowser=$bname;
                   2648:             $httpbrowser=~/$vreg/i;
                   2649: 	    $clientversion=$1;
                   2650:             $clientmathml=($clientversion>=$minv);
                   2651:             $clientunicode=($clientversion>=$univ);
                   2652: 	}
                   2653:     }
                   2654:     my $clientos='unknown';
1.1141    raeburn  2655:     my $clientinfo;
1.87      matthew  2656:     if (($httpbrowser=~/linux/i) ||
                   2657:         ($httpbrowser=~/unix/i) ||
                   2658:         ($httpbrowser=~/ux/i) ||
                   2659:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2660:     if (($httpbrowser=~/vax/i) ||
                   2661:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2662:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2663:     if (($httpbrowser=~/mac/i) ||
                   2664:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  2665:     if ($httpbrowser=~/win/i) {
                   2666:         $clientos='win';
                   2667:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2668:             $clientosversion = $1;
                   2669:         }
                   2670:     }
1.87      matthew  2671:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  2672:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2673:         $clientmobile=lc($1);
                   2674:     }
1.1141    raeburn  2675:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2676:         $clientinfo = 'firefox-'.$1;
                   2677:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2678:         $clientinfo = 'chromeframe-'.$1;
                   2679:     }
1.87      matthew  2680:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  2681:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2682:             $clientosversion);
1.87      matthew  2683: }
                   2684: 
1.32      matthew  2685: ###############################################################
                   2686: ##    Authentication changing form generation subroutines    ##
                   2687: ###############################################################
                   2688: ##
                   2689: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2690: ## hash, and have reasonable default values.
                   2691: ##
                   2692: ##    formname = the name given in the <form> tag.
1.35      matthew  2693: #-------------------------------------------
                   2694: 
1.45      matthew  2695: =pod
                   2696: 
1.112     bowersj2 2697: =head1 Authentication Routines
                   2698: 
                   2699: =over 4
                   2700: 
1.648     raeburn  2701: =item * &authform_xxxxxx()
1.35      matthew  2702: 
                   2703: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2704: handle some of the conveniences required for authentication forms.  
                   2705: This is not an optimal method, but it works.  
                   2706: 
                   2707: =over 4
                   2708: 
1.112     bowersj2 2709: =item * authform_header
1.35      matthew  2710: 
1.112     bowersj2 2711: =item * authform_authorwarning
1.35      matthew  2712: 
1.112     bowersj2 2713: =item * authform_nochange
1.35      matthew  2714: 
1.112     bowersj2 2715: =item * authform_kerberos
1.35      matthew  2716: 
1.112     bowersj2 2717: =item * authform_internal
1.35      matthew  2718: 
1.112     bowersj2 2719: =item * authform_filesystem
1.35      matthew  2720: 
                   2721: =back
                   2722: 
1.648     raeburn  2723: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2724: 
1.35      matthew  2725: =cut
                   2726: 
                   2727: #-------------------------------------------
1.32      matthew  2728: sub authform_header{  
                   2729:     my %in = (
                   2730:         formname => 'cu',
1.80      albertel 2731:         kerb_def_dom => '',
1.32      matthew  2732:         @_,
                   2733:     );
                   2734:     $in{'formname'} = 'document.' . $in{'formname'};
                   2735:     my $result='';
1.80      albertel 2736: 
                   2737: #---------------------------------------------- Code for upper case translation
                   2738:     my $Javascript_toUpperCase;
                   2739:     unless ($in{kerb_def_dom}) {
                   2740:         $Javascript_toUpperCase =<<"END";
                   2741:         switch (choice) {
                   2742:            case 'krb': currentform.elements[choicearg].value =
                   2743:                currentform.elements[choicearg].value.toUpperCase();
                   2744:                break;
                   2745:            default:
                   2746:         }
                   2747: END
                   2748:     } else {
                   2749:         $Javascript_toUpperCase = "";
                   2750:     }
                   2751: 
1.165     raeburn  2752:     my $radioval = "'nochange'";
1.591     raeburn  2753:     if (defined($in{'curr_authtype'})) {
                   2754:         if ($in{'curr_authtype'} ne '') {
                   2755:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2756:         }
1.174     matthew  2757:     }
1.165     raeburn  2758:     my $argfield = 'null';
1.591     raeburn  2759:     if (defined($in{'mode'})) {
1.165     raeburn  2760:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2761:             if (defined($in{'curr_autharg'})) {
                   2762:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2763:                     $argfield = "'$in{'curr_autharg'}'";
                   2764:                 }
                   2765:             }
                   2766:         }
                   2767:     }
                   2768: 
1.32      matthew  2769:     $result.=<<"END";
                   2770: var current = new Object();
1.165     raeburn  2771: current.radiovalue = $radioval;
                   2772: current.argfield = $argfield;
1.32      matthew  2773: 
                   2774: function changed_radio(choice,currentform) {
                   2775:     var choicearg = choice + 'arg';
                   2776:     // If a radio button in changed, we need to change the argfield
                   2777:     if (current.radiovalue != choice) {
                   2778:         current.radiovalue = choice;
                   2779:         if (current.argfield != null) {
                   2780:             currentform.elements[current.argfield].value = '';
                   2781:         }
                   2782:         if (choice == 'nochange') {
                   2783:             current.argfield = null;
                   2784:         } else {
                   2785:             current.argfield = choicearg;
                   2786:             switch(choice) {
                   2787:                 case 'krb': 
                   2788:                     currentform.elements[current.argfield].value = 
                   2789:                         "$in{'kerb_def_dom'}";
                   2790:                 break;
                   2791:               default:
                   2792:                 break;
                   2793:             }
                   2794:         }
                   2795:     }
                   2796:     return;
                   2797: }
1.22      www      2798: 
1.32      matthew  2799: function changed_text(choice,currentform) {
                   2800:     var choicearg = choice + 'arg';
                   2801:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2802:         $Javascript_toUpperCase
1.32      matthew  2803:         // clear old field
                   2804:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2805:             currentform.elements[current.argfield].value = '';
                   2806:         }
                   2807:         current.argfield = choicearg;
                   2808:     }
                   2809:     set_auth_radio_buttons(choice,currentform);
                   2810:     return;
1.20      www      2811: }
1.32      matthew  2812: 
                   2813: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2814:     var numauthchoices = currentform.login.length;
                   2815:     if (typeof numauthchoices  == "undefined") {
                   2816:         return;
                   2817:     } 
1.32      matthew  2818:     var i=0;
1.986     raeburn  2819:     while (i < numauthchoices) {
1.32      matthew  2820:         if (currentform.login[i].value == newvalue) { break; }
                   2821:         i++;
                   2822:     }
1.986     raeburn  2823:     if (i == numauthchoices) {
1.32      matthew  2824:         return;
                   2825:     }
                   2826:     current.radiovalue = newvalue;
                   2827:     currentform.login[i].checked = true;
                   2828:     return;
                   2829: }
                   2830: END
                   2831:     return $result;
                   2832: }
                   2833: 
1.1106    raeburn  2834: sub authform_authorwarning {
1.32      matthew  2835:     my $result='';
1.144     matthew  2836:     $result='<i>'.
                   2837:         &mt('As a general rule, only authors or co-authors should be '.
                   2838:             'filesystem authenticated '.
                   2839:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2840:     return $result;
                   2841: }
                   2842: 
1.1106    raeburn  2843: sub authform_nochange {
1.32      matthew  2844:     my %in = (
                   2845:               formname => 'document.cu',
                   2846:               kerb_def_dom => 'MSU.EDU',
                   2847:               @_,
                   2848:           );
1.1106    raeburn  2849:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  2850:     my $result;
1.1104    raeburn  2851:     if (!$authnum) {
1.1105    raeburn  2852:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2853:     } else {
                   2854:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2855:                   '<input type="radio" name="login" value="nochange" '.
                   2856:                   'checked="checked" onclick="'.
1.281     albertel 2857:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2858: 	    '</label>';
1.586     raeburn  2859:     }
1.32      matthew  2860:     return $result;
                   2861: }
                   2862: 
1.591     raeburn  2863: sub authform_kerberos {
1.32      matthew  2864:     my %in = (
                   2865:               formname => 'document.cu',
                   2866:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2867:               kerb_def_auth => 'krb4',
1.32      matthew  2868:               @_,
                   2869:               );
1.586     raeburn  2870:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   2871:         $autharg,$jscall);
1.1106    raeburn  2872:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2873:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2874:        $check5 = ' checked="checked"';
1.80      albertel 2875:     } else {
1.772     bisitz   2876:        $check4 = ' checked="checked"';
1.80      albertel 2877:     }
1.165     raeburn  2878:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2879:     if (defined($in{'curr_authtype'})) {
                   2880:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2881:             $krbcheck = ' checked="checked"';
1.623     raeburn  2882:             if (defined($in{'mode'})) {
                   2883:                 if ($in{'mode'} eq 'modifyuser') {
                   2884:                     $krbcheck = '';
                   2885:                 }
                   2886:             }
1.591     raeburn  2887:             if (defined($in{'curr_kerb_ver'})) {
                   2888:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2889:                     $check5 = ' checked="checked"';
1.591     raeburn  2890:                     $check4 = '';
                   2891:                 } else {
1.772     bisitz   2892:                     $check4 = ' checked="checked"';
1.591     raeburn  2893:                     $check5 = '';
                   2894:                 }
1.586     raeburn  2895:             }
1.591     raeburn  2896:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2897:                 $krbarg = $in{'curr_autharg'};
                   2898:             }
1.586     raeburn  2899:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2900:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2901:                     $result = 
                   2902:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2903:         $in{'curr_autharg'},$krbver);
                   2904:                 } else {
                   2905:                     $result =
                   2906:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2907:                 }
                   2908:                 return $result; 
                   2909:             }
                   2910:         }
                   2911:     } else {
                   2912:         if ($authnum == 1) {
1.784     bisitz   2913:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2914:         }
                   2915:     }
1.586     raeburn  2916:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2917:         return;
1.587     raeburn  2918:     } elsif ($authtype eq '') {
1.591     raeburn  2919:         if (defined($in{'mode'})) {
1.587     raeburn  2920:             if ($in{'mode'} eq 'modifycourse') {
                   2921:                 if ($authnum == 1) {
1.1104    raeburn  2922:                     $authtype = '<input type="radio" name="login" value="krb" />';
1.587     raeburn  2923:                 }
                   2924:             }
                   2925:         }
1.586     raeburn  2926:     }
                   2927:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2928:     if ($authtype eq '') {
                   2929:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2930:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   2931:                     $krbcheck.' />';
                   2932:     }
                   2933:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  2934:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2935:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  2936:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2937:          $in{'curr_authtype'} eq 'krb4')) {
                   2938:         $result .= &mt
1.144     matthew  2939:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2940:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2941:          '<label>'.$authtype,
1.281     albertel 2942:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2943:              'value="'.$krbarg.'" '.
1.144     matthew  2944:              'onchange="'.$jscall.'" />',
1.281     albertel 2945:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   2946:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   2947: 	 '</label>');
1.586     raeburn  2948:     } elsif ($can_assign{'krb4'}) {
                   2949:         $result .= &mt
                   2950:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2951:          '[_3] Version 4 [_4]',
                   2952:          '<label>'.$authtype,
                   2953:          '</label><input type="text" size="10" name="krbarg" '.
                   2954:              'value="'.$krbarg.'" '.
                   2955:              'onchange="'.$jscall.'" />',
                   2956:          '<label><input type="hidden" name="krbver" value="4" />',
                   2957:          '</label>');
                   2958:     } elsif ($can_assign{'krb5'}) {
                   2959:         $result .= &mt
                   2960:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2961:          '[_3] Version 5 [_4]',
                   2962:          '<label>'.$authtype,
                   2963:          '</label><input type="text" size="10" name="krbarg" '.
                   2964:              'value="'.$krbarg.'" '.
                   2965:              'onchange="'.$jscall.'" />',
                   2966:          '<label><input type="hidden" name="krbver" value="5" />',
                   2967:          '</label>');
                   2968:     }
1.32      matthew  2969:     return $result;
                   2970: }
                   2971: 
1.1106    raeburn  2972: sub authform_internal {
1.586     raeburn  2973:     my %in = (
1.32      matthew  2974:                 formname => 'document.cu',
                   2975:                 kerb_def_dom => 'MSU.EDU',
                   2976:                 @_,
                   2977:                 );
1.586     raeburn  2978:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  2979:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2980:     if (defined($in{'curr_authtype'})) {
                   2981:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2982:             if ($can_assign{'int'}) {
1.772     bisitz   2983:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2984:                 if (defined($in{'mode'})) {
                   2985:                     if ($in{'mode'} eq 'modifyuser') {
                   2986:                         $intcheck = '';
                   2987:                     }
                   2988:                 }
1.591     raeburn  2989:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2990:                     $intarg = $in{'curr_autharg'};
                   2991:                 }
                   2992:             } else {
                   2993:                 $result = &mt('Currently internally authenticated.');
                   2994:                 return $result;
1.165     raeburn  2995:             }
                   2996:         }
1.586     raeburn  2997:     } else {
                   2998:         if ($authnum == 1) {
1.784     bisitz   2999:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3000:         }
                   3001:     }
                   3002:     if (!$can_assign{'int'}) {
                   3003:         return;
1.587     raeburn  3004:     } elsif ($authtype eq '') {
1.591     raeburn  3005:         if (defined($in{'mode'})) {
1.587     raeburn  3006:             if ($in{'mode'} eq 'modifycourse') {
                   3007:                 if ($authnum == 1) {
1.1104    raeburn  3008:                     $authtype = '<input type="radio" name="login" value="int" />';
1.587     raeburn  3009:                 }
                   3010:             }
                   3011:         }
1.165     raeburn  3012:     }
1.586     raeburn  3013:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3014:     if ($authtype eq '') {
                   3015:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   3016:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   3017:     }
1.605     bisitz   3018:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  3019:                $intarg.'" onchange="'.$jscall.'" />';
                   3020:     $result = &mt
1.144     matthew  3021:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3022:          '<label>'.$authtype,'</label>'.$autharg);
1.824     bisitz   3023:     $result.="<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
1.32      matthew  3024:     return $result;
                   3025: }
                   3026: 
1.1104    raeburn  3027: sub authform_local {
1.32      matthew  3028:     my %in = (
                   3029:               formname => 'document.cu',
                   3030:               kerb_def_dom => 'MSU.EDU',
                   3031:               @_,
                   3032:               );
1.586     raeburn  3033:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  3034:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  3035:     if (defined($in{'curr_authtype'})) {
                   3036:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3037:             if ($can_assign{'loc'}) {
1.772     bisitz   3038:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3039:                 if (defined($in{'mode'})) {
                   3040:                     if ($in{'mode'} eq 'modifyuser') {
                   3041:                         $loccheck = '';
                   3042:                     }
                   3043:                 }
1.591     raeburn  3044:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3045:                     $locarg = $in{'curr_autharg'};
                   3046:                 }
                   3047:             } else {
                   3048:                 $result = &mt('Currently using local (institutional) authentication.');
                   3049:                 return $result;
1.165     raeburn  3050:             }
                   3051:         }
1.586     raeburn  3052:     } else {
                   3053:         if ($authnum == 1) {
1.784     bisitz   3054:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3055:         }
                   3056:     }
                   3057:     if (!$can_assign{'loc'}) {
                   3058:         return;
1.587     raeburn  3059:     } elsif ($authtype eq '') {
1.591     raeburn  3060:         if (defined($in{'mode'})) {
1.587     raeburn  3061:             if ($in{'mode'} eq 'modifycourse') {
                   3062:                 if ($authnum == 1) {
1.1104    raeburn  3063:                     $authtype = '<input type="radio" name="login" value="loc" />';
1.587     raeburn  3064:                 }
                   3065:             }
                   3066:         }
1.165     raeburn  3067:     }
1.586     raeburn  3068:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3069:     if ($authtype eq '') {
                   3070:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3071:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   3072:                     $jscall.'" />';
                   3073:     }
                   3074:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   3075:                $locarg.'" onchange="'.$jscall.'" />';
                   3076:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3077:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3078:     return $result;
                   3079: }
                   3080: 
1.1106    raeburn  3081: sub authform_filesystem {
1.32      matthew  3082:     my %in = (
                   3083:               formname => 'document.cu',
                   3084:               kerb_def_dom => 'MSU.EDU',
                   3085:               @_,
                   3086:               );
1.586     raeburn  3087:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  3088:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  3089:     if (defined($in{'curr_authtype'})) {
                   3090:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3091:             if ($can_assign{'fsys'}) {
1.772     bisitz   3092:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3093:                 if (defined($in{'mode'})) {
                   3094:                     if ($in{'mode'} eq 'modifyuser') {
                   3095:                         $fsyscheck = '';
                   3096:                     }
                   3097:                 }
1.586     raeburn  3098:             } else {
                   3099:                 $result = &mt('Currently Filesystem Authenticated.');
                   3100:                 return $result;
                   3101:             }           
                   3102:         }
                   3103:     } else {
                   3104:         if ($authnum == 1) {
1.784     bisitz   3105:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3106:         }
                   3107:     }
                   3108:     if (!$can_assign{'fsys'}) {
                   3109:         return;
1.587     raeburn  3110:     } elsif ($authtype eq '') {
1.591     raeburn  3111:         if (defined($in{'mode'})) {
1.587     raeburn  3112:             if ($in{'mode'} eq 'modifycourse') {
                   3113:                 if ($authnum == 1) {
1.1104    raeburn  3114:                     $authtype = '<input type="radio" name="login" value="fsys" />';
1.587     raeburn  3115:                 }
                   3116:             }
                   3117:         }
1.586     raeburn  3118:     }
                   3119:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3120:     if ($authtype eq '') {
                   3121:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3122:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   3123:                     $jscall.'" />';
                   3124:     }
                   3125:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   3126:                ' onchange="'.$jscall.'" />';
                   3127:     $result = &mt
1.144     matthew  3128:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3129:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  3130:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   3131:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  3132:                   'onchange="'.$jscall.'" />');
1.32      matthew  3133:     return $result;
                   3134: }
                   3135: 
1.586     raeburn  3136: sub get_assignable_auth {
                   3137:     my ($dom) = @_;
                   3138:     if ($dom eq '') {
                   3139:         $dom = $env{'request.role.domain'};
                   3140:     }
                   3141:     my %can_assign = (
                   3142:                           krb4 => 1,
                   3143:                           krb5 => 1,
                   3144:                           int  => 1,
                   3145:                           loc  => 1,
                   3146:                      );
                   3147:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3148:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3149:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3150:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3151:             my $context;
                   3152:             if ($env{'request.role'} =~ /^au/) {
                   3153:                 $context = 'author';
                   3154:             } elsif ($env{'request.role'} =~ /^dc/) {
                   3155:                 $context = 'domain';
                   3156:             } elsif ($env{'request.course.id'}) {
                   3157:                 $context = 'course';
                   3158:             }
                   3159:             if ($context) {
                   3160:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3161:                    %can_assign = %{$authhash->{$context}}; 
                   3162:                 }
                   3163:             }
                   3164:         }
                   3165:     }
                   3166:     my $authnum = 0;
                   3167:     foreach my $key (keys(%can_assign)) {
                   3168:         if ($can_assign{$key}) {
                   3169:             $authnum ++;
                   3170:         }
                   3171:     }
                   3172:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3173:         $authnum --;
                   3174:     }
                   3175:     return ($authnum,%can_assign);
                   3176: }
                   3177: 
1.80      albertel 3178: ###############################################################
                   3179: ##    Get Kerberos Defaults for Domain                 ##
                   3180: ###############################################################
                   3181: ##
                   3182: ## Returns default kerberos version and an associated argument
                   3183: ## as listed in file domain.tab. If not listed, provides
                   3184: ## appropriate default domain and kerberos version.
                   3185: ##
                   3186: #-------------------------------------------
                   3187: 
                   3188: =pod
                   3189: 
1.648     raeburn  3190: =item * &get_kerberos_defaults()
1.80      albertel 3191: 
                   3192: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3193: version and domain. If not found, it defaults to version 4 and the 
                   3194: domain of the server.
1.80      albertel 3195: 
1.648     raeburn  3196: =over 4
                   3197: 
1.80      albertel 3198: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3199: 
1.648     raeburn  3200: =back
                   3201: 
                   3202: =back
                   3203: 
1.80      albertel 3204: =cut
                   3205: 
                   3206: #-------------------------------------------
                   3207: sub get_kerberos_defaults {
                   3208:     my $domain=shift;
1.641     raeburn  3209:     my ($krbdef,$krbdefdom);
                   3210:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3211:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3212:         $krbdef = $domdefaults{'auth_def'};
                   3213:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3214:     } else {
1.80      albertel 3215:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3216:         my $krbdefdom=$1;
                   3217:         $krbdefdom=~tr/a-z/A-Z/;
                   3218:         $krbdef = "krb4";
                   3219:     }
                   3220:     return ($krbdef,$krbdefdom);
                   3221: }
1.112     bowersj2 3222: 
1.32      matthew  3223: 
1.46      matthew  3224: ###############################################################
                   3225: ##                Thesaurus Functions                        ##
                   3226: ###############################################################
1.20      www      3227: 
1.46      matthew  3228: =pod
1.20      www      3229: 
1.112     bowersj2 3230: =head1 Thesaurus Functions
                   3231: 
                   3232: =over 4
                   3233: 
1.648     raeburn  3234: =item * &initialize_keywords()
1.46      matthew  3235: 
                   3236: Initializes the package variable %Keywords if it is empty.  Uses the
                   3237: package variable $thesaurus_db_file.
                   3238: 
                   3239: =cut
                   3240: 
                   3241: ###################################################
                   3242: 
                   3243: sub initialize_keywords {
                   3244:     return 1 if (scalar keys(%Keywords));
                   3245:     # If we are here, %Keywords is empty, so fill it up
                   3246:     #   Make sure the file we need exists...
                   3247:     if (! -e $thesaurus_db_file) {
                   3248:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3249:                                  " failed because it does not exist");
                   3250:         return 0;
                   3251:     }
                   3252:     #   Set up the hash as a database
                   3253:     my %thesaurus_db;
                   3254:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3255:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3256:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3257:                                  $thesaurus_db_file);
                   3258:         return 0;
                   3259:     } 
                   3260:     #  Get the average number of appearances of a word.
                   3261:     my $avecount = $thesaurus_db{'average.count'};
                   3262:     #  Put keywords (those that appear > average) into %Keywords
                   3263:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3264:         my ($count,undef) = split /:/,$data;
                   3265:         $Keywords{$word}++ if ($count > $avecount);
                   3266:     }
                   3267:     untie %thesaurus_db;
                   3268:     # Remove special values from %Keywords.
1.356     albertel 3269:     foreach my $value ('total.count','average.count') {
                   3270:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3271:   }
1.46      matthew  3272:     return 1;
                   3273: }
                   3274: 
                   3275: ###################################################
                   3276: 
                   3277: =pod
                   3278: 
1.648     raeburn  3279: =item * &keyword($word)
1.46      matthew  3280: 
                   3281: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3282: than the average number of times in the thesaurus database.  Calls 
                   3283: &initialize_keywords
                   3284: 
                   3285: =cut
                   3286: 
                   3287: ###################################################
1.20      www      3288: 
                   3289: sub keyword {
1.46      matthew  3290:     return if (!&initialize_keywords());
                   3291:     my $word=lc(shift());
                   3292:     $word=~s/\W//g;
                   3293:     return exists($Keywords{$word});
1.20      www      3294: }
1.46      matthew  3295: 
                   3296: ###############################################################
                   3297: 
                   3298: =pod 
1.20      www      3299: 
1.648     raeburn  3300: =item * &get_related_words()
1.46      matthew  3301: 
1.160     matthew  3302: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3303: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3304: will be returned.  The order of the words returned is determined by the
                   3305: database which holds them.
                   3306: 
                   3307: Uses global $thesaurus_db_file.
                   3308: 
1.1057    foxr     3309: 
1.46      matthew  3310: =cut
                   3311: 
                   3312: ###############################################################
                   3313: sub get_related_words {
                   3314:     my $keyword = shift;
                   3315:     my %thesaurus_db;
                   3316:     if (! -e $thesaurus_db_file) {
                   3317:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3318:                                  "failed because the file does not exist");
                   3319:         return ();
                   3320:     }
                   3321:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3322:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3323:         return ();
                   3324:     } 
                   3325:     my @Words=();
1.429     www      3326:     my $count=0;
1.46      matthew  3327:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3328: 	# The first element is the number of times
                   3329: 	# the word appears.  We do not need it now.
1.429     www      3330: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3331: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3332: 	my $threshold=$mostfrequentcount/10;
                   3333:         foreach my $possibleword (@RelatedWords) {
                   3334:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3335:             if ($wordcount>$threshold) {
                   3336: 		push(@Words,$word);
                   3337:                 $count++;
                   3338:                 if ($count>10) { last; }
                   3339: 	    }
1.20      www      3340:         }
                   3341:     }
1.46      matthew  3342:     untie %thesaurus_db;
                   3343:     return @Words;
1.14      harris41 3344: }
1.1090    foxr     3345: ###############################################################
                   3346: #
                   3347: #  Spell checking
                   3348: #
                   3349: 
                   3350: =pod
                   3351: 
1.1142    raeburn  3352: =back
                   3353: 
1.1090    foxr     3354: =head1 Spell checking
                   3355: 
                   3356: =over 4
                   3357: 
                   3358: =item * &check_spelling($wordlist $language)
                   3359: 
                   3360: Takes a string containing words and feeds it to an external
                   3361: spellcheck program via a pipeline. Returns a string containing
                   3362: them mis-spelled words.
                   3363: 
                   3364: Parameters:
                   3365: 
                   3366: =over 4
                   3367: 
                   3368: =item - $wordlist
                   3369: 
                   3370: String that will be fed into the spellcheck program.
                   3371: 
                   3372: =item - $language
                   3373: 
                   3374: Language string that specifies the language for which the spell
                   3375: check will be performed.
                   3376: 
                   3377: =back
                   3378: 
                   3379: =back
                   3380: 
                   3381: Note: This sub assumes that aspell is installed.
                   3382: 
                   3383: 
                   3384: =cut
                   3385: 
1.46      matthew  3386: 
1.1090    foxr     3387: sub check_spelling {
                   3388:     my ($wordlist, $language) = @_;
1.1091    foxr     3389:     my @misspellings;
                   3390:     
                   3391:     # Generate the speller and set the langauge.
                   3392:     # if explicitly selected:
1.1090    foxr     3393: 
1.1091    foxr     3394:     my $speller = Text::Aspell->new;
1.1090    foxr     3395:     if ($language) {
1.1091    foxr     3396: 	$speller->set_option('lang', $language);
1.1090    foxr     3397:     }
                   3398: 
1.1091    foxr     3399:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3400: 
1.1091    foxr     3401:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3402: 
1.1091    foxr     3403:     foreach my $word (@words) {
                   3404: 	if(! $speller->check($word)) {
                   3405: 	    push(@misspellings, $word);
1.1090    foxr     3406: 	}
                   3407:     }
1.1091    foxr     3408:     return join(' ', @misspellings);
                   3409:     
1.1090    foxr     3410: }
                   3411: 
1.61      www      3412: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3413: =pod
                   3414: 
1.112     bowersj2 3415: =head1 User Name Functions
                   3416: 
                   3417: =over 4
                   3418: 
1.648     raeburn  3419: =item * &plainname($uname,$udom,$first)
1.81      albertel 3420: 
1.112     bowersj2 3421: Takes a users logon name and returns it as a string in
1.226     albertel 3422: "first middle last generation" form 
                   3423: if $first is set to 'lastname' then it returns it as
                   3424: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3425: 
                   3426: =cut
1.61      www      3427: 
1.295     www      3428: 
1.81      albertel 3429: ###############################################################
1.61      www      3430: sub plainname {
1.226     albertel 3431:     my ($uname,$udom,$first)=@_;
1.537     albertel 3432:     return if (!defined($uname) || !defined($udom));
1.295     www      3433:     my %names=&getnames($uname,$udom);
1.226     albertel 3434:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3435: 					  $names{'middlename'},
                   3436: 					  $names{'lastname'},
                   3437: 					  $names{'generation'},$first);
                   3438:     $name=~s/^\s+//;
1.62      www      3439:     $name=~s/\s+$//;
                   3440:     $name=~s/\s+/ /g;
1.353     albertel 3441:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3442:     return $name;
1.61      www      3443: }
1.66      www      3444: 
                   3445: # -------------------------------------------------------------------- Nickname
1.81      albertel 3446: =pod
                   3447: 
1.648     raeburn  3448: =item * &nickname($uname,$udom)
1.81      albertel 3449: 
                   3450: Gets a users name and returns it as a string as
                   3451: 
                   3452: "&quot;nickname&quot;"
1.66      www      3453: 
1.81      albertel 3454: if the user has a nickname or
                   3455: 
                   3456: "first middle last generation"
                   3457: 
                   3458: if the user does not
                   3459: 
                   3460: =cut
1.66      www      3461: 
                   3462: sub nickname {
                   3463:     my ($uname,$udom)=@_;
1.537     albertel 3464:     return if (!defined($uname) || !defined($udom));
1.295     www      3465:     my %names=&getnames($uname,$udom);
1.68      albertel 3466:     my $name=$names{'nickname'};
1.66      www      3467:     if ($name) {
                   3468:        $name='&quot;'.$name.'&quot;'; 
                   3469:     } else {
                   3470:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3471: 	     $names{'lastname'}.' '.$names{'generation'};
                   3472:        $name=~s/\s+$//;
                   3473:        $name=~s/\s+/ /g;
                   3474:     }
                   3475:     return $name;
                   3476: }
                   3477: 
1.295     www      3478: sub getnames {
                   3479:     my ($uname,$udom)=@_;
1.537     albertel 3480:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3481:     if ($udom eq 'public' && $uname eq 'public') {
                   3482: 	return ('lastname' => &mt('Public'));
                   3483:     }
1.295     www      3484:     my $id=$uname.':'.$udom;
                   3485:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3486:     if ($cached) {
                   3487: 	return %{$names};
                   3488:     } else {
                   3489: 	my %loadnames=&Apache::lonnet::get('environment',
                   3490:                     ['firstname','middlename','lastname','generation','nickname'],
                   3491: 					 $udom,$uname);
                   3492: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3493: 	return %loadnames;
                   3494:     }
                   3495: }
1.61      www      3496: 
1.542     raeburn  3497: # -------------------------------------------------------------------- getemails
1.648     raeburn  3498: 
1.542     raeburn  3499: =pod
                   3500: 
1.648     raeburn  3501: =item * &getemails($uname,$udom)
1.542     raeburn  3502: 
                   3503: Gets a user's email information and returns it as a hash with keys:
                   3504: notification, critnotification, permanentemail
                   3505: 
                   3506: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3507: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3508:  
1.648     raeburn  3509: 
1.542     raeburn  3510: =cut
                   3511: 
1.648     raeburn  3512: 
1.466     albertel 3513: sub getemails {
                   3514:     my ($uname,$udom)=@_;
                   3515:     if ($udom eq 'public' && $uname eq 'public') {
                   3516: 	return;
                   3517:     }
1.467     www      3518:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3519:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3520:     my $id=$uname.':'.$udom;
                   3521:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3522:     if ($cached) {
                   3523: 	return %{$names};
                   3524:     } else {
                   3525: 	my %loadnames=&Apache::lonnet::get('environment',
                   3526:                     			   ['notification','critnotification',
                   3527: 					    'permanentemail'],
                   3528: 					   $udom,$uname);
                   3529: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3530: 	return %loadnames;
                   3531:     }
                   3532: }
                   3533: 
1.551     albertel 3534: sub flush_email_cache {
                   3535:     my ($uname,$udom)=@_;
                   3536:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3537:     if (!$uname) { $uname=$env{'user.name'};   }
                   3538:     return if ($udom eq 'public' && $uname eq 'public');
                   3539:     my $id=$uname.':'.$udom;
                   3540:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3541: }
                   3542: 
1.728     raeburn  3543: # -------------------------------------------------------------------- getlangs
                   3544: 
                   3545: =pod
                   3546: 
                   3547: =item * &getlangs($uname,$udom)
                   3548: 
                   3549: Gets a user's language preference and returns it as a hash with key:
                   3550: language.
                   3551: 
                   3552: =cut
                   3553: 
                   3554: 
                   3555: sub getlangs {
                   3556:     my ($uname,$udom) = @_;
                   3557:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3558:     if (!$uname) { $uname=$env{'user.name'};   }
                   3559:     my $id=$uname.':'.$udom;
                   3560:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3561:     if ($cached) {
                   3562:         return %{$langs};
                   3563:     } else {
                   3564:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3565:                                            $udom,$uname);
                   3566:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3567:         return %loadlangs;
                   3568:     }
                   3569: }
                   3570: 
                   3571: sub flush_langs_cache {
                   3572:     my ($uname,$udom)=@_;
                   3573:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3574:     if (!$uname) { $uname=$env{'user.name'};   }
                   3575:     return if ($udom eq 'public' && $uname eq 'public');
                   3576:     my $id=$uname.':'.$udom;
                   3577:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3578: }
                   3579: 
1.61      www      3580: # ------------------------------------------------------------------ Screenname
1.81      albertel 3581: 
                   3582: =pod
                   3583: 
1.648     raeburn  3584: =item * &screenname($uname,$udom)
1.81      albertel 3585: 
                   3586: Gets a users screenname and returns it as a string
                   3587: 
                   3588: =cut
1.61      www      3589: 
                   3590: sub screenname {
                   3591:     my ($uname,$udom)=@_;
1.258     albertel 3592:     if ($uname eq $env{'user.name'} &&
                   3593: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3594:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3595:     return $names{'screenname'};
1.62      www      3596: }
                   3597: 
1.212     albertel 3598: 
1.802     bisitz   3599: # ------------------------------------------------------------- Confirm Wrapper
                   3600: =pod
                   3601: 
1.1142    raeburn  3602: =item * &confirmwrapper($message)
1.802     bisitz   3603: 
                   3604: Wrap messages about completion of operation in box
                   3605: 
                   3606: =cut
                   3607: 
                   3608: sub confirmwrapper {
                   3609:     my ($message)=@_;
                   3610:     if ($message) {
                   3611:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3612:                .$message."\n"
                   3613:                .'</div>'."\n";
                   3614:     } else {
                   3615:         return $message;
                   3616:     }
                   3617: }
                   3618: 
1.62      www      3619: # ------------------------------------------------------------- Message Wrapper
                   3620: 
                   3621: sub messagewrapper {
1.369     www      3622:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3623:     return 
1.441     albertel 3624:         '<a href="/adm/email?compose=individual&amp;'.
                   3625:         'recname='.$username.'&amp;recdom='.$domain.
                   3626: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3627:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3628: }
1.802     bisitz   3629: 
1.74      www      3630: # --------------------------------------------------------------- Notes Wrapper
                   3631: 
                   3632: sub noteswrapper {
                   3633:     my ($link,$un,$do)=@_;
                   3634:     return 
1.896     amueller 3635: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3636: }
1.802     bisitz   3637: 
1.62      www      3638: # ------------------------------------------------------------- Aboutme Wrapper
                   3639: 
                   3640: sub aboutmewrapper {
1.1070    raeburn  3641:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3642:     if (!defined($username)  && !defined($domain)) {
                   3643:         return;
                   3644:     }
1.1096    raeburn  3645:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3646: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3647: }
                   3648: 
                   3649: # ------------------------------------------------------------ Syllabus Wrapper
                   3650: 
                   3651: sub syllabuswrapper {
1.707     bisitz   3652:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3653:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3654: }
1.14      harris41 3655: 
1.802     bisitz   3656: # -----------------------------------------------------------------------------
                   3657: 
1.208     matthew  3658: sub track_student_link {
1.887     raeburn  3659:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3660:     my $link ="/adm/trackstudent?";
1.208     matthew  3661:     my $title = 'View recent activity';
                   3662:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3663:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3664:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3665:         $title .= ' of this student';
1.268     albertel 3666:     } 
1.208     matthew  3667:     if (defined($target) && $target !~ /^\s*$/) {
                   3668:         $target = qq{target="$target"};
                   3669:     } else {
                   3670:         $target = '';
                   3671:     }
1.268     albertel 3672:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3673:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3674:     $title = &mt($title);
                   3675:     $linktext = &mt($linktext);
1.448     albertel 3676:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3677: 	&help_open_topic('View_recent_activity');
1.208     matthew  3678: }
                   3679: 
1.781     raeburn  3680: sub slot_reservations_link {
                   3681:     my ($linktext,$sname,$sdom,$target) = @_;
                   3682:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3683:     my $title = 'View slot reservation history';
                   3684:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3685:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3686:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3687:         $title .= ' of this student';
                   3688:     }
                   3689:     if (defined($target) && $target !~ /^\s*$/) {
                   3690:         $target = qq{target="$target"};
                   3691:     } else {
                   3692:         $target = '';
                   3693:     }
                   3694:     $title = &mt($title);
                   3695:     $linktext = &mt($linktext);
                   3696:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3697: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3698: 
                   3699: }
                   3700: 
1.508     www      3701: # ===================================================== Display a student photo
                   3702: 
                   3703: 
1.509     albertel 3704: sub student_image_tag {
1.508     www      3705:     my ($domain,$user)=@_;
                   3706:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3707:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3708: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3709:     } else {
                   3710: 	return '';
                   3711:     }
                   3712: }
                   3713: 
1.112     bowersj2 3714: =pod
                   3715: 
                   3716: =back
                   3717: 
                   3718: =head1 Access .tab File Data
                   3719: 
                   3720: =over 4
                   3721: 
1.648     raeburn  3722: =item * &languageids() 
1.112     bowersj2 3723: 
                   3724: returns list of all language ids
                   3725: 
                   3726: =cut
                   3727: 
1.14      harris41 3728: sub languageids {
1.16      harris41 3729:     return sort(keys(%language));
1.14      harris41 3730: }
                   3731: 
1.112     bowersj2 3732: =pod
                   3733: 
1.648     raeburn  3734: =item * &languagedescription() 
1.112     bowersj2 3735: 
                   3736: returns description of a specified language id
                   3737: 
                   3738: =cut
                   3739: 
1.14      harris41 3740: sub languagedescription {
1.125     www      3741:     my $code=shift;
                   3742:     return  ($supported_language{$code}?'* ':'').
                   3743:             $language{$code}.
1.126     www      3744: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3745: }
                   3746: 
1.1048    foxr     3747: =pod
                   3748: 
                   3749: =item * &plainlanguagedescription
                   3750: 
                   3751: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3752: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3753: 
                   3754: =cut
                   3755: 
1.145     www      3756: sub plainlanguagedescription {
                   3757:     my $code=shift;
                   3758:     return $language{$code};
                   3759: }
                   3760: 
1.1048    foxr     3761: =pod
                   3762: 
                   3763: =item * &supportedlanguagecode
                   3764: 
                   3765: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3766: code.
                   3767: 
                   3768: =cut
                   3769: 
1.145     www      3770: sub supportedlanguagecode {
                   3771:     my $code=shift;
                   3772:     return $supported_language{$code};
1.97      www      3773: }
                   3774: 
1.112     bowersj2 3775: =pod
                   3776: 
1.1048    foxr     3777: =item * &latexlanguage()
                   3778: 
                   3779: Given a language key code returns the correspondnig language to use
                   3780: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3781: is no supported hyphenation for the language code.
                   3782: 
                   3783: =cut
                   3784: 
                   3785: sub latexlanguage {
                   3786:     my $code = shift;
                   3787:     return $latex_language{$code};
                   3788: }
                   3789: 
                   3790: =pod
                   3791: 
                   3792: =item * &latexhyphenation()
                   3793: 
                   3794: Same as above but what's supplied is the language as it might be stored
                   3795: in the metadata.
                   3796: 
                   3797: =cut
                   3798: 
                   3799: sub latexhyphenation {
                   3800:     my $key = shift;
                   3801:     return $latex_language_bykey{$key};
                   3802: }
                   3803: 
                   3804: =pod
                   3805: 
1.648     raeburn  3806: =item * &copyrightids() 
1.112     bowersj2 3807: 
                   3808: returns list of all copyrights
                   3809: 
                   3810: =cut
                   3811: 
                   3812: sub copyrightids {
                   3813:     return sort(keys(%cprtag));
                   3814: }
                   3815: 
                   3816: =pod
                   3817: 
1.648     raeburn  3818: =item * &copyrightdescription() 
1.112     bowersj2 3819: 
                   3820: returns description of a specified copyright id
                   3821: 
                   3822: =cut
                   3823: 
                   3824: sub copyrightdescription {
1.166     www      3825:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3826: }
1.197     matthew  3827: 
                   3828: =pod
                   3829: 
1.648     raeburn  3830: =item * &source_copyrightids() 
1.192     taceyjo1 3831: 
                   3832: returns list of all source copyrights
                   3833: 
                   3834: =cut
                   3835: 
                   3836: sub source_copyrightids {
                   3837:     return sort(keys(%scprtag));
                   3838: }
                   3839: 
                   3840: =pod
                   3841: 
1.648     raeburn  3842: =item * &source_copyrightdescription() 
1.192     taceyjo1 3843: 
                   3844: returns description of a specified source copyright id
                   3845: 
                   3846: =cut
                   3847: 
                   3848: sub source_copyrightdescription {
                   3849:     return &mt($scprtag{shift(@_)});
                   3850: }
1.112     bowersj2 3851: 
                   3852: =pod
                   3853: 
1.648     raeburn  3854: =item * &filecategories() 
1.112     bowersj2 3855: 
                   3856: returns list of all file categories
                   3857: 
                   3858: =cut
                   3859: 
                   3860: sub filecategories {
                   3861:     return sort(keys(%category_extensions));
                   3862: }
                   3863: 
                   3864: =pod
                   3865: 
1.648     raeburn  3866: =item * &filecategorytypes() 
1.112     bowersj2 3867: 
                   3868: returns list of file types belonging to a given file
                   3869: category
                   3870: 
                   3871: =cut
                   3872: 
                   3873: sub filecategorytypes {
1.356     albertel 3874:     my ($cat) = @_;
                   3875:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3876: }
                   3877: 
                   3878: =pod
                   3879: 
1.648     raeburn  3880: =item * &fileembstyle() 
1.112     bowersj2 3881: 
                   3882: returns embedding style for a specified file type
                   3883: 
                   3884: =cut
                   3885: 
                   3886: sub fileembstyle {
                   3887:     return $fe{lc(shift(@_))};
1.169     www      3888: }
                   3889: 
1.351     www      3890: sub filemimetype {
                   3891:     return $fm{lc(shift(@_))};
                   3892: }
                   3893: 
1.169     www      3894: 
                   3895: sub filecategoryselect {
                   3896:     my ($name,$value)=@_;
1.189     matthew  3897:     return &select_form($value,$name,
1.970     raeburn  3898:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3899: }
                   3900: 
                   3901: =pod
                   3902: 
1.648     raeburn  3903: =item * &filedescription() 
1.112     bowersj2 3904: 
                   3905: returns description for a specified file type
                   3906: 
                   3907: =cut
                   3908: 
                   3909: sub filedescription {
1.188     matthew  3910:     my $file_description = $fd{lc(shift())};
                   3911:     $file_description =~ s:([\[\]]):~$1:g;
                   3912:     return &mt($file_description);
1.112     bowersj2 3913: }
                   3914: 
                   3915: =pod
                   3916: 
1.648     raeburn  3917: =item * &filedescriptionex() 
1.112     bowersj2 3918: 
                   3919: returns description for a specified file type with
                   3920: extra formatting
                   3921: 
                   3922: =cut
                   3923: 
                   3924: sub filedescriptionex {
                   3925:     my $ex=shift;
1.188     matthew  3926:     my $file_description = $fd{lc($ex)};
                   3927:     $file_description =~ s:([\[\]]):~$1:g;
                   3928:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3929: }
                   3930: 
                   3931: # End of .tab access
                   3932: =pod
                   3933: 
                   3934: =back
                   3935: 
                   3936: =cut
                   3937: 
                   3938: # ------------------------------------------------------------------ File Types
                   3939: sub fileextensions {
                   3940:     return sort(keys(%fe));
                   3941: }
                   3942: 
1.97      www      3943: # ----------------------------------------------------------- Display Languages
                   3944: # returns a hash with all desired display languages
                   3945: #
                   3946: 
                   3947: sub display_languages {
                   3948:     my %languages=();
1.695     raeburn  3949:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3950: 	$languages{$lang}=1;
1.97      www      3951:     }
                   3952:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3953:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3954: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3955: 	    $languages{$lang}=1;
1.97      www      3956:         }
                   3957:     }
                   3958:     return %languages;
1.14      harris41 3959: }
                   3960: 
1.582     albertel 3961: sub languages {
                   3962:     my ($possible_langs) = @_;
1.695     raeburn  3963:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3964:     if (!ref($possible_langs)) {
                   3965: 	if( wantarray ) {
                   3966: 	    return @preferred_langs;
                   3967: 	} else {
                   3968: 	    return $preferred_langs[0];
                   3969: 	}
                   3970:     }
                   3971:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3972:     my @preferred_possibilities;
                   3973:     foreach my $preferred_lang (@preferred_langs) {
                   3974: 	if (exists($possibilities{$preferred_lang})) {
                   3975: 	    push(@preferred_possibilities, $preferred_lang);
                   3976: 	}
                   3977:     }
                   3978:     if( wantarray ) {
                   3979: 	return @preferred_possibilities;
                   3980:     }
                   3981:     return $preferred_possibilities[0];
                   3982: }
                   3983: 
1.742     raeburn  3984: sub user_lang {
                   3985:     my ($touname,$toudom,$fromcid) = @_;
                   3986:     my @userlangs;
                   3987:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3988:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3989:                     $env{'course.'.$fromcid.'.languages'}));
                   3990:     } else {
                   3991:         my %langhash = &getlangs($touname,$toudom);
                   3992:         if ($langhash{'languages'} ne '') {
                   3993:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3994:         } else {
                   3995:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3996:             if ($domdefs{'lang_def'} ne '') {
                   3997:                 @userlangs = ($domdefs{'lang_def'});
                   3998:             }
                   3999:         }
                   4000:     }
                   4001:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4002:     my $user_lh = Apache::localize->get_handle(@languages);
                   4003:     return $user_lh;
                   4004: }
                   4005: 
                   4006: 
1.112     bowersj2 4007: ###############################################################
                   4008: ##               Student Answer Attempts                     ##
                   4009: ###############################################################
                   4010: 
                   4011: =pod
                   4012: 
                   4013: =head1 Alternate Problem Views
                   4014: 
                   4015: =over 4
                   4016: 
1.648     raeburn  4017: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4018:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4019: 
                   4020: Return string with previous attempt on problem. Arguments:
                   4021: 
                   4022: =over 4
                   4023: 
                   4024: =item * $symb: Problem, including path
                   4025: 
                   4026: =item * $username: username of the desired student
                   4027: 
                   4028: =item * $domain: domain of the desired student
1.14      harris41 4029: 
1.112     bowersj2 4030: =item * $course: Course ID
1.14      harris41 4031: 
1.112     bowersj2 4032: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4033:     something
1.14      harris41 4034: 
1.112     bowersj2 4035: =item * $regexp: if string matches this regexp, the string will be
                   4036:     sent to $gradesub
1.14      harris41 4037: 
1.112     bowersj2 4038: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4039: 
1.1199    raeburn  4040: =item * $usec: section of the desired student
                   4041: 
                   4042: =item * $identifier: counter for student (multiple students one problem) or 
                   4043:     problem (one student; whole sequence).
                   4044: 
1.112     bowersj2 4045: =back
1.14      harris41 4046: 
1.112     bowersj2 4047: The output string is a table containing all desired attempts, if any.
1.16      harris41 4048: 
1.112     bowersj2 4049: =cut
1.1       albertel 4050: 
                   4051: sub get_previous_attempt {
1.1199    raeburn  4052:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4053:   my $prevattempts='';
1.43      ng       4054:   no strict 'refs';
1.1       albertel 4055:   if ($symb) {
1.3       albertel 4056:     my (%returnhash)=
                   4057:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4058:     if ($returnhash{'version'}) {
                   4059:       my %lasthash=();
                   4060:       my $version;
                   4061:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4062:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4063:             if ($key =~ /\.rawrndseed$/) {
                   4064:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4065:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4066:             } else {
                   4067:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4068:             }
1.19      harris41 4069:         }
1.1       albertel 4070:       }
1.596     albertel 4071:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4072:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4073:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4074:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4075:       foreach my $key (sort(keys(%lasthash))) {
                   4076: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4077: 	if ($#parts > 0) {
1.31      albertel 4078: 	  my $data=$parts[-1];
1.989     raeburn  4079:           next if ($data eq 'foilorder');
1.31      albertel 4080: 	  pop(@parts);
1.1010    www      4081:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4082:           if ($data eq 'type') {
                   4083:               unless ($showsurv) {
                   4084:                   my $id = join(',',@parts);
                   4085:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4086:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4087:                       $lasthidden{$ign.'.'.$id} = 1;
                   4088:                   }
1.945     raeburn  4089:               }
1.1199    raeburn  4090:               if ($identifier ne '') {
                   4091:                   my $id = join(',',@parts);
                   4092:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4093:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4094:                       $hidestatus{$ign.'.'.$id} = 1;
                   4095:                   }
                   4096:               }
                   4097:           } elsif ($data eq 'regrader') {
                   4098:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4099:                   my $id = join(',',@parts);
                   4100:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4101:               }
1.1010    www      4102:           } 
1.31      albertel 4103: 	} else {
1.41      ng       4104: 	  if ($#parts == 0) {
                   4105: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4106: 	  } else {
                   4107: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4108: 	  }
1.31      albertel 4109: 	}
1.16      harris41 4110:       }
1.596     albertel 4111:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4112:       if ($getattempt eq '') {
1.1199    raeburn  4113:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4114:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4115:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4116:                 foreach my $id (keys(%regraded)) {
                   4117:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4118:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4119:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4120:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4121:                     }
                   4122:                 }
                   4123:             }
1.1200    raeburn  4124:         }
                   4125: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4126:             my (@hidden,@unsolved);
1.945     raeburn  4127:             if (%typeparts) {
                   4128:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4129:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4130:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4131:                         push(@hidden,$id);
1.1199    raeburn  4132:                     } elsif ($identifier ne '') {
                   4133:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4134:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4135:                                 ($hidestatus{$id})) {
1.1200    raeburn  4136:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4137:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4138:                                 push(@{$solved{$id}},$version);
                   4139:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4140:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4141:                                 my $skip;
                   4142:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4143:                                     foreach my $reset (@{$resets{$id}}) {
                   4144:                                         if ($reset > $solved{$id}[-1]) {
                   4145:                                             $skip=1;
                   4146:                                             last;
                   4147:                                         }
                   4148:                                     }
                   4149:                                 }
                   4150:                                 unless ($skip) {
                   4151:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4152:                                     push(@unsolved,$partslist);
                   4153:                                 }
                   4154:                             }
                   4155:                         }
1.945     raeburn  4156:                     }
                   4157:                 }
                   4158:             }
                   4159:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4160:                            '<td>'.&mt('Transaction [_1]',$version);
                   4161:             if (@unsolved) {
                   4162:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4163:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4164:                                  &mt('Hide').'</label></span>';
                   4165:             }
                   4166:             $prevattempts .= '</td>';
1.945     raeburn  4167:             if (@hidden) {
                   4168:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4169:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4170:                     my $hide;
                   4171:                     foreach my $id (@hidden) {
                   4172:                         if ($key =~ /^\Q$id\E/) {
                   4173:                             $hide = 1;
                   4174:                             last;
                   4175:                         }
                   4176:                     }
                   4177:                     if ($hide) {
                   4178:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4179:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4180:                             my $value = &format_previous_attempt_value($key,
                   4181:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4182:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4183:                         } else {
                   4184:                             $prevattempts.='<td>&nbsp;</td>';
                   4185:                         }
                   4186:                     } else {
                   4187:                         if ($key =~ /\./) {
1.1212    raeburn  4188:                             my $value = $returnhash{$version.':'.$key};
                   4189:                             if ($key =~ /\.rndseed$/) {
                   4190:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4191:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4192:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4193:                                 }
                   4194:                             }
                   4195:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4196:                                            '&nbsp;</td>';
1.945     raeburn  4197:                         } else {
                   4198:                             $prevattempts.='<td>&nbsp;</td>';
                   4199:                         }
                   4200:                     }
                   4201:                 }
                   4202:             } else {
                   4203: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4204:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4205:                     my $value = $returnhash{$version.':'.$key};
                   4206:                     if ($key =~ /\.rndseed$/) {
                   4207:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4208:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4209:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4210:                         }
                   4211:                     }
                   4212:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4213:                                    '&nbsp;</td>';
1.945     raeburn  4214: 	        }
                   4215:             }
                   4216: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4217: 	 }
1.1       albertel 4218:       }
1.945     raeburn  4219:       my @currhidden = keys(%lasthidden);
1.596     albertel 4220:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4221:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4222:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4223:           if (%typeparts) {
                   4224:               my $hidden;
                   4225:               foreach my $id (@currhidden) {
                   4226:                   if ($key =~ /^\Q$id\E/) {
                   4227:                       $hidden = 1;
                   4228:                       last;
                   4229:                   }
                   4230:               }
                   4231:               if ($hidden) {
                   4232:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4233:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4234:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4235:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4236:                           $value = &$gradesub($value);
                   4237:                       }
1.1173    kruse    4238:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4239:                   } else {
                   4240:                       $prevattempts.='<td>&nbsp;</td>';
                   4241:                   }
                   4242:               } else {
                   4243:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4244:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4245:                       $value = &$gradesub($value);
                   4246:                   }
1.1173    kruse    4247:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4248:               }
                   4249:           } else {
                   4250: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4251: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4252:                   $value = &$gradesub($value);
                   4253:               }
1.1173    kruse    4254: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4255:           }
1.16      harris41 4256:       }
1.596     albertel 4257:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4258:     } else {
1.596     albertel 4259:       $prevattempts=
                   4260: 	  &start_data_table().&start_data_table_row().
                   4261: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4262: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4263:     }
                   4264:   } else {
1.596     albertel 4265:     $prevattempts=
                   4266: 	  &start_data_table().&start_data_table_row().
                   4267: 	  '<td>'.&mt('No data.').'</td>'.
                   4268: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4269:   }
1.10      albertel 4270: }
                   4271: 
1.581     albertel 4272: sub format_previous_attempt_value {
                   4273:     my ($key,$value) = @_;
1.1011    www      4274:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4275:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4276:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4277:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4278:     } elsif ($key =~ /answerstring$/) {
                   4279:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4280:         my @answer = %answers;
                   4281:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4282:         my @anskeys = sort(keys(%answers));
                   4283:         if (@anskeys == 1) {
                   4284:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4285:             if ($answer =~ m{\0}) {
                   4286:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4287:             }
                   4288:             my $tag_internal_answer_name = 'INTERNAL';
                   4289:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4290:                 $value = $answer; 
                   4291:             } else {
                   4292:                 $value = $anskeys[0].'='.$answer;
                   4293:             }
                   4294:         } else {
                   4295:             foreach my $ans (@anskeys) {
                   4296:                 my $answer = $answers{$ans};
1.1001    raeburn  4297:                 if ($answer =~ m{\0}) {
                   4298:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4299:                 }
                   4300:                 $value .=  $ans.'='.$answer.'<br />';;
                   4301:             } 
                   4302:         }
1.581     albertel 4303:     } else {
1.1173    kruse    4304:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4305:     }
                   4306:     return $value;
                   4307: }
                   4308: 
                   4309: 
1.107     albertel 4310: sub relative_to_absolute {
                   4311:     my ($url,$output)=@_;
                   4312:     my $parser=HTML::TokeParser->new(\$output);
                   4313:     my $token;
                   4314:     my $thisdir=$url;
                   4315:     my @rlinks=();
                   4316:     while ($token=$parser->get_token) {
                   4317: 	if ($token->[0] eq 'S') {
                   4318: 	    if ($token->[1] eq 'a') {
                   4319: 		if ($token->[2]->{'href'}) {
                   4320: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4321: 		}
                   4322: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4323: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4324: 	    } elsif ($token->[1] eq 'base') {
                   4325: 		$thisdir=$token->[2]->{'href'};
                   4326: 	    }
                   4327: 	}
                   4328:     }
                   4329:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4330:     foreach my $link (@rlinks) {
1.726     raeburn  4331: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4332: 		($link=~/^\//) ||
                   4333: 		($link=~/^javascript:/i) ||
                   4334: 		($link=~/^mailto:/i) ||
                   4335: 		($link=~/^\#/)) {
                   4336: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4337: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4338: 	}
                   4339:     }
                   4340: # -------------------------------------------------- Deal with Applet codebases
                   4341:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4342:     return $output;
                   4343: }
                   4344: 
1.112     bowersj2 4345: =pod
                   4346: 
1.648     raeburn  4347: =item * &get_student_view()
1.112     bowersj2 4348: 
                   4349: show a snapshot of what student was looking at
                   4350: 
                   4351: =cut
                   4352: 
1.10      albertel 4353: sub get_student_view {
1.186     albertel 4354:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4355:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4356:   my (%form);
1.10      albertel 4357:   my @elements=('symb','courseid','domain','username');
                   4358:   foreach my $element (@elements) {
1.186     albertel 4359:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4360:   }
1.186     albertel 4361:   if (defined($moreenv)) {
                   4362:       %form=(%form,%{$moreenv});
                   4363:   }
1.236     albertel 4364:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4365:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4366:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4367:   $userview=~s/\<body[^\>]*\>//gi;
                   4368:   $userview=~s/\<\/body\>//gi;
                   4369:   $userview=~s/\<html\>//gi;
                   4370:   $userview=~s/\<\/html\>//gi;
                   4371:   $userview=~s/\<head\>//gi;
                   4372:   $userview=~s/\<\/head\>//gi;
                   4373:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4374:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4375:   if (wantarray) {
                   4376:      return ($userview,$response);
                   4377:   } else {
                   4378:      return $userview;
                   4379:   }
                   4380: }
                   4381: 
                   4382: sub get_student_view_with_retries {
                   4383:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4384: 
                   4385:     my $ok = 0;                 # True if we got a good response.
                   4386:     my $content;
                   4387:     my $response;
                   4388: 
                   4389:     # Try to get the student_view done. within the retries count:
                   4390:     
                   4391:     do {
                   4392:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4393:          $ok      = $response->is_success;
                   4394:          if (!$ok) {
                   4395:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4396:          }
                   4397:          $retries--;
                   4398:     } while (!$ok && ($retries > 0));
                   4399:     
                   4400:     if (!$ok) {
                   4401:        $content = '';          # On error return an empty content.
                   4402:     }
1.651     www      4403:     if (wantarray) {
                   4404:        return ($content, $response);
                   4405:     } else {
                   4406:        return $content;
                   4407:     }
1.11      albertel 4408: }
                   4409: 
1.112     bowersj2 4410: =pod
                   4411: 
1.648     raeburn  4412: =item * &get_student_answers() 
1.112     bowersj2 4413: 
                   4414: show a snapshot of how student was answering problem
                   4415: 
                   4416: =cut
                   4417: 
1.11      albertel 4418: sub get_student_answers {
1.100     sakharuk 4419:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4420:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4421:   my (%moreenv);
1.11      albertel 4422:   my @elements=('symb','courseid','domain','username');
                   4423:   foreach my $element (@elements) {
1.186     albertel 4424:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4425:   }
1.186     albertel 4426:   $moreenv{'grade_target'}='answer';
                   4427:   %moreenv=(%form,%moreenv);
1.497     raeburn  4428:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4429:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4430:   return $userview;
1.1       albertel 4431: }
1.116     albertel 4432: 
                   4433: =pod
                   4434: 
                   4435: =item * &submlink()
                   4436: 
1.242     albertel 4437: Inputs: $text $uname $udom $symb $target
1.116     albertel 4438: 
                   4439: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4440: 
                   4441: =cut
                   4442: 
                   4443: ###############################################
                   4444: sub submlink {
1.242     albertel 4445:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4446:     if (!($uname && $udom)) {
                   4447: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4448: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4449: 	if (!$symb) { $symb=$cursymb; }
                   4450:     }
1.254     matthew  4451:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4452:     $symb=&escape($symb);
1.960     bisitz   4453:     if ($target) { $target=" target=\"$target\""; }
                   4454:     return
                   4455:         '<a href="/adm/grades?command=submission'.
                   4456:         '&amp;symb='.$symb.
                   4457:         '&amp;student='.$uname.
                   4458:         '&amp;userdom='.$udom.'"'.
                   4459:         $target.'>'.$text.'</a>';
1.242     albertel 4460: }
                   4461: ##############################################
                   4462: 
                   4463: =pod
                   4464: 
                   4465: =item * &pgrdlink()
                   4466: 
                   4467: Inputs: $text $uname $udom $symb $target
                   4468: 
                   4469: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4470: 
                   4471: =cut
                   4472: 
                   4473: ###############################################
                   4474: sub pgrdlink {
                   4475:     my $link=&submlink(@_);
                   4476:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4477:     return $link;
                   4478: }
                   4479: ##############################################
                   4480: 
                   4481: =pod
                   4482: 
                   4483: =item * &pprmlink()
                   4484: 
                   4485: Inputs: $text $uname $udom $symb $target
                   4486: 
                   4487: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4488: student and a specific resource
1.242     albertel 4489: 
                   4490: =cut
                   4491: 
                   4492: ###############################################
                   4493: sub pprmlink {
                   4494:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4495:     if (!($uname && $udom)) {
                   4496: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4497: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4498: 	if (!$symb) { $symb=$cursymb; }
                   4499:     }
1.254     matthew  4500:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4501:     $symb=&escape($symb);
1.242     albertel 4502:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4503:     return '<a href="/adm/parmset?command=set&amp;'.
                   4504: 	'symb='.$symb.'&amp;uname='.$uname.
                   4505: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4506: }
                   4507: ##############################################
1.37      matthew  4508: 
1.112     bowersj2 4509: =pod
                   4510: 
                   4511: =back
                   4512: 
                   4513: =cut
                   4514: 
1.37      matthew  4515: ###############################################
1.51      www      4516: 
                   4517: 
                   4518: sub timehash {
1.687     raeburn  4519:     my ($thistime) = @_;
                   4520:     my $timezone = &Apache::lonlocal::gettimezone();
                   4521:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4522:                      ->set_time_zone($timezone);
                   4523:     my $wday = $dt->day_of_week();
                   4524:     if ($wday == 7) { $wday = 0; }
                   4525:     return ( 'second' => $dt->second(),
                   4526:              'minute' => $dt->minute(),
                   4527:              'hour'   => $dt->hour(),
                   4528:              'day'     => $dt->day_of_month(),
                   4529:              'month'   => $dt->month(),
                   4530:              'year'    => $dt->year(),
                   4531:              'weekday' => $wday,
                   4532:              'dayyear' => $dt->day_of_year(),
                   4533:              'dlsav'   => $dt->is_dst() );
1.51      www      4534: }
                   4535: 
1.370     www      4536: sub utc_string {
                   4537:     my ($date)=@_;
1.371     www      4538:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4539: }
                   4540: 
1.51      www      4541: sub maketime {
                   4542:     my %th=@_;
1.687     raeburn  4543:     my ($epoch_time,$timezone,$dt);
                   4544:     $timezone = &Apache::lonlocal::gettimezone();
                   4545:     eval {
                   4546:         $dt = DateTime->new( year   => $th{'year'},
                   4547:                              month  => $th{'month'},
                   4548:                              day    => $th{'day'},
                   4549:                              hour   => $th{'hour'},
                   4550:                              minute => $th{'minute'},
                   4551:                              second => $th{'second'},
                   4552:                              time_zone => $timezone,
                   4553:                          );
                   4554:     };
                   4555:     if (!$@) {
                   4556:         $epoch_time = $dt->epoch;
                   4557:         if ($epoch_time) {
                   4558:             return $epoch_time;
                   4559:         }
                   4560:     }
1.51      www      4561:     return POSIX::mktime(
                   4562:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4563:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4564: }
                   4565: 
                   4566: #########################################
1.51      www      4567: 
                   4568: sub findallcourses {
1.482     raeburn  4569:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4570:     my %roles;
                   4571:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4572:     my %courses;
1.51      www      4573:     my $now=time;
1.482     raeburn  4574:     if (!defined($uname)) {
                   4575:         $uname = $env{'user.name'};
                   4576:     }
                   4577:     if (!defined($udom)) {
                   4578:         $udom = $env{'user.domain'};
                   4579:     }
                   4580:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4581:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4582:         if (!%roles) {
                   4583:             %roles = (
                   4584:                        cc => 1,
1.907     raeburn  4585:                        co => 1,
1.482     raeburn  4586:                        in => 1,
                   4587:                        ep => 1,
                   4588:                        ta => 1,
                   4589:                        cr => 1,
                   4590:                        st => 1,
                   4591:              );
                   4592:         }
                   4593:         foreach my $entry (keys(%roleshash)) {
                   4594:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4595:             if ($trole =~ /^cr/) { 
                   4596:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4597:             } else {
                   4598:                 next if (!exists($roles{$trole}));
                   4599:             }
                   4600:             if ($tend) {
                   4601:                 next if ($tend < $now);
                   4602:             }
                   4603:             if ($tstart) {
                   4604:                 next if ($tstart > $now);
                   4605:             }
1.1058    raeburn  4606:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4607:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4608:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4609:             if ($secpart eq '') {
                   4610:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4611:                 $sec = 'none';
1.1058    raeburn  4612:                 $value .= $cnum.'/';
1.482     raeburn  4613:             } else {
                   4614:                 $cnum = $cnumpart;
                   4615:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4616:                 $value .= $cnum.'/'.$sec;
                   4617:             }
                   4618:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4619:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4620:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4621:                 }
                   4622:             } else {
                   4623:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4624:             }
1.482     raeburn  4625:         }
                   4626:     } else {
                   4627:         foreach my $key (keys(%env)) {
1.483     albertel 4628: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4629:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4630: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4631: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4632: 	        next if (%roles && !exists($roles{$role}));
                   4633: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4634:                 my $active=1;
                   4635:                 if ($starttime) {
                   4636: 		    if ($now<$starttime) { $active=0; }
                   4637:                 }
                   4638:                 if ($endtime) {
                   4639:                     if ($now>$endtime) { $active=0; }
                   4640:                 }
                   4641:                 if ($active) {
1.1058    raeburn  4642:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4643:                     if ($sec eq '') {
                   4644:                         $sec = 'none';
1.1058    raeburn  4645:                     } else {
                   4646:                         $value .= $sec;
                   4647:                     }
                   4648:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4649:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4650:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4651:                         }
                   4652:                     } else {
                   4653:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4654:                     }
1.474     raeburn  4655:                 }
                   4656:             }
1.51      www      4657:         }
                   4658:     }
1.474     raeburn  4659:     return %courses;
1.51      www      4660: }
1.37      matthew  4661: 
1.54      www      4662: ###############################################
1.474     raeburn  4663: 
                   4664: sub blockcheck {
1.1189    raeburn  4665:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4666: 
1.1189    raeburn  4667:     if (defined($udom) && defined($uname)) {
                   4668:         # If uname and udom are for a course, check for blocks in the course.
                   4669:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4670:             my ($startblock,$endblock,$triggerblock) =
                   4671:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4672:             return ($startblock,$endblock,$triggerblock);
                   4673:         }
                   4674:     } else {
1.490     raeburn  4675:         $udom = $env{'user.domain'};
                   4676:         $uname = $env{'user.name'};
                   4677:     }
                   4678: 
1.502     raeburn  4679:     my $startblock = 0;
                   4680:     my $endblock = 0;
1.1062    raeburn  4681:     my $triggerblock = '';
1.482     raeburn  4682:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4683: 
1.490     raeburn  4684:     # If uname is for a user, and activity is course-specific, i.e.,
                   4685:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4686: 
1.490     raeburn  4687:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1189    raeburn  4688:          $activity eq 'groups' || $activity eq 'printout') &&
                   4689:         ($env{'request.course.id'})) {
1.490     raeburn  4690:         foreach my $key (keys(%live_courses)) {
                   4691:             if ($key ne $env{'request.course.id'}) {
                   4692:                 delete($live_courses{$key});
                   4693:             }
                   4694:         }
                   4695:     }
                   4696: 
                   4697:     my $otheruser = 0;
                   4698:     my %own_courses;
                   4699:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4700:         # Resource belongs to user other than current user.
                   4701:         $otheruser = 1;
                   4702:         # Gather courses for current user
                   4703:         %own_courses = 
                   4704:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4705:     }
                   4706: 
                   4707:     # Gather active course roles - course coordinator, instructor, 
                   4708:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4709: 
                   4710:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4711:         my ($cdom,$cnum);
                   4712:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4713:             $cdom = $env{'course.'.$course.'.domain'};
                   4714:             $cnum = $env{'course.'.$course.'.num'};
                   4715:         } else {
1.490     raeburn  4716:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4717:         }
                   4718:         my $no_ownblock = 0;
                   4719:         my $no_userblock = 0;
1.533     raeburn  4720:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4721:             # Check if current user has 'evb' priv for this
                   4722:             if (defined($own_courses{$course})) {
                   4723:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4724:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4725:                     if ($sec ne 'none') {
                   4726:                         $checkrole .= '/'.$sec;
                   4727:                     }
                   4728:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4729:                         $no_ownblock = 1;
                   4730:                         last;
                   4731:                     }
                   4732:                 }
                   4733:             }
                   4734:             # if they have 'evb' priv and are currently not playing student
                   4735:             next if (($no_ownblock) &&
                   4736:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4737:         }
1.474     raeburn  4738:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4739:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4740:             if ($sec ne 'none') {
1.482     raeburn  4741:                 $checkrole .= '/'.$sec;
1.474     raeburn  4742:             }
1.490     raeburn  4743:             if ($otheruser) {
                   4744:                 # Resource belongs to user other than current user.
                   4745:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4746:                 my (%allroles,%userroles);
                   4747:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4748:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4749:                         my ($trole,$tdom,$tnum,$tsec);
                   4750:                         if ($entry =~ /^cr/) {
                   4751:                             ($trole,$tdom,$tnum,$tsec) = 
                   4752:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4753:                         } else {
                   4754:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4755:                         }
                   4756:                         my ($spec,$area,$trest);
                   4757:                         $area = '/'.$tdom.'/'.$tnum;
                   4758:                         $trest = $tnum;
                   4759:                         if ($tsec ne '') {
                   4760:                             $area .= '/'.$tsec;
                   4761:                             $trest .= '/'.$tsec;
                   4762:                         }
                   4763:                         $spec = $trole.'.'.$area;
                   4764:                         if ($trole =~ /^cr/) {
                   4765:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4766:                                                               $tdom,$spec,$trest,$area);
                   4767:                         } else {
                   4768:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4769:                                                                 $tdom,$spec,$trest,$area);
                   4770:                         }
                   4771:                     }
                   4772:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
                   4773:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4774:                         if ($1) {
                   4775:                             $no_userblock = 1;
                   4776:                             last;
                   4777:                         }
1.486     raeburn  4778:                     }
                   4779:                 }
1.490     raeburn  4780:             } else {
                   4781:                 # Resource belongs to current user
                   4782:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4783:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4784:                     $no_ownblock = 1;
                   4785:                     last;
                   4786:                 }
1.474     raeburn  4787:             }
                   4788:         }
                   4789:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4790:         next if (($no_ownblock) &&
1.491     albertel 4791:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4792:         next if ($no_userblock);
1.474     raeburn  4793: 
1.866     kalberla 4794:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  4795:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4796:         
1.1062    raeburn  4797:         my ($start,$end,$trigger) = 
                   4798:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4799:         if (($start != 0) && 
                   4800:             (($startblock == 0) || ($startblock > $start))) {
                   4801:             $startblock = $start;
1.1062    raeburn  4802:             if ($trigger ne '') {
                   4803:                 $triggerblock = $trigger;
                   4804:             }
1.502     raeburn  4805:         }
                   4806:         if (($end != 0)  &&
                   4807:             (($endblock == 0) || ($endblock < $end))) {
                   4808:             $endblock = $end;
1.1062    raeburn  4809:             if ($trigger ne '') {
                   4810:                 $triggerblock = $trigger;
                   4811:             }
1.502     raeburn  4812:         }
1.490     raeburn  4813:     }
1.1062    raeburn  4814:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4815: }
                   4816: 
                   4817: sub get_blocks {
1.1062    raeburn  4818:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4819:     my $startblock = 0;
                   4820:     my $endblock = 0;
1.1062    raeburn  4821:     my $triggerblock = '';
1.490     raeburn  4822:     my $course = $cdom.'_'.$cnum;
                   4823:     $setters->{$course} = {};
                   4824:     $setters->{$course}{'staff'} = [];
                   4825:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4826:     $setters->{$course}{'triggers'} = [];
                   4827:     my (@blockers,%triggered);
                   4828:     my $now = time;
                   4829:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4830:     if ($activity eq 'docs') {
                   4831:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4832:         foreach my $block (@blockers) {
                   4833:             if ($block =~ /^firstaccess____(.+)$/) {
                   4834:                 my $item = $1;
                   4835:                 my $type = 'map';
                   4836:                 my $timersymb = $item;
                   4837:                 if ($item eq 'course') {
                   4838:                     $type = 'course';
                   4839:                 } elsif ($item =~ /___\d+___/) {
                   4840:                     $type = 'resource';
                   4841:                 } else {
                   4842:                     $timersymb = &Apache::lonnet::symbread($item);
                   4843:                 }
                   4844:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4845:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4846:                 $triggered{$block} = {
                   4847:                                        start => $start,
                   4848:                                        end   => $end,
                   4849:                                        type  => $type,
                   4850:                                      };
                   4851:             }
                   4852:         }
                   4853:     } else {
                   4854:         foreach my $block (keys(%commblocks)) {
                   4855:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4856:                 my ($start,$end) = ($1,$2);
                   4857:                 if ($start <= time && $end >= time) {
                   4858:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4859:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4860:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4861:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4862:                                     push(@blockers,$block);
                   4863:                                 }
                   4864:                             }
                   4865:                         }
                   4866:                     }
                   4867:                 }
                   4868:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4869:                 my $item = $1;
                   4870:                 my $timersymb = $item; 
                   4871:                 my $type = 'map';
                   4872:                 if ($item eq 'course') {
                   4873:                     $type = 'course';
                   4874:                 } elsif ($item =~ /___\d+___/) {
                   4875:                     $type = 'resource';
                   4876:                 } else {
                   4877:                     $timersymb = &Apache::lonnet::symbread($item);
                   4878:                 }
                   4879:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4880:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4881:                 if ($start && $end) {
                   4882:                     if (($start <= time) && ($end >= time)) {
                   4883:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4884:                             push(@blockers,$block);
                   4885:                             $triggered{$block} = {
                   4886:                                                    start => $start,
                   4887:                                                    end   => $end,
                   4888:                                                    type  => $type,
                   4889:                                                  };
                   4890:                         }
                   4891:                     }
1.490     raeburn  4892:                 }
1.1062    raeburn  4893:             }
                   4894:         }
                   4895:     }
                   4896:     foreach my $blocker (@blockers) {
                   4897:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4898:             &parse_block_record($commblocks{$blocker});
                   4899:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4900:         my ($start,$end,$triggertype);
                   4901:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4902:             ($start,$end) = ($1,$2);
                   4903:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4904:             $start = $triggered{$blocker}{'start'};
                   4905:             $end = $triggered{$blocker}{'end'};
                   4906:             $triggertype = $triggered{$blocker}{'type'};
                   4907:         }
                   4908:         if ($start) {
                   4909:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4910:             if ($triggertype) {
                   4911:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4912:             } else {
                   4913:                 push(@{$$setters{$course}{'triggers'}},0);
                   4914:             }
                   4915:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4916:                 $startblock = $start;
                   4917:                 if ($triggertype) {
                   4918:                     $triggerblock = $blocker;
1.474     raeburn  4919:                 }
                   4920:             }
1.1062    raeburn  4921:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4922:                $endblock = $end;
                   4923:                if ($triggertype) {
                   4924:                    $triggerblock = $blocker;
                   4925:                }
                   4926:             }
1.474     raeburn  4927:         }
                   4928:     }
1.1062    raeburn  4929:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4930: }
                   4931: 
                   4932: sub parse_block_record {
                   4933:     my ($record) = @_;
                   4934:     my ($setuname,$setudom,$title,$blocks);
                   4935:     if (ref($record) eq 'HASH') {
                   4936:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4937:         $title = &unescape($record->{'event'});
                   4938:         $blocks = $record->{'blocks'};
                   4939:     } else {
                   4940:         my @data = split(/:/,$record,3);
                   4941:         if (scalar(@data) eq 2) {
                   4942:             $title = $data[1];
                   4943:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4944:         } else {
                   4945:             ($setuname,$setudom,$title) = @data;
                   4946:         }
                   4947:         $blocks = { 'com' => 'on' };
                   4948:     }
                   4949:     return ($setuname,$setudom,$title,$blocks);
                   4950: }
                   4951: 
1.854     kalberla 4952: sub blocking_status {
1.1189    raeburn  4953:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  4954:     my %setters;
1.890     droeschl 4955: 
1.1061    raeburn  4956: # check for active blocking
1.1062    raeburn  4957:     my ($startblock,$endblock,$triggerblock) = 
1.1189    raeburn  4958:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  4959:     my $blocked = 0;
                   4960:     if ($startblock && $endblock) {
                   4961:         $blocked = 1;
                   4962:     }
1.890     droeschl 4963: 
1.1061    raeburn  4964: # caller just wants to know whether a block is active
                   4965:     if (!wantarray) { return $blocked; }
                   4966: 
                   4967: # build a link to a popup window containing the details
                   4968:     my $querystring  = "?activity=$activity";
                   4969: # $uname and $udom decide whose portfolio the user is trying to look at
1.1232    raeburn  4970:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   4971:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   4972:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  4973:     } elsif ($activity eq 'docs') {
                   4974:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4975:     }
1.1061    raeburn  4976: 
                   4977:     my $output .= <<'END_MYBLOCK';
                   4978: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4979:     var options = "width=" + w + ",height=" + h + ",";
                   4980:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4981:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   4982:     var newWin = window.open(url, wdwName, options);
                   4983:     newWin.focus();
                   4984: }
1.890     droeschl 4985: END_MYBLOCK
1.854     kalberla 4986: 
1.1061    raeburn  4987:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 4988:   
1.1061    raeburn  4989:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  4990:     my $text = &mt('Communication Blocked');
1.1217    raeburn  4991:     my $class = 'LC_comblock';
1.1062    raeburn  4992:     if ($activity eq 'docs') {
                   4993:         $text = &mt('Content Access Blocked');
1.1217    raeburn  4994:         $class = '';
1.1063    raeburn  4995:     } elsif ($activity eq 'printout') {
                   4996:         $text = &mt('Printing Blocked');
1.1232    raeburn  4997:     } elsif ($activity eq 'passwd') {
                   4998:         $text = &mt('Password Changing Blocked');
1.1062    raeburn  4999:     }
1.1061    raeburn  5000:     $output .= <<"END_BLOCK";
1.1217    raeburn  5001: <div class='$class'>
1.869     kalberla 5002:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5003:   title='$text'>
                   5004:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5005:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5006:   title='$text'>$text</a>
1.867     kalberla 5007: </div>
                   5008: 
                   5009: END_BLOCK
1.474     raeburn  5010: 
1.1061    raeburn  5011:     return ($blocked, $output);
1.854     kalberla 5012: }
1.490     raeburn  5013: 
1.60      matthew  5014: ###############################################
                   5015: 
1.682     raeburn  5016: sub check_ip_acc {
1.1201    raeburn  5017:     my ($acc,$clientip)=@_;
1.682     raeburn  5018:     &Apache::lonxml::debug("acc is $acc");
                   5019:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5020:         return 1;
                   5021:     }
1.1219    raeburn  5022:     my $allowed;
1.1201    raeburn  5023:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
1.682     raeburn  5024: 
                   5025:     my $name;
1.1219    raeburn  5026:     my %access = (
                   5027:                      allowfrom => 1,
                   5028:                      denyfrom  => 0,
                   5029:                  );
                   5030:     my @allows;
                   5031:     my @denies;
                   5032:     foreach my $item (split(',',$acc)) {
                   5033:         $item =~ s/^\s*//;
                   5034:         $item =~ s/\s*$//;
                   5035:         my $pattern;
                   5036:         if ($item =~ /^\!(.+)$/) {
                   5037:             push(@denies,$1);
                   5038:         } else {
                   5039:             push(@allows,$item);
                   5040:         }
                   5041:    }
                   5042:    my $numdenies = scalar(@denies);
                   5043:    my $numallows = scalar(@allows);
                   5044:    my $count = 0;
                   5045:    foreach my $pattern (@denies,@allows) {
                   5046:         $count ++; 
                   5047:         my $acctype = 'allowfrom';
                   5048:         if ($count <= $numdenies) {
                   5049:             $acctype = 'denyfrom';
                   5050:         }
1.682     raeburn  5051:         if ($pattern =~ /\*$/) {
                   5052:             #35.8.*
                   5053:             $pattern=~s/\*//;
1.1219    raeburn  5054:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5055:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5056:             #35.8.3.[34-56]
                   5057:             my $low=$2;
                   5058:             my $high=$3;
                   5059:             $pattern=$1;
                   5060:             if ($ip =~ /^\Q$pattern\E/) {
                   5061:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  5062:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5063:             }
                   5064:         } elsif ($pattern =~ /^\*/) {
                   5065:             #*.msu.edu
                   5066:             $pattern=~s/\*//;
                   5067:             if (!defined($name)) {
                   5068:                 use Socket;
                   5069:                 my $netaddr=inet_aton($ip);
                   5070:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5071:             }
1.1219    raeburn  5072:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5073:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5074:             #127.0.0.1
1.1219    raeburn  5075:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5076:         } else {
                   5077:             #some.name.com
                   5078:             if (!defined($name)) {
                   5079:                 use Socket;
                   5080:                 my $netaddr=inet_aton($ip);
                   5081:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5082:             }
1.1219    raeburn  5083:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5084:         }
                   5085:         if ($allowed =~ /^(0|1)$/) { last; }
                   5086:     }
                   5087:     if ($allowed eq '') {
                   5088:         if ($numdenies && !$numallows) {
                   5089:             $allowed = 1;
                   5090:         } else {
                   5091:             $allowed = 0;
1.682     raeburn  5092:         }
                   5093:     }
                   5094:     return $allowed;
                   5095: }
                   5096: 
                   5097: ###############################################
                   5098: 
1.60      matthew  5099: =pod
                   5100: 
1.112     bowersj2 5101: =head1 Domain Template Functions
                   5102: 
                   5103: =over 4
                   5104: 
                   5105: =item * &determinedomain()
1.60      matthew  5106: 
                   5107: Inputs: $domain (usually will be undef)
                   5108: 
1.63      www      5109: Returns: Determines which domain should be used for designs
1.60      matthew  5110: 
                   5111: =cut
1.54      www      5112: 
1.60      matthew  5113: ###############################################
1.63      www      5114: sub determinedomain {
                   5115:     my $domain=shift;
1.531     albertel 5116:     if (! $domain) {
1.60      matthew  5117:         # Determine domain if we have not been given one
1.893     raeburn  5118:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5119:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5120:         if ($env{'request.role.domain'}) { 
                   5121:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5122:         }
                   5123:     }
1.63      www      5124:     return $domain;
                   5125: }
                   5126: ###############################################
1.517     raeburn  5127: 
1.518     albertel 5128: sub devalidate_domconfig_cache {
                   5129:     my ($udom)=@_;
                   5130:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5131: }
                   5132: 
                   5133: # ---------------------- Get domain configuration for a domain
                   5134: sub get_domainconf {
                   5135:     my ($udom) = @_;
                   5136:     my $cachetime=1800;
                   5137:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5138:     if (defined($cached)) { return %{$result}; }
                   5139: 
                   5140:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5141: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5142:     my (%designhash,%legacy);
1.518     albertel 5143:     if (keys(%domconfig) > 0) {
                   5144:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5145:             if (keys(%{$domconfig{'login'}})) {
                   5146:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5147:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5148:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5149:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5150:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5151:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5152:                                         if ($key eq 'loginvia') {
                   5153:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5154:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5155:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5156:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5157: 
                   5158:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5159:                                                 } else {
                   5160:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5161:                                                 }
1.948     raeburn  5162:                                             }
1.1208    raeburn  5163:                                         } elsif ($key eq 'headtag') {
                   5164:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5165:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5166:                                             }
1.946     raeburn  5167:                                         }
1.1208    raeburn  5168:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5169:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5170:                                         }
1.946     raeburn  5171:                                     }
                   5172:                                 }
                   5173:                             }
                   5174:                         } else {
                   5175:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5176:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5177:                                     $domconfig{'login'}{$key}{$img};
                   5178:                             }
1.699     raeburn  5179:                         }
                   5180:                     } else {
                   5181:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5182:                     }
1.632     raeburn  5183:                 }
                   5184:             } else {
                   5185:                 $legacy{'login'} = 1;
1.518     albertel 5186:             }
1.632     raeburn  5187:         } else {
                   5188:             $legacy{'login'} = 1;
1.518     albertel 5189:         }
                   5190:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5191:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5192:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5193:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5194:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5195:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5196:                         }
1.518     albertel 5197:                     }
                   5198:                 }
1.632     raeburn  5199:             } else {
                   5200:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5201:             }
1.632     raeburn  5202:         } else {
                   5203:             $legacy{'rolecolors'} = 1;
1.518     albertel 5204:         }
1.948     raeburn  5205:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5206:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5207:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5208:             }
                   5209:         }
1.632     raeburn  5210:         if (keys(%legacy) > 0) {
                   5211:             my %legacyhash = &get_legacy_domconf($udom);
                   5212:             foreach my $item (keys(%legacyhash)) {
                   5213:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5214:                     if ($legacy{'login'}) { 
                   5215:                         $designhash{$item} = $legacyhash{$item};
                   5216:                     }
                   5217:                 } else {
                   5218:                     if ($legacy{'rolecolors'}) {
                   5219:                         $designhash{$item} = $legacyhash{$item};
                   5220:                     }
1.518     albertel 5221:                 }
                   5222:             }
                   5223:         }
1.632     raeburn  5224:     } else {
                   5225:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5226:     }
                   5227:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5228: 				  $cachetime);
                   5229:     return %designhash;
                   5230: }
                   5231: 
1.632     raeburn  5232: sub get_legacy_domconf {
                   5233:     my ($udom) = @_;
                   5234:     my %legacyhash;
                   5235:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5236:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5237:     if (-e $designfile) {
                   5238:         if ( open (my $fh,"<$designfile") ) {
                   5239:             while (my $line = <$fh>) {
                   5240:                 next if ($line =~ /^\#/);
                   5241:                 chomp($line);
                   5242:                 my ($key,$val)=(split(/\=/,$line));
                   5243:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5244:             }
                   5245:             close($fh);
                   5246:         }
                   5247:     }
1.1026    raeburn  5248:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5249:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5250:     }
                   5251:     return %legacyhash;
                   5252: }
                   5253: 
1.63      www      5254: =pod
                   5255: 
1.112     bowersj2 5256: =item * &domainlogo()
1.63      www      5257: 
                   5258: Inputs: $domain (usually will be undef)
                   5259: 
                   5260: Returns: A link to a domain logo, if the domain logo exists.
                   5261: If the domain logo does not exist, a description of the domain.
                   5262: 
                   5263: =cut
1.112     bowersj2 5264: 
1.63      www      5265: ###############################################
                   5266: sub domainlogo {
1.517     raeburn  5267:     my $domain = &determinedomain(shift);
1.518     albertel 5268:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5269:     # See if there is a logo
                   5270:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5271:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5272:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5273: 	    if ($imgsrc =~ m{^/res/}) {
                   5274: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5275: 		&Apache::lonnet::repcopy($local_name);
                   5276: 	    }
                   5277: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5278:         } 
                   5279:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5280:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5281:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5282:     } else {
1.60      matthew  5283:         return '';
1.59      www      5284:     }
                   5285: }
1.63      www      5286: ##############################################
                   5287: 
                   5288: =pod
                   5289: 
1.112     bowersj2 5290: =item * &designparm()
1.63      www      5291: 
                   5292: Inputs: $which parameter; $domain (usually will be undef)
                   5293: 
                   5294: Returns: value of designparamter $which
                   5295: 
                   5296: =cut
1.112     bowersj2 5297: 
1.397     albertel 5298: 
1.400     albertel 5299: ##############################################
1.397     albertel 5300: sub designparm {
                   5301:     my ($which,$domain)=@_;
                   5302:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5303:         return $env{'environment.color.'.$which};
1.96      www      5304:     }
1.63      www      5305:     $domain=&determinedomain($domain);
1.1016    raeburn  5306:     my %domdesign;
                   5307:     unless ($domain eq 'public') {
                   5308:         %domdesign = &get_domainconf($domain);
                   5309:     }
1.520     raeburn  5310:     my $output;
1.517     raeburn  5311:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5312:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5313:     } else {
1.520     raeburn  5314:         $output = $defaultdesign{$which};
                   5315:     }
                   5316:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5317:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5318:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5319:             if ($output =~ m{^/res/}) {
                   5320:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5321:                 &Apache::lonnet::repcopy($local_name);
                   5322:             }
1.520     raeburn  5323:             $output = &lonhttpdurl($output);
                   5324:         }
1.63      www      5325:     }
1.520     raeburn  5326:     return $output;
1.63      www      5327: }
1.59      www      5328: 
1.822     bisitz   5329: ##############################################
                   5330: =pod
                   5331: 
1.832     bisitz   5332: =item * &authorspace()
                   5333: 
1.1028    raeburn  5334: Inputs: $url (usually will be undef).
1.832     bisitz   5335: 
1.1132    raeburn  5336: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5337:          directory being viewed (or for which action is being taken). 
                   5338:          If $url is provided, and begins /priv/<domain>/<uname>
                   5339:          the path will be that portion of the $context argument.
                   5340:          Otherwise the path will be for the author space of the current
                   5341:          user when the current role is author, or for that of the 
                   5342:          co-author/assistant co-author space when the current role 
                   5343:          is co-author or assistant co-author.
1.832     bisitz   5344: 
                   5345: =cut
                   5346: 
                   5347: sub authorspace {
1.1028    raeburn  5348:     my ($url) = @_;
                   5349:     if ($url ne '') {
                   5350:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5351:            return $1;
                   5352:         }
                   5353:     }
1.832     bisitz   5354:     my $caname = '';
1.1024    www      5355:     my $cadom = '';
1.1028    raeburn  5356:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5357:         ($cadom,$caname) =
1.832     bisitz   5358:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5359:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5360:         $caname = $env{'user.name'};
1.1024    www      5361:         $cadom = $env{'user.domain'};
1.832     bisitz   5362:     }
1.1028    raeburn  5363:     if (($caname ne '') && ($cadom ne '')) {
                   5364:         return "/priv/$cadom/$caname/";
                   5365:     }
                   5366:     return;
1.832     bisitz   5367: }
                   5368: 
                   5369: ##############################################
                   5370: =pod
                   5371: 
1.822     bisitz   5372: =item * &head_subbox()
                   5373: 
                   5374: Inputs: $content (contains HTML code with page functions, etc.)
                   5375: 
                   5376: Returns: HTML div with $content
                   5377:          To be included in page header
                   5378: 
                   5379: =cut
                   5380: 
                   5381: sub head_subbox {
                   5382:     my ($content)=@_;
                   5383:     my $output =
1.993     raeburn  5384:         '<div class="LC_head_subbox">'
1.822     bisitz   5385:        .$content
                   5386:        .'</div>'
                   5387: }
                   5388: 
                   5389: ##############################################
                   5390: =pod
                   5391: 
                   5392: =item * &CSTR_pageheader()
                   5393: 
1.1026    raeburn  5394: Input: (optional) filename from which breadcrumb trail is built.
                   5395:        In most cases no input as needed, as $env{'request.filename'}
                   5396:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5397: 
                   5398: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  5399:          To be included on Authoring Space pages
1.822     bisitz   5400: 
                   5401: =cut
                   5402: 
                   5403: sub CSTR_pageheader {
1.1026    raeburn  5404:     my ($trailfile) = @_;
                   5405:     if ($trailfile eq '') {
                   5406:         $trailfile = $env{'request.filename'};
                   5407:     }
                   5408: 
                   5409: # this is for resources; directories have customtitle, and crumbs
                   5410: # and select recent are created in lonpubdir.pm
                   5411: 
                   5412:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5413:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  5414:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5415:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5416:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5417: 
                   5418:     my $parentpath = '';
                   5419:     my $lastitem = '';
                   5420:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5421:         $parentpath = $1;
                   5422:         $lastitem = $2;
                   5423:     } else {
                   5424:         $lastitem = $thisdisfn;
                   5425:     }
1.921     bisitz   5426: 
                   5427:     my $output =
1.822     bisitz   5428:          '<div>'
                   5429:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1132    raeburn  5430:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5431:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5432:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5433:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5434: 
                   5435:     if ($lastitem) {
                   5436:         $output .=
                   5437:              '<span class="LC_filename">'
                   5438:             .$lastitem
                   5439:             .'</span>';
                   5440:     }
                   5441:     $output .=
                   5442:          '<br />'
1.822     bisitz   5443:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5444:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5445:         .'</form>'
                   5446:         .&Apache::lonmenu::constspaceform()
                   5447:         .'</div>';
1.921     bisitz   5448: 
                   5449:     return $output;
1.822     bisitz   5450: }
                   5451: 
1.60      matthew  5452: ###############################################
                   5453: ###############################################
                   5454: 
                   5455: =pod
                   5456: 
1.112     bowersj2 5457: =back
                   5458: 
1.549     albertel 5459: =head1 HTML Helpers
1.112     bowersj2 5460: 
                   5461: =over 4
                   5462: 
                   5463: =item * &bodytag()
1.60      matthew  5464: 
                   5465: Returns a uniform header for LON-CAPA web pages.
                   5466: 
                   5467: Inputs: 
                   5468: 
1.112     bowersj2 5469: =over 4
                   5470: 
                   5471: =item * $title, A title to be displayed on the page.
                   5472: 
                   5473: =item * $function, the current role (can be undef).
                   5474: 
                   5475: =item * $addentries, extra parameters for the <body> tag.
                   5476: 
                   5477: =item * $bodyonly, if defined, only return the <body> tag.
                   5478: 
                   5479: =item * $domain, if defined, force a given domain.
                   5480: 
                   5481: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5482:             text interface only)
1.60      matthew  5483: 
1.814     bisitz   5484: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5485:                      navigational links
1.317     albertel 5486: 
1.338     albertel 5487: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5488: 
1.460     albertel 5489: =item * $args, optional argument valid values are
                   5490:             no_auto_mt_title -> prevents &mt()ing the title arg
                   5491: 
1.1096    raeburn  5492: =item * $advtoolsref, optional argument, ref to an array containing
                   5493:             inlineremote items to be added in "Functions" menu below
                   5494:             breadcrumbs.
                   5495: 
1.112     bowersj2 5496: =back
                   5497: 
1.60      matthew  5498: Returns: A uniform header for LON-CAPA web pages.  
                   5499: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5500: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5501: other decorations will be returned.
                   5502: 
                   5503: =cut
                   5504: 
1.54      www      5505: sub bodytag {
1.831     bisitz   5506:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1096    raeburn  5507:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
1.339     albertel 5508: 
1.954     raeburn  5509:     my $public;
                   5510:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5511:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5512:         $public = 1;
                   5513:     }
1.460     albertel 5514:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  5515:     my $httphost = $args->{'use_absolute'};
1.339     albertel 5516: 
1.183     matthew  5517:     $function = &get_users_function() if (!$function);
1.339     albertel 5518:     my $img =    &designparm($function.'.img',$domain);
                   5519:     my $font =   &designparm($function.'.font',$domain);
                   5520:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5521: 
1.803     bisitz   5522:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5523: 		   'bgcolor' => $pgbg,
1.339     albertel 5524: 		   'text'    => $font,
                   5525:                    'alink'   => &designparm($function.'.alink',$domain),
                   5526: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5527: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5528:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5529: 
1.63      www      5530:  # role and realm
1.1178    raeburn  5531:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5532:     if ($realm) {
                   5533:         $realm = '/'.$realm;
                   5534:     }
1.378     raeburn  5535:     if ($role  eq 'ca') {
1.479     albertel 5536:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5537:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5538:     } 
1.55      www      5539: # realm
1.258     albertel 5540:     if ($env{'request.course.id'}) {
1.378     raeburn  5541:         if ($env{'request.role'} !~ /^cr/) {
                   5542:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   5543:         }
1.898     raeburn  5544:         if ($env{'request.course.sec'}) {
                   5545:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5546:         }   
1.359     albertel 5547: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5548:     } else {
                   5549:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5550:     }
1.433     albertel 5551: 
1.359     albertel 5552:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5553: 
1.438     albertel 5554:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5555: 
1.101     www      5556: # construct main body tag
1.359     albertel 5557:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  5558: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5559: 
1.1131    raeburn  5560:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5561: 
1.1130    raeburn  5562:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5563:         return $bodytag;
1.1130    raeburn  5564:     }
1.359     albertel 5565: 
1.954     raeburn  5566:     if ($public) {
1.433     albertel 5567: 	undef($role);
                   5568:     }
1.359     albertel 5569:     
1.762     bisitz   5570:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5571:     #
                   5572:     # Extra info if you are the DC
                   5573:     my $dc_info = '';
                   5574:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5575:                         $env{'course.'.$env{'request.course.id'}.
                   5576:                                  '.domain'}.'/'})) {
                   5577:         my $cid = $env{'request.course.id'};
1.917     raeburn  5578:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5579:         $dc_info =~ s/\s+$//;
1.359     albertel 5580:     }
                   5581: 
1.1237    raeburn  5582:     my $crstype;
                   5583:     if ($env{'request.course.id'}) {
                   5584:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
                   5585:     } elsif ($args->{'crstype'}) {
                   5586:         $crstype = $args->{'crstype'};
                   5587:     }
                   5588:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   5589:         undef($role);
                   5590:     } else {
                   5591:         $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
                   5592:     }
1.853     droeschl 5593: 
1.903     droeschl 5594:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5595: 
                   5596:         #    if ($env{'request.state'} eq 'construct') {
                   5597:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5598:         #    }
                   5599: 
1.1130    raeburn  5600:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  5601:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5602: 
1.1237    raeburn  5603:         my ($left,$right) = Apache::lonmenu::primary_menu($crstype);
1.359     albertel 5604: 
1.916     droeschl 5605:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.917     raeburn  5606:              if ($dc_info) {
                   5607:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   5608:              }
1.1130    raeburn  5609:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.916     droeschl 5610:                 <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5611:             return $bodytag;
                   5612:         }
1.894     droeschl 5613: 
1.927     raeburn  5614:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1130    raeburn  5615:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5616:         }
1.916     droeschl 5617: 
1.1130    raeburn  5618:         $bodytag .= $right;
1.852     droeschl 5619: 
1.917     raeburn  5620:         if ($dc_info) {
                   5621:             $dc_info = &dc_courseid_toggle($dc_info);
                   5622:         }
                   5623:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5624: 
1.1169    raeburn  5625:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  5626:         if ($args->{'no_secondary_menu'}) {
                   5627:             return $bodytag;
                   5628:         }
1.1169    raeburn  5629:         #don't show menus for public users
1.954     raeburn  5630:         if (!$public){
1.1154    raeburn  5631:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5632:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5633:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5634:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5635:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5636:                                 $args->{'bread_crumbs'});
1.1096    raeburn  5637:             } elsif ($forcereg) {
                   5638:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
                   5639:                                                             $args->{'group'});
                   5640:             } else {
                   5641:                 $bodytag .= 
                   5642:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5643:                                                         $forcereg,$args->{'group'},
                   5644:                                                         $args->{'bread_crumbs'},
                   5645:                                                         $advtoolsref);
1.920     raeburn  5646:             }
1.903     droeschl 5647:         }else{
                   5648:             # this is to seperate menu from content when there's no secondary
                   5649:             # menu. Especially needed for public accessible ressources.
                   5650:             $bodytag .= '<hr style="clear:both" />';
                   5651:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5652:         }
1.903     droeschl 5653: 
1.235     raeburn  5654:         return $bodytag;
1.182     matthew  5655: }
                   5656: 
1.917     raeburn  5657: sub dc_courseid_toggle {
                   5658:     my ($dc_info) = @_;
1.980     raeburn  5659:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5660:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5661:            &mt('(More ...)').'</a></span>'.
                   5662:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5663: }
                   5664: 
1.330     albertel 5665: sub make_attr_string {
                   5666:     my ($register,$attr_ref) = @_;
                   5667: 
                   5668:     if ($attr_ref && !ref($attr_ref)) {
                   5669: 	die("addentries Must be a hash ref ".
                   5670: 	    join(':',caller(1))." ".
                   5671: 	    join(':',caller(0))." ");
                   5672:     }
                   5673: 
                   5674:     if ($register) {
1.339     albertel 5675: 	my ($on_load,$on_unload);
                   5676: 	foreach my $key (keys(%{$attr_ref})) {
                   5677: 	    if      (lc($key) eq 'onload') {
                   5678: 		$on_load.=$attr_ref->{$key}.';';
                   5679: 		delete($attr_ref->{$key});
                   5680: 
                   5681: 	    } elsif (lc($key) eq 'onunload') {
                   5682: 		$on_unload.=$attr_ref->{$key}.';';
                   5683: 		delete($attr_ref->{$key});
                   5684: 	    }
                   5685: 	}
1.953     droeschl 5686: 	$attr_ref->{'onload'}  = $on_load;
                   5687: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 5688:     }
1.339     albertel 5689: 
1.330     albertel 5690:     my $attr_string;
1.1159    raeburn  5691:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5692: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5693:     }
                   5694:     return $attr_string;
                   5695: }
                   5696: 
                   5697: 
1.182     matthew  5698: ###############################################
1.251     albertel 5699: ###############################################
                   5700: 
                   5701: =pod
                   5702: 
                   5703: =item * &endbodytag()
                   5704: 
                   5705: Returns a uniform footer for LON-CAPA web pages.
                   5706: 
1.635     raeburn  5707: Inputs: 1 - optional reference to an args hash
                   5708: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5709: a 'Continue' link is not displayed if the page contains an
                   5710: internal redirect in the <head></head> section,
                   5711: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5712: 
                   5713: =cut
                   5714: 
                   5715: sub endbodytag {
1.635     raeburn  5716:     my ($args) = @_;
1.1080    raeburn  5717:     my $endbodytag;
                   5718:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5719:         $endbodytag='</body>';
                   5720:     }
1.315     albertel 5721:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5722:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5723: 	    $endbodytag=
                   5724: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5725: 	        &mt('Continue').'</a>'.
                   5726: 	        $endbodytag;
                   5727:         }
1.315     albertel 5728:     }
1.251     albertel 5729:     return $endbodytag;
                   5730: }
                   5731: 
1.352     albertel 5732: =pod
                   5733: 
                   5734: =item * &standard_css()
                   5735: 
                   5736: Returns a style sheet
                   5737: 
                   5738: Inputs: (all optional)
                   5739:             domain         -> force to color decorate a page for a specific
                   5740:                                domain
                   5741:             function       -> force usage of a specific rolish color scheme
                   5742:             bgcolor        -> override the default page bgcolor
                   5743: 
                   5744: =cut
                   5745: 
1.343     albertel 5746: sub standard_css {
1.345     albertel 5747:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5748:     $function  = &get_users_function() if (!$function);
                   5749:     my $img    = &designparm($function.'.img',   $domain);
                   5750:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5751:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5752:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5753: #second colour for later usage
1.345     albertel 5754:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5755:     my $pgbg_or_bgcolor =
                   5756: 	         $bgcolor ||
1.352     albertel 5757: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5758:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5759:     my $alink  = &designparm($function.'.alink', $domain);
                   5760:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5761:     my $link   = &designparm($function.'.link',  $domain);
                   5762: 
1.602     albertel 5763:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5764:     my $mono                 = 'monospace';
1.850     bisitz   5765:     my $data_table_head      = $sidebg;
                   5766:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5767:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5768:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5769:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5770:     my $mail_new             = '#FFBB77';
                   5771:     my $mail_new_hover       = '#DD9955';
                   5772:     my $mail_read            = '#BBBB77';
                   5773:     my $mail_read_hover      = '#999944';
                   5774:     my $mail_replied         = '#AAAA88';
                   5775:     my $mail_replied_hover   = '#888855';
                   5776:     my $mail_other           = '#99BBBB';
                   5777:     my $mail_other_hover     = '#669999';
1.391     albertel 5778:     my $table_header         = '#DDDDDD';
1.489     raeburn  5779:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5780:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5781:     my $button_hover         = '#BF2317';
1.392     albertel 5782: 
1.608     albertel 5783:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5784:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5785:                                              : '0 3px 0 4px';
1.448     albertel 5786: 
1.523     albertel 5787: 
1.343     albertel 5788:     return <<END;
1.947     droeschl 5789: 
                   5790: /* needed for iframe to allow 100% height in FF */
                   5791: body, html { 
                   5792:     margin: 0;
                   5793:     padding: 0 0.5%;
                   5794:     height: 99%; /* to avoid scrollbars */
                   5795: }
                   5796: 
1.795     www      5797: body {
1.911     bisitz   5798:   font-family: $sans;
                   5799:   line-height:130%;
                   5800:   font-size:0.83em;
                   5801:   color:$font;
1.795     www      5802: }
                   5803: 
1.959     onken    5804: a:focus,
                   5805: a:focus img {
1.795     www      5806:   color: red;
                   5807: }
1.698     harmsja  5808: 
1.911     bisitz   5809: form, .inline {
                   5810:   display: inline;
1.795     www      5811: }
1.721     harmsja  5812: 
1.795     www      5813: .LC_right {
1.911     bisitz   5814:   text-align:right;
1.795     www      5815: }
                   5816: 
                   5817: .LC_middle {
1.911     bisitz   5818:   vertical-align:middle;
1.795     www      5819: }
1.721     harmsja  5820: 
1.1130    raeburn  5821: .LC_floatleft {
                   5822:   float: left;
                   5823: }
                   5824: 
                   5825: .LC_floatright {
                   5826:   float: right;
                   5827: }
                   5828: 
1.911     bisitz   5829: .LC_400Box {
                   5830:   width:400px;
                   5831: }
1.721     harmsja  5832: 
1.947     droeschl 5833: .LC_iframecontainer {
                   5834:     width: 98%;
                   5835:     margin: 0;
                   5836:     position: fixed;
                   5837:     top: 8.5em;
                   5838:     bottom: 0;
                   5839: }
                   5840: 
                   5841: .LC_iframecontainer iframe{
                   5842:     border: none;
                   5843:     width: 100%;
                   5844:     height: 100%;
                   5845: }
                   5846: 
1.778     bisitz   5847: .LC_filename {
                   5848:   font-family: $mono;
                   5849:   white-space:pre;
1.921     bisitz   5850:   font-size: 120%;
1.778     bisitz   5851: }
                   5852: 
                   5853: .LC_fileicon {
                   5854:   border: none;
                   5855:   height: 1.3em;
                   5856:   vertical-align: text-bottom;
                   5857:   margin-right: 0.3em;
                   5858:   text-decoration:none;
                   5859: }
                   5860: 
1.1008    www      5861: .LC_setting {
                   5862:   text-decoration:underline;
                   5863: }
                   5864: 
1.350     albertel 5865: .LC_error {
                   5866:   color: red;
                   5867: }
1.795     www      5868: 
1.1097    bisitz   5869: .LC_warning {
                   5870:   color: darkorange;
                   5871: }
                   5872: 
1.457     albertel 5873: .LC_diff_removed {
1.733     bisitz   5874:   color: red;
1.394     albertel 5875: }
1.532     albertel 5876: 
                   5877: .LC_info,
1.457     albertel 5878: .LC_success,
                   5879: .LC_diff_added {
1.350     albertel 5880:   color: green;
                   5881: }
1.795     www      5882: 
1.802     bisitz   5883: div.LC_confirm_box {
                   5884:   background-color: #FAFAFA;
                   5885:   border: 1px solid $lg_border_color;
                   5886:   margin-right: 0;
                   5887:   padding: 5px;
                   5888: }
                   5889: 
                   5890: div.LC_confirm_box .LC_error img,
                   5891: div.LC_confirm_box .LC_success img {
                   5892:   vertical-align: middle;
                   5893: }
                   5894: 
1.440     albertel 5895: .LC_icon {
1.771     droeschl 5896:   border: none;
1.790     droeschl 5897:   vertical-align: middle;
1.771     droeschl 5898: }
                   5899: 
1.543     albertel 5900: .LC_docs_spacer {
                   5901:   width: 25px;
                   5902:   height: 1px;
1.771     droeschl 5903:   border: none;
1.543     albertel 5904: }
1.346     albertel 5905: 
1.532     albertel 5906: .LC_internal_info {
1.735     bisitz   5907:   color: #999999;
1.532     albertel 5908: }
                   5909: 
1.794     www      5910: .LC_discussion {
1.1050    www      5911:   background: $data_table_dark;
1.911     bisitz   5912:   border: 1px solid black;
                   5913:   margin: 2px;
1.794     www      5914: }
                   5915: 
                   5916: .LC_disc_action_left {
1.1050    www      5917:   background: $sidebg;
1.911     bisitz   5918:   text-align: left;
1.1050    www      5919:   padding: 4px;
                   5920:   margin: 2px;
1.794     www      5921: }
                   5922: 
                   5923: .LC_disc_action_right {
1.1050    www      5924:   background: $sidebg;
1.911     bisitz   5925:   text-align: right;
1.1050    www      5926:   padding: 4px;
                   5927:   margin: 2px;
1.794     www      5928: }
                   5929: 
                   5930: .LC_disc_new_item {
1.911     bisitz   5931:   background: white;
                   5932:   border: 2px solid red;
1.1050    www      5933:   margin: 4px;
                   5934:   padding: 4px;
1.794     www      5935: }
                   5936: 
                   5937: .LC_disc_old_item {
1.911     bisitz   5938:   background: white;
1.1050    www      5939:   margin: 4px;
                   5940:   padding: 4px;
1.794     www      5941: }
                   5942: 
1.458     albertel 5943: table.LC_pastsubmission {
                   5944:   border: 1px solid black;
                   5945:   margin: 2px;
                   5946: }
                   5947: 
1.924     bisitz   5948: table#LC_menubuttons {
1.345     albertel 5949:   width: 100%;
                   5950:   background: $pgbg;
1.392     albertel 5951:   border: 2px;
1.402     albertel 5952:   border-collapse: separate;
1.803     bisitz   5953:   padding: 0;
1.345     albertel 5954: }
1.392     albertel 5955: 
1.801     tempelho 5956: table#LC_title_bar a {
                   5957:   color: $fontmenu;
                   5958: }
1.836     bisitz   5959: 
1.807     droeschl 5960: table#LC_title_bar {
1.819     tempelho 5961:   clear: both;
1.836     bisitz   5962:   display: none;
1.807     droeschl 5963: }
                   5964: 
1.795     www      5965: table#LC_title_bar,
1.933     droeschl 5966: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5967: table#LC_title_bar.LC_with_remote {
1.359     albertel 5968:   width: 100%;
1.392     albertel 5969:   border-color: $pgbg;
                   5970:   border-style: solid;
                   5971:   border-width: $border;
1.379     albertel 5972:   background: $pgbg;
1.801     tempelho 5973:   color: $fontmenu;
1.392     albertel 5974:   border-collapse: collapse;
1.803     bisitz   5975:   padding: 0;
1.819     tempelho 5976:   margin: 0;
1.359     albertel 5977: }
1.795     www      5978: 
1.933     droeschl 5979: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5980:     margin: 0;
                   5981:     padding: 0;
1.933     droeschl 5982:     position: relative;
                   5983:     list-style: none;
1.913     droeschl 5984: }
1.933     droeschl 5985: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5986:     display: inline;
                   5987: }
1.933     droeschl 5988: 
                   5989: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5990:     padding: 0;
1.933     droeschl 5991:     margin: 0;
                   5992:     float: left;
1.913     droeschl 5993: }
1.933     droeschl 5994: .LC_breadcrumb_tools_tools {
                   5995:     padding: 0;
                   5996:     margin: 0;
1.913     droeschl 5997:     float: right;
                   5998: }
                   5999: 
1.1240    raeburn  6000: .LC_placement_prog {
                   6001:     padding-right: 20px;
                   6002:     font-weight: bold;
                   6003:     font-size: 90%;
                   6004: }
                   6005: 
1.359     albertel 6006: table#LC_title_bar td {
                   6007:   background: $tabbg;
                   6008: }
1.795     www      6009: 
1.911     bisitz   6010: table#LC_menubuttons img {
1.803     bisitz   6011:   border: none;
1.346     albertel 6012: }
1.795     www      6013: 
1.842     droeschl 6014: .LC_breadcrumbs_component {
1.911     bisitz   6015:   float: right;
                   6016:   margin: 0 1em;
1.357     albertel 6017: }
1.842     droeschl 6018: .LC_breadcrumbs_component img {
1.911     bisitz   6019:   vertical-align: middle;
1.777     tempelho 6020: }
1.795     www      6021: 
1.383     albertel 6022: td.LC_table_cell_checkbox {
                   6023:   text-align: center;
                   6024: }
1.795     www      6025: 
                   6026: .LC_fontsize_small {
1.911     bisitz   6027:   font-size: 70%;
1.705     tempelho 6028: }
                   6029: 
1.844     bisitz   6030: #LC_breadcrumbs {
1.911     bisitz   6031:   clear:both;
                   6032:   background: $sidebg;
                   6033:   border-bottom: 1px solid $lg_border_color;
                   6034:   line-height: 2.5em;
1.933     droeschl 6035:   overflow: hidden;
1.911     bisitz   6036:   margin: 0;
                   6037:   padding: 0;
1.995     raeburn  6038:   text-align: left;
1.819     tempelho 6039: }
1.862     bisitz   6040: 
1.1098    bisitz   6041: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6042:   clear:both;
                   6043:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6044:   border: 1px solid $sidebg;
1.1098    bisitz   6045:   margin: 0 0 10px 0;
1.966     bisitz   6046:   padding: 3px;
1.995     raeburn  6047:   text-align: left;
1.822     bisitz   6048: }
                   6049: 
1.795     www      6050: .LC_fontsize_medium {
1.911     bisitz   6051:   font-size: 85%;
1.705     tempelho 6052: }
                   6053: 
1.795     www      6054: .LC_fontsize_large {
1.911     bisitz   6055:   font-size: 120%;
1.705     tempelho 6056: }
                   6057: 
1.346     albertel 6058: .LC_menubuttons_inline_text {
                   6059:   color: $font;
1.698     harmsja  6060:   font-size: 90%;
1.701     harmsja  6061:   padding-left:3px;
1.346     albertel 6062: }
                   6063: 
1.934     droeschl 6064: .LC_menubuttons_inline_text img{
                   6065:   vertical-align: middle;
                   6066: }
                   6067: 
1.1051    www      6068: li.LC_menubuttons_inline_text img {
1.951     onken    6069:   cursor:pointer;
1.1002    droeschl 6070:   text-decoration: none;
1.951     onken    6071: }
                   6072: 
1.526     www      6073: .LC_menubuttons_link {
                   6074:   text-decoration: none;
                   6075: }
1.795     www      6076: 
1.522     albertel 6077: .LC_menubuttons_category {
1.521     www      6078:   color: $font;
1.526     www      6079:   background: $pgbg;
1.521     www      6080:   font-size: larger;
                   6081:   font-weight: bold;
                   6082: }
                   6083: 
1.346     albertel 6084: td.LC_menubuttons_text {
1.911     bisitz   6085:   color: $font;
1.346     albertel 6086: }
1.706     harmsja  6087: 
1.346     albertel 6088: .LC_current_location {
                   6089:   background: $tabbg;
                   6090: }
1.795     www      6091: 
1.938     bisitz   6092: table.LC_data_table {
1.347     albertel 6093:   border: 1px solid #000000;
1.402     albertel 6094:   border-collapse: separate;
1.426     albertel 6095:   border-spacing: 1px;
1.610     albertel 6096:   background: $pgbg;
1.347     albertel 6097: }
1.795     www      6098: 
1.422     albertel 6099: .LC_data_table_dense {
                   6100:   font-size: small;
                   6101: }
1.795     www      6102: 
1.507     raeburn  6103: table.LC_nested_outer {
                   6104:   border: 1px solid #000000;
1.589     raeburn  6105:   border-collapse: collapse;
1.803     bisitz   6106:   border-spacing: 0;
1.507     raeburn  6107:   width: 100%;
                   6108: }
1.795     www      6109: 
1.879     raeburn  6110: table.LC_innerpickbox,
1.507     raeburn  6111: table.LC_nested {
1.803     bisitz   6112:   border: none;
1.589     raeburn  6113:   border-collapse: collapse;
1.803     bisitz   6114:   border-spacing: 0;
1.507     raeburn  6115:   width: 100%;
                   6116: }
1.795     www      6117: 
1.911     bisitz   6118: table.LC_data_table tr th,
                   6119: table.LC_calendar tr th,
1.879     raeburn  6120: table.LC_prior_tries tr th,
                   6121: table.LC_innerpickbox tr th {
1.349     albertel 6122:   font-weight: bold;
                   6123:   background-color: $data_table_head;
1.801     tempelho 6124:   color:$fontmenu;
1.701     harmsja  6125:   font-size:90%;
1.347     albertel 6126: }
1.795     www      6127: 
1.879     raeburn  6128: table.LC_innerpickbox tr th,
                   6129: table.LC_innerpickbox tr td {
                   6130:   vertical-align: top;
                   6131: }
                   6132: 
1.711     raeburn  6133: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6134:   background-color: #CCCCCC;
1.711     raeburn  6135:   font-weight: bold;
                   6136:   text-align: left;
                   6137: }
1.795     www      6138: 
1.912     bisitz   6139: table.LC_data_table tr.LC_odd_row > td {
                   6140:   background-color: $data_table_light;
                   6141:   padding: 2px;
                   6142:   vertical-align: top;
                   6143: }
                   6144: 
1.809     bisitz   6145: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6146:   background-color: $data_table_light;
1.912     bisitz   6147:   vertical-align: top;
                   6148: }
                   6149: 
                   6150: table.LC_data_table tr.LC_even_row > td {
                   6151:   background-color: $data_table_dark;
1.425     albertel 6152:   padding: 2px;
1.900     bisitz   6153:   vertical-align: top;
1.347     albertel 6154: }
1.795     www      6155: 
1.809     bisitz   6156: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6157:   background-color: $data_table_dark;
1.900     bisitz   6158:   vertical-align: top;
1.347     albertel 6159: }
1.795     www      6160: 
1.425     albertel 6161: table.LC_data_table tr.LC_data_table_highlight td {
                   6162:   background-color: $data_table_darker;
                   6163: }
1.795     www      6164: 
1.639     raeburn  6165: table.LC_data_table tr td.LC_leftcol_header {
                   6166:   background-color: $data_table_head;
                   6167:   font-weight: bold;
                   6168: }
1.795     www      6169: 
1.451     albertel 6170: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6171: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6172:   font-weight: bold;
                   6173:   font-style: italic;
                   6174:   text-align: center;
                   6175:   padding: 8px;
1.347     albertel 6176: }
1.795     www      6177: 
1.1114    raeburn  6178: table.LC_data_table tr.LC_empty_row td,
                   6179: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6180:   background-color: $sidebg;
                   6181: }
                   6182: 
                   6183: table.LC_nested tr.LC_empty_row td {
                   6184:   background-color: #FFFFFF;
                   6185: }
                   6186: 
1.890     droeschl 6187: table.LC_caption {
                   6188: }
                   6189: 
1.507     raeburn  6190: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6191:   padding: 4ex
                   6192: }
1.795     www      6193: 
1.507     raeburn  6194: table.LC_nested_outer tr th {
                   6195:   font-weight: bold;
1.801     tempelho 6196:   color:$fontmenu;
1.507     raeburn  6197:   background-color: $data_table_head;
1.701     harmsja  6198:   font-size: small;
1.507     raeburn  6199:   border-bottom: 1px solid #000000;
                   6200: }
1.795     www      6201: 
1.507     raeburn  6202: table.LC_nested_outer tr td.LC_subheader {
                   6203:   background-color: $data_table_head;
                   6204:   font-weight: bold;
                   6205:   font-size: small;
                   6206:   border-bottom: 1px solid #000000;
                   6207:   text-align: right;
1.451     albertel 6208: }
1.795     www      6209: 
1.507     raeburn  6210: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6211:   background-color: #CCCCCC;
1.451     albertel 6212:   font-weight: bold;
                   6213:   font-size: small;
1.507     raeburn  6214:   text-align: center;
                   6215: }
1.795     www      6216: 
1.589     raeburn  6217: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6218: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6219:   text-align: left;
1.451     albertel 6220: }
1.795     www      6221: 
1.507     raeburn  6222: table.LC_nested td {
1.735     bisitz   6223:   background-color: #FFFFFF;
1.451     albertel 6224:   font-size: small;
1.507     raeburn  6225: }
1.795     www      6226: 
1.507     raeburn  6227: table.LC_nested_outer tr th.LC_right_item,
                   6228: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6229: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6230: table.LC_nested tr td.LC_right_item {
1.451     albertel 6231:   text-align: right;
                   6232: }
                   6233: 
1.507     raeburn  6234: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6235:   background-color: #EEEEEE;
1.451     albertel 6236: }
                   6237: 
1.473     raeburn  6238: table.LC_createuser {
                   6239: }
                   6240: 
                   6241: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6242:   font-size: small;
1.473     raeburn  6243: }
                   6244: 
                   6245: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6246:   background-color: #CCCCCC;
1.473     raeburn  6247:   font-weight: bold;
                   6248:   text-align: center;
                   6249: }
                   6250: 
1.349     albertel 6251: table.LC_calendar {
                   6252:   border: 1px solid #000000;
                   6253:   border-collapse: collapse;
1.917     raeburn  6254:   width: 98%;
1.349     albertel 6255: }
1.795     www      6256: 
1.349     albertel 6257: table.LC_calendar_pickdate {
                   6258:   font-size: xx-small;
                   6259: }
1.795     www      6260: 
1.349     albertel 6261: table.LC_calendar tr td {
                   6262:   border: 1px solid #000000;
                   6263:   vertical-align: top;
1.917     raeburn  6264:   width: 14%;
1.349     albertel 6265: }
1.795     www      6266: 
1.349     albertel 6267: table.LC_calendar tr td.LC_calendar_day_empty {
                   6268:   background-color: $data_table_dark;
                   6269: }
1.795     www      6270: 
1.779     bisitz   6271: table.LC_calendar tr td.LC_calendar_day_current {
                   6272:   background-color: $data_table_highlight;
1.777     tempelho 6273: }
1.795     www      6274: 
1.938     bisitz   6275: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6276:   background-color: $mail_new;
                   6277: }
1.795     www      6278: 
1.938     bisitz   6279: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6280:   background-color: $mail_new_hover;
                   6281: }
1.795     www      6282: 
1.938     bisitz   6283: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6284:   background-color: $mail_read;
                   6285: }
1.795     www      6286: 
1.938     bisitz   6287: /*
                   6288: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6289:   background-color: $mail_read_hover;
                   6290: }
1.938     bisitz   6291: */
1.795     www      6292: 
1.938     bisitz   6293: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6294:   background-color: $mail_replied;
                   6295: }
1.795     www      6296: 
1.938     bisitz   6297: /*
                   6298: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6299:   background-color: $mail_replied_hover;
                   6300: }
1.938     bisitz   6301: */
1.795     www      6302: 
1.938     bisitz   6303: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6304:   background-color: $mail_other;
                   6305: }
1.795     www      6306: 
1.938     bisitz   6307: /*
                   6308: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6309:   background-color: $mail_other_hover;
                   6310: }
1.938     bisitz   6311: */
1.494     raeburn  6312: 
1.777     tempelho 6313: table.LC_data_table tr > td.LC_browser_file,
                   6314: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6315:   background: #AAEE77;
1.389     albertel 6316: }
1.795     www      6317: 
1.777     tempelho 6318: table.LC_data_table tr > td.LC_browser_file_locked,
                   6319: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6320:   background: #FFAA99;
1.387     albertel 6321: }
1.795     www      6322: 
1.777     tempelho 6323: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6324:   background: #888888;
1.779     bisitz   6325: }
1.795     www      6326: 
1.777     tempelho 6327: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6328: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6329:   background: #F8F866;
1.777     tempelho 6330: }
1.795     www      6331: 
1.696     bisitz   6332: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6333:   background: #E0E8FF;
1.387     albertel 6334: }
1.696     bisitz   6335: 
1.707     bisitz   6336: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6337:   /* background: #77FF77; */
1.707     bisitz   6338: }
1.795     www      6339: 
1.707     bisitz   6340: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6341:   border-right: 8px solid #FFFF77;
1.707     bisitz   6342: }
1.795     www      6343: 
1.707     bisitz   6344: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6345:   border-right: 8px solid #FFAA77;
1.707     bisitz   6346: }
1.795     www      6347: 
1.707     bisitz   6348: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6349:   border-right: 8px solid #FF7777;
1.707     bisitz   6350: }
1.795     www      6351: 
1.707     bisitz   6352: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6353:   border-right: 8px solid #AAFF77;
1.707     bisitz   6354: }
1.795     www      6355: 
1.707     bisitz   6356: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6357:   border-right: 8px solid #11CC55;
1.707     bisitz   6358: }
                   6359: 
1.388     albertel 6360: span.LC_current_location {
1.701     harmsja  6361:   font-size:larger;
1.388     albertel 6362:   background: $pgbg;
                   6363: }
1.387     albertel 6364: 
1.1029    www      6365: span.LC_current_nav_location {
                   6366:   font-weight:bold;
                   6367:   background: $sidebg;
                   6368: }
                   6369: 
1.395     albertel 6370: span.LC_parm_menu_item {
                   6371:   font-size: larger;
                   6372: }
1.795     www      6373: 
1.395     albertel 6374: span.LC_parm_scope_all {
                   6375:   color: red;
                   6376: }
1.795     www      6377: 
1.395     albertel 6378: span.LC_parm_scope_folder {
                   6379:   color: green;
                   6380: }
1.795     www      6381: 
1.395     albertel 6382: span.LC_parm_scope_resource {
                   6383:   color: orange;
                   6384: }
1.795     www      6385: 
1.395     albertel 6386: span.LC_parm_part {
                   6387:   color: blue;
                   6388: }
1.795     www      6389: 
1.911     bisitz   6390: span.LC_parm_folder,
                   6391: span.LC_parm_symb {
1.395     albertel 6392:   font-size: x-small;
                   6393:   font-family: $mono;
                   6394:   color: #AAAAAA;
                   6395: }
                   6396: 
1.977     bisitz   6397: ul.LC_parm_parmlist li {
                   6398:   display: inline-block;
                   6399:   padding: 0.3em 0.8em;
                   6400:   vertical-align: top;
                   6401:   width: 150px;
                   6402:   border-top:1px solid $lg_border_color;
                   6403: }
                   6404: 
1.795     www      6405: td.LC_parm_overview_level_menu,
                   6406: td.LC_parm_overview_map_menu,
                   6407: td.LC_parm_overview_parm_selectors,
                   6408: td.LC_parm_overview_restrictions  {
1.396     albertel 6409:   border: 1px solid black;
                   6410:   border-collapse: collapse;
                   6411: }
1.795     www      6412: 
1.396     albertel 6413: table.LC_parm_overview_restrictions td {
                   6414:   border-width: 1px 4px 1px 4px;
                   6415:   border-style: solid;
                   6416:   border-color: $pgbg;
                   6417:   text-align: center;
                   6418: }
1.795     www      6419: 
1.396     albertel 6420: table.LC_parm_overview_restrictions th {
                   6421:   background: $tabbg;
                   6422:   border-width: 1px 4px 1px 4px;
                   6423:   border-style: solid;
                   6424:   border-color: $pgbg;
                   6425: }
1.795     www      6426: 
1.398     albertel 6427: table#LC_helpmenu {
1.803     bisitz   6428:   border: none;
1.398     albertel 6429:   height: 55px;
1.803     bisitz   6430:   border-spacing: 0;
1.398     albertel 6431: }
                   6432: 
                   6433: table#LC_helpmenu fieldset legend {
                   6434:   font-size: larger;
                   6435: }
1.795     www      6436: 
1.397     albertel 6437: table#LC_helpmenu_links {
                   6438:   width: 100%;
                   6439:   border: 1px solid black;
                   6440:   background: $pgbg;
1.803     bisitz   6441:   padding: 0;
1.397     albertel 6442:   border-spacing: 1px;
                   6443: }
1.795     www      6444: 
1.397     albertel 6445: table#LC_helpmenu_links tr td {
                   6446:   padding: 1px;
                   6447:   background: $tabbg;
1.399     albertel 6448:   text-align: center;
                   6449:   font-weight: bold;
1.397     albertel 6450: }
1.396     albertel 6451: 
1.795     www      6452: table#LC_helpmenu_links a:link,
                   6453: table#LC_helpmenu_links a:visited,
1.397     albertel 6454: table#LC_helpmenu_links a:active {
                   6455:   text-decoration: none;
                   6456:   color: $font;
                   6457: }
1.795     www      6458: 
1.397     albertel 6459: table#LC_helpmenu_links a:hover {
                   6460:   text-decoration: underline;
                   6461:   color: $vlink;
                   6462: }
1.396     albertel 6463: 
1.417     albertel 6464: .LC_chrt_popup_exists {
                   6465:   border: 1px solid #339933;
                   6466:   margin: -1px;
                   6467: }
1.795     www      6468: 
1.417     albertel 6469: .LC_chrt_popup_up {
                   6470:   border: 1px solid yellow;
                   6471:   margin: -1px;
                   6472: }
1.795     www      6473: 
1.417     albertel 6474: .LC_chrt_popup {
                   6475:   border: 1px solid #8888FF;
                   6476:   background: #CCCCFF;
                   6477: }
1.795     www      6478: 
1.421     albertel 6479: table.LC_pick_box {
                   6480:   border-collapse: separate;
                   6481:   background: white;
                   6482:   border: 1px solid black;
                   6483:   border-spacing: 1px;
                   6484: }
1.795     www      6485: 
1.421     albertel 6486: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6487:   background: $sidebg;
1.421     albertel 6488:   font-weight: bold;
1.900     bisitz   6489:   text-align: left;
1.740     bisitz   6490:   vertical-align: top;
1.421     albertel 6491:   width: 184px;
                   6492:   padding: 8px;
                   6493: }
1.795     www      6494: 
1.579     raeburn  6495: table.LC_pick_box td.LC_pick_box_value {
                   6496:   text-align: left;
                   6497:   padding: 8px;
                   6498: }
1.795     www      6499: 
1.579     raeburn  6500: table.LC_pick_box td.LC_pick_box_select {
                   6501:   text-align: left;
                   6502:   padding: 8px;
                   6503: }
1.795     www      6504: 
1.424     albertel 6505: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6506:   padding: 0;
1.421     albertel 6507:   height: 1px;
                   6508:   background: black;
                   6509: }
1.795     www      6510: 
1.421     albertel 6511: table.LC_pick_box td.LC_pick_box_submit {
                   6512:   text-align: right;
                   6513: }
1.795     www      6514: 
1.579     raeburn  6515: table.LC_pick_box td.LC_evenrow_value {
                   6516:   text-align: left;
                   6517:   padding: 8px;
                   6518:   background-color: $data_table_light;
                   6519: }
1.795     www      6520: 
1.579     raeburn  6521: table.LC_pick_box td.LC_oddrow_value {
                   6522:   text-align: left;
                   6523:   padding: 8px;
                   6524:   background-color: $data_table_light;
                   6525: }
1.795     www      6526: 
1.579     raeburn  6527: span.LC_helpform_receipt_cat {
                   6528:   font-weight: bold;
                   6529: }
1.795     www      6530: 
1.424     albertel 6531: table.LC_group_priv_box {
                   6532:   background: white;
                   6533:   border: 1px solid black;
                   6534:   border-spacing: 1px;
                   6535: }
1.795     www      6536: 
1.424     albertel 6537: table.LC_group_priv_box td.LC_pick_box_title {
                   6538:   background: $tabbg;
                   6539:   font-weight: bold;
                   6540:   text-align: right;
                   6541:   width: 184px;
                   6542: }
1.795     www      6543: 
1.424     albertel 6544: table.LC_group_priv_box td.LC_groups_fixed {
                   6545:   background: $data_table_light;
                   6546:   text-align: center;
                   6547: }
1.795     www      6548: 
1.424     albertel 6549: table.LC_group_priv_box td.LC_groups_optional {
                   6550:   background: $data_table_dark;
                   6551:   text-align: center;
                   6552: }
1.795     www      6553: 
1.424     albertel 6554: table.LC_group_priv_box td.LC_groups_functionality {
                   6555:   background: $data_table_darker;
                   6556:   text-align: center;
                   6557:   font-weight: bold;
                   6558: }
1.795     www      6559: 
1.424     albertel 6560: table.LC_group_priv td {
                   6561:   text-align: left;
1.803     bisitz   6562:   padding: 0;
1.424     albertel 6563: }
                   6564: 
                   6565: .LC_navbuttons {
                   6566:   margin: 2ex 0ex 2ex 0ex;
                   6567: }
1.795     www      6568: 
1.423     albertel 6569: .LC_topic_bar {
                   6570:   font-weight: bold;
                   6571:   background: $tabbg;
1.918     wenzelju 6572:   margin: 1em 0em 1em 2em;
1.805     bisitz   6573:   padding: 3px;
1.918     wenzelju 6574:   font-size: 1.2em;
1.423     albertel 6575: }
1.795     www      6576: 
1.423     albertel 6577: .LC_topic_bar span {
1.918     wenzelju 6578:   left: 0.5em;
                   6579:   position: absolute;
1.423     albertel 6580:   vertical-align: middle;
1.918     wenzelju 6581:   font-size: 1.2em;
1.423     albertel 6582: }
1.795     www      6583: 
1.423     albertel 6584: table.LC_course_group_status {
                   6585:   margin: 20px;
                   6586: }
1.795     www      6587: 
1.423     albertel 6588: table.LC_status_selector td {
                   6589:   vertical-align: top;
                   6590:   text-align: center;
1.424     albertel 6591:   padding: 4px;
                   6592: }
1.795     www      6593: 
1.599     albertel 6594: div.LC_feedback_link {
1.616     albertel 6595:   clear: both;
1.829     kalberla 6596:   background: $sidebg;
1.779     bisitz   6597:   width: 100%;
1.829     kalberla 6598:   padding-bottom: 10px;
                   6599:   border: 1px $tabbg solid;
1.833     kalberla 6600:   height: 22px;
                   6601:   line-height: 22px;
                   6602:   padding-top: 5px;
                   6603: }
                   6604: 
                   6605: div.LC_feedback_link img {
                   6606:   height: 22px;
1.867     kalberla 6607:   vertical-align:middle;
1.829     kalberla 6608: }
                   6609: 
1.911     bisitz   6610: div.LC_feedback_link a {
1.829     kalberla 6611:   text-decoration: none;
1.489     raeburn  6612: }
1.795     www      6613: 
1.867     kalberla 6614: div.LC_comblock {
1.911     bisitz   6615:   display:inline;
1.867     kalberla 6616:   color:$font;
                   6617:   font-size:90%;
                   6618: }
                   6619: 
                   6620: div.LC_feedback_link div.LC_comblock {
                   6621:   padding-left:5px;
                   6622: }
                   6623: 
                   6624: div.LC_feedback_link div.LC_comblock a {
                   6625:   color:$font;
                   6626: }
                   6627: 
1.489     raeburn  6628: span.LC_feedback_link {
1.858     bisitz   6629:   /* background: $feedback_link_bg; */
1.599     albertel 6630:   font-size: larger;
                   6631: }
1.795     www      6632: 
1.599     albertel 6633: span.LC_message_link {
1.858     bisitz   6634:   /* background: $feedback_link_bg; */
1.599     albertel 6635:   font-size: larger;
                   6636:   position: absolute;
                   6637:   right: 1em;
1.489     raeburn  6638: }
1.421     albertel 6639: 
1.515     albertel 6640: table.LC_prior_tries {
1.524     albertel 6641:   border: 1px solid #000000;
                   6642:   border-collapse: separate;
                   6643:   border-spacing: 1px;
1.515     albertel 6644: }
1.523     albertel 6645: 
1.515     albertel 6646: table.LC_prior_tries td {
1.524     albertel 6647:   padding: 2px;
1.515     albertel 6648: }
1.523     albertel 6649: 
                   6650: .LC_answer_correct {
1.795     www      6651:   background: lightgreen;
                   6652:   color: darkgreen;
                   6653:   padding: 6px;
1.523     albertel 6654: }
1.795     www      6655: 
1.523     albertel 6656: .LC_answer_charged_try {
1.797     www      6657:   background: #FFAAAA;
1.795     www      6658:   color: darkred;
                   6659:   padding: 6px;
1.523     albertel 6660: }
1.795     www      6661: 
1.779     bisitz   6662: .LC_answer_not_charged_try,
1.523     albertel 6663: .LC_answer_no_grade,
                   6664: .LC_answer_late {
1.795     www      6665:   background: lightyellow;
1.523     albertel 6666:   color: black;
1.795     www      6667:   padding: 6px;
1.523     albertel 6668: }
1.795     www      6669: 
1.523     albertel 6670: .LC_answer_previous {
1.795     www      6671:   background: lightblue;
                   6672:   color: darkblue;
                   6673:   padding: 6px;
1.523     albertel 6674: }
1.795     www      6675: 
1.779     bisitz   6676: .LC_answer_no_message {
1.777     tempelho 6677:   background: #FFFFFF;
                   6678:   color: black;
1.795     www      6679:   padding: 6px;
1.779     bisitz   6680: }
1.795     www      6681: 
1.779     bisitz   6682: .LC_answer_unknown {
                   6683:   background: orange;
                   6684:   color: black;
1.795     www      6685:   padding: 6px;
1.777     tempelho 6686: }
1.795     www      6687: 
1.529     albertel 6688: span.LC_prior_numerical,
                   6689: span.LC_prior_string,
                   6690: span.LC_prior_custom,
                   6691: span.LC_prior_reaction,
                   6692: span.LC_prior_math {
1.925     bisitz   6693:   font-family: $mono;
1.523     albertel 6694:   white-space: pre;
                   6695: }
                   6696: 
1.525     albertel 6697: span.LC_prior_string {
1.925     bisitz   6698:   font-family: $mono;
1.525     albertel 6699:   white-space: pre;
                   6700: }
                   6701: 
1.523     albertel 6702: table.LC_prior_option {
                   6703:   width: 100%;
                   6704:   border-collapse: collapse;
                   6705: }
1.795     www      6706: 
1.911     bisitz   6707: table.LC_prior_rank,
1.795     www      6708: table.LC_prior_match {
1.528     albertel 6709:   border-collapse: collapse;
                   6710: }
1.795     www      6711: 
1.528     albertel 6712: table.LC_prior_option tr td,
                   6713: table.LC_prior_rank tr td,
                   6714: table.LC_prior_match tr td {
1.524     albertel 6715:   border: 1px solid #000000;
1.515     albertel 6716: }
                   6717: 
1.855     bisitz   6718: .LC_nobreak {
1.544     albertel 6719:   white-space: nowrap;
1.519     raeburn  6720: }
                   6721: 
1.576     raeburn  6722: span.LC_cusr_emph {
                   6723:   font-style: italic;
                   6724: }
                   6725: 
1.633     raeburn  6726: span.LC_cusr_subheading {
                   6727:   font-weight: normal;
                   6728:   font-size: 85%;
                   6729: }
                   6730: 
1.861     bisitz   6731: div.LC_docs_entry_move {
1.859     bisitz   6732:   border: 1px solid #BBBBBB;
1.545     albertel 6733:   background: #DDDDDD;
1.861     bisitz   6734:   width: 22px;
1.859     bisitz   6735:   padding: 1px;
                   6736:   margin: 0;
1.545     albertel 6737: }
                   6738: 
1.861     bisitz   6739: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6740: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6741:   font-size: x-small;
                   6742: }
1.795     www      6743: 
1.861     bisitz   6744: .LC_docs_entry_parameter {
                   6745:   white-space: nowrap;
                   6746: }
                   6747: 
1.544     albertel 6748: .LC_docs_copy {
1.545     albertel 6749:   color: #000099;
1.544     albertel 6750: }
1.795     www      6751: 
1.544     albertel 6752: .LC_docs_cut {
1.545     albertel 6753:   color: #550044;
1.544     albertel 6754: }
1.795     www      6755: 
1.544     albertel 6756: .LC_docs_rename {
1.545     albertel 6757:   color: #009900;
1.544     albertel 6758: }
1.795     www      6759: 
1.544     albertel 6760: .LC_docs_remove {
1.545     albertel 6761:   color: #990000;
                   6762: }
                   6763: 
1.547     albertel 6764: .LC_docs_reinit_warn,
                   6765: .LC_docs_ext_edit {
                   6766:   font-size: x-small;
                   6767: }
                   6768: 
1.545     albertel 6769: table.LC_docs_adddocs td,
                   6770: table.LC_docs_adddocs th {
                   6771:   border: 1px solid #BBBBBB;
                   6772:   padding: 4px;
                   6773:   background: #DDDDDD;
1.543     albertel 6774: }
                   6775: 
1.584     albertel 6776: table.LC_sty_begin {
                   6777:   background: #BBFFBB;
                   6778: }
1.795     www      6779: 
1.584     albertel 6780: table.LC_sty_end {
                   6781:   background: #FFBBBB;
                   6782: }
                   6783: 
1.589     raeburn  6784: table.LC_double_column {
1.803     bisitz   6785:   border-width: 0;
1.589     raeburn  6786:   border-collapse: collapse;
                   6787:   width: 100%;
                   6788:   padding: 2px;
                   6789: }
                   6790: 
                   6791: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6792:   top: 2px;
1.589     raeburn  6793:   left: 2px;
                   6794:   width: 47%;
                   6795:   vertical-align: top;
                   6796: }
                   6797: 
                   6798: table.LC_double_column tr td.LC_right_col {
                   6799:   top: 2px;
1.779     bisitz   6800:   right: 2px;
1.589     raeburn  6801:   width: 47%;
                   6802:   vertical-align: top;
                   6803: }
                   6804: 
1.591     raeburn  6805: div.LC_left_float {
                   6806:   float: left;
                   6807:   padding-right: 5%;
1.597     albertel 6808:   padding-bottom: 4px;
1.591     raeburn  6809: }
                   6810: 
                   6811: div.LC_clear_float_header {
1.597     albertel 6812:   padding-bottom: 2px;
1.591     raeburn  6813: }
                   6814: 
                   6815: div.LC_clear_float_footer {
1.597     albertel 6816:   padding-top: 10px;
1.591     raeburn  6817:   clear: both;
                   6818: }
                   6819: 
1.597     albertel 6820: div.LC_grade_show_user {
1.941     bisitz   6821: /*  border-left: 5px solid $sidebg; */
                   6822:   border-top: 5px solid #000000;
                   6823:   margin: 50px 0 0 0;
1.936     bisitz   6824:   padding: 15px 0 5px 10px;
1.597     albertel 6825: }
1.795     www      6826: 
1.936     bisitz   6827: div.LC_grade_show_user_odd_row {
1.941     bisitz   6828: /*  border-left: 5px solid #000000; */
                   6829: }
                   6830: 
                   6831: div.LC_grade_show_user div.LC_Box {
                   6832:   margin-right: 50px;
1.597     albertel 6833: }
                   6834: 
                   6835: div.LC_grade_submissions,
                   6836: div.LC_grade_message_center,
1.936     bisitz   6837: div.LC_grade_info_links {
1.597     albertel 6838:   margin: 5px;
                   6839:   width: 99%;
                   6840:   background: #FFFFFF;
                   6841: }
1.795     www      6842: 
1.597     albertel 6843: div.LC_grade_submissions_header,
1.936     bisitz   6844: div.LC_grade_message_center_header {
1.705     tempelho 6845:   font-weight: bold;
                   6846:   font-size: large;
1.597     albertel 6847: }
1.795     www      6848: 
1.597     albertel 6849: div.LC_grade_submissions_body,
1.936     bisitz   6850: div.LC_grade_message_center_body {
1.597     albertel 6851:   border: 1px solid black;
                   6852:   width: 99%;
                   6853:   background: #FFFFFF;
                   6854: }
1.795     www      6855: 
1.613     albertel 6856: table.LC_scantron_action {
                   6857:   width: 100%;
                   6858: }
1.795     www      6859: 
1.613     albertel 6860: table.LC_scantron_action tr th {
1.698     harmsja  6861:   font-weight:bold;
                   6862:   font-style:normal;
1.613     albertel 6863: }
1.795     www      6864: 
1.779     bisitz   6865: .LC_edit_problem_header,
1.614     albertel 6866: div.LC_edit_problem_footer {
1.705     tempelho 6867:   font-weight: normal;
                   6868:   font-size:  medium;
1.602     albertel 6869:   margin: 2px;
1.1060    bisitz   6870:   background-color: $sidebg;
1.600     albertel 6871: }
1.795     www      6872: 
1.600     albertel 6873: div.LC_edit_problem_header,
1.602     albertel 6874: div.LC_edit_problem_header div,
1.614     albertel 6875: div.LC_edit_problem_footer,
                   6876: div.LC_edit_problem_footer div,
1.602     albertel 6877: div.LC_edit_problem_editxml_header,
                   6878: div.LC_edit_problem_editxml_header div {
1.1205    golterma 6879:   z-index: 100;
1.600     albertel 6880: }
1.795     www      6881: 
1.600     albertel 6882: div.LC_edit_problem_header_title {
1.705     tempelho 6883:   font-weight: bold;
                   6884:   font-size: larger;
1.602     albertel 6885:   background: $tabbg;
                   6886:   padding: 3px;
1.1060    bisitz   6887:   margin: 0 0 5px 0;
1.602     albertel 6888: }
1.795     www      6889: 
1.602     albertel 6890: table.LC_edit_problem_header_title {
                   6891:   width: 100%;
1.600     albertel 6892:   background: $tabbg;
1.602     albertel 6893: }
                   6894: 
1.1205    golterma 6895: div.LC_edit_actionbar {
                   6896:     background-color: $sidebg;
1.1218    droeschl 6897:     margin: 0;
                   6898:     padding: 0;
                   6899:     line-height: 200%;
1.602     albertel 6900: }
1.795     www      6901: 
1.1218    droeschl 6902: div.LC_edit_actionbar div{
                   6903:     padding: 0;
                   6904:     margin: 0;
                   6905:     display: inline-block;
1.600     albertel 6906: }
1.795     www      6907: 
1.1124    bisitz   6908: .LC_edit_opt {
                   6909:   padding-left: 1em;
                   6910:   white-space: nowrap;
                   6911: }
                   6912: 
1.1152    golterma 6913: .LC_edit_problem_latexhelper{
                   6914:     text-align: right;
                   6915: }
                   6916: 
                   6917: #LC_edit_problem_colorful div{
                   6918:     margin-left: 40px;
                   6919: }
                   6920: 
1.1205    golterma 6921: #LC_edit_problem_codemirror div{
                   6922:     margin-left: 0px;
                   6923: }
                   6924: 
1.911     bisitz   6925: img.stift {
1.803     bisitz   6926:   border-width: 0;
                   6927:   vertical-align: middle;
1.677     riegler  6928: }
1.680     riegler  6929: 
1.923     bisitz   6930: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6931:   vertical-align: top;
1.777     tempelho 6932: }
1.795     www      6933: 
1.716     raeburn  6934: div.LC_createcourse {
1.911     bisitz   6935:   margin: 10px 10px 10px 10px;
1.716     raeburn  6936: }
                   6937: 
1.917     raeburn  6938: .LC_dccid {
1.1130    raeburn  6939:   float: right;
1.917     raeburn  6940:   margin: 0.2em 0 0 0;
                   6941:   padding: 0;
                   6942:   font-size: 90%;
                   6943:   display:none;
                   6944: }
                   6945: 
1.897     wenzelju 6946: ol.LC_primary_menu a:hover,
1.721     harmsja  6947: ol#LC_MenuBreadcrumbs a:hover,
                   6948: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6949: ul#LC_secondary_menu a:hover,
1.721     harmsja  6950: .LC_FormSectionClearButton input:hover
1.795     www      6951: ul.LC_TabContent   li:hover a {
1.952     onken    6952:   color:$button_hover;
1.911     bisitz   6953:   text-decoration:none;
1.693     droeschl 6954: }
                   6955: 
1.779     bisitz   6956: h1 {
1.911     bisitz   6957:   padding: 0;
                   6958:   line-height:130%;
1.693     droeschl 6959: }
1.698     harmsja  6960: 
1.911     bisitz   6961: h2,
                   6962: h3,
                   6963: h4,
                   6964: h5,
                   6965: h6 {
                   6966:   margin: 5px 0 5px 0;
                   6967:   padding: 0;
                   6968:   line-height:130%;
1.693     droeschl 6969: }
1.795     www      6970: 
                   6971: .LC_hcell {
1.911     bisitz   6972:   padding:3px 15px 3px 15px;
                   6973:   margin: 0;
                   6974:   background-color:$tabbg;
                   6975:   color:$fontmenu;
                   6976:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6977: }
1.795     www      6978: 
1.840     bisitz   6979: .LC_Box > .LC_hcell {
1.911     bisitz   6980:   margin: 0 -10px 10px -10px;
1.835     bisitz   6981: }
                   6982: 
1.721     harmsja  6983: .LC_noBorder {
1.911     bisitz   6984:   border: 0;
1.698     harmsja  6985: }
1.693     droeschl 6986: 
1.721     harmsja  6987: .LC_FormSectionClearButton input {
1.911     bisitz   6988:   background-color:transparent;
                   6989:   border: none;
                   6990:   cursor:pointer;
                   6991:   text-decoration:underline;
1.693     droeschl 6992: }
1.763     bisitz   6993: 
                   6994: .LC_help_open_topic {
1.911     bisitz   6995:   color: #FFFFFF;
                   6996:   background-color: #EEEEFF;
                   6997:   margin: 1px;
                   6998:   padding: 4px;
                   6999:   border: 1px solid #000033;
                   7000:   white-space: nowrap;
                   7001:   /* vertical-align: middle; */
1.759     neumanie 7002: }
1.693     droeschl 7003: 
1.911     bisitz   7004: dl,
                   7005: ul,
                   7006: div,
                   7007: fieldset {
                   7008:   margin: 10px 10px 10px 0;
                   7009:   /* overflow: hidden; */
1.693     droeschl 7010: }
1.795     www      7011: 
1.1211    raeburn  7012: article.geogebraweb div {
                   7013:     margin: 0;
                   7014: }
                   7015: 
1.838     bisitz   7016: fieldset > legend {
1.911     bisitz   7017:   font-weight: bold;
                   7018:   padding: 0 5px 0 5px;
1.838     bisitz   7019: }
                   7020: 
1.813     bisitz   7021: #LC_nav_bar {
1.911     bisitz   7022:   float: left;
1.995     raeburn  7023:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7024:   margin: 0 0 2px 0;
1.807     droeschl 7025: }
                   7026: 
1.916     droeschl 7027: #LC_realm {
                   7028:   margin: 0.2em 0 0 0;
                   7029:   padding: 0;
                   7030:   font-weight: bold;
                   7031:   text-align: center;
1.995     raeburn  7032:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7033: }
                   7034: 
1.911     bisitz   7035: #LC_nav_bar em {
                   7036:   font-weight: bold;
                   7037:   font-style: normal;
1.807     droeschl 7038: }
                   7039: 
1.897     wenzelju 7040: ol.LC_primary_menu {
1.934     droeschl 7041:   margin: 0;
1.1076    raeburn  7042:   padding: 0;
1.807     droeschl 7043: }
                   7044: 
1.852     droeschl 7045: ol#LC_PathBreadcrumbs {
1.911     bisitz   7046:   margin: 0;
1.693     droeschl 7047: }
                   7048: 
1.897     wenzelju 7049: ol.LC_primary_menu li {
1.1076    raeburn  7050:   color: RGB(80, 80, 80);
                   7051:   vertical-align: middle;
                   7052:   text-align: left;
                   7053:   list-style: none;
1.1205    golterma 7054:   position: relative;
1.1076    raeburn  7055:   float: left;
1.1205    golterma 7056:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7057:   line-height: 1.5em;
1.1076    raeburn  7058: }
                   7059: 
1.1205    golterma 7060: ol.LC_primary_menu li a,
                   7061: ol.LC_primary_menu li p {
1.1076    raeburn  7062:   display: block;
                   7063:   margin: 0;
                   7064:   padding: 0 5px 0 10px;
                   7065:   text-decoration: none;
                   7066: }
                   7067: 
1.1205    golterma 7068: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7069:   display: inline-block;
                   7070:   width: 95%;
                   7071:   text-align: left;
                   7072: }
                   7073: 
                   7074: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7075:   display: inline-block;	
                   7076:   width: 5%;
                   7077:   float: right;
                   7078:   text-align: right;
                   7079:   font-size: 70%;
                   7080: }
                   7081: 
                   7082: ol.LC_primary_menu ul {
1.1076    raeburn  7083:   display: none;
1.1205    golterma 7084:   width: 15em;
1.1076    raeburn  7085:   background-color: $data_table_light;
1.1205    golterma 7086:   position: absolute;
                   7087:   top: 100%;
1.1076    raeburn  7088: }
                   7089: 
1.1205    golterma 7090: ol.LC_primary_menu ul ul {
                   7091:   left: 100%;
                   7092:   top: 0;
                   7093: }
                   7094: 
                   7095: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7096:   display: block;
                   7097:   position: absolute;
                   7098:   margin: 0;
                   7099:   padding: 0;
1.1078    raeburn  7100:   z-index: 2;
1.1076    raeburn  7101: }
                   7102: 
                   7103: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7104: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7105:   font-size: 90%;
1.911     bisitz   7106:   vertical-align: top;
1.1076    raeburn  7107:   float: none;
1.1079    raeburn  7108:   border-left: 1px solid black;
                   7109:   border-right: 1px solid black;
1.1205    golterma 7110: /* A dark bottom border to visualize different menu options; 
                   7111: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7112:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7113: }
                   7114: 
1.1205    golterma 7115: ol.LC_primary_menu li li p:hover {
                   7116:   color:$button_hover;
                   7117:   text-decoration:none;
                   7118:   background-color:$data_table_dark;
1.1076    raeburn  7119: }
                   7120: 
                   7121: ol.LC_primary_menu li li a:hover {
                   7122:    color:$button_hover;
                   7123:    background-color:$data_table_dark;
1.693     droeschl 7124: }
                   7125: 
1.1205    golterma 7126: /* Font-size equal to the size of the predecessors*/
                   7127: ol.LC_primary_menu li:hover li li {
                   7128:   font-size: 100%;
                   7129: }
                   7130: 
1.897     wenzelju 7131: ol.LC_primary_menu li img {
1.911     bisitz   7132:   vertical-align: bottom;
1.934     droeschl 7133:   height: 1.1em;
1.1077    raeburn  7134:   margin: 0.2em 0 0 0;
1.693     droeschl 7135: }
                   7136: 
1.897     wenzelju 7137: ol.LC_primary_menu a {
1.911     bisitz   7138:   color: RGB(80, 80, 80);
                   7139:   text-decoration: none;
1.693     droeschl 7140: }
1.795     www      7141: 
1.949     droeschl 7142: ol.LC_primary_menu a.LC_new_message {
                   7143:   font-weight:bold;
                   7144:   color: darkred;
                   7145: }
                   7146: 
1.975     raeburn  7147: ol.LC_docs_parameters {
                   7148:   margin-left: 0;
                   7149:   padding: 0;
                   7150:   list-style: none;
                   7151: }
                   7152: 
                   7153: ol.LC_docs_parameters li {
                   7154:   margin: 0;
                   7155:   padding-right: 20px;
                   7156:   display: inline;
                   7157: }
                   7158: 
1.976     raeburn  7159: ol.LC_docs_parameters li:before {
                   7160:   content: "\\002022 \\0020";
                   7161: }
                   7162: 
                   7163: li.LC_docs_parameters_title {
                   7164:   font-weight: bold;
                   7165: }
                   7166: 
                   7167: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7168:   content: "";
                   7169: }
                   7170: 
1.897     wenzelju 7171: ul#LC_secondary_menu {
1.1107    raeburn  7172:   clear: right;
1.911     bisitz   7173:   color: $fontmenu;
                   7174:   background: $tabbg;
                   7175:   list-style: none;
                   7176:   padding: 0;
                   7177:   margin: 0;
                   7178:   width: 100%;
1.995     raeburn  7179:   text-align: left;
1.1107    raeburn  7180:   float: left;
1.808     droeschl 7181: }
                   7182: 
1.897     wenzelju 7183: ul#LC_secondary_menu li {
1.911     bisitz   7184:   font-weight: bold;
                   7185:   line-height: 1.8em;
1.1107    raeburn  7186:   border-right: 1px solid black;
                   7187:   float: left;
                   7188: }
                   7189: 
                   7190: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7191:   background-color: $data_table_light;
                   7192: }
                   7193: 
                   7194: ul#LC_secondary_menu li a {
1.911     bisitz   7195:   padding: 0 0.8em;
1.1107    raeburn  7196: }
                   7197: 
                   7198: ul#LC_secondary_menu li ul {
                   7199:   display: none;
                   7200: }
                   7201: 
                   7202: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7203:   display: block;
                   7204:   position: absolute;
                   7205:   margin: 0;
                   7206:   padding: 0;
                   7207:   list-style:none;
                   7208:   float: none;
                   7209:   background-color: $data_table_light;
                   7210:   z-index: 2;
                   7211:   margin-left: -1px;
                   7212: }
                   7213: 
                   7214: ul#LC_secondary_menu li ul li {
                   7215:   font-size: 90%;
                   7216:   vertical-align: top;
                   7217:   border-left: 1px solid black;
1.911     bisitz   7218:   border-right: 1px solid black;
1.1119    raeburn  7219:   background-color: $data_table_light;
1.1107    raeburn  7220:   list-style:none;
                   7221:   float: none;
                   7222: }
                   7223: 
                   7224: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7225:   background-color: $data_table_dark;
1.807     droeschl 7226: }
                   7227: 
1.847     tempelho 7228: ul.LC_TabContent {
1.911     bisitz   7229:   display:block;
                   7230:   background: $sidebg;
                   7231:   border-bottom: solid 1px $lg_border_color;
                   7232:   list-style:none;
1.1020    raeburn  7233:   margin: -1px -10px 0 -10px;
1.911     bisitz   7234:   padding: 0;
1.693     droeschl 7235: }
                   7236: 
1.795     www      7237: ul.LC_TabContent li,
                   7238: ul.LC_TabContentBigger li {
1.911     bisitz   7239:   float:left;
1.741     harmsja  7240: }
1.795     www      7241: 
1.897     wenzelju 7242: ul#LC_secondary_menu li a {
1.911     bisitz   7243:   color: $fontmenu;
                   7244:   text-decoration: none;
1.693     droeschl 7245: }
1.795     www      7246: 
1.721     harmsja  7247: ul.LC_TabContent {
1.952     onken    7248:   min-height:20px;
1.721     harmsja  7249: }
1.795     www      7250: 
                   7251: ul.LC_TabContent li {
1.911     bisitz   7252:   vertical-align:middle;
1.959     onken    7253:   padding: 0 16px 0 10px;
1.911     bisitz   7254:   background-color:$tabbg;
                   7255:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7256:   border-left: solid 1px $font;
1.721     harmsja  7257: }
1.795     www      7258: 
1.847     tempelho 7259: ul.LC_TabContent .right {
1.911     bisitz   7260:   float:right;
1.847     tempelho 7261: }
                   7262: 
1.911     bisitz   7263: ul.LC_TabContent li a,
                   7264: ul.LC_TabContent li {
                   7265:   color:rgb(47,47,47);
                   7266:   text-decoration:none;
                   7267:   font-size:95%;
                   7268:   font-weight:bold;
1.952     onken    7269:   min-height:20px;
                   7270: }
                   7271: 
1.959     onken    7272: ul.LC_TabContent li a:hover,
                   7273: ul.LC_TabContent li a:focus {
1.952     onken    7274:   color: $button_hover;
1.959     onken    7275:   background:none;
                   7276:   outline:none;
1.952     onken    7277: }
                   7278: 
                   7279: ul.LC_TabContent li:hover {
                   7280:   color: $button_hover;
                   7281:   cursor:pointer;
1.721     harmsja  7282: }
1.795     www      7283: 
1.911     bisitz   7284: ul.LC_TabContent li.active {
1.952     onken    7285:   color: $font;
1.911     bisitz   7286:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7287:   border-bottom:solid 1px #FFFFFF;
                   7288:   cursor: default;
1.744     ehlerst  7289: }
1.795     www      7290: 
1.959     onken    7291: ul.LC_TabContent li.active a {
                   7292:   color:$font;
                   7293:   background:#FFFFFF;
                   7294:   outline: none;
                   7295: }
1.1047    raeburn  7296: 
                   7297: ul.LC_TabContent li.goback {
                   7298:   float: left;
                   7299:   border-left: none;
                   7300: }
                   7301: 
1.870     tempelho 7302: #maincoursedoc {
1.911     bisitz   7303:   clear:both;
1.870     tempelho 7304: }
                   7305: 
                   7306: ul.LC_TabContentBigger {
1.911     bisitz   7307:   display:block;
                   7308:   list-style:none;
                   7309:   padding: 0;
1.870     tempelho 7310: }
                   7311: 
1.795     www      7312: ul.LC_TabContentBigger li {
1.911     bisitz   7313:   vertical-align:bottom;
                   7314:   height: 30px;
                   7315:   font-size:110%;
                   7316:   font-weight:bold;
                   7317:   color: #737373;
1.841     tempelho 7318: }
                   7319: 
1.957     onken    7320: ul.LC_TabContentBigger li.active {
                   7321:   position: relative;
                   7322:   top: 1px;
                   7323: }
                   7324: 
1.870     tempelho 7325: ul.LC_TabContentBigger li a {
1.911     bisitz   7326:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7327:   height: 30px;
                   7328:   line-height: 30px;
                   7329:   text-align: center;
                   7330:   display: block;
                   7331:   text-decoration: none;
1.958     onken    7332:   outline: none;  
1.741     harmsja  7333: }
1.795     www      7334: 
1.870     tempelho 7335: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7336:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7337:   color:$font;
1.744     ehlerst  7338: }
1.795     www      7339: 
1.870     tempelho 7340: ul.LC_TabContentBigger li b {
1.911     bisitz   7341:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7342:   display: block;
                   7343:   float: left;
                   7344:   padding: 0 30px;
1.957     onken    7345:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7346: }
                   7347: 
1.956     onken    7348: ul.LC_TabContentBigger li:hover b {
                   7349:   color:$button_hover;
                   7350: }
                   7351: 
1.870     tempelho 7352: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7353:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7354:   color:$font;
1.957     onken    7355:   border: 0;
1.741     harmsja  7356: }
1.693     droeschl 7357: 
1.870     tempelho 7358: 
1.862     bisitz   7359: ul.LC_CourseBreadcrumbs {
                   7360:   background: $sidebg;
1.1020    raeburn  7361:   height: 2em;
1.862     bisitz   7362:   padding-left: 10px;
1.1020    raeburn  7363:   margin: 0;
1.862     bisitz   7364:   list-style-position: inside;
                   7365: }
                   7366: 
1.911     bisitz   7367: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7368: ol#LC_PathBreadcrumbs {
1.911     bisitz   7369:   padding-left: 10px;
                   7370:   margin: 0;
1.933     droeschl 7371:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7372: }
                   7373: 
1.911     bisitz   7374: ol#LC_MenuBreadcrumbs li,
                   7375: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7376: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7377:   display: inline;
1.933     droeschl 7378:   white-space: normal;  
1.693     droeschl 7379: }
                   7380: 
1.823     bisitz   7381: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7382: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7383:   text-decoration: none;
                   7384:   font-size:90%;
1.693     droeschl 7385: }
1.795     www      7386: 
1.969     droeschl 7387: ol#LC_MenuBreadcrumbs h1 {
                   7388:   display: inline;
                   7389:   font-size: 90%;
                   7390:   line-height: 2.5em;
                   7391:   margin: 0;
                   7392:   padding: 0;
                   7393: }
                   7394: 
1.795     www      7395: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7396:   text-decoration:none;
                   7397:   font-size:100%;
                   7398:   font-weight:bold;
1.693     droeschl 7399: }
1.795     www      7400: 
1.840     bisitz   7401: .LC_Box {
1.911     bisitz   7402:   border: solid 1px $lg_border_color;
                   7403:   padding: 0 10px 10px 10px;
1.746     neumanie 7404: }
1.795     www      7405: 
1.1020    raeburn  7406: .LC_DocsBox {
                   7407:   border: solid 1px $lg_border_color;
                   7408:   padding: 0 0 10px 10px;
                   7409: }
                   7410: 
1.795     www      7411: .LC_AboutMe_Image {
1.911     bisitz   7412:   float:left;
                   7413:   margin-right:10px;
1.747     neumanie 7414: }
1.795     www      7415: 
                   7416: .LC_Clear_AboutMe_Image {
1.911     bisitz   7417:   clear:left;
1.747     neumanie 7418: }
1.795     www      7419: 
1.721     harmsja  7420: dl.LC_ListStyleClean dt {
1.911     bisitz   7421:   padding-right: 5px;
                   7422:   display: table-header-group;
1.693     droeschl 7423: }
                   7424: 
1.721     harmsja  7425: dl.LC_ListStyleClean dd {
1.911     bisitz   7426:   display: table-row;
1.693     droeschl 7427: }
                   7428: 
1.721     harmsja  7429: .LC_ListStyleClean,
                   7430: .LC_ListStyleSimple,
                   7431: .LC_ListStyleNormal,
1.795     www      7432: .LC_ListStyleSpecial {
1.911     bisitz   7433:   /* display:block; */
                   7434:   list-style-position: inside;
                   7435:   list-style-type: none;
                   7436:   overflow: hidden;
                   7437:   padding: 0;
1.693     droeschl 7438: }
                   7439: 
1.721     harmsja  7440: .LC_ListStyleSimple li,
                   7441: .LC_ListStyleSimple dd,
                   7442: .LC_ListStyleNormal li,
                   7443: .LC_ListStyleNormal dd,
                   7444: .LC_ListStyleSpecial li,
1.795     www      7445: .LC_ListStyleSpecial dd {
1.911     bisitz   7446:   margin: 0;
                   7447:   padding: 5px 5px 5px 10px;
                   7448:   clear: both;
1.693     droeschl 7449: }
                   7450: 
1.721     harmsja  7451: .LC_ListStyleClean li,
                   7452: .LC_ListStyleClean dd {
1.911     bisitz   7453:   padding-top: 0;
                   7454:   padding-bottom: 0;
1.693     droeschl 7455: }
                   7456: 
1.721     harmsja  7457: .LC_ListStyleSimple dd,
1.795     www      7458: .LC_ListStyleSimple li {
1.911     bisitz   7459:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7460: }
                   7461: 
1.721     harmsja  7462: .LC_ListStyleSpecial li,
                   7463: .LC_ListStyleSpecial dd {
1.911     bisitz   7464:   list-style-type: none;
                   7465:   background-color: RGB(220, 220, 220);
                   7466:   margin-bottom: 4px;
1.693     droeschl 7467: }
                   7468: 
1.721     harmsja  7469: table.LC_SimpleTable {
1.911     bisitz   7470:   margin:5px;
                   7471:   border:solid 1px $lg_border_color;
1.795     www      7472: }
1.693     droeschl 7473: 
1.721     harmsja  7474: table.LC_SimpleTable tr {
1.911     bisitz   7475:   padding: 0;
                   7476:   border:solid 1px $lg_border_color;
1.693     droeschl 7477: }
1.795     www      7478: 
                   7479: table.LC_SimpleTable thead {
1.911     bisitz   7480:   background:rgb(220,220,220);
1.693     droeschl 7481: }
                   7482: 
1.721     harmsja  7483: div.LC_columnSection {
1.911     bisitz   7484:   display: block;
                   7485:   clear: both;
                   7486:   overflow: hidden;
                   7487:   margin: 0;
1.693     droeschl 7488: }
                   7489: 
1.721     harmsja  7490: div.LC_columnSection>* {
1.911     bisitz   7491:   float: left;
                   7492:   margin: 10px 20px 10px 0;
                   7493:   overflow:hidden;
1.693     droeschl 7494: }
1.721     harmsja  7495: 
1.795     www      7496: table em {
1.911     bisitz   7497:   font-weight: bold;
                   7498:   font-style: normal;
1.748     schulted 7499: }
1.795     www      7500: 
1.779     bisitz   7501: table.LC_tableBrowseRes,
1.795     www      7502: table.LC_tableOfContent {
1.911     bisitz   7503:   border:none;
                   7504:   border-spacing: 1px;
                   7505:   padding: 3px;
                   7506:   background-color: #FFFFFF;
                   7507:   font-size: 90%;
1.753     droeschl 7508: }
1.789     droeschl 7509: 
1.911     bisitz   7510: table.LC_tableOfContent {
                   7511:   border-collapse: collapse;
1.789     droeschl 7512: }
                   7513: 
1.771     droeschl 7514: table.LC_tableBrowseRes a,
1.768     schulted 7515: table.LC_tableOfContent a {
1.911     bisitz   7516:   background-color: transparent;
                   7517:   text-decoration: none;
1.753     droeschl 7518: }
                   7519: 
1.795     www      7520: table.LC_tableOfContent img {
1.911     bisitz   7521:   border: none;
                   7522:   height: 1.3em;
                   7523:   vertical-align: text-bottom;
                   7524:   margin-right: 0.3em;
1.753     droeschl 7525: }
1.757     schulted 7526: 
1.795     www      7527: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7528:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7529: }
                   7530: 
1.795     www      7531: a#LC_content_toolbar_everything {
1.911     bisitz   7532:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7533: }
                   7534: 
1.795     www      7535: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7536:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7537: }
                   7538: 
1.795     www      7539: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7540:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7541: }
                   7542: 
1.795     www      7543: a#LC_content_toolbar_changefolder {
1.911     bisitz   7544:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7545: }
                   7546: 
1.795     www      7547: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7548:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7549: }
                   7550: 
1.1043    raeburn  7551: a#LC_content_toolbar_edittoplevel {
                   7552:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7553: }
                   7554: 
1.795     www      7555: ul#LC_toolbar li a:hover {
1.911     bisitz   7556:   background-position: bottom center;
1.757     schulted 7557: }
                   7558: 
1.795     www      7559: ul#LC_toolbar {
1.911     bisitz   7560:   padding: 0;
                   7561:   margin: 2px;
                   7562:   list-style:none;
                   7563:   position:relative;
                   7564:   background-color:white;
1.1082    raeburn  7565:   overflow: auto;
1.757     schulted 7566: }
                   7567: 
1.795     www      7568: ul#LC_toolbar li {
1.911     bisitz   7569:   border:1px solid white;
                   7570:   padding: 0;
                   7571:   margin: 0;
                   7572:   float: left;
                   7573:   display:inline;
                   7574:   vertical-align:middle;
1.1082    raeburn  7575:   white-space: nowrap;
1.911     bisitz   7576: }
1.757     schulted 7577: 
1.783     amueller 7578: 
1.795     www      7579: a.LC_toolbarItem {
1.911     bisitz   7580:   display:block;
                   7581:   padding: 0;
                   7582:   margin: 0;
                   7583:   height: 32px;
                   7584:   width: 32px;
                   7585:   color:white;
                   7586:   border: none;
                   7587:   background-repeat:no-repeat;
                   7588:   background-color:transparent;
1.757     schulted 7589: }
                   7590: 
1.915     droeschl 7591: ul.LC_funclist {
                   7592:     margin: 0;
                   7593:     padding: 0.5em 1em 0.5em 0;
                   7594: }
                   7595: 
1.933     droeschl 7596: ul.LC_funclist > li:first-child {
                   7597:     font-weight:bold; 
                   7598:     margin-left:0.8em;
                   7599: }
                   7600: 
1.915     droeschl 7601: ul.LC_funclist + ul.LC_funclist {
                   7602:     /* 
                   7603:        left border as a seperator if we have more than
                   7604:        one list 
                   7605:     */
                   7606:     border-left: 1px solid $sidebg;
                   7607:     /* 
                   7608:        this hides the left border behind the border of the 
                   7609:        outer box if element is wrapped to the next 'line' 
                   7610:     */
                   7611:     margin-left: -1px;
                   7612: }
                   7613: 
1.843     bisitz   7614: ul.LC_funclist li {
1.915     droeschl 7615:   display: inline;
1.782     bisitz   7616:   white-space: nowrap;
1.915     droeschl 7617:   margin: 0 0 0 25px;
                   7618:   line-height: 150%;
1.782     bisitz   7619: }
                   7620: 
1.974     wenzelju 7621: .LC_hidden {
                   7622:   display: none;
                   7623: }
                   7624: 
1.1030    www      7625: .LCmodal-overlay {
                   7626: 		position:fixed;
                   7627: 		top:0;
                   7628: 		right:0;
                   7629: 		bottom:0;
                   7630: 		left:0;
                   7631: 		height:100%;
                   7632: 		width:100%;
                   7633: 		margin:0;
                   7634: 		padding:0;
                   7635: 		background:#999;
                   7636: 		opacity:.75;
                   7637: 		filter: alpha(opacity=75);
                   7638: 		-moz-opacity: 0.75;
                   7639: 		z-index:101;
                   7640: }
                   7641: 
                   7642: * html .LCmodal-overlay {   
                   7643: 		position: absolute;
                   7644: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7645: }
                   7646: 
                   7647: .LCmodal-window {
                   7648: 		position:fixed;
                   7649: 		top:50%;
                   7650: 		left:50%;
                   7651: 		margin:0;
                   7652: 		padding:0;
                   7653: 		z-index:102;
                   7654: 	}
                   7655: 
                   7656: * html .LCmodal-window {
                   7657: 		position:absolute;
                   7658: }
                   7659: 
                   7660: .LCclose-window {
                   7661: 		position:absolute;
                   7662: 		width:32px;
                   7663: 		height:32px;
                   7664: 		right:8px;
                   7665: 		top:8px;
                   7666: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7667: 		text-indent:-99999px;
                   7668: 		overflow:hidden;
                   7669: 		cursor:pointer;
                   7670: }
                   7671: 
1.1100    raeburn  7672: /*
1.1231    damieng  7673:   styles used for response display
                   7674: */
                   7675: div.LC_radiofoil, div.LC_rankfoil {
                   7676:   margin: .5em 0em .5em 0em;
                   7677: }
                   7678: table.LC_itemgroup {
                   7679:   margin-top: 1em;
                   7680: }
                   7681: 
                   7682: /*
1.1100    raeburn  7683:   styles used by TTH when "Default set of options to pass to tth/m
                   7684:   when converting TeX" in course settings has been set
                   7685: 
                   7686:   option passed: -t
                   7687: 
                   7688: */
                   7689: 
                   7690: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7691: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7692: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7693: td div.norm {line-height:normal;}
                   7694: 
                   7695: /*
                   7696:   option passed -y3
                   7697: */
                   7698: 
                   7699: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7700: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7701: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7702: 
1.1230    damieng  7703: /*
                   7704:   sections with roles, for content only
                   7705: */
                   7706: section[class^="role-"] {
                   7707:   padding-left: 10px;
                   7708:   padding-right: 5px;
                   7709:   margin-top: 8px;
                   7710:   margin-bottom: 8px;
                   7711:   border: 1px solid #2A4;
                   7712:   border-radius: 5px;
                   7713:   box-shadow: 0px 1px 1px #BBB;
                   7714: }
                   7715: section[class^="role-"]>h1 {
                   7716:   position: relative;
                   7717:   margin: 0px;
                   7718:   padding-top: 10px;
                   7719:   padding-left: 40px;
                   7720: }
                   7721: section[class^="role-"]>h1:before {
                   7722:   position: absolute;
                   7723:   left: -5px;
                   7724:   top: 5px;
                   7725: }
                   7726: section.role-activity>h1:before {
                   7727:   content:url('/adm/daxe/images/section_icons/activity.png');
                   7728: }
                   7729: section.role-advice>h1:before {
                   7730:   content:url('/adm/daxe/images/section_icons/advice.png');
                   7731: }
                   7732: section.role-bibliography>h1:before {
                   7733:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   7734: }
                   7735: section.role-citation>h1:before {
                   7736:   content:url('/adm/daxe/images/section_icons/citation.png');
                   7737: }
                   7738: section.role-conclusion>h1:before {
                   7739:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   7740: }
                   7741: section.role-definition>h1:before {
                   7742:   content:url('/adm/daxe/images/section_icons/definition.png');
                   7743: }
                   7744: section.role-demonstration>h1:before {
                   7745:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   7746: }
                   7747: section.role-example>h1:before {
                   7748:   content:url('/adm/daxe/images/section_icons/example.png');
                   7749: }
                   7750: section.role-explanation>h1:before {
                   7751:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   7752: }
                   7753: section.role-introduction>h1:before {
                   7754:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   7755: }
                   7756: section.role-method>h1:before {
                   7757:   content:url('/adm/daxe/images/section_icons/method.png');
                   7758: }
                   7759: section.role-more_information>h1:before {
                   7760:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   7761: }
                   7762: section.role-objectives>h1:before {
                   7763:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   7764: }
                   7765: section.role-prerequisites>h1:before {
                   7766:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   7767: }
                   7768: section.role-remark>h1:before {
                   7769:   content:url('/adm/daxe/images/section_icons/remark.png');
                   7770: }
                   7771: section.role-reminder>h1:before {
                   7772:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   7773: }
                   7774: section.role-summary>h1:before {
                   7775:   content:url('/adm/daxe/images/section_icons/summary.png');
                   7776: }
                   7777: section.role-syntax>h1:before {
                   7778:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   7779: }
                   7780: section.role-warning>h1:before {
                   7781:   content:url('/adm/daxe/images/section_icons/warning.png');
                   7782: }
                   7783: 
1.343     albertel 7784: END
                   7785: }
                   7786: 
1.306     albertel 7787: =pod
                   7788: 
                   7789: =item * &headtag()
                   7790: 
                   7791: Returns a uniform footer for LON-CAPA web pages.
                   7792: 
1.307     albertel 7793: Inputs: $title - optional title for the head
                   7794:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7795:         $args - optional arguments
1.319     albertel 7796:             force_register - if is true call registerurl so the remote is 
                   7797:                              informed
1.415     albertel 7798:             redirect       -> array ref of
                   7799:                                    1- seconds before redirect occurs
                   7800:                                    2- url to redirect to
                   7801:                                    3- whether the side effect should occur
1.315     albertel 7802:                            (side effect of setting 
                   7803:                                $env{'internal.head.redirect'} to the url 
                   7804:                                redirected too)
1.352     albertel 7805:             domain         -> force to color decorate a page for a specific
                   7806:                                domain
                   7807:             function       -> force usage of a specific rolish color scheme
                   7808:             bgcolor        -> override the default page bgcolor
1.460     albertel 7809:             no_auto_mt_title
                   7810:                            -> prevent &mt()ing the title arg
1.464     albertel 7811: 
1.306     albertel 7812: =cut
                   7813: 
                   7814: sub headtag {
1.313     albertel 7815:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7816:     
1.363     albertel 7817:     my $function = $args->{'function'} || &get_users_function();
                   7818:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7819:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  7820:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7821:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7822: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7823: 		   #time(),
1.418     albertel 7824: 		   $env{'environment.color.timestamp'},
1.363     albertel 7825: 		   $function,$domain,$bgcolor);
                   7826: 
1.369     www      7827:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7828: 
1.308     albertel 7829:     my $result =
                   7830: 	'<head>'.
1.1160    raeburn  7831: 	&font_settings($args);
1.319     albertel 7832: 
1.1188    raeburn  7833:     my $inhibitprint;
                   7834:     if ($args->{'print_suppress'}) {
                   7835:         $inhibitprint = &print_suppression();
                   7836:     }
1.1064    raeburn  7837: 
1.461     albertel 7838:     if (!$args->{'frameset'}) {
                   7839: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7840:     }
1.962     droeschl 7841:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   7842:         $result .= Apache::lonxml::display_title();
1.319     albertel 7843:     }
1.436     albertel 7844:     if (!$args->{'no_nav_bar'} 
                   7845: 	&& !$args->{'only_body'}
                   7846: 	&& !$args->{'frameset'}) {
1.1154    raeburn  7847: 	$result .= &help_menu_js($httphost);
1.1032    www      7848:         $result.=&modal_window();
1.1038    www      7849:         $result.=&togglebox_script();
1.1034    www      7850:         $result.=&wishlist_window();
1.1041    www      7851:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7852:     } else {
                   7853:         if ($args->{'add_modal'}) {
                   7854:            $result.=&modal_window();
                   7855:         }
                   7856:         if ($args->{'add_wishlist'}) {
                   7857:            $result.=&wishlist_window();
                   7858:         }
1.1038    www      7859:         if ($args->{'add_togglebox'}) {
                   7860:            $result.=&togglebox_script();
                   7861:         }
1.1041    www      7862:         if ($args->{'add_progressbar'}) {
                   7863:            $result.=&LCprogressbarUpdate_script();
                   7864:         }
1.436     albertel 7865:     }
1.314     albertel 7866:     if (ref($args->{'redirect'})) {
1.414     albertel 7867: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7868: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7869: 	if (!$inhibit_continue) {
                   7870: 	    $env{'internal.head.redirect'} = $url;
                   7871: 	}
1.313     albertel 7872: 	$result.=<<ADDMETA
                   7873: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7874: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7875: ADDMETA
1.1210    raeburn  7876:     } else {
                   7877:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7878:             my $requrl = $env{'request.uri'};
                   7879:             if ($requrl eq '') {
                   7880:                 $requrl = $ENV{'REQUEST_URI'};
                   7881:                 $requrl =~ s/\?.+$//;
                   7882:             }
                   7883:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7884:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7885:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7886:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7887:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7888:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   7889:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7890:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7891:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   7892:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   7893:                             if (($newserver) && ($newserver ne $lonhost)) {
                   7894:                                 my $numsec = 5;
                   7895:                                 my $timeout = $numsec * 1000;
                   7896:                                 my ($newurl,$locknum,%locks,$msg);
                   7897:                                 if ($env{'request.role.adv'}) {
                   7898:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   7899:                                 }
                   7900:                                 my $disable_submit = 0;
                   7901:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   7902:                                     $disable_submit = 1;
                   7903:                                 }
                   7904:                                 if ($locknum) {
                   7905:                                     my @lockinfo = sort(values(%locks));
                   7906:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   7907:                                            join(", ",sort(values(%locks)))."\\n".
                   7908:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   7909:                                 } else {
                   7910:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   7911:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   7912:                                     }
                   7913:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   7914:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   7915:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   7916:                                         $newurl .= '&role='.$env{'request.role'};
                   7917:                                     }
                   7918:                                     if ($env{'request.symb'}) {
                   7919:                                         $newurl .= '&symb='.$env{'request.symb'};
                   7920:                                     } else {
                   7921:                                         $newurl .= '&origurl='.$requrl;
                   7922:                                     }
                   7923:                                 }
1.1222    damieng  7924:                                 &js_escape(\$msg);
1.1210    raeburn  7925:                                 $result.=<<OFFLOAD
                   7926: <meta http-equiv="pragma" content="no-cache" />
                   7927: <script type="text/javascript">
1.1215    raeburn  7928: // <![CDATA[
1.1210    raeburn  7929: function LC_Offload_Now() {
                   7930:     var dest = "$newurl";
                   7931:     if (dest != '') {
                   7932:         window.location.href="$newurl";
                   7933:     }
                   7934: }
1.1214    raeburn  7935: \$(document).ready(function () {
                   7936:     window.alert('$msg');
                   7937:     if ($disable_submit) {
1.1210    raeburn  7938:         \$(".LC_hwk_submit").prop("disabled", true);
                   7939:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  7940:     }
                   7941:     setTimeout('LC_Offload_Now()', $timeout);
                   7942: });
1.1215    raeburn  7943: // ]]>
1.1210    raeburn  7944: </script>
                   7945: OFFLOAD
                   7946:                             }
                   7947:                         }
                   7948:                     }
                   7949:                 }
                   7950:             }
                   7951:         }
1.313     albertel 7952:     }
1.306     albertel 7953:     if (!defined($title)) {
                   7954: 	$title = 'The LearningOnline Network with CAPA';
                   7955:     }
1.460     albertel 7956:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7957:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  7958: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   7959:     if (!$args->{'frameset'}) {
                   7960:         $result .= ' /';
                   7961:     }
                   7962:     $result .= '>' 
1.1064    raeburn  7963:         .$inhibitprint
1.414     albertel 7964: 	.$head_extra;
1.1137    raeburn  7965:     if ($env{'browser.mobile'}) {
                   7966:         $result .= '
                   7967: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   7968: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   7969:     }
1.962     droeschl 7970:     return $result.'</head>';
1.306     albertel 7971: }
                   7972: 
                   7973: =pod
                   7974: 
1.340     albertel 7975: =item * &font_settings()
                   7976: 
                   7977: Returns neccessary <meta> to set the proper encoding
                   7978: 
1.1160    raeburn  7979: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 7980: 
                   7981: =cut
                   7982: 
                   7983: sub font_settings {
1.1160    raeburn  7984:     my ($args) = @_;
1.340     albertel 7985:     my $headerstring='';
1.1160    raeburn  7986:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   7987:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  7988:         $headerstring.=
                   7989:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   7990:         if (!$args->{'frameset'}) {
                   7991: 	    $headerstring.= ' /';
                   7992:         }
                   7993: 	$headerstring .= '>'."\n";
1.340     albertel 7994:     }
                   7995:     return $headerstring;
                   7996: }
                   7997: 
1.341     albertel 7998: =pod
                   7999: 
1.1064    raeburn  8000: =item * &print_suppression()
                   8001: 
                   8002: In course context returns css which causes the body to be blank when media="print",
                   8003: if printout generation is unavailable for the current resource.
                   8004: 
                   8005: This could be because:
                   8006: 
                   8007: (a) printstartdate is in the future
                   8008: 
                   8009: (b) printenddate is in the past
                   8010: 
                   8011: (c) there is an active exam block with "printout"
                   8012: functionality blocked
                   8013: 
                   8014: Users with pav, pfo or evb privileges are exempt.
                   8015: 
                   8016: Inputs: none
                   8017: 
                   8018: =cut
                   8019: 
                   8020: 
                   8021: sub print_suppression {
                   8022:     my $noprint;
                   8023:     if ($env{'request.course.id'}) {
                   8024:         my $scope = $env{'request.course.id'};
                   8025:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8026:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8027:             return;
                   8028:         }
                   8029:         if ($env{'request.course.sec'} ne '') {
                   8030:             $scope .= "/$env{'request.course.sec'}";
                   8031:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8032:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8033:                 return;
1.1064    raeburn  8034:             }
                   8035:         }
                   8036:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8037:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  8038:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8039:         if ($blocked) {
                   8040:             my $checkrole = "cm./$cdom/$cnum";
                   8041:             if ($env{'request.course.sec'} ne '') {
                   8042:                 $checkrole .= "/$env{'request.course.sec'}";
                   8043:             }
                   8044:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8045:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8046:                 $noprint = 1;
                   8047:             }
                   8048:         }
                   8049:         unless ($noprint) {
                   8050:             my $symb = &Apache::lonnet::symbread();
                   8051:             if ($symb ne '') {
                   8052:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8053:                 if (ref($navmap)) {
                   8054:                     my $res = $navmap->getBySymb($symb);
                   8055:                     if (ref($res)) {
                   8056:                         if (!$res->resprintable()) {
                   8057:                             $noprint = 1;
                   8058:                         }
                   8059:                     }
                   8060:                 }
                   8061:             }
                   8062:         }
                   8063:         if ($noprint) {
                   8064:             return <<"ENDSTYLE";
                   8065: <style type="text/css" media="print">
                   8066:     body { display:none }
                   8067: </style>
                   8068: ENDSTYLE
                   8069:         }
                   8070:     }
                   8071:     return;
                   8072: }
                   8073: 
                   8074: =pod
                   8075: 
1.341     albertel 8076: =item * &xml_begin()
                   8077: 
                   8078: Returns the needed doctype and <html>
                   8079: 
                   8080: Inputs: none
                   8081: 
                   8082: =cut
                   8083: 
                   8084: sub xml_begin {
1.1168    raeburn  8085:     my ($is_frameset) = @_;
1.341     albertel 8086:     my $output='';
                   8087: 
                   8088:     if ($env{'browser.mathml'}) {
                   8089: 	$output='<?xml version="1.0"?>'
                   8090:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8091: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8092:             
                   8093: #	    .'<!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">] >'
                   8094: 	    .'<!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">'
                   8095:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8096: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  8097:     } elsif ($is_frameset) {
                   8098:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8099:                 '<html>'."\n";
1.341     albertel 8100:     } else {
1.1168    raeburn  8101: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8102:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8103:     }
                   8104:     return $output;
                   8105: }
1.340     albertel 8106: 
                   8107: =pod
                   8108: 
1.306     albertel 8109: =item * &start_page()
                   8110: 
                   8111: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8112: 
1.648     raeburn  8113: Inputs:
                   8114: 
                   8115: =over 4
                   8116: 
                   8117: $title - optional title for the page
                   8118: 
                   8119: $head_extra - optional extra HTML to incude inside the <head>
                   8120: 
                   8121: $args - additional optional args supported are:
                   8122: 
                   8123: =over 8
                   8124: 
                   8125:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8126:                                     arg on
1.814     bisitz   8127:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8128:              add_entries    -> additional attributes to add to the  <body>
                   8129:              domain         -> force to color decorate a page for a 
1.317     albertel 8130:                                     specific domain
1.648     raeburn  8131:              function       -> force usage of a specific rolish color
1.317     albertel 8132:                                     scheme
1.648     raeburn  8133:              redirect       -> see &headtag()
                   8134:              bgcolor        -> override the default page bg color
                   8135:              js_ready       -> return a string ready for being used in 
1.317     albertel 8136:                                     a javascript writeln
1.648     raeburn  8137:              html_encode    -> return a string ready for being used in 
1.320     albertel 8138:                                     a html attribute
1.648     raeburn  8139:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8140:                                     $forcereg arg
1.648     raeburn  8141:              frameset       -> if true will start with a <frameset>
1.330     albertel 8142:                                     rather than <body>
1.648     raeburn  8143:              skip_phases    -> hash ref of 
1.338     albertel 8144:                                     head -> skip the <html><head> generation
                   8145:                                     body -> skip all <body> generation
1.648     raeburn  8146:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8147:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8148:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1096    raeburn  8149:              group          -> includes the current group, if page is for a 
                   8150:                                specific group  
1.361     albertel 8151: 
1.648     raeburn  8152: =back
1.460     albertel 8153: 
1.648     raeburn  8154: =back
1.562     albertel 8155: 
1.306     albertel 8156: =cut
                   8157: 
                   8158: sub start_page {
1.309     albertel 8159:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8160:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8161: 
1.315     albertel 8162:     $env{'internal.start_page'}++;
1.1096    raeburn  8163:     my ($result,@advtools);
1.964     droeschl 8164: 
1.338     albertel 8165:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8166:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8167:     }
                   8168:     
                   8169:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8170: 	if ($args->{'frameset'}) {
                   8171: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8172: 						$args->{'add_entries'});
                   8173: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8174:         } else {
                   8175:             $result .=
                   8176:                 &bodytag($title, 
                   8177:                          $args->{'function'},       $args->{'add_entries'},
                   8178:                          $args->{'only_body'},      $args->{'domain'},
                   8179:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  8180:                          $args->{'bgcolor'},        $args,
                   8181:                          \@advtools);
1.831     bisitz   8182:         }
1.330     albertel 8183:     }
1.338     albertel 8184: 
1.315     albertel 8185:     if ($args->{'js_ready'}) {
1.713     kaisler  8186: 		$result = &js_ready($result);
1.315     albertel 8187:     }
1.320     albertel 8188:     if ($args->{'html_encode'}) {
1.713     kaisler  8189: 		$result = &html_encode($result);
                   8190:     }
                   8191: 
1.813     bisitz   8192:     # Preparation for new and consistent functionlist at top of screen
                   8193:     # if ($args->{'functionlist'}) {
                   8194:     #            $result .= &build_functionlist();
                   8195:     #}
                   8196: 
1.964     droeschl 8197:     # Don't add anything more if only_body wanted or in const space
                   8198:     return $result if    $args->{'only_body'} 
                   8199:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8200: 
                   8201:     #Breadcrumbs
1.758     kaisler  8202:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8203: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8204: 		#if any br links exists, add them to the breadcrumbs
                   8205: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8206: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8207: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8208: 			}
                   8209: 		}
1.1096    raeburn  8210:                 # if @advtools array contains items add then to the breadcrumbs
                   8211:                 if (@advtools > 0) {
                   8212:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8213:                 }
1.758     kaisler  8214: 
                   8215: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8216: 		if(exists($args->{'bread_crumbs_component'})){
                   8217: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
1.1237    raeburn  8218: 		} elsif ($args->{'crstype'} eq 'Placement') {
                   8219: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','','','','','','','','',
                   8220:                                                                        $args->{'crstype'});
                   8221:                 } else {
1.758     kaisler  8222: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   8223: 		}
1.320     albertel 8224:     }
1.315     albertel 8225:     return $result;
1.306     albertel 8226: }
                   8227: 
                   8228: sub end_page {
1.315     albertel 8229:     my ($args) = @_;
                   8230:     $env{'internal.end_page'}++;
1.330     albertel 8231:     my $result;
1.335     albertel 8232:     if ($args->{'discussion'}) {
                   8233: 	my ($target,$parser);
                   8234: 	if (ref($args->{'discussion'})) {
                   8235: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8236: 				$args->{'discussion'}{'parser'});
                   8237: 	}
                   8238: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8239:     }
1.330     albertel 8240:     if ($args->{'frameset'}) {
                   8241: 	$result .= '</frameset>';
                   8242:     } else {
1.635     raeburn  8243: 	$result .= &endbodytag($args);
1.330     albertel 8244:     }
1.1080    raeburn  8245:     unless ($args->{'notbody'}) {
                   8246:         $result .= "\n</html>";
                   8247:     }
1.330     albertel 8248: 
1.315     albertel 8249:     if ($args->{'js_ready'}) {
1.317     albertel 8250: 	$result = &js_ready($result);
1.315     albertel 8251:     }
1.335     albertel 8252: 
1.320     albertel 8253:     if ($args->{'html_encode'}) {
                   8254: 	$result = &html_encode($result);
                   8255:     }
1.335     albertel 8256: 
1.315     albertel 8257:     return $result;
                   8258: }
                   8259: 
1.1034    www      8260: sub wishlist_window {
                   8261:     return(<<'ENDWISHLIST');
1.1046    raeburn  8262: <script type="text/javascript">
1.1034    www      8263: // <![CDATA[
                   8264: // <!-- BEGIN LON-CAPA Internal
                   8265: function set_wishlistlink(title, path) {
                   8266:     if (!title) {
                   8267:         title = document.title;
                   8268:         title = title.replace(/^LON-CAPA /,'');
                   8269:     }
1.1175    raeburn  8270:     title = encodeURIComponent(title);
1.1203    raeburn  8271:     title = title.replace("'","\\\'");
1.1034    www      8272:     if (!path) {
                   8273:         path = location.pathname;
                   8274:     }
1.1175    raeburn  8275:     path = encodeURIComponent(path);
1.1203    raeburn  8276:     path = path.replace("'","\\\'");
1.1034    www      8277:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8278:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8279: }
                   8280: // END LON-CAPA Internal -->
                   8281: // ]]>
                   8282: </script>
                   8283: ENDWISHLIST
                   8284: }
                   8285: 
1.1030    www      8286: sub modal_window {
                   8287:     return(<<'ENDMODAL');
1.1046    raeburn  8288: <script type="text/javascript">
1.1030    www      8289: // <![CDATA[
                   8290: // <!-- BEGIN LON-CAPA Internal
                   8291: var modalWindow = {
                   8292: 	parent:"body",
                   8293: 	windowId:null,
                   8294: 	content:null,
                   8295: 	width:null,
                   8296: 	height:null,
                   8297: 	close:function()
                   8298: 	{
                   8299: 	        $(".LCmodal-window").remove();
                   8300: 	        $(".LCmodal-overlay").remove();
                   8301: 	},
                   8302: 	open:function()
                   8303: 	{
                   8304: 		var modal = "";
                   8305: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8306: 		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;\">";
                   8307: 		modal += this.content;
                   8308: 		modal += "</div>";	
                   8309: 
                   8310: 		$(this.parent).append(modal);
                   8311: 
                   8312: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8313: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8314: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8315: 	}
                   8316: };
1.1140    raeburn  8317: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8318: 	{
1.1203    raeburn  8319:                 source = source.replace("'","&#39;");
1.1030    www      8320: 		modalWindow.windowId = "myModal";
                   8321: 		modalWindow.width = width;
                   8322: 		modalWindow.height = height;
1.1196    raeburn  8323: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8324: 		modalWindow.open();
1.1208    raeburn  8325: 	};
1.1030    www      8326: // END LON-CAPA Internal -->
                   8327: // ]]>
                   8328: </script>
                   8329: ENDMODAL
                   8330: }
                   8331: 
                   8332: sub modal_link {
1.1140    raeburn  8333:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8334:     unless ($width) { $width=480; }
                   8335:     unless ($height) { $height=400; }
1.1031    www      8336:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  8337:     unless ($transparency) { $transparency='true'; }
                   8338: 
1.1074    raeburn  8339:     my $target_attr;
                   8340:     if (defined($target)) {
                   8341:         $target_attr = 'target="'.$target.'"';
                   8342:     }
                   8343:     return <<"ENDLINK";
1.1140    raeburn  8344: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8345:            $linktext</a>
                   8346: ENDLINK
1.1030    www      8347: }
                   8348: 
1.1032    www      8349: sub modal_adhoc_script {
                   8350:     my ($funcname,$width,$height,$content)=@_;
                   8351:     return (<<ENDADHOC);
1.1046    raeburn  8352: <script type="text/javascript">
1.1032    www      8353: // <![CDATA[
                   8354:         var $funcname = function()
                   8355:         {
                   8356:                 modalWindow.windowId = "myModal";
                   8357:                 modalWindow.width = $width;
                   8358:                 modalWindow.height = $height;
                   8359:                 modalWindow.content = '$content';
                   8360:                 modalWindow.open();
                   8361:         };  
                   8362: // ]]>
                   8363: </script>
                   8364: ENDADHOC
                   8365: }
                   8366: 
1.1041    www      8367: sub modal_adhoc_inner {
                   8368:     my ($funcname,$width,$height,$content)=@_;
                   8369:     my $innerwidth=$width-20;
                   8370:     $content=&js_ready(
1.1140    raeburn  8371:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   8372:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8373:                  $content.
1.1041    www      8374:                  &end_scrollbox().
1.1140    raeburn  8375:                  &end_page()
1.1041    www      8376:              );
                   8377:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8378: }
                   8379: 
                   8380: sub modal_adhoc_window {
                   8381:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8382:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8383:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8384: }
                   8385: 
                   8386: sub modal_adhoc_launch {
                   8387:     my ($funcname,$width,$height,$content)=@_;
                   8388:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8389: <script type="text/javascript">
                   8390: // <![CDATA[
                   8391: $funcname();
                   8392: // ]]>
                   8393: </script>
                   8394: ENDLAUNCH
                   8395: }
                   8396: 
                   8397: sub modal_adhoc_close {
                   8398:     return (<<ENDCLOSE);
                   8399: <script type="text/javascript">
                   8400: // <![CDATA[
                   8401: modalWindow.close();
                   8402: // ]]>
                   8403: </script>
                   8404: ENDCLOSE
                   8405: }
                   8406: 
1.1038    www      8407: sub togglebox_script {
                   8408:    return(<<ENDTOGGLE);
                   8409: <script type="text/javascript"> 
                   8410: // <![CDATA[
                   8411: function LCtoggleDisplay(id,hidetext,showtext) {
                   8412:    link = document.getElementById(id + "link").childNodes[0];
                   8413:    with (document.getElementById(id).style) {
                   8414:       if (display == "none" ) {
                   8415:           display = "inline";
                   8416:           link.nodeValue = hidetext;
                   8417:         } else {
                   8418:           display = "none";
                   8419:           link.nodeValue = showtext;
                   8420:        }
                   8421:    }
                   8422: }
                   8423: // ]]>
                   8424: </script>
                   8425: ENDTOGGLE
                   8426: }
                   8427: 
1.1039    www      8428: sub start_togglebox {
                   8429:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8430:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8431:     unless ($showtext) { $showtext=&mt('show'); }
                   8432:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8433:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8434:     return &start_data_table().
                   8435:            &start_data_table_header_row().
                   8436:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8437:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8438:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8439:            &end_data_table_header_row().
                   8440:            '<tr id="'.$id.'" style="display:none""><td>';
                   8441: }
                   8442: 
                   8443: sub end_togglebox {
                   8444:     return '</td></tr>'.&end_data_table();
                   8445: }
                   8446: 
1.1041    www      8447: sub LCprogressbar_script {
1.1045    www      8448:    my ($id)=@_;
1.1041    www      8449:    return(<<ENDPROGRESS);
                   8450: <script type="text/javascript">
                   8451: // <![CDATA[
1.1045    www      8452: \$('#progressbar$id').progressbar({
1.1041    www      8453:   value: 0,
                   8454:   change: function(event, ui) {
                   8455:     var newVal = \$(this).progressbar('option', 'value');
                   8456:     \$('.pblabel', this).text(LCprogressTxt);
                   8457:   }
                   8458: });
                   8459: // ]]>
                   8460: </script>
                   8461: ENDPROGRESS
                   8462: }
                   8463: 
                   8464: sub LCprogressbarUpdate_script {
                   8465:    return(<<ENDPROGRESSUPDATE);
                   8466: <style type="text/css">
                   8467: .ui-progressbar { position:relative; }
                   8468: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8469: </style>
                   8470: <script type="text/javascript">
                   8471: // <![CDATA[
1.1045    www      8472: var LCprogressTxt='---';
                   8473: 
                   8474: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8475:    LCprogressTxt=progresstext;
1.1045    www      8476:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8477: }
                   8478: // ]]>
                   8479: </script>
                   8480: ENDPROGRESSUPDATE
                   8481: }
                   8482: 
1.1042    www      8483: my $LClastpercent;
1.1045    www      8484: my $LCidcnt;
                   8485: my $LCcurrentid;
1.1042    www      8486: 
1.1041    www      8487: sub LCprogressbar {
1.1042    www      8488:     my ($r)=(@_);
                   8489:     $LClastpercent=0;
1.1045    www      8490:     $LCidcnt++;
                   8491:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8492:     my $starting=&mt('Starting');
                   8493:     my $content=(<<ENDPROGBAR);
1.1045    www      8494:   <div id="progressbar$LCcurrentid">
1.1041    www      8495:     <span class="pblabel">$starting</span>
                   8496:   </div>
                   8497: ENDPROGBAR
1.1045    www      8498:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8499: }
                   8500: 
                   8501: sub LCprogressbarUpdate {
1.1042    www      8502:     my ($r,$val,$text)=@_;
                   8503:     unless ($val) { 
                   8504:        if ($LClastpercent) {
                   8505:            $val=$LClastpercent;
                   8506:        } else {
                   8507:            $val=0;
                   8508:        }
                   8509:     }
1.1041    www      8510:     if ($val<0) { $val=0; }
                   8511:     if ($val>100) { $val=0; }
1.1042    www      8512:     $LClastpercent=$val;
1.1041    www      8513:     unless ($text) { $text=$val.'%'; }
                   8514:     $text=&js_ready($text);
1.1044    www      8515:     &r_print($r,<<ENDUPDATE);
1.1041    www      8516: <script type="text/javascript">
                   8517: // <![CDATA[
1.1045    www      8518: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8519: // ]]>
                   8520: </script>
                   8521: ENDUPDATE
1.1035    www      8522: }
                   8523: 
1.1042    www      8524: sub LCprogressbarClose {
                   8525:     my ($r)=@_;
                   8526:     $LClastpercent=0;
1.1044    www      8527:     &r_print($r,<<ENDCLOSE);
1.1042    www      8528: <script type="text/javascript">
                   8529: // <![CDATA[
1.1045    www      8530: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8531: // ]]>
                   8532: </script>
                   8533: ENDCLOSE
1.1044    www      8534: }
                   8535: 
                   8536: sub r_print {
                   8537:     my ($r,$to_print)=@_;
                   8538:     if ($r) {
                   8539:       $r->print($to_print);
                   8540:       $r->rflush();
                   8541:     } else {
                   8542:       print($to_print);
                   8543:     }
1.1042    www      8544: }
                   8545: 
1.320     albertel 8546: sub html_encode {
                   8547:     my ($result) = @_;
                   8548: 
1.322     albertel 8549:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8550:     
                   8551:     return $result;
                   8552: }
1.1044    www      8553: 
1.317     albertel 8554: sub js_ready {
                   8555:     my ($result) = @_;
                   8556: 
1.323     albertel 8557:     $result =~ s/[\n\r]/ /xmsg;
                   8558:     $result =~ s/\\/\\\\/xmsg;
                   8559:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8560:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8561:     
                   8562:     return $result;
                   8563: }
                   8564: 
1.315     albertel 8565: sub validate_page {
                   8566:     if (  exists($env{'internal.start_page'})
1.316     albertel 8567: 	  &&     $env{'internal.start_page'} > 1) {
                   8568: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8569: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8570: 				 $ENV{'request.filename'});
1.315     albertel 8571:     }
                   8572:     if (  exists($env{'internal.end_page'})
1.316     albertel 8573: 	  &&     $env{'internal.end_page'} > 1) {
                   8574: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8575: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8576: 				 $env{'request.filename'});
1.315     albertel 8577:     }
                   8578:     if (     exists($env{'internal.start_page'})
                   8579: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8580: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8581: 				 $env{'request.filename'});
1.315     albertel 8582:     }
                   8583:     if (   ! exists($env{'internal.start_page'})
                   8584: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8585: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8586: 				 $env{'request.filename'});
1.315     albertel 8587:     }
1.306     albertel 8588: }
1.315     albertel 8589: 
1.996     www      8590: 
                   8591: sub start_scrollbox {
1.1140    raeburn  8592:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8593:     unless ($outerwidth) { $outerwidth='520px'; }
                   8594:     unless ($width) { $width='500px'; }
                   8595:     unless ($height) { $height='200px'; }
1.1075    raeburn  8596:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8597:     if ($id ne '') {
1.1140    raeburn  8598:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  8599:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8600:     }
1.1075    raeburn  8601:     if ($bgcolor ne '') {
                   8602:         $tdcol = "background-color: $bgcolor;";
                   8603:     }
1.1137    raeburn  8604:     my $nicescroll_js;
                   8605:     if ($env{'browser.mobile'}) {
1.1140    raeburn  8606:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8607:     }
                   8608:     return <<"END";
                   8609: $nicescroll_js
                   8610: 
                   8611: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   8612: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   8613: END
                   8614: }
                   8615: 
                   8616: sub end_scrollbox {
                   8617:     return '</div></td></tr></table>';
                   8618: }
                   8619: 
                   8620: sub nicescroll_javascript {
                   8621:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8622:     my %options;
                   8623:     if (ref($cursor) eq 'HASH') {
                   8624:         %options = %{$cursor};
                   8625:     }
                   8626:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8627:         $options{'railalign'} = 'left';
                   8628:     }
                   8629:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8630:         my $function  = &get_users_function();
                   8631:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  8632:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  8633:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  8634:         }
1.1140    raeburn  8635:     }
                   8636:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8637:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  8638:             $options{'cursoropacity'}='1.0';
                   8639:         }
1.1140    raeburn  8640:     } else {
                   8641:         $options{'cursoropacity'}='1.0';
                   8642:     }
                   8643:     if ($options{'cursorfixedheight'} eq 'none') {
                   8644:         delete($options{'cursorfixedheight'});
                   8645:     } else {
                   8646:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8647:     }
                   8648:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8649:         delete($options{'railoffset'});
                   8650:     }
                   8651:     my @niceoptions;
                   8652:     while (my($key,$value) = each(%options)) {
                   8653:         if ($value =~ /^\{.+\}$/) {
                   8654:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  8655:         } else {
1.1140    raeburn  8656:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  8657:         }
1.1140    raeburn  8658:     }
                   8659:     my $nicescroll_js = '
1.1137    raeburn  8660: $(document).ready(
1.1140    raeburn  8661:       function() {
                   8662:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8663:       }
1.1137    raeburn  8664: );
                   8665: ';
1.1140    raeburn  8666:     if ($framecheck) {
                   8667:         $nicescroll_js .= '
                   8668: function expand_div(caller) {
                   8669:     if (top === self) {
                   8670:         document.getElementById("'.$id.'").style.width = "auto";
                   8671:         document.getElementById("'.$id.'").style.height = "auto";
                   8672:     } else {
                   8673:         try {
                   8674:             if (parent.frames) {
                   8675:                 if (parent.frames.length > 1) {
                   8676:                     var framesrc = parent.frames[1].location.href;
                   8677:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8678:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8679:                         document.getElementById("'.$id.'").style.width = "auto";
                   8680:                         document.getElementById("'.$id.'").style.height = "auto";
                   8681:                     }
                   8682:                 }
                   8683:             }
                   8684:         } catch (e) {
                   8685:             return;
                   8686:         }
1.1137    raeburn  8687:     }
1.1140    raeburn  8688:     return;
1.996     www      8689: }
1.1140    raeburn  8690: ';
                   8691:     }
                   8692:     if ($needjsready) {
                   8693:         $nicescroll_js = '
                   8694: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8695:     } else {
                   8696:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8697:     }
                   8698:     return $nicescroll_js;
1.996     www      8699: }
                   8700: 
1.318     albertel 8701: sub simple_error_page {
1.1150    bisitz   8702:     my ($r,$title,$msg,$args) = @_;
1.1151    raeburn  8703:     if (ref($args) eq 'HASH') {
                   8704:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8705:     } else {
                   8706:         $msg = &mt($msg);
                   8707:     }
1.1150    bisitz   8708: 
1.318     albertel 8709:     my $page =
                   8710: 	&Apache::loncommon::start_page($title).
1.1150    bisitz   8711: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8712: 	&Apache::loncommon::end_page();
                   8713:     if (ref($r)) {
                   8714: 	$r->print($page);
1.327     albertel 8715: 	return;
1.318     albertel 8716:     }
                   8717:     return $page;
                   8718: }
1.347     albertel 8719: 
                   8720: {
1.610     albertel 8721:     my @row_count;
1.961     onken    8722: 
                   8723:     sub start_data_table_count {
                   8724:         unshift(@row_count, 0);
                   8725:         return;
                   8726:     }
                   8727: 
                   8728:     sub end_data_table_count {
                   8729:         shift(@row_count);
                   8730:         return;
                   8731:     }
                   8732: 
1.347     albertel 8733:     sub start_data_table {
1.1018    raeburn  8734: 	my ($add_class,$id) = @_;
1.422     albertel 8735: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8736:         my $table_id;
                   8737:         if (defined($id)) {
                   8738:             $table_id = ' id="'.$id.'"';
                   8739:         }
1.961     onken    8740: 	&start_data_table_count();
1.1018    raeburn  8741: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8742:     }
                   8743: 
                   8744:     sub end_data_table {
1.961     onken    8745: 	&end_data_table_count();
1.389     albertel 8746: 	return '</table>'."\n";;
1.347     albertel 8747:     }
                   8748: 
                   8749:     sub start_data_table_row {
1.974     wenzelju 8750: 	my ($add_class, $id) = @_;
1.610     albertel 8751: 	$row_count[0]++;
                   8752: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8753: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8754:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8755:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8756:     }
1.471     banghart 8757:     
                   8758:     sub continue_data_table_row {
1.974     wenzelju 8759: 	my ($add_class, $id) = @_;
1.610     albertel 8760: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8761: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8762:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8763:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8764:     }
1.347     albertel 8765: 
                   8766:     sub end_data_table_row {
1.389     albertel 8767: 	return '</tr>'."\n";;
1.347     albertel 8768:     }
1.367     www      8769: 
1.421     albertel 8770:     sub start_data_table_empty_row {
1.707     bisitz   8771: #	$row_count[0]++;
1.421     albertel 8772: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8773:     }
                   8774: 
                   8775:     sub end_data_table_empty_row {
                   8776: 	return '</tr>'."\n";;
                   8777:     }
                   8778: 
1.367     www      8779:     sub start_data_table_header_row {
1.389     albertel 8780: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8781:     }
                   8782: 
                   8783:     sub end_data_table_header_row {
1.389     albertel 8784: 	return '</tr>'."\n";;
1.367     www      8785:     }
1.890     droeschl 8786: 
                   8787:     sub data_table_caption {
                   8788:         my $caption = shift;
                   8789:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8790:     }
1.347     albertel 8791: }
                   8792: 
1.548     albertel 8793: =pod
                   8794: 
                   8795: =item * &inhibit_menu_check($arg)
                   8796: 
                   8797: Checks for a inhibitmenu state and generates output to preserve it
                   8798: 
                   8799: Inputs:         $arg - can be any of
                   8800:                      - undef - in which case the return value is a string 
                   8801:                                to add  into arguments list of a uri
                   8802:                      - 'input' - in which case the return value is a HTML
                   8803:                                  <form> <input> field of type hidden to
                   8804:                                  preserve the value
                   8805:                      - a url - in which case the return value is the url with
                   8806:                                the neccesary cgi args added to preserve the
                   8807:                                inhibitmenu state
                   8808:                      - a ref to a url - no return value, but the string is
                   8809:                                         updated to include the neccessary cgi
                   8810:                                         args to preserve the inhibitmenu state
                   8811: 
                   8812: =cut
                   8813: 
                   8814: sub inhibit_menu_check {
                   8815:     my ($arg) = @_;
                   8816:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8817:     if ($arg eq 'input') {
                   8818: 	if ($env{'form.inhibitmenu'}) {
                   8819: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8820: 	} else {
                   8821: 	    return
                   8822: 	}
                   8823:     }
                   8824:     if ($env{'form.inhibitmenu'}) {
                   8825: 	if (ref($arg)) {
                   8826: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8827: 	} elsif ($arg eq '') {
                   8828: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8829: 	} else {
                   8830: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8831: 	}
                   8832:     }
                   8833:     if (!ref($arg)) {
                   8834: 	return $arg;
                   8835:     }
                   8836: }
                   8837: 
1.251     albertel 8838: ###############################################
1.182     matthew  8839: 
                   8840: =pod
                   8841: 
1.549     albertel 8842: =back
                   8843: 
                   8844: =head1 User Information Routines
                   8845: 
                   8846: =over 4
                   8847: 
1.405     albertel 8848: =item * &get_users_function()
1.182     matthew  8849: 
                   8850: Used by &bodytag to determine the current users primary role.
                   8851: Returns either 'student','coordinator','admin', or 'author'.
                   8852: 
                   8853: =cut
                   8854: 
                   8855: ###############################################
                   8856: sub get_users_function {
1.815     tempelho 8857:     my $function = 'norole';
1.818     tempelho 8858:     if ($env{'request.role'}=~/^(st)/) {
                   8859:         $function='student';
                   8860:     }
1.907     raeburn  8861:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8862:         $function='coordinator';
                   8863:     }
1.258     albertel 8864:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8865:         $function='admin';
                   8866:     }
1.826     bisitz   8867:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8868:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8869:         $function='author';
                   8870:     }
                   8871:     return $function;
1.54      www      8872: }
1.99      www      8873: 
                   8874: ###############################################
                   8875: 
1.233     raeburn  8876: =pod
                   8877: 
1.821     raeburn  8878: =item * &show_course()
                   8879: 
                   8880: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8881: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8882: 
                   8883: Inputs:
                   8884: None
                   8885: 
                   8886: Outputs:
                   8887: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8888: 
                   8889: =cut
                   8890: 
                   8891: ###############################################
                   8892: sub show_course {
                   8893:     my $course = !$env{'user.adv'};
                   8894:     if (!$env{'user.adv'}) {
                   8895:         foreach my $env (keys(%env)) {
                   8896:             next if ($env !~ m/^user\.priv\./);
                   8897:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8898:                 $course = 0;
                   8899:                 last;
                   8900:             }
                   8901:         }
                   8902:     }
                   8903:     return $course;
                   8904: }
                   8905: 
                   8906: ###############################################
                   8907: 
                   8908: =pod
                   8909: 
1.542     raeburn  8910: =item * &check_user_status()
1.274     raeburn  8911: 
                   8912: Determines current status of supplied role for a
                   8913: specific user. Roles can be active, previous or future.
                   8914: 
                   8915: Inputs: 
                   8916: user's domain, user's username, course's domain,
1.375     raeburn  8917: course's number, optional section ID.
1.274     raeburn  8918: 
                   8919: Outputs:
                   8920: role status: active, previous or future. 
                   8921: 
                   8922: =cut
                   8923: 
                   8924: sub check_user_status {
1.412     raeburn  8925:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8926:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  8927:     my @uroles = keys(%userinfo);
1.274     raeburn  8928:     my $srchstr;
                   8929:     my $active_chk = 'none';
1.412     raeburn  8930:     my $now = time;
1.274     raeburn  8931:     if (@uroles > 0) {
1.908     raeburn  8932:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8933:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8934:         } else {
1.412     raeburn  8935:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8936:         }
                   8937:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8938:             my $role_end = 0;
                   8939:             my $role_start = 0;
                   8940:             $active_chk = 'active';
1.412     raeburn  8941:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8942:                 $role_end = $1;
                   8943:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8944:                     $role_start = $1;
1.274     raeburn  8945:                 }
                   8946:             }
                   8947:             if ($role_start > 0) {
1.412     raeburn  8948:                 if ($now < $role_start) {
1.274     raeburn  8949:                     $active_chk = 'future';
                   8950:                 }
                   8951:             }
                   8952:             if ($role_end > 0) {
1.412     raeburn  8953:                 if ($now > $role_end) {
1.274     raeburn  8954:                     $active_chk = 'previous';
                   8955:                 }
                   8956:             }
                   8957:         }
                   8958:     }
                   8959:     return $active_chk;
                   8960: }
                   8961: 
                   8962: ###############################################
                   8963: 
                   8964: =pod
                   8965: 
1.405     albertel 8966: =item * &get_sections()
1.233     raeburn  8967: 
                   8968: Determines all the sections for a course including
                   8969: sections with students and sections containing other roles.
1.419     raeburn  8970: Incoming parameters: 
                   8971: 
                   8972: 1. domain
                   8973: 2. course number 
                   8974: 3. reference to array containing roles for which sections should 
                   8975: be gathered (optional).
                   8976: 4. reference to array containing status types for which sections 
                   8977: should be gathered (optional).
                   8978: 
                   8979: If the third argument is undefined, sections are gathered for any role. 
                   8980: If the fourth argument is undefined, sections are gathered for any status.
                   8981: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8982:  
1.374     raeburn  8983: Returns section hash (keys are section IDs, values are
                   8984: number of users in each section), subject to the
1.419     raeburn  8985: optional roles filter, optional status filter 
1.233     raeburn  8986: 
                   8987: =cut
                   8988: 
                   8989: ###############################################
                   8990: sub get_sections {
1.419     raeburn  8991:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8992:     if (!defined($cdom) || !defined($cnum)) {
                   8993:         my $cid =  $env{'request.course.id'};
                   8994: 
                   8995: 	return if (!defined($cid));
                   8996: 
                   8997:         $cdom = $env{'course.'.$cid.'.domain'};
                   8998:         $cnum = $env{'course.'.$cid.'.num'};
                   8999:     }
                   9000: 
                   9001:     my %sectioncount;
1.419     raeburn  9002:     my $now = time;
1.240     albertel 9003: 
1.1118    raeburn  9004:     my $check_students = 1;
                   9005:     my $only_students = 0;
                   9006:     if (ref($possible_roles) eq 'ARRAY') {
                   9007:         if (grep(/^st$/,@{$possible_roles})) {
                   9008:             if (@{$possible_roles} == 1) {
                   9009:                 $only_students = 1;
                   9010:             }
                   9011:         } else {
                   9012:             $check_students = 0;
                   9013:         }
                   9014:     }
                   9015: 
                   9016:     if ($check_students) { 
1.276     albertel 9017: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9018: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9019: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9020:         my $start_index = &Apache::loncoursedata::CL_START();
                   9021:         my $end_index = &Apache::loncoursedata::CL_END();
                   9022:         my $status;
1.366     albertel 9023: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9024: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9025: 				                     $data->[$status_index],
                   9026:                                                      $data->[$start_index],
                   9027:                                                      $data->[$end_index]);
                   9028:             if ($stu_status eq 'Active') {
                   9029:                 $status = 'active';
                   9030:             } elsif ($end < $now) {
                   9031:                 $status = 'previous';
                   9032:             } elsif ($start > $now) {
                   9033:                 $status = 'future';
                   9034:             } 
                   9035: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9036:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9037:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9038: 		    $sectioncount{$section}++;
                   9039:                 }
1.240     albertel 9040: 	    }
                   9041: 	}
                   9042:     }
1.1118    raeburn  9043:     if ($only_students) {
                   9044:         return %sectioncount;
                   9045:     }
1.240     albertel 9046:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9047:     foreach my $user (sort(keys(%courseroles))) {
                   9048: 	if ($user !~ /^(\w{2})/) { next; }
                   9049: 	my ($role) = ($user =~ /^(\w{2})/);
                   9050: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9051: 	my ($section,$status);
1.240     albertel 9052: 	if ($role eq 'cr' &&
                   9053: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9054: 	    $section=$1;
                   9055: 	}
                   9056: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9057: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9058:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9059:         if ($end == -1 && $start == -1) {
                   9060:             next; #deleted role
                   9061:         }
                   9062:         if (!defined($possible_status)) { 
                   9063:             $sectioncount{$section}++;
                   9064:         } else {
                   9065:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9066:                 $status = 'active';
                   9067:             } elsif ($end < $now) {
                   9068:                 $status = 'future';
                   9069:             } elsif ($start > $now) {
                   9070:                 $status = 'previous';
                   9071:             }
                   9072:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9073:                 $sectioncount{$section}++;
                   9074:             }
                   9075:         }
1.233     raeburn  9076:     }
1.366     albertel 9077:     return %sectioncount;
1.233     raeburn  9078: }
                   9079: 
1.274     raeburn  9080: ###############################################
1.294     raeburn  9081: 
                   9082: =pod
1.405     albertel 9083: 
                   9084: =item * &get_course_users()
                   9085: 
1.275     raeburn  9086: Retrieves usernames:domains for users in the specified course
                   9087: with specific role(s), and access status. 
                   9088: 
                   9089: Incoming parameters:
1.277     albertel 9090: 1. course domain
                   9091: 2. course number
                   9092: 3. access status: users must have - either active, 
1.275     raeburn  9093: previous, future, or all.
1.277     albertel 9094: 4. reference to array of permissible roles
1.288     raeburn  9095: 5. reference to array of section restrictions (optional)
                   9096: 6. reference to results object (hash of hashes).
                   9097: 7. reference to optional userdata hash
1.609     raeburn  9098: 8. reference to optional statushash
1.630     raeburn  9099: 9. flag if privileged users (except those set to unhide in
                   9100:    course settings) should be excluded    
1.609     raeburn  9101: Keys of top level results hash are roles.
1.275     raeburn  9102: Keys of inner hashes are username:domain, with 
                   9103: values set to access type.
1.288     raeburn  9104: Optional userdata hash returns an array with arguments in the 
                   9105: same order as loncoursedata::get_classlist() for student data.
                   9106: 
1.609     raeburn  9107: Optional statushash returns
                   9108: 
1.288     raeburn  9109: Entries for end, start, section and status are blank because
                   9110: of the possibility of multiple values for non-student roles.
                   9111: 
1.275     raeburn  9112: =cut
1.405     albertel 9113: 
1.275     raeburn  9114: ###############################################
1.405     albertel 9115: 
1.275     raeburn  9116: sub get_course_users {
1.630     raeburn  9117:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9118:     my %idx = ();
1.419     raeburn  9119:     my %seclists;
1.288     raeburn  9120: 
                   9121:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9122:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9123:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9124:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9125:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9126:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9127:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9128:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9129: 
1.290     albertel 9130:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9131:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9132:         my $now = time;
1.277     albertel 9133:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9134:             my $match = 0;
1.412     raeburn  9135:             my $secmatch = 0;
1.419     raeburn  9136:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9137:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9138:             if ($section eq '') {
                   9139:                 $section = 'none';
                   9140:             }
1.291     albertel 9141:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9142:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9143:                     $secmatch = 1;
                   9144:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9145:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9146:                         $secmatch = 1;
                   9147:                     }
                   9148:                 } else {  
1.419     raeburn  9149: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9150: 		        $secmatch = 1;
                   9151:                     }
1.290     albertel 9152: 		}
1.412     raeburn  9153:                 if (!$secmatch) {
                   9154:                     next;
                   9155:                 }
1.419     raeburn  9156:             }
1.275     raeburn  9157:             if (defined($$types{'active'})) {
1.288     raeburn  9158:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9159:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9160:                     $match = 1;
1.275     raeburn  9161:                 }
                   9162:             }
                   9163:             if (defined($$types{'previous'})) {
1.609     raeburn  9164:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9165:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9166:                     $match = 1;
1.275     raeburn  9167:                 }
                   9168:             }
                   9169:             if (defined($$types{'future'})) {
1.609     raeburn  9170:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9171:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9172:                     $match = 1;
1.275     raeburn  9173:                 }
                   9174:             }
1.609     raeburn  9175:             if ($match) {
                   9176:                 push(@{$seclists{$student}},$section);
                   9177:                 if (ref($userdata) eq 'HASH') {
                   9178:                     $$userdata{$student} = $$classlist{$student};
                   9179:                 }
                   9180:                 if (ref($statushash) eq 'HASH') {
                   9181:                     $statushash->{$student}{'st'}{$section} = $status;
                   9182:                 }
1.288     raeburn  9183:             }
1.275     raeburn  9184:         }
                   9185:     }
1.412     raeburn  9186:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9187:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9188:         my $now = time;
1.609     raeburn  9189:         my %displaystatus = ( previous => 'Expired',
                   9190:                               active   => 'Active',
                   9191:                               future   => 'Future',
                   9192:                             );
1.1121    raeburn  9193:         my (%nothide,@possdoms);
1.630     raeburn  9194:         if ($hidepriv) {
                   9195:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9196:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9197:                 if ($user !~ /:/) {
                   9198:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9199:                 } else {
                   9200:                     $nothide{$user} = 1;
                   9201:                 }
                   9202:             }
1.1121    raeburn  9203:             my @possdoms = ($cdom);
                   9204:             if ($coursehash{'checkforpriv'}) {
                   9205:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9206:             }
1.630     raeburn  9207:         }
1.439     raeburn  9208:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9209:             my $match = 0;
1.412     raeburn  9210:             my $secmatch = 0;
1.439     raeburn  9211:             my $status;
1.412     raeburn  9212:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9213:             $user =~ s/:$//;
1.439     raeburn  9214:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9215:             if ($end == -1 || $start == -1) {
                   9216:                 next;
                   9217:             }
                   9218:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9219:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9220:                 my ($uname,$udom) = split(/:/,$user);
                   9221:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9222:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9223:                         $secmatch = 1;
                   9224:                     } elsif ($usec eq '') {
1.420     albertel 9225:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9226:                             $secmatch = 1;
                   9227:                         }
                   9228:                     } else {
                   9229:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9230:                             $secmatch = 1;
                   9231:                         }
                   9232:                     }
                   9233:                     if (!$secmatch) {
                   9234:                         next;
                   9235:                     }
1.288     raeburn  9236:                 }
1.419     raeburn  9237:                 if ($usec eq '') {
                   9238:                     $usec = 'none';
                   9239:                 }
1.275     raeburn  9240:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9241:                     if ($hidepriv) {
1.1121    raeburn  9242:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9243:                             (!$nothide{$uname.':'.$udom})) {
                   9244:                             next;
                   9245:                         }
                   9246:                     }
1.503     raeburn  9247:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9248:                         $status = 'previous';
                   9249:                     } elsif ($start > $now) {
                   9250:                         $status = 'future';
                   9251:                     } else {
                   9252:                         $status = 'active';
                   9253:                     }
1.277     albertel 9254:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9255:                         if ($status eq $type) {
1.420     albertel 9256:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9257:                                 push(@{$$users{$role}{$user}},$type);
                   9258:                             }
1.288     raeburn  9259:                             $match = 1;
                   9260:                         }
                   9261:                     }
1.419     raeburn  9262:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9263:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9264: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9265:                         }
1.420     albertel 9266:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9267:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9268:                         }
1.609     raeburn  9269:                         if (ref($statushash) eq 'HASH') {
                   9270:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9271:                         }
1.275     raeburn  9272:                     }
                   9273:                 }
                   9274:             }
                   9275:         }
1.290     albertel 9276:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9277:             if ((defined($cdom)) && (defined($cnum))) {
                   9278:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9279:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9280:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9281:                     next if ($owner eq '');
                   9282:                     my ($ownername,$ownerdom);
                   9283:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9284:                         $ownername = $1;
                   9285:                         $ownerdom = $2;
                   9286:                     } else {
                   9287:                         $ownername = $owner;
                   9288:                         $ownerdom = $cdom;
                   9289:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9290:                     }
                   9291:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9292:                     if (defined($userdata) && 
1.609     raeburn  9293: 			!exists($$userdata{$owner})) {
                   9294: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9295:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9296:                             push(@{$seclists{$owner}},'none');
                   9297:                         }
                   9298:                         if (ref($statushash) eq 'HASH') {
                   9299:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9300:                         }
1.290     albertel 9301: 		    }
1.279     raeburn  9302:                 }
                   9303:             }
                   9304:         }
1.419     raeburn  9305:         foreach my $user (keys(%seclists)) {
                   9306:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9307:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9308:         }
1.275     raeburn  9309:     }
                   9310:     return;
                   9311: }
                   9312: 
1.288     raeburn  9313: sub get_user_info {
                   9314:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9315:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9316: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9317:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9318:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9319:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9320:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9321:     return;
                   9322: }
1.275     raeburn  9323: 
1.472     raeburn  9324: ###############################################
                   9325: 
                   9326: =pod
                   9327: 
                   9328: =item * &get_user_quota()
                   9329: 
1.1134    raeburn  9330: Retrieves quota assigned for storage of user files.
                   9331: Default is to report quota for portfolio files.
1.472     raeburn  9332: 
                   9333: Incoming parameters:
                   9334: 1. user's username
                   9335: 2. user's domain
1.1134    raeburn  9336: 3. quota name - portfolio, author, or course
1.1136    raeburn  9337:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  9338: 4. crstype - official, unofficial, textbook, placement or community, 
                   9339:    if quota name is course
1.472     raeburn  9340: 
                   9341: Returns:
1.1163    raeburn  9342: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9343: 2. (Optional) Type of setting: custom or default
                   9344:    (individually assigned or default for user's 
                   9345:    institutional status).
                   9346: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9347:    or student - types as defined in localenroll::inst_usertypes 
                   9348:    for user's domain, which determines default quota for user.
                   9349: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9350: 
                   9351: If a value has been stored in the user's environment, 
1.536     raeburn  9352: it will return that, otherwise it returns the maximal default
1.1134    raeburn  9353: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9354: 
                   9355: =cut
                   9356: 
                   9357: ###############################################
                   9358: 
                   9359: 
                   9360: sub get_user_quota {
1.1136    raeburn  9361:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9362:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9363:     if (!defined($udom)) {
                   9364:         $udom = $env{'user.domain'};
                   9365:     }
                   9366:     if (!defined($uname)) {
                   9367:         $uname = $env{'user.name'};
                   9368:     }
                   9369:     if (($udom eq '' || $uname eq '') ||
                   9370:         ($udom eq 'public') && ($uname eq 'public')) {
                   9371:         $quota = 0;
1.536     raeburn  9372:         $quotatype = 'default';
                   9373:         $defquota = 0; 
1.472     raeburn  9374:     } else {
1.536     raeburn  9375:         my $inststatus;
1.1134    raeburn  9376:         if ($quotaname eq 'course') {
                   9377:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9378:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9379:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9380:             } else {
                   9381:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9382:                 $quota = $cenv{'internal.uploadquota'};
                   9383:             }
1.536     raeburn  9384:         } else {
1.1134    raeburn  9385:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9386:                 if ($quotaname eq 'author') {
                   9387:                     $quota = $env{'environment.authorquota'};
                   9388:                 } else {
                   9389:                     $quota = $env{'environment.portfolioquota'};
                   9390:                 }
                   9391:                 $inststatus = $env{'environment.inststatus'};
                   9392:             } else {
                   9393:                 my %userenv = 
                   9394:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9395:                                          'authorquota','inststatus'],$udom,$uname);
                   9396:                 my ($tmp) = keys(%userenv);
                   9397:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9398:                     if ($quotaname eq 'author') {
                   9399:                         $quota = $userenv{'authorquota'};
                   9400:                     } else {
                   9401:                         $quota = $userenv{'portfolioquota'};
                   9402:                     }
                   9403:                     $inststatus = $userenv{'inststatus'};
                   9404:                 } else {
                   9405:                     undef(%userenv);
                   9406:                 }
                   9407:             }
                   9408:         }
                   9409:         if ($quota eq '' || wantarray) {
                   9410:             if ($quotaname eq 'course') {
                   9411:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  9412:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  9413:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   9414:                     ($crstype eq 'placement')) { 
1.1136    raeburn  9415:                     $defquota = $domdefs{$crstype.'quota'};
                   9416:                 }
                   9417:                 if ($defquota eq '') {
                   9418:                     $defquota = 500;
                   9419:                 }
1.1134    raeburn  9420:             } else {
                   9421:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9422:             }
                   9423:             if ($quota eq '') {
                   9424:                 $quota = $defquota;
                   9425:                 $quotatype = 'default';
                   9426:             } else {
                   9427:                 $quotatype = 'custom';
                   9428:             }
1.472     raeburn  9429:         }
                   9430:     }
1.536     raeburn  9431:     if (wantarray) {
                   9432:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9433:     } else {
                   9434:         return $quota;
                   9435:     }
1.472     raeburn  9436: }
                   9437: 
                   9438: ###############################################
                   9439: 
                   9440: =pod
                   9441: 
                   9442: =item * &default_quota()
                   9443: 
1.536     raeburn  9444: Retrieves default quota assigned for storage of user portfolio files,
                   9445: given an (optional) user's institutional status.
1.472     raeburn  9446: 
                   9447: Incoming parameters:
1.1142    raeburn  9448: 
1.472     raeburn  9449: 1. domain
1.536     raeburn  9450: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9451:    status types (e.g., faculty, staff, student etc.)
                   9452:    which apply to the user for whom the default is being retrieved.
                   9453:    If the institutional status string in undefined, the domain
1.1134    raeburn  9454:    default quota will be returned.
                   9455: 3.  quota name - portfolio, author, or course
                   9456:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9457: 
                   9458: Returns:
1.1142    raeburn  9459: 
1.1163    raeburn  9460: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9461: 2. (Optional) institutional type which determined the value of the
                   9462:    default quota.
1.472     raeburn  9463: 
                   9464: If a value has been stored in the domain's configuration db,
                   9465: it will return that, otherwise it returns 20 (for backwards 
                   9466: compatibility with domains which have not set up a configuration
1.1163    raeburn  9467: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9468: 
1.536     raeburn  9469: If the user's status includes multiple types (e.g., staff and student),
                   9470: the largest default quota which applies to the user determines the
                   9471: default quota returned.
                   9472: 
1.472     raeburn  9473: =cut
                   9474: 
                   9475: ###############################################
                   9476: 
                   9477: 
                   9478: sub default_quota {
1.1134    raeburn  9479:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9480:     my ($defquota,$settingstatus);
                   9481:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9482:                                             ['quotas'],$udom);
1.1134    raeburn  9483:     my $key = 'defaultquota';
                   9484:     if ($quotaname eq 'author') {
                   9485:         $key = 'authorquota';
                   9486:     }
1.622     raeburn  9487:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9488:         if ($inststatus ne '') {
1.765     raeburn  9489:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9490:             foreach my $item (@statuses) {
1.1134    raeburn  9491:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9492:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9493:                         if ($defquota eq '') {
1.1134    raeburn  9494:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9495:                             $settingstatus = $item;
1.1134    raeburn  9496:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9497:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9498:                             $settingstatus = $item;
                   9499:                         }
                   9500:                     }
1.1134    raeburn  9501:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9502:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9503:                         if ($defquota eq '') {
                   9504:                             $defquota = $quotahash{'quotas'}{$item};
                   9505:                             $settingstatus = $item;
                   9506:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9507:                             $defquota = $quotahash{'quotas'}{$item};
                   9508:                             $settingstatus = $item;
                   9509:                         }
1.536     raeburn  9510:                     }
                   9511:                 }
                   9512:             }
                   9513:         }
                   9514:         if ($defquota eq '') {
1.1134    raeburn  9515:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9516:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9517:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9518:                 $defquota = $quotahash{'quotas'}{'default'};
                   9519:             }
1.536     raeburn  9520:             $settingstatus = 'default';
1.1139    raeburn  9521:             if ($defquota eq '') {
                   9522:                 if ($quotaname eq 'author') {
                   9523:                     $defquota = 500;
                   9524:                 }
                   9525:             }
1.536     raeburn  9526:         }
                   9527:     } else {
                   9528:         $settingstatus = 'default';
1.1134    raeburn  9529:         if ($quotaname eq 'author') {
                   9530:             $defquota = 500;
                   9531:         } else {
                   9532:             $defquota = 20;
                   9533:         }
1.536     raeburn  9534:     }
                   9535:     if (wantarray) {
                   9536:         return ($defquota,$settingstatus);
1.472     raeburn  9537:     } else {
1.536     raeburn  9538:         return $defquota;
1.472     raeburn  9539:     }
                   9540: }
                   9541: 
1.1135    raeburn  9542: ###############################################
                   9543: 
                   9544: =pod
                   9545: 
1.1136    raeburn  9546: =item * &excess_filesize_warning()
1.1135    raeburn  9547: 
                   9548: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  9549: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  9550: space to be exceeded.
1.1136    raeburn  9551: 
                   9552: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  9553: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  9554: 
1.1165    raeburn  9555: Inputs: 7 
1.1136    raeburn  9556: 1. username or coursenum
1.1135    raeburn  9557: 2. domain
1.1136    raeburn  9558: 3. context ('author' or 'course')
1.1135    raeburn  9559: 4. filename of file for which action is being requested
                   9560: 5. filesize (kB) of file
                   9561: 6. action being taken: copy or upload.
1.1237    raeburn  9562: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  9563: 
                   9564: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  9565:          otherwise return null.
                   9566: 
                   9567: =back
1.1135    raeburn  9568: 
                   9569: =cut
                   9570: 
1.1136    raeburn  9571: sub excess_filesize_warning {
1.1165    raeburn  9572:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  9573:     my $current_disk_usage = 0;
1.1165    raeburn  9574:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  9575:     if ($context eq 'author') {
                   9576:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9577:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9578:     } else {
                   9579:         foreach my $subdir ('docs','supplemental') {
                   9580:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9581:         }
                   9582:     }
1.1135    raeburn  9583:     $disk_quota = int($disk_quota * 1000);
                   9584:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   9585:         return '<p class="LC_warning">'.
1.1135    raeburn  9586:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   9587:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9588:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  9589:                             $disk_quota,$current_disk_usage).
                   9590:                '</p>';
                   9591:     }
                   9592:     return;
                   9593: }
                   9594: 
                   9595: ###############################################
                   9596: 
                   9597: 
1.1136    raeburn  9598: 
                   9599: 
1.384     raeburn  9600: sub get_secgrprole_info {
                   9601:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9602:     my %sections_count = &get_sections($cdom,$cnum);
                   9603:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9604:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9605:     my @groups = sort(keys(%curr_groups));
                   9606:     my $allroles = [];
                   9607:     my $rolehash;
                   9608:     my $accesshash = {
                   9609:                      active => 'Currently has access',
                   9610:                      future => 'Will have future access',
                   9611:                      previous => 'Previously had access',
                   9612:                   };
                   9613:     if ($needroles) {
                   9614:         $rolehash = {'all' => 'all'};
1.385     albertel 9615:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9616: 	if (&Apache::lonnet::error(%user_roles)) {
                   9617: 	    undef(%user_roles);
                   9618: 	}
                   9619:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9620:             my ($role)=split(/\:/,$item,2);
                   9621:             if ($role eq 'cr') { next; }
                   9622:             if ($role =~ /^cr/) {
                   9623:                 $$rolehash{$role} = (split('/',$role))[3];
                   9624:             } else {
                   9625:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9626:             }
                   9627:         }
                   9628:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9629:             push(@{$allroles},$key);
                   9630:         }
                   9631:         push (@{$allroles},'st');
                   9632:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9633:     }
                   9634:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9635: }
                   9636: 
1.555     raeburn  9637: sub user_picker {
1.994     raeburn  9638:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  9639:     my $currdom = $dom;
                   9640:     my %curr_selected = (
                   9641:                         srchin => 'dom',
1.580     raeburn  9642:                         srchby => 'lastname',
1.555     raeburn  9643:                       );
                   9644:     my $srchterm;
1.625     raeburn  9645:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9646:         if ($srch->{'srchby'} ne '') {
                   9647:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9648:         }
                   9649:         if ($srch->{'srchin'} ne '') {
                   9650:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9651:         }
                   9652:         if ($srch->{'srchtype'} ne '') {
                   9653:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9654:         }
                   9655:         if ($srch->{'srchdomain'} ne '') {
                   9656:             $currdom = $srch->{'srchdomain'};
                   9657:         }
                   9658:         $srchterm = $srch->{'srchterm'};
                   9659:     }
1.1222    damieng  9660:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  9661:                     'usr'       => 'Search criteria',
1.563     raeburn  9662:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9663:                     'uname'     => 'username',
                   9664:                     'lastname'  => 'last name',
1.555     raeburn  9665:                     'lastfirst' => 'last name, first name',
1.558     albertel 9666:                     'crs'       => 'in this course',
1.576     raeburn  9667:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9668:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9669:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9670:                     'exact'     => 'is',
                   9671:                     'contains'  => 'contains',
1.569     raeburn  9672:                     'begins'    => 'begins with',
1.1222    damieng  9673:                                        );
                   9674:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  9675:                     'youm'      => "You must include some text to search for.",
                   9676:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9677:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9678:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9679:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9680:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9681:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9682:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9683:                                        );
1.1222    damieng  9684:     &html_escape(\%html_lt);
                   9685:     &js_escape(\%js_lt);
1.563     raeburn  9686:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   9687:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9688: 
                   9689:     my @srchins = ('crs','dom','alc','instd');
                   9690: 
                   9691:     foreach my $option (@srchins) {
                   9692:         # FIXME 'alc' option unavailable until 
                   9693:         #       loncreateuser::print_user_query_page()
                   9694:         #       has been completed.
                   9695:         next if ($option eq 'alc');
1.880     raeburn  9696:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9697:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  9698:         if ($curr_selected{'srchin'} eq $option) {
                   9699:             $srchinsel .= ' 
1.1222    damieng  9700:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  9701:         } else {
                   9702:             $srchinsel .= '
1.1222    damieng  9703:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  9704:         }
1.555     raeburn  9705:     }
1.563     raeburn  9706:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9707: 
                   9708:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9709:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9710:         if ($curr_selected{'srchby'} eq $option) {
                   9711:             $srchbysel .= '
1.1222    damieng  9712:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9713:         } else {
                   9714:             $srchbysel .= '
1.1222    damieng  9715:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9716:          }
                   9717:     }
                   9718:     $srchbysel .= "\n  </select>\n";
                   9719: 
                   9720:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9721:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9722:         if ($curr_selected{'srchtype'} eq $option) {
                   9723:             $srchtypesel .= '
1.1222    damieng  9724:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9725:         } else {
                   9726:             $srchtypesel .= '
1.1222    damieng  9727:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9728:         }
                   9729:     }
                   9730:     $srchtypesel .= "\n  </select>\n";
                   9731: 
1.558     albertel 9732:     my ($newuserscript,$new_user_create);
1.994     raeburn  9733:     my $context_dom = $env{'request.role.domain'};
                   9734:     if ($context eq 'requestcrs') {
                   9735:         if ($env{'form.coursedom'} ne '') { 
                   9736:             $context_dom = $env{'form.coursedom'};
                   9737:         }
                   9738:     }
1.556     raeburn  9739:     if ($forcenewuser) {
1.576     raeburn  9740:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9741:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9742:                 if ($cancreate) {
                   9743:                     $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>';
                   9744:                 } else {
1.799     bisitz   9745:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9746:                     my %usertypetext = (
                   9747:                         official   => 'institutional',
                   9748:                         unofficial => 'non-institutional',
                   9749:                     );
1.799     bisitz   9750:                     $new_user_create = '<p class="LC_warning">'
                   9751:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9752:                                       .' '
                   9753:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9754:                                           ,'<a href="'.$helplink.'">','</a>')
                   9755:                                       .'</p><br />';
1.627     raeburn  9756:                 }
1.576     raeburn  9757:             }
                   9758:         }
                   9759: 
1.556     raeburn  9760:         $newuserscript = <<"ENDSCRIPT";
                   9761: 
1.570     raeburn  9762: function setSearch(createnew,callingForm) {
1.556     raeburn  9763:     if (createnew == 1) {
1.570     raeburn  9764:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9765:             if (callingForm.srchby.options[i].value == 'uname') {
                   9766:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9767:             }
                   9768:         }
1.570     raeburn  9769:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9770:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9771: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9772:             }
                   9773:         }
1.570     raeburn  9774:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9775:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9776:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9777:             }
                   9778:         }
1.570     raeburn  9779:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9780:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9781:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9782:             }
                   9783:         }
                   9784:     }
                   9785: }
                   9786: ENDSCRIPT
1.558     albertel 9787: 
1.556     raeburn  9788:     }
                   9789: 
1.555     raeburn  9790:     my $output = <<"END_BLOCK";
1.556     raeburn  9791: <script type="text/javascript">
1.824     bisitz   9792: // <![CDATA[
1.570     raeburn  9793: function validateEntry(callingForm) {
1.558     albertel 9794: 
1.556     raeburn  9795:     var checkok = 1;
1.558     albertel 9796:     var srchin;
1.570     raeburn  9797:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9798: 	if ( callingForm.srchin[i].checked ) {
                   9799: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9800: 	}
                   9801:     }
                   9802: 
1.570     raeburn  9803:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9804:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9805:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9806:     var srchterm =  callingForm.srchterm.value;
                   9807:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9808:     var msg = "";
                   9809: 
                   9810:     if (srchterm == "") {
                   9811:         checkok = 0;
1.1222    damieng  9812:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  9813:     }
                   9814: 
1.569     raeburn  9815:     if (srchtype== 'begins') {
                   9816:         if (srchterm.length < 2) {
                   9817:             checkok = 0;
1.1222    damieng  9818:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  9819:         }
                   9820:     }
                   9821: 
1.556     raeburn  9822:     if (srchtype== 'contains') {
                   9823:         if (srchterm.length < 3) {
                   9824:             checkok = 0;
1.1222    damieng  9825:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  9826:         }
                   9827:     }
                   9828:     if (srchin == 'instd') {
                   9829:         if (srchdomain == '') {
                   9830:             checkok = 0;
1.1222    damieng  9831:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  9832:         }
                   9833:     }
                   9834:     if (srchin == 'dom') {
                   9835:         if (srchdomain == '') {
                   9836:             checkok = 0;
1.1222    damieng  9837:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  9838:         }
                   9839:     }
                   9840:     if (srchby == 'lastfirst') {
                   9841:         if (srchterm.indexOf(",") == -1) {
                   9842:             checkok = 0;
1.1222    damieng  9843:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  9844:         }
                   9845:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9846:             checkok = 0;
1.1222    damieng  9847:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  9848:         }
                   9849:     }
                   9850:     if (checkok == 0) {
1.1222    damieng  9851:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  9852:         return;
                   9853:     }
                   9854:     if (checkok == 1) {
1.570     raeburn  9855:         callingForm.submit();
1.556     raeburn  9856:     }
                   9857: }
                   9858: 
                   9859: $newuserscript
                   9860: 
1.824     bisitz   9861: // ]]>
1.556     raeburn  9862: </script>
1.558     albertel 9863: 
                   9864: $new_user_create
                   9865: 
1.555     raeburn  9866: END_BLOCK
1.558     albertel 9867: 
1.876     raeburn  9868:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  9869:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  9870:                $domform.
                   9871:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  9872:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  9873:                $srchbysel.
                   9874:                $srchtypesel. 
                   9875:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9876:                $srchinsel.
                   9877:                &Apache::lonhtmlcommon::row_closure(1). 
                   9878:                &Apache::lonhtmlcommon::end_pick_box().
                   9879:                '<br />';
1.555     raeburn  9880:     return $output;
                   9881: }
                   9882: 
1.612     raeburn  9883: sub user_rule_check {
1.615     raeburn  9884:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  9885:     my ($response,%inst_response);
1.612     raeburn  9886:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  9887:         if (keys(%{$usershash}) > 1) {
                   9888:             my (%by_username,%by_id,%userdoms);
                   9889:             my $checkid; 
                   9890:             if (ref($checks) eq 'HASH') {
                   9891:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   9892:                     $checkid = 1;
                   9893:                 }
                   9894:             }
                   9895:             foreach my $user (keys(%{$usershash})) {
                   9896:                 my ($uname,$udom) = split(/:/,$user);
                   9897:                 if ($checkid) {
                   9898:                     if (ref($usershash->{$user}) eq 'HASH') {
                   9899:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  9900:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  9901:                             $userdoms{$udom} = 1;
1.1227    raeburn  9902:                             if (ref($inst_results) eq 'HASH') {
                   9903:                                 $inst_results->{$uname.':'.$udom} = {};
                   9904:                             }
1.1226    raeburn  9905:                         }
                   9906:                     }
                   9907:                 } else {
                   9908:                     $by_username{$udom}{$uname} = 1;
                   9909:                     $userdoms{$udom} = 1;
1.1227    raeburn  9910:                     if (ref($inst_results) eq 'HASH') {
                   9911:                         $inst_results->{$uname.':'.$udom} = {};
                   9912:                     }
1.1226    raeburn  9913:                 }
                   9914:             }
                   9915:             foreach my $udom (keys(%userdoms)) {
                   9916:                 if (!$got_rules->{$udom}) {
                   9917:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9918:                                                              ['usercreation'],$udom);
                   9919:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   9920:                         foreach my $item ('username','id') {
                   9921:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  9922:                                 $$curr_rules{$udom}{$item} =
                   9923:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  9924:                             }
                   9925:                         }
                   9926:                     }
                   9927:                     $got_rules->{$udom} = 1;
                   9928:                 }
1.612     raeburn  9929:             }
1.1226    raeburn  9930:             if ($checkid) {
                   9931:                 foreach my $udom (keys(%by_id)) {
                   9932:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   9933:                     if ($outcome eq 'ok') {
1.1227    raeburn  9934:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   9935:                             my $uname = $by_id{$udom}{$id};
                   9936:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9937:                         }
1.1226    raeburn  9938:                         if (ref($results) eq 'HASH') {
                   9939:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  9940:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   9941:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   9942:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   9943:                                 }
1.1226    raeburn  9944:                             }
                   9945:                         }
                   9946:                     }
1.612     raeburn  9947:                 }
1.615     raeburn  9948:             } else {
1.1226    raeburn  9949:                 foreach my $udom (keys(%by_username)) {
                   9950:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   9951:                     if ($outcome eq 'ok') {
1.1227    raeburn  9952:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   9953:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9954:                         }
1.1226    raeburn  9955:                         if (ref($results) eq 'HASH') {
                   9956:                             foreach my $uname (keys(%{$results})) {
                   9957:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   9958:                             }
                   9959:                         }
                   9960:                     }
                   9961:                 }
1.612     raeburn  9962:             }
1.1226    raeburn  9963:         } elsif (keys(%{$usershash}) == 1) {
                   9964:             my $user = (keys(%{$usershash}))[0];
                   9965:             my ($uname,$udom) = split(/:/,$user);
                   9966:             if (($udom ne '') && ($uname ne '')) {
                   9967:                 if (ref($usershash->{$user}) eq 'HASH') {
                   9968:                     if (ref($checks) eq 'HASH') {
                   9969:                         if (defined($checks->{'username'})) {
                   9970:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   9971:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   9972:                         } elsif (defined($checks->{'id'})) {
                   9973:                             if ($usershash->{$user}->{'id'} ne '') {
                   9974:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   9975:                                     &Apache::lonnet::get_instuser($udom,undef,
                   9976:                                                                   $usershash->{$user}->{'id'});
                   9977:                             } else {
                   9978:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   9979:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   9980:                             }
1.585     raeburn  9981:                         }
1.1226    raeburn  9982:                     } else {
                   9983:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   9984:                             &Apache::lonnet::get_instuser($udom,$uname);
                   9985:                        return;
                   9986:                     }
                   9987:                     if (!$got_rules->{$udom}) {
                   9988:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9989:                                                                  ['usercreation'],$udom);
                   9990:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   9991:                             foreach my $item ('username','id') {
                   9992:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9993:                                    $$curr_rules{$udom}{$item} = 
                   9994:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   9995:                                 }
                   9996:                             }
                   9997:                         }
                   9998:                         $got_rules->{$udom} = 1;
1.585     raeburn  9999:                     }
                   10000:                 }
1.1226    raeburn  10001:             } else {
                   10002:                 return;
                   10003:             }
                   10004:         } else {
                   10005:             return;
                   10006:         }
                   10007:         foreach my $user (keys(%{$usershash})) {
                   10008:             my ($uname,$udom) = split(/:/,$user);
                   10009:             next if (($udom eq '') || ($uname eq ''));
                   10010:             my $id;
1.1227    raeburn  10011:             if (ref($inst_results) eq 'HASH') {
                   10012:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10013:                     $id = $inst_results->{$user}->{'id'};
                   10014:                 }
                   10015:             }
                   10016:             if ($id eq '') { 
                   10017:                 if (ref($usershash->{$user})) {
                   10018:                     $id = $usershash->{$user}->{'id'};
                   10019:                 }
1.585     raeburn  10020:             }
1.612     raeburn  10021:             foreach my $item (keys(%{$checks})) {
                   10022:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10023:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10024:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  10025:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10026:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10027:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10028:                                 if ($rule_check{$rule}) {
                   10029:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  10030:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10031:                                         if (ref($inst_results) eq 'HASH') {
                   10032:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10033:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10034:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  10035:                                                 } elsif ($item eq 'id') {
                   10036:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10037:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10038:                                                     }
1.615     raeburn  10039:                                                 }
1.612     raeburn  10040:                                             }
                   10041:                                         }
1.615     raeburn  10042:                                     }
                   10043:                                     last;
1.585     raeburn  10044:                                 }
                   10045:                             }
                   10046:                         }
                   10047:                     }
                   10048:                 }
                   10049:             }
                   10050:         }
                   10051:     }
1.612     raeburn  10052:     return;
                   10053: }
                   10054: 
                   10055: sub user_rule_formats {
                   10056:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10057:     my %text = ( 
                   10058:                  'username' => 'Usernames',
                   10059:                  'id'       => 'IDs',
                   10060:                );
                   10061:     my $output;
                   10062:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10063:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10064:         if (@{$ruleorder} > 0) {
1.1102    raeburn  10065:             $output = '<br />'.
                   10066:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10067:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10068:                       ' <ul>';
1.612     raeburn  10069:             foreach my $rule (@{$ruleorder}) {
                   10070:                 if (ref($curr_rules) eq 'ARRAY') {
                   10071:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10072:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10073:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10074:                                         $rules->{$rule}{'desc'}.'</li>';
                   10075:                         }
                   10076:                     }
                   10077:                 }
                   10078:             }
                   10079:             $output .= '</ul>';
                   10080:         }
                   10081:     }
                   10082:     return $output;
                   10083: }
                   10084: 
                   10085: sub instrule_disallow_msg {
1.615     raeburn  10086:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10087:     my $response;
                   10088:     my %text = (
                   10089:                   item   => 'username',
                   10090:                   items  => 'usernames',
                   10091:                   match  => 'matches',
                   10092:                   do     => 'does',
                   10093:                   action => 'a username',
                   10094:                   one    => 'one',
                   10095:                );
                   10096:     if ($count > 1) {
                   10097:         $text{'item'} = 'usernames';
                   10098:         $text{'match'} ='match';
                   10099:         $text{'do'} = 'do';
                   10100:         $text{'action'} = 'usernames',
                   10101:         $text{'one'} = 'ones';
                   10102:     }
                   10103:     if ($checkitem eq 'id') {
                   10104:         $text{'items'} = 'IDs';
                   10105:         $text{'item'} = 'ID';
                   10106:         $text{'action'} = 'an ID';
1.615     raeburn  10107:         if ($count > 1) {
                   10108:             $text{'item'} = 'IDs';
                   10109:             $text{'action'} = 'IDs';
                   10110:         }
1.612     raeburn  10111:     }
1.674     bisitz   10112:     $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  10113:     if ($mode eq 'upload') {
                   10114:         if ($checkitem eq 'username') {
                   10115:             $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'}.");
                   10116:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10117:             $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  10118:         }
1.669     raeburn  10119:     } elsif ($mode eq 'selfcreate') {
                   10120:         if ($checkitem eq 'id') {
                   10121:             $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.");
                   10122:         }
1.615     raeburn  10123:     } else {
                   10124:         if ($checkitem eq 'username') {
                   10125:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10126:         } elsif ($checkitem eq 'id') {
                   10127:             $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.");
                   10128:         }
1.612     raeburn  10129:     }
                   10130:     return $response;
1.585     raeburn  10131: }
                   10132: 
1.624     raeburn  10133: sub personal_data_fieldtitles {
                   10134:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10135:                         id => 'Student/Employee ID',
                   10136:                         permanentemail => 'E-mail address',
                   10137:                         lastname => 'Last Name',
                   10138:                         firstname => 'First Name',
                   10139:                         middlename => 'Middle Name',
                   10140:                         generation => 'Generation',
                   10141:                         gen => 'Generation',
1.765     raeburn  10142:                         inststatus => 'Affiliation',
1.624     raeburn  10143:                    );
                   10144:     return %fieldtitles;
                   10145: }
                   10146: 
1.642     raeburn  10147: sub sorted_inst_types {
                   10148:     my ($dom) = @_;
1.1185    raeburn  10149:     my ($usertypes,$order);
                   10150:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10151:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10152:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10153:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10154:     } else {
                   10155:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10156:     }
1.642     raeburn  10157:     my $othertitle = &mt('All users');
                   10158:     if ($env{'request.course.id'}) {
1.668     raeburn  10159:         $othertitle  = &mt('Any users');
1.642     raeburn  10160:     }
                   10161:     my @types;
                   10162:     if (ref($order) eq 'ARRAY') {
                   10163:         @types = @{$order};
                   10164:     }
                   10165:     if (@types == 0) {
                   10166:         if (ref($usertypes) eq 'HASH') {
                   10167:             @types = sort(keys(%{$usertypes}));
                   10168:         }
                   10169:     }
                   10170:     if (keys(%{$usertypes}) > 0) {
                   10171:         $othertitle = &mt('Other users');
                   10172:     }
                   10173:     return ($othertitle,$usertypes,\@types);
                   10174: }
                   10175: 
1.645     raeburn  10176: sub get_institutional_codes {
                   10177:     my ($settings,$allcourses,$LC_code) = @_;
                   10178: # Get complete list of course sections to update
                   10179:     my @currsections = ();
                   10180:     my @currxlists = ();
                   10181:     my $coursecode = $$settings{'internal.coursecode'};
                   10182: 
                   10183:     if ($$settings{'internal.sectionnums'} ne '') {
                   10184:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10185:     }
                   10186: 
                   10187:     if ($$settings{'internal.crosslistings'} ne '') {
                   10188:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10189:     }
                   10190: 
                   10191:     if (@currxlists > 0) {
                   10192:         foreach (@currxlists) {
                   10193:             if (m/^([^:]+):(\w*)$/) {
                   10194:                 unless (grep/^$1$/,@{$allcourses}) {
                   10195:                     push @{$allcourses},$1;
                   10196:                     $$LC_code{$1} = $2;
                   10197:                 }
                   10198:             }
                   10199:         }
                   10200:     }
                   10201:  
                   10202:     if (@currsections > 0) {
                   10203:         foreach (@currsections) {
                   10204:             if (m/^(\w+):(\w*)$/) {
                   10205:                 my $sec = $coursecode.$1;
                   10206:                 my $lc_sec = $2;
                   10207:                 unless (grep/^$sec$/,@{$allcourses}) {
                   10208:                     push @{$allcourses},$sec;
                   10209:                     $$LC_code{$sec} = $lc_sec;
                   10210:                 }
                   10211:             }
                   10212:         }
                   10213:     }
                   10214:     return;
                   10215: }
                   10216: 
1.971     raeburn  10217: sub get_standard_codeitems {
                   10218:     return ('Year','Semester','Department','Number','Section');
                   10219: }
                   10220: 
1.112     bowersj2 10221: =pod
                   10222: 
1.780     raeburn  10223: =head1 Slot Helpers
                   10224: 
                   10225: =over 4
                   10226: 
                   10227: =item * sorted_slots()
                   10228: 
1.1040    raeburn  10229: Sorts an array of slot names in order of an optional sort key,
                   10230: default sort is by slot start time (earliest first). 
1.780     raeburn  10231: 
                   10232: Inputs:
                   10233: 
                   10234: =over 4
                   10235: 
                   10236: slotsarr  - Reference to array of unsorted slot names.
                   10237: 
                   10238: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10239: 
1.1040    raeburn  10240: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10241: 
1.549     albertel 10242: =back
                   10243: 
1.780     raeburn  10244: Returns:
                   10245: 
                   10246: =over 4
                   10247: 
1.1040    raeburn  10248: sorted   - An array of slot names sorted by a specified sort key 
                   10249:            (default sort key is start time of the slot).
1.780     raeburn  10250: 
                   10251: =back
                   10252: 
                   10253: =cut
                   10254: 
                   10255: 
                   10256: sub sorted_slots {
1.1040    raeburn  10257:     my ($slotsarr,$slots,$sortkey) = @_;
                   10258:     if ($sortkey eq '') {
                   10259:         $sortkey = 'starttime';
                   10260:     }
1.780     raeburn  10261:     my @sorted;
                   10262:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10263:         @sorted =
                   10264:             sort {
                   10265:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10266:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10267:                      }
                   10268:                      if (ref($slots->{$a})) { return -1;}
                   10269:                      if (ref($slots->{$b})) { return 1;}
                   10270:                      return 0;
                   10271:                  } @{$slotsarr};
                   10272:     }
                   10273:     return @sorted;
                   10274: }
                   10275: 
1.1040    raeburn  10276: =pod
                   10277: 
                   10278: =item * get_future_slots()
                   10279: 
                   10280: Inputs:
                   10281: 
                   10282: =over 4
                   10283: 
                   10284: cnum - course number
                   10285: 
                   10286: cdom - course domain
                   10287: 
                   10288: now - current UNIX time
                   10289: 
                   10290: symb - optional symb
                   10291: 
                   10292: =back
                   10293: 
                   10294: Returns:
                   10295: 
                   10296: =over 4
                   10297: 
                   10298: sorted_reservable - ref to array of student_schedulable slots currently 
                   10299:                     reservable, ordered by end date of reservation period.
                   10300: 
                   10301: reservable_now - ref to hash of student_schedulable slots currently
                   10302:                  reservable.
                   10303: 
                   10304:     Keys in inner hash are:
                   10305:     (a) symb: either blank or symb to which slot use is restricted.
                   10306:     (b) endreserve: end date of reservation period. 
                   10307: 
                   10308: sorted_future - ref to array of student_schedulable slots reservable in
                   10309:                 the future, ordered by start date of reservation period.
                   10310: 
                   10311: future_reservable - ref to hash of student_schedulable slots reservable
                   10312:                     in the future.
                   10313: 
                   10314:     Keys in inner hash are:
                   10315:     (a) symb: either blank or symb to which slot use is restricted.
                   10316:     (b) startreserve:  start date of reservation period.
                   10317: 
                   10318: =back
                   10319: 
                   10320: =cut
                   10321: 
                   10322: sub get_future_slots {
                   10323:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  10324:     my $map;
                   10325:     if ($symb) {
                   10326:         ($map) = &Apache::lonnet::decode_symb($symb);
                   10327:     }
1.1040    raeburn  10328:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10329:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10330:     foreach my $slot (keys(%slots)) {
                   10331:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10332:         if ($symb) {
1.1229    raeburn  10333:             if ($slots{$slot}->{'symb'} ne '') {
                   10334:                 my $canuse;
                   10335:                 my %oksymbs;
                   10336:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   10337:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   10338:                 if ($oksymbs{$symb}) {
                   10339:                     $canuse = 1;
                   10340:                 } else {
                   10341:                     foreach my $item (@slotsymbs) {
                   10342:                         if ($item =~ /\.(page|sequence)$/) {
                   10343:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   10344:                             if (($map ne '') && ($map eq $sloturl)) {
                   10345:                                 $canuse = 1;
                   10346:                                 last;
                   10347:                             }
                   10348:                         }
                   10349:                     }
                   10350:                 }
                   10351:                 next unless ($canuse);
                   10352:             }
1.1040    raeburn  10353:         }
                   10354:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10355:             ($slots{$slot}->{'endtime'} > $now)) {
                   10356:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10357:                 my $userallowed = 0;
                   10358:                 if ($slots{$slot}->{'allowedsections'}) {
                   10359:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10360:                     if (!defined($env{'request.role.sec'})
                   10361:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10362:                         $userallowed=1;
                   10363:                     } else {
                   10364:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10365:                             $userallowed=1;
                   10366:                         }
                   10367:                     }
                   10368:                     unless ($userallowed) {
                   10369:                         if (defined($env{'request.course.groups'})) {
                   10370:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10371:                             foreach my $group (@groups) {
                   10372:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10373:                                     $userallowed=1;
                   10374:                                     last;
                   10375:                                 }
                   10376:                             }
                   10377:                         }
                   10378:                     }
                   10379:                 }
                   10380:                 if ($slots{$slot}->{'allowedusers'}) {
                   10381:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10382:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10383:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10384:                         $userallowed = 1;
                   10385:                     }
                   10386:                 }
                   10387:                 next unless($userallowed);
                   10388:             }
                   10389:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10390:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10391:             my $symb = $slots{$slot}->{'symb'};
                   10392:             if (($startreserve < $now) &&
                   10393:                 (!$endreserve || $endreserve > $now)) {
                   10394:                 my $lastres = $endreserve;
                   10395:                 if (!$lastres) {
                   10396:                     $lastres = $slots{$slot}->{'starttime'};
                   10397:                 }
                   10398:                 $reservable_now{$slot} = {
                   10399:                                            symb       => $symb,
                   10400:                                            endreserve => $lastres
                   10401:                                          };
                   10402:             } elsif (($startreserve > $now) &&
                   10403:                      (!$endreserve || $endreserve > $startreserve)) {
                   10404:                 $future_reservable{$slot} = {
                   10405:                                               symb         => $symb,
                   10406:                                               startreserve => $startreserve
                   10407:                                             };
                   10408:             }
                   10409:         }
                   10410:     }
                   10411:     my @unsorted_reservable = keys(%reservable_now);
                   10412:     if (@unsorted_reservable > 0) {
                   10413:         @sorted_reservable = 
                   10414:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10415:     }
                   10416:     my @unsorted_future = keys(%future_reservable);
                   10417:     if (@unsorted_future > 0) {
                   10418:         @sorted_future =
                   10419:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10420:     }
                   10421:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10422: }
1.780     raeburn  10423: 
                   10424: =pod
                   10425: 
1.1057    foxr     10426: =back
                   10427: 
1.549     albertel 10428: =head1 HTTP Helpers
                   10429: 
                   10430: =over 4
                   10431: 
1.648     raeburn  10432: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10433: 
1.258     albertel 10434: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10435: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10436: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10437: 
                   10438: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10439: $possible_names is an ref to an array of form element names.  As an example:
                   10440: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10441: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10442: 
                   10443: =cut
1.1       albertel 10444: 
1.6       albertel 10445: sub get_unprocessed_cgi {
1.25      albertel 10446:   my ($query,$possible_names)= @_;
1.26      matthew  10447:   # $Apache::lonxml::debug=1;
1.356     albertel 10448:   foreach my $pair (split(/&/,$query)) {
                   10449:     my ($name, $value) = split(/=/,$pair);
1.369     www      10450:     $name = &unescape($name);
1.25      albertel 10451:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10452:       $value =~ tr/+/ /;
                   10453:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10454:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10455:     }
1.16      harris41 10456:   }
1.6       albertel 10457: }
                   10458: 
1.112     bowersj2 10459: =pod
                   10460: 
1.648     raeburn  10461: =item * &cacheheader() 
1.112     bowersj2 10462: 
                   10463: returns cache-controlling header code
                   10464: 
                   10465: =cut
                   10466: 
1.7       albertel 10467: sub cacheheader {
1.258     albertel 10468:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10469:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10470:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10471:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10472:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10473:     return $output;
1.7       albertel 10474: }
                   10475: 
1.112     bowersj2 10476: =pod
                   10477: 
1.648     raeburn  10478: =item * &no_cache($r) 
1.112     bowersj2 10479: 
                   10480: specifies header code to not have cache
                   10481: 
                   10482: =cut
                   10483: 
1.9       albertel 10484: sub no_cache {
1.216     albertel 10485:     my ($r) = @_;
                   10486:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10487: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10488:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10489:     $r->no_cache(1);
                   10490:     $r->header_out("Expires" => $date);
                   10491:     $r->header_out("Pragma" => "no-cache");
1.123     www      10492: }
                   10493: 
                   10494: sub content_type {
1.181     albertel 10495:     my ($r,$type,$charset) = @_;
1.299     foxr     10496:     if ($r) {
                   10497: 	#  Note that printout.pl calls this with undef for $r.
                   10498: 	&no_cache($r);
                   10499:     }
1.258     albertel 10500:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10501:     unless ($charset) {
                   10502: 	$charset=&Apache::lonlocal::current_encoding;
                   10503:     }
                   10504:     if ($charset) { $type.='; charset='.$charset; }
                   10505:     if ($r) {
                   10506: 	$r->content_type($type);
                   10507:     } else {
                   10508: 	print("Content-type: $type\n\n");
                   10509:     }
1.9       albertel 10510: }
1.25      albertel 10511: 
1.112     bowersj2 10512: =pod
                   10513: 
1.648     raeburn  10514: =item * &add_to_env($name,$value) 
1.112     bowersj2 10515: 
1.258     albertel 10516: adds $name to the %env hash with value
1.112     bowersj2 10517: $value, if $name already exists, the entry is converted to an array
                   10518: reference and $value is added to the array.
                   10519: 
                   10520: =cut
                   10521: 
1.25      albertel 10522: sub add_to_env {
                   10523:   my ($name,$value)=@_;
1.258     albertel 10524:   if (defined($env{$name})) {
                   10525:     if (ref($env{$name})) {
1.25      albertel 10526:       #already have multiple values
1.258     albertel 10527:       push(@{ $env{$name} },$value);
1.25      albertel 10528:     } else {
                   10529:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10530:       my $first=$env{$name};
                   10531:       undef($env{$name});
                   10532:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10533:     }
                   10534:   } else {
1.258     albertel 10535:     $env{$name}=$value;
1.25      albertel 10536:   }
1.31      albertel 10537: }
1.149     albertel 10538: 
                   10539: =pod
                   10540: 
1.648     raeburn  10541: =item * &get_env_multiple($name) 
1.149     albertel 10542: 
1.258     albertel 10543: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10544: values may be defined and end up as an array ref.
                   10545: 
                   10546: returns an array of values
                   10547: 
                   10548: =cut
                   10549: 
                   10550: sub get_env_multiple {
                   10551:     my ($name) = @_;
                   10552:     my @values;
1.258     albertel 10553:     if (defined($env{$name})) {
1.149     albertel 10554:         # exists is it an array
1.258     albertel 10555:         if (ref($env{$name})) {
                   10556:             @values=@{ $env{$name} };
1.149     albertel 10557:         } else {
1.258     albertel 10558:             $values[0]=$env{$name};
1.149     albertel 10559:         }
                   10560:     }
                   10561:     return(@values);
                   10562: }
                   10563: 
1.660     raeburn  10564: sub ask_for_embedded_content {
                   10565:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10566:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  10567:         %currsubfile,%unused,$rem);
1.1071    raeburn  10568:     my $counter = 0;
                   10569:     my $numnew = 0;
1.987     raeburn  10570:     my $numremref = 0;
                   10571:     my $numinvalid = 0;
                   10572:     my $numpathchg = 0;
                   10573:     my $numexisting = 0;
1.1071    raeburn  10574:     my $numunused = 0;
                   10575:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  10576:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10577:     my $heading = &mt('Upload embedded files');
                   10578:     my $buttontext = &mt('Upload');
                   10579: 
1.1085    raeburn  10580:     if ($env{'request.course.id'}) {
1.1123    raeburn  10581:         if ($actionurl eq '/adm/dependencies') {
                   10582:             $navmap = Apache::lonnavmaps::navmap->new();
                   10583:         }
                   10584:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10585:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  10586:     }
1.1123    raeburn  10587:     if (($actionurl eq '/adm/portfolio') || 
                   10588:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10589:         my $current_path='/';
                   10590:         if ($env{'form.currentpath'}) {
                   10591:             $current_path = $env{'form.currentpath'};
                   10592:         }
                   10593:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  10594:             $udom = $cdom;
                   10595:             $uname = $cnum;
1.984     raeburn  10596:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10597:         } else {
                   10598:             $udom = $env{'user.domain'};
                   10599:             $uname = $env{'user.name'};
                   10600:             $url = '/userfiles/portfolio';
                   10601:         }
1.987     raeburn  10602:         $toplevel = $url.'/';
1.984     raeburn  10603:         $url .= $current_path;
                   10604:         $getpropath = 1;
1.987     raeburn  10605:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10606:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10607:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10608:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10609:         $toplevel = $url;
1.984     raeburn  10610:         if ($rest ne '') {
1.987     raeburn  10611:             $url .= $rest;
                   10612:         }
                   10613:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10614:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10615:             $url = $args->{'docs_url'};
                   10616:             $toplevel = $url;
1.1084    raeburn  10617:             if ($args->{'context'} eq 'paste') {
                   10618:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10619:                 ($path) = 
                   10620:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10621:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10622:                 $fileloc =~ s{^/}{};
                   10623:             }
1.1071    raeburn  10624:         }
1.1084    raeburn  10625:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  10626:         if ($env{'request.course.id'} ne '') {
                   10627:             if (ref($args) eq 'HASH') {
                   10628:                 $url = $args->{'docs_url'};
                   10629:                 $title = $args->{'docs_title'};
1.1126    raeburn  10630:                 $toplevel = $url; 
                   10631:                 unless ($toplevel =~ m{^/}) {
                   10632:                     $toplevel = "/$url";
                   10633:                 }
1.1085    raeburn  10634:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  10635:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10636:                     $path = $1;
                   10637:                 } else {
                   10638:                     ($path) =
                   10639:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10640:                 }
1.1195    raeburn  10641:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10642:                     $fileloc = $toplevel;
                   10643:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10644:                     my ($udom,$uname,$fname) =
                   10645:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10646:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10647:                 } else {
                   10648:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10649:                 }
1.1071    raeburn  10650:                 $fileloc =~ s{^/}{};
                   10651:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10652:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10653:             }
1.987     raeburn  10654:         }
1.1123    raeburn  10655:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10656:         $udom = $cdom;
                   10657:         $uname = $cnum;
                   10658:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10659:         $toplevel = $url;
                   10660:         $path = $url;
                   10661:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10662:         $fileloc =~ s{^/}{};
1.987     raeburn  10663:     }
1.1126    raeburn  10664:     foreach my $file (keys(%{$allfiles})) {
                   10665:         my $embed_file;
                   10666:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10667:             $embed_file = $1;
                   10668:         } else {
                   10669:             $embed_file = $file;
                   10670:         }
1.1158    raeburn  10671:         my ($absolutepath,$cleaned_file);
                   10672:         if ($embed_file =~ m{^\w+://}) {
                   10673:             $cleaned_file = $embed_file;
1.1147    raeburn  10674:             $newfiles{$cleaned_file} = 1;
                   10675:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10676:         } else {
1.1158    raeburn  10677:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10678:             if ($embed_file =~ m{^/}) {
                   10679:                 $absolutepath = $embed_file;
                   10680:             }
1.1147    raeburn  10681:             if ($cleaned_file =~ m{/}) {
                   10682:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10683:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10684:                 my $item = $fname;
                   10685:                 if ($path ne '') {
                   10686:                     $item = $path.'/'.$fname;
                   10687:                     $subdependencies{$path}{$fname} = 1;
                   10688:                 } else {
                   10689:                     $dependencies{$item} = 1;
                   10690:                 }
                   10691:                 if ($absolutepath) {
                   10692:                     $mapping{$item} = $absolutepath;
                   10693:                 } else {
                   10694:                     $mapping{$item} = $embed_file;
                   10695:                 }
                   10696:             } else {
                   10697:                 $dependencies{$embed_file} = 1;
                   10698:                 if ($absolutepath) {
1.1147    raeburn  10699:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10700:                 } else {
1.1147    raeburn  10701:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10702:                 }
                   10703:             }
1.984     raeburn  10704:         }
                   10705:     }
1.1071    raeburn  10706:     my $dirptr = 16384;
1.984     raeburn  10707:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10708:         $currsubfile{$path} = {};
1.1123    raeburn  10709:         if (($actionurl eq '/adm/portfolio') || 
                   10710:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10711:             my ($sublistref,$listerror) =
                   10712:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10713:             if (ref($sublistref) eq 'ARRAY') {
                   10714:                 foreach my $line (@{$sublistref}) {
                   10715:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10716:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10717:                 }
1.984     raeburn  10718:             }
1.987     raeburn  10719:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10720:             if (opendir(my $dir,$url.'/'.$path)) {
                   10721:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10722:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10723:             }
1.1084    raeburn  10724:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10725:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  10726:                   ($args->{'context'} eq 'paste')) ||
                   10727:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10728:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  10729:                 my $dir;
                   10730:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10731:                     $dir = $fileloc;
                   10732:                 } else {
                   10733:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10734:                 }
1.1071    raeburn  10735:                 if ($dir ne '') {
                   10736:                     my ($sublistref,$listerror) =
                   10737:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10738:                     if (ref($sublistref) eq 'ARRAY') {
                   10739:                         foreach my $line (@{$sublistref}) {
                   10740:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10741:                                 undef,$mtime)=split(/\&/,$line,12);
                   10742:                             unless (($testdir&$dirptr) ||
                   10743:                                     ($file_name =~ /^\.\.?$/)) {
                   10744:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10745:                             }
                   10746:                         }
                   10747:                     }
                   10748:                 }
1.984     raeburn  10749:             }
                   10750:         }
                   10751:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10752:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10753:                 my $item = $path.'/'.$file;
                   10754:                 unless ($mapping{$item} eq $item) {
                   10755:                     $pathchanges{$item} = 1;
                   10756:                 }
                   10757:                 $existing{$item} = 1;
                   10758:                 $numexisting ++;
                   10759:             } else {
                   10760:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10761:             }
                   10762:         }
1.1071    raeburn  10763:         if ($actionurl eq '/adm/dependencies') {
                   10764:             foreach my $path (keys(%currsubfile)) {
                   10765:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10766:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10767:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  10768:                              next if (($rem ne '') &&
                   10769:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10770:                                        (ref($navmap) &&
                   10771:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10772:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10773:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10774:                              $unused{$path.'/'.$file} = 1; 
                   10775:                          }
                   10776:                     }
                   10777:                 }
                   10778:             }
                   10779:         }
1.984     raeburn  10780:     }
1.987     raeburn  10781:     my %currfile;
1.1123    raeburn  10782:     if (($actionurl eq '/adm/portfolio') ||
                   10783:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10784:         my ($dirlistref,$listerror) =
                   10785:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10786:         if (ref($dirlistref) eq 'ARRAY') {
                   10787:             foreach my $line (@{$dirlistref}) {
                   10788:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10789:                 $currfile{$file_name} = 1;
                   10790:             }
1.984     raeburn  10791:         }
1.987     raeburn  10792:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10793:         if (opendir(my $dir,$url)) {
1.987     raeburn  10794:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10795:             map {$currfile{$_} = 1;} @dir_list;
                   10796:         }
1.1084    raeburn  10797:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10798:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  10799:               ($args->{'context'} eq 'paste')) ||
                   10800:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10801:         if ($env{'request.course.id'} ne '') {
                   10802:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10803:             if ($dir ne '') {
                   10804:                 my ($dirlistref,$listerror) =
                   10805:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10806:                 if (ref($dirlistref) eq 'ARRAY') {
                   10807:                     foreach my $line (@{$dirlistref}) {
                   10808:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10809:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10810:                         unless (($testdir&$dirptr) ||
                   10811:                                 ($file_name =~ /^\.\.?$/)) {
                   10812:                             $currfile{$file_name} = [$size,$mtime];
                   10813:                         }
                   10814:                     }
                   10815:                 }
                   10816:             }
                   10817:         }
1.984     raeburn  10818:     }
                   10819:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10820:         if (exists($currfile{$file})) {
1.987     raeburn  10821:             unless ($mapping{$file} eq $file) {
                   10822:                 $pathchanges{$file} = 1;
                   10823:             }
                   10824:             $existing{$file} = 1;
                   10825:             $numexisting ++;
                   10826:         } else {
1.984     raeburn  10827:             $newfiles{$file} = 1;
                   10828:         }
                   10829:     }
1.1071    raeburn  10830:     foreach my $file (keys(%currfile)) {
                   10831:         unless (($file eq $filename) ||
                   10832:                 ($file eq $filename.'.bak') ||
                   10833:                 ($dependencies{$file})) {
1.1085    raeburn  10834:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  10835:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10836:                     next if (($rem ne '') &&
                   10837:                              (($env{"httpref.$rem".$file} ne '') ||
                   10838:                               (ref($navmap) &&
                   10839:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10840:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10841:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10842:                 }
1.1085    raeburn  10843:             }
1.1071    raeburn  10844:             $unused{$file} = 1;
                   10845:         }
                   10846:     }
1.1084    raeburn  10847:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10848:         ($args->{'context'} eq 'paste')) {
                   10849:         $counter = scalar(keys(%existing));
                   10850:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  10851:         return ($output,$counter,$numpathchg,\%existing);
                   10852:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   10853:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10854:         $counter = scalar(keys(%existing));
                   10855:         $numpathchg = scalar(keys(%pathchanges));
                   10856:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  10857:     }
1.984     raeburn  10858:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10859:         if ($actionurl eq '/adm/dependencies') {
                   10860:             next if ($embed_file =~ m{^\w+://});
                   10861:         }
1.660     raeburn  10862:         $upload_output .= &start_data_table_row().
1.1123    raeburn  10863:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  10864:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  10865:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  10866:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   10867:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  10868:         }
1.1123    raeburn  10869:         $upload_output .= '</td>';
1.1071    raeburn  10870:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  10871:             $upload_output.='<td align="right">'.
                   10872:                             '<span class="LC_info LC_fontsize_medium">'.
                   10873:                             &mt("URL points to web address").'</span>';
1.987     raeburn  10874:             $numremref++;
1.660     raeburn  10875:         } elsif ($args->{'error_on_invalid_names'}
                   10876:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  10877:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   10878:                             &mt('Invalid characters').'</span>';
1.987     raeburn  10879:             $numinvalid++;
1.660     raeburn  10880:         } else {
1.1123    raeburn  10881:             $upload_output .= '<td>'.
                   10882:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  10883:                                                      $embed_file,\%mapping,
1.1071    raeburn  10884:                                                      $allfiles,$codebase,'upload');
                   10885:             $counter ++;
                   10886:             $numnew ++;
1.987     raeburn  10887:         }
                   10888:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   10889:     }
                   10890:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  10891:         if ($actionurl eq '/adm/dependencies') {
                   10892:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   10893:             $modify_output .= &start_data_table_row().
                   10894:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   10895:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   10896:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   10897:                               '<td>'.$size.'</td>'.
                   10898:                               '<td>'.$mtime.'</td>'.
                   10899:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   10900:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   10901:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   10902:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   10903:                               &embedded_file_element('upload_embedded',$counter,
                   10904:                                                      $embed_file,\%mapping,
                   10905:                                                      $allfiles,$codebase,'modify').
                   10906:                               '</div></td>'.
                   10907:                               &end_data_table_row()."\n";
                   10908:             $counter ++;
                   10909:         } else {
                   10910:             $upload_output .= &start_data_table_row().
1.1123    raeburn  10911:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   10912:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   10913:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  10914:                               &Apache::loncommon::end_data_table_row()."\n";
                   10915:         }
                   10916:     }
                   10917:     my $delidx = $counter;
                   10918:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   10919:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   10920:         $delete_output .= &start_data_table_row().
                   10921:                           '<td><img src="'.&icon($oldfile).'" />'.
                   10922:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   10923:                           '<td>'.$size.'</td>'.
                   10924:                           '<td>'.$mtime.'</td>'.
                   10925:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   10926:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   10927:                           &embedded_file_element('upload_embedded',$delidx,
                   10928:                                                  $oldfile,\%mapping,$allfiles,
                   10929:                                                  $codebase,'delete').'</td>'.
                   10930:                           &end_data_table_row()."\n"; 
                   10931:         $numunused ++;
                   10932:         $delidx ++;
1.987     raeburn  10933:     }
                   10934:     if ($upload_output) {
                   10935:         $upload_output = &start_data_table().
                   10936:                          $upload_output.
                   10937:                          &end_data_table()."\n";
                   10938:     }
1.1071    raeburn  10939:     if ($modify_output) {
                   10940:         $modify_output = &start_data_table().
                   10941:                          &start_data_table_header_row().
                   10942:                          '<th>'.&mt('File').'</th>'.
                   10943:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10944:                          '<th>'.&mt('Modified').'</th>'.
                   10945:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   10946:                          &end_data_table_header_row().
                   10947:                          $modify_output.
                   10948:                          &end_data_table()."\n";
                   10949:     }
                   10950:     if ($delete_output) {
                   10951:         $delete_output = &start_data_table().
                   10952:                          &start_data_table_header_row().
                   10953:                          '<th>'.&mt('File').'</th>'.
                   10954:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10955:                          '<th>'.&mt('Modified').'</th>'.
                   10956:                          '<th>'.&mt('Delete?').'</th>'.
                   10957:                          &end_data_table_header_row().
                   10958:                          $delete_output.
                   10959:                          &end_data_table()."\n";
                   10960:     }
1.987     raeburn  10961:     my $applies = 0;
                   10962:     if ($numremref) {
                   10963:         $applies ++;
                   10964:     }
                   10965:     if ($numinvalid) {
                   10966:         $applies ++;
                   10967:     }
                   10968:     if ($numexisting) {
                   10969:         $applies ++;
                   10970:     }
1.1071    raeburn  10971:     if ($counter || $numunused) {
1.987     raeburn  10972:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   10973:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  10974:                   $state.'<h3>'.$heading.'</h3>'; 
                   10975:         if ($actionurl eq '/adm/dependencies') {
                   10976:             if ($numnew) {
                   10977:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   10978:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   10979:                            $upload_output.'<br />'."\n";
                   10980:             }
                   10981:             if ($numexisting) {
                   10982:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   10983:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   10984:                            $modify_output.'<br />'."\n";
                   10985:                            $buttontext = &mt('Save changes');
                   10986:             }
                   10987:             if ($numunused) {
                   10988:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   10989:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   10990:                            $delete_output.'<br />'."\n";
                   10991:                            $buttontext = &mt('Save changes');
                   10992:             }
                   10993:         } else {
                   10994:             $output .= $upload_output.'<br />'."\n";
                   10995:         }
                   10996:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   10997:                    $counter.'" />'."\n";
                   10998:         if ($actionurl eq '/adm/dependencies') { 
                   10999:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11000:                        $numnew.'" />'."\n";
                   11001:         } elsif ($actionurl eq '') {
1.987     raeburn  11002:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11003:         }
                   11004:     } elsif ($applies) {
                   11005:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11006:         if ($applies > 1) {
                   11007:             $output .=  
1.1123    raeburn  11008:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11009:             if ($numremref) {
                   11010:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11011:             }
                   11012:             if ($numinvalid) {
                   11013:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11014:             }
                   11015:             if ($numexisting) {
                   11016:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11017:             }
                   11018:             $output .= '</ul><br />';
                   11019:         } elsif ($numremref) {
                   11020:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11021:         } elsif ($numinvalid) {
                   11022:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11023:         } elsif ($numexisting) {
                   11024:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11025:         }
                   11026:         $output .= $upload_output.'<br />';
                   11027:     }
                   11028:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11029:     $chgcount = $counter;
1.987     raeburn  11030:     if (keys(%pathchanges) > 0) {
                   11031:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11032:             if ($counter) {
1.987     raeburn  11033:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11034:                                                   $embed_file,\%mapping,
1.1071    raeburn  11035:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11036:             } else {
                   11037:                 $pathchange_output .= 
                   11038:                     &start_data_table_row().
                   11039:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11040:                     $chgcount.'" checked="checked" /></td>'.
                   11041:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11042:                     '<td>'.$embed_file.
                   11043:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11044:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11045:                     '</td>'.&end_data_table_row();
1.660     raeburn  11046:             }
1.987     raeburn  11047:             $numpathchg ++;
                   11048:             $chgcount ++;
1.660     raeburn  11049:         }
                   11050:     }
1.1127    raeburn  11051:     if (($counter) || ($numunused)) {
1.987     raeburn  11052:         if ($numpathchg) {
                   11053:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11054:                        $numpathchg.'" />'."\n";
                   11055:         }
                   11056:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11057:             ($actionurl eq '/adm/imsimport')) {
                   11058:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11059:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11060:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11061:         } elsif ($actionurl eq '/adm/dependencies') {
                   11062:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11063:         }
1.1123    raeburn  11064:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11065:     } elsif ($numpathchg) {
                   11066:         my %pathchange = ();
                   11067:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11068:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11069:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  11070:         }
1.987     raeburn  11071:     }
1.1071    raeburn  11072:     return ($output,$counter,$numpathchg);
1.987     raeburn  11073: }
                   11074: 
1.1147    raeburn  11075: =pod
                   11076: 
                   11077: =item * clean_path($name)
                   11078: 
                   11079: Performs clean-up of directories, subdirectories and filename in an
                   11080: embedded object, referenced in an HTML file which is being uploaded
                   11081: to a course or portfolio, where 
                   11082: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11083: checked.
                   11084: 
                   11085: Clean-up is similar to replacements in lonnet::clean_filename()
                   11086: except each / between sub-directory and next level is preserved.
                   11087: 
                   11088: =cut
                   11089: 
                   11090: sub clean_path {
                   11091:     my ($embed_file) = @_;
                   11092:     $embed_file =~s{^/+}{};
                   11093:     my @contents;
                   11094:     if ($embed_file =~ m{/}) {
                   11095:         @contents = split(/\//,$embed_file);
                   11096:     } else {
                   11097:         @contents = ($embed_file);
                   11098:     }
                   11099:     my $lastidx = scalar(@contents)-1;
                   11100:     for (my $i=0; $i<=$lastidx; $i++) { 
                   11101:         $contents[$i]=~s{\\}{/}g;
                   11102:         $contents[$i]=~s/\s+/\_/g;
                   11103:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11104:         if ($i == $lastidx) {
                   11105:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11106:         }
                   11107:     }
                   11108:     if ($lastidx > 0) {
                   11109:         return join('/',@contents);
                   11110:     } else {
                   11111:         return $contents[0];
                   11112:     }
                   11113: }
                   11114: 
1.987     raeburn  11115: sub embedded_file_element {
1.1071    raeburn  11116:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11117:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11118:                    (ref($codebase) eq 'HASH'));
                   11119:     my $output;
1.1071    raeburn  11120:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11121:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11122:     }
                   11123:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11124:                &escape($embed_file).'" />';
                   11125:     unless (($context eq 'upload_embedded') && 
                   11126:             ($mapping->{$embed_file} eq $embed_file)) {
                   11127:         $output .='
                   11128:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11129:     }
                   11130:     my $attrib;
                   11131:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11132:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11133:     }
                   11134:     $output .=
                   11135:         "\n\t\t".
                   11136:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11137:         $attrib.'" />';
                   11138:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11139:         $output .=
                   11140:             "\n\t\t".
                   11141:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11142:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11143:     }
1.987     raeburn  11144:     return $output;
1.660     raeburn  11145: }
                   11146: 
1.1071    raeburn  11147: sub get_dependency_details {
                   11148:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11149:     my ($size,$mtime,$showsize,$showmtime);
                   11150:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11151:         if ($embed_file =~ m{/}) {
                   11152:             my ($path,$fname) = split(/\//,$embed_file);
                   11153:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11154:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11155:             }
                   11156:         } else {
                   11157:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11158:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11159:             }
                   11160:         }
                   11161:         $showsize = $size/1024.0;
                   11162:         $showsize = sprintf("%.1f",$showsize);
                   11163:         if ($mtime > 0) {
                   11164:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11165:         }
                   11166:     }
                   11167:     return ($showsize,$showmtime);
                   11168: }
                   11169: 
                   11170: sub ask_embedded_js {
                   11171:     return <<"END";
                   11172: <script type="text/javascript"">
                   11173: // <![CDATA[
                   11174: function toggleBrowse(counter) {
                   11175:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11176:     var fileid = document.getElementById('embedded_item_'+counter);
                   11177:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11178:     if (chkboxid.checked == true) {
                   11179:         uploaddivid.style.display='block';
                   11180:     } else {
                   11181:         uploaddivid.style.display='none';
                   11182:         fileid.value = '';
                   11183:     }
                   11184: }
                   11185: // ]]>
                   11186: </script>
                   11187: 
                   11188: END
                   11189: }
                   11190: 
1.661     raeburn  11191: sub upload_embedded {
                   11192:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11193:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11194:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11195:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11196:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11197:         my $orig_uploaded_filename =
                   11198:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11199:         foreach my $type ('orig','ref','attrib','codebase') {
                   11200:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11201:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11202:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11203:             }
                   11204:         }
1.661     raeburn  11205:         my ($path,$fname) =
                   11206:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11207:         # no path, whole string is fname
                   11208:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11209:         $fname = &Apache::lonnet::clean_filename($fname);
                   11210:         # See if there is anything left
                   11211:         next if ($fname eq '');
                   11212: 
                   11213:         # Check if file already exists as a file or directory.
                   11214:         my ($state,$msg);
                   11215:         if ($context eq 'portfolio') {
                   11216:             my $port_path = $dirpath;
                   11217:             if ($group ne '') {
                   11218:                 $port_path = "groups/$group/$port_path";
                   11219:             }
1.987     raeburn  11220:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11221:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11222:                                               $dir_root,$port_path,$disk_quota,
                   11223:                                               $current_disk_usage,$uname,$udom);
                   11224:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11225:                 || $state eq 'file_locked') {
1.661     raeburn  11226:                 $output .= $msg;
                   11227:                 next;
                   11228:             }
                   11229:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11230:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11231:             if ($state eq 'exists') {
                   11232:                 $output .= $msg;
                   11233:                 next;
                   11234:             }
                   11235:         }
                   11236:         # Check if extension is valid
                   11237:         if (($fname =~ /\.(\w+)$/) &&
                   11238:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   11239:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11240:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11241:             next;
                   11242:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11243:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11244:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11245:             next;
                   11246:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   11247:             $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  11248:             next;
                   11249:         }
                   11250:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  11251:         my $subdir = $path;
                   11252:         $subdir =~ s{/+$}{};
1.661     raeburn  11253:         if ($context eq 'portfolio') {
1.984     raeburn  11254:             my $result;
                   11255:             if ($state eq 'existingfile') {
                   11256:                 $result=
                   11257:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  11258:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11259:             } else {
1.984     raeburn  11260:                 $result=
                   11261:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11262:                                                     $dirpath.
1.1123    raeburn  11263:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11264:                 if ($result !~ m|^/uploaded/|) {
                   11265:                     $output .= '<span class="LC_error">'
                   11266:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11267:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11268:                                .'</span><br />';
                   11269:                     next;
                   11270:                 } else {
1.987     raeburn  11271:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11272:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11273:                 }
1.661     raeburn  11274:             }
1.1123    raeburn  11275:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  11276:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11277:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11278:             my $result =
1.1126    raeburn  11279:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11280:             if ($result !~ m|^/uploaded/|) {
                   11281:                 $output .= '<span class="LC_error">'
                   11282:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11283:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11284:                            .'</span><br />';
                   11285:                     next;
                   11286:             } else {
                   11287:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11288:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  11289:                 if ($context eq 'syllabus') {
                   11290:                     &Apache::lonnet::make_public_indefinitely($result);
                   11291:                 }
1.987     raeburn  11292:             }
1.661     raeburn  11293:         } else {
                   11294: # Save the file
                   11295:             my $target = $env{'form.embedded_item_'.$i};
                   11296:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11297:             my $dest = $fullpath.$fname;
                   11298:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11299:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11300:             my $count;
                   11301:             my $filepath = $dir_root;
1.1027    raeburn  11302:             foreach my $subdir (@parts) {
                   11303:                 $filepath .= "/$subdir";
                   11304:                 if (!-e $filepath) {
1.661     raeburn  11305:                     mkdir($filepath,0770);
                   11306:                 }
                   11307:             }
                   11308:             my $fh;
                   11309:             if (!open($fh,'>'.$dest)) {
                   11310:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11311:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11312:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11313:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11314:                            '</span><br />';
                   11315:             } else {
                   11316:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11317:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11318:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11319:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11320:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11321:                               '</span><br />';
                   11322:                 } else {
1.987     raeburn  11323:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11324:                                $url.'</span>').'<br />';
                   11325:                     unless ($context eq 'testbank') {
                   11326:                         $footer .= &mt('View embedded file: [_1]',
                   11327:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11328:                     }
                   11329:                 }
                   11330:                 close($fh);
                   11331:             }
                   11332:         }
                   11333:         if ($env{'form.embedded_ref_'.$i}) {
                   11334:             $pathchange{$i} = 1;
                   11335:         }
                   11336:     }
                   11337:     if ($output) {
                   11338:         $output = '<p>'.$output.'</p>';
                   11339:     }
                   11340:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11341:     $returnflag = 'ok';
1.1071    raeburn  11342:     my $numpathchgs = scalar(keys(%pathchange));
                   11343:     if ($numpathchgs > 0) {
1.987     raeburn  11344:         if ($context eq 'portfolio') {
                   11345:             $output .= '<p>'.&mt('or').'</p>';
                   11346:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11347:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11348:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11349:             $returnflag = 'modify_orightml';
                   11350:         }
                   11351:     }
1.1071    raeburn  11352:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11353: }
                   11354: 
                   11355: sub modify_html_form {
                   11356:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11357:     my $end = 0;
                   11358:     my $modifyform;
                   11359:     if ($context eq 'upload_embedded') {
                   11360:         return unless (ref($pathchange) eq 'HASH');
                   11361:         if ($env{'form.number_embedded_items'}) {
                   11362:             $end += $env{'form.number_embedded_items'};
                   11363:         }
                   11364:         if ($env{'form.number_pathchange_items'}) {
                   11365:             $end += $env{'form.number_pathchange_items'};
                   11366:         }
                   11367:         if ($end) {
                   11368:             for (my $i=0; $i<$end; $i++) {
                   11369:                 if ($i < $env{'form.number_embedded_items'}) {
                   11370:                     next unless($pathchange->{$i});
                   11371:                 }
                   11372:                 $modifyform .=
                   11373:                     &start_data_table_row().
                   11374:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11375:                     'checked="checked" /></td>'.
                   11376:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11377:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11378:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11379:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11380:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11381:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11382:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11383:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11384:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11385:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11386:                     &end_data_table_row();
1.1071    raeburn  11387:             }
1.987     raeburn  11388:         }
                   11389:     } else {
                   11390:         $modifyform = $pathchgtable;
                   11391:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11392:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11393:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11394:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11395:         }
                   11396:     }
                   11397:     if ($modifyform) {
1.1071    raeburn  11398:         if ($actionurl eq '/adm/dependencies') {
                   11399:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11400:         }
1.987     raeburn  11401:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11402:                '<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".
                   11403:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11404:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11405:                '</ol></p>'."\n".'<p>'.
                   11406:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11407:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11408:                &start_data_table()."\n".
                   11409:                &start_data_table_header_row().
                   11410:                '<th>'.&mt('Change?').'</th>'.
                   11411:                '<th>'.&mt('Current reference').'</th>'.
                   11412:                '<th>'.&mt('Required reference').'</th>'.
                   11413:                &end_data_table_header_row()."\n".
                   11414:                $modifyform.
                   11415:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11416:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11417:                '</form>'."\n";
                   11418:     }
                   11419:     return;
                   11420: }
                   11421: 
                   11422: sub modify_html_refs {
1.1123    raeburn  11423:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11424:     my $container;
                   11425:     if ($context eq 'portfolio') {
                   11426:         $container = $env{'form.container'};
                   11427:     } elsif ($context eq 'coursedoc') {
                   11428:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11429:     } elsif ($context eq 'manage_dependencies') {
                   11430:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11431:         $container = "/$container";
1.1123    raeburn  11432:     } elsif ($context eq 'syllabus') {
                   11433:         $container = $url;
1.987     raeburn  11434:     } else {
1.1027    raeburn  11435:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11436:     }
                   11437:     my (%allfiles,%codebase,$output,$content);
                   11438:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  11439:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  11440:         if (wantarray) {
                   11441:             return ('',0,0); 
                   11442:         } else {
                   11443:             return;
                   11444:         }
                   11445:     }
                   11446:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11447:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11448:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11449:             if (wantarray) {
                   11450:                 return ('',0,0);
                   11451:             } else {
                   11452:                 return;
                   11453:             }
                   11454:         } 
1.987     raeburn  11455:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11456:         if ($content eq '-1') {
                   11457:             if (wantarray) {
                   11458:                 return ('',0,0);
                   11459:             } else {
                   11460:                 return;
                   11461:             }
                   11462:         }
1.987     raeburn  11463:     } else {
1.1071    raeburn  11464:         unless ($container =~ /^\Q$dir_root\E/) {
                   11465:             if (wantarray) {
                   11466:                 return ('',0,0);
                   11467:             } else {
                   11468:                 return;
                   11469:             }
                   11470:         } 
1.987     raeburn  11471:         if (open(my $fh,"<$container")) {
                   11472:             $content = join('', <$fh>);
                   11473:             close($fh);
                   11474:         } else {
1.1071    raeburn  11475:             if (wantarray) {
                   11476:                 return ('',0,0);
                   11477:             } else {
                   11478:                 return;
                   11479:             }
1.987     raeburn  11480:         }
                   11481:     }
                   11482:     my ($count,$codebasecount) = (0,0);
                   11483:     my $mm = new File::MMagic;
                   11484:     my $mime_type = $mm->checktype_contents($content);
                   11485:     if ($mime_type eq 'text/html') {
                   11486:         my $parse_result = 
                   11487:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11488:                                                     \%codebase,\$content);
                   11489:         if ($parse_result eq 'ok') {
                   11490:             foreach my $i (@changes) {
                   11491:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11492:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11493:                 if ($allfiles{$ref}) {
                   11494:                     my $newname =  $orig;
                   11495:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11496:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11497:                     if ($attrib_regexp =~ /:/) {
                   11498:                         $attrib_regexp =~ s/\:/|/g;
                   11499:                     }
                   11500:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11501:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11502:                         $count += $numchg;
1.1123    raeburn  11503:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  11504:                         delete($allfiles{$ref});
1.987     raeburn  11505:                     }
                   11506:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11507:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11508:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11509:                         $codebasecount ++;
                   11510:                     }
                   11511:                 }
                   11512:             }
1.1123    raeburn  11513:             my $skiprewrites;
1.987     raeburn  11514:             if ($count || $codebasecount) {
                   11515:                 my $saveresult;
1.1071    raeburn  11516:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11517:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11518:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11519:                     if ($url eq $container) {
                   11520:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11521:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11522:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11523:                                             $fname.'</span>').'</p>';
1.987     raeburn  11524:                     } else {
                   11525:                          $output = '<p class="LC_error">'.
                   11526:                                    &mt('Error: update failed for: [_1].',
                   11527:                                    '<span class="LC_filename">'.
                   11528:                                    $container.'</span>').'</p>';
                   11529:                     }
1.1123    raeburn  11530:                     if ($context eq 'syllabus') {
                   11531:                         unless ($saveresult eq 'ok') {
                   11532:                             $skiprewrites = 1;
                   11533:                         }
                   11534:                     }
1.987     raeburn  11535:                 } else {
                   11536:                     if (open(my $fh,">$container")) {
                   11537:                         print $fh $content;
                   11538:                         close($fh);
                   11539:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11540:                                   $count,'<span class="LC_filename">'.
                   11541:                                   $container.'</span>').'</p>';
1.661     raeburn  11542:                     } else {
1.987     raeburn  11543:                          $output = '<p class="LC_error">'.
                   11544:                                    &mt('Error: could not update [_1].',
                   11545:                                    '<span class="LC_filename">'.
                   11546:                                    $container.'</span>').'</p>';
1.661     raeburn  11547:                     }
                   11548:                 }
                   11549:             }
1.1123    raeburn  11550:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11551:                 my ($actionurl,$state);
                   11552:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11553:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11554:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11555:                                               \%codebase,
                   11556:                                               {'context' => 'rewrites',
                   11557:                                                'ignore_remote_references' => 1,});
                   11558:                 if (ref($mapping) eq 'HASH') {
                   11559:                     my $rewrites = 0;
                   11560:                     foreach my $key (keys(%{$mapping})) {
                   11561:                         next if ($key =~ m{^https?://});
                   11562:                         my $ref = $mapping->{$key};
                   11563:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11564:                         my $attrib;
                   11565:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11566:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11567:                         }
                   11568:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11569:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11570:                             $rewrites += $numchg;
                   11571:                         }
                   11572:                     }
                   11573:                     if ($rewrites) {
                   11574:                         my $saveresult; 
                   11575:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11576:                         if ($url eq $container) {
                   11577:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11578:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11579:                                             $count,'<span class="LC_filename">'.
                   11580:                                             $fname.'</span>').'</p>';
                   11581:                         } else {
                   11582:                             $output .= '<p class="LC_error">'.
                   11583:                                        &mt('Error: could not update links in [_1].',
                   11584:                                        '<span class="LC_filename">'.
                   11585:                                        $container.'</span>').'</p>';
                   11586: 
                   11587:                         }
                   11588:                     }
                   11589:                 }
                   11590:             }
1.987     raeburn  11591:         } else {
                   11592:             &logthis('Failed to parse '.$container.
                   11593:                      ' to modify references: '.$parse_result);
1.661     raeburn  11594:         }
                   11595:     }
1.1071    raeburn  11596:     if (wantarray) {
                   11597:         return ($output,$count,$codebasecount);
                   11598:     } else {
                   11599:         return $output;
                   11600:     }
1.661     raeburn  11601: }
                   11602: 
                   11603: sub check_for_existing {
                   11604:     my ($path,$fname,$element) = @_;
                   11605:     my ($state,$msg);
                   11606:     if (-d $path.'/'.$fname) {
                   11607:         $state = 'exists';
                   11608:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11609:     } elsif (-e $path.'/'.$fname) {
                   11610:         $state = 'exists';
                   11611:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11612:     }
                   11613:     if ($state eq 'exists') {
                   11614:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11615:     }
                   11616:     return ($state,$msg);
                   11617: }
                   11618: 
                   11619: sub check_for_upload {
                   11620:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11621:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11622:     my $filesize = length($env{'form.'.$element});
                   11623:     if (!$filesize) {
                   11624:         my $msg = '<span class="LC_error">'.
                   11625:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11626:                       '<span class="LC_filename">'.$fname.'</span>',
                   11627:                       $filesize).'<br />'.
1.1007    raeburn  11628:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11629:                   '</span>';
                   11630:         return ('zero_bytes',$msg);
                   11631:     }
                   11632:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11633:     my $getpropath = 1;
1.1021    raeburn  11634:     my ($dirlistref,$listerror) =
                   11635:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11636:     my $found_file = 0;
                   11637:     my $locked_file = 0;
1.991     raeburn  11638:     my @lockers;
                   11639:     my $navmap;
                   11640:     if ($env{'request.course.id'}) {
                   11641:         $navmap = Apache::lonnavmaps::navmap->new();
                   11642:     }
1.1021    raeburn  11643:     if (ref($dirlistref) eq 'ARRAY') {
                   11644:         foreach my $line (@{$dirlistref}) {
                   11645:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11646:             if ($file_name eq $fname){
                   11647:                 $file_name = $path.$file_name;
                   11648:                 if ($group ne '') {
                   11649:                     $file_name = $group.$file_name;
                   11650:                 }
                   11651:                 $found_file = 1;
                   11652:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11653:                     foreach my $lock (@lockers) {
                   11654:                         if (ref($lock) eq 'ARRAY') {
                   11655:                             my ($symb,$crsid) = @{$lock};
                   11656:                             if ($crsid eq $env{'request.course.id'}) {
                   11657:                                 if (ref($navmap)) {
                   11658:                                     my $res = $navmap->getBySymb($symb);
                   11659:                                     foreach my $part (@{$res->parts()}) { 
                   11660:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11661:                                         unless (($slot_status == $res->RESERVED) ||
                   11662:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11663:                                             $locked_file = 1;
                   11664:                                         }
1.991     raeburn  11665:                                     }
1.1021    raeburn  11666:                                 } else {
                   11667:                                     $locked_file = 1;
1.991     raeburn  11668:                                 }
                   11669:                             } else {
                   11670:                                 $locked_file = 1;
                   11671:                             }
                   11672:                         }
1.1021    raeburn  11673:                    }
                   11674:                 } else {
                   11675:                     my @info = split(/\&/,$rest);
                   11676:                     my $currsize = $info[6]/1000;
                   11677:                     if ($currsize < $filesize) {
                   11678:                         my $extra = $filesize - $currsize;
                   11679:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   11680:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11681:                                       &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.1179    bisitz   11682:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11683:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11684:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11685:                             return ('will_exceed_quota',$msg);
                   11686:                         }
1.984     raeburn  11687:                     }
                   11688:                 }
1.661     raeburn  11689:             }
                   11690:         }
                   11691:     }
                   11692:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   11693:         my $msg = '<p class="LC_warning">'.
                   11694:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  11695:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11696:         return ('will_exceed_quota',$msg);
                   11697:     } elsif ($found_file) {
                   11698:         if ($locked_file) {
1.1179    bisitz   11699:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11700:             $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.1179    bisitz   11701:             $msg .= '</p>';
1.661     raeburn  11702:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11703:             return ('file_locked',$msg);
                   11704:         } else {
1.1179    bisitz   11705:             my $msg = '<p class="LC_error">';
1.984     raeburn  11706:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.1179    bisitz   11707:             $msg .= '</p>';
1.984     raeburn  11708:             return ('existingfile',$msg);
1.661     raeburn  11709:         }
                   11710:     }
                   11711: }
                   11712: 
1.987     raeburn  11713: sub check_for_traversal {
                   11714:     my ($path,$url,$toplevel) = @_;
                   11715:     my @parts=split(/\//,$path);
                   11716:     my $cleanpath;
                   11717:     my $fullpath = $url;
                   11718:     for (my $i=0;$i<@parts;$i++) {
                   11719:         next if ($parts[$i] eq '.');
                   11720:         if ($parts[$i] eq '..') {
                   11721:             $fullpath =~ s{([^/]+/)$}{};
                   11722:         } else {
                   11723:             $fullpath .= $parts[$i].'/';
                   11724:         }
                   11725:     }
                   11726:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11727:         $cleanpath = $1;
                   11728:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11729:         my $curr_toprel = $1;
                   11730:         my @parts = split(/\//,$curr_toprel);
                   11731:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11732:         my @urlparts = split(/\//,$url_toprel);
                   11733:         my $doubledots;
                   11734:         my $startdiff = -1;
                   11735:         for (my $i=0; $i<@urlparts; $i++) {
                   11736:             if ($startdiff == -1) {
                   11737:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11738:                     $startdiff = $i;
                   11739:                     $doubledots .= '../';
                   11740:                 }
                   11741:             } else {
                   11742:                 $doubledots .= '../';
                   11743:             }
                   11744:         }
                   11745:         if ($startdiff > -1) {
                   11746:             $cleanpath = $doubledots;
                   11747:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11748:                 $cleanpath .= $parts[$i].'/';
                   11749:             }
                   11750:         }
                   11751:     }
                   11752:     $cleanpath =~ s{(/)$}{};
                   11753:     return $cleanpath;
                   11754: }
1.31      albertel 11755: 
1.1053    raeburn  11756: sub is_archive_file {
                   11757:     my ($mimetype) = @_;
                   11758:     if (($mimetype eq 'application/octet-stream') ||
                   11759:         ($mimetype eq 'application/x-stuffit') ||
                   11760:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11761:         return 1;
                   11762:     }
                   11763:     return;
                   11764: }
                   11765: 
                   11766: sub decompress_form {
1.1065    raeburn  11767:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11768:     my %lt = &Apache::lonlocal::texthash (
                   11769:         this => 'This file is an archive file.',
1.1067    raeburn  11770:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11771:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11772:         youm => 'You may wish to extract its contents.',
                   11773:         extr => 'Extract contents',
1.1067    raeburn  11774:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11775:         proa => 'Process automatically?',
1.1053    raeburn  11776:         yes  => 'Yes',
                   11777:         no   => 'No',
1.1067    raeburn  11778:         fold => 'Title for folder containing movie',
                   11779:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11780:     );
1.1065    raeburn  11781:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11782:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11783:     my $info = &list_archive_contents($fileloc,\@paths);
                   11784:     if (@paths) {
                   11785:         foreach my $path (@paths) {
                   11786:             $path =~ s{^/}{};
1.1067    raeburn  11787:             if ($path =~ m{^([^/]+)/$}) {
                   11788:                 $topdir = $1;
                   11789:             }
1.1065    raeburn  11790:             if ($path =~ m{^([^/]+)/}) {
                   11791:                 $toplevel{$1} = $path;
                   11792:             } else {
                   11793:                 $toplevel{$path} = $path;
                   11794:             }
                   11795:         }
                   11796:     }
1.1067    raeburn  11797:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  11798:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11799:                         "$topdir/media/",
                   11800:                         "$topdir/media/$topdir.mp4",
                   11801:                         "$topdir/media/FirstFrame.png",
                   11802:                         "$topdir/media/player.swf",
                   11803:                         "$topdir/media/swfobject.js",
                   11804:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  11805:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  11806:                          "$topdir/$topdir.mp4",
                   11807:                          "$topdir/$topdir\_config.xml",
                   11808:                          "$topdir/$topdir\_controller.swf",
                   11809:                          "$topdir/$topdir\_embed.css",
                   11810:                          "$topdir/$topdir\_First_Frame.png",
                   11811:                          "$topdir/$topdir\_player.html",
                   11812:                          "$topdir/$topdir\_Thumbnails.png",
                   11813:                          "$topdir/playerProductInstall.swf",
                   11814:                          "$topdir/scripts/",
                   11815:                          "$topdir/scripts/config_xml.js",
                   11816:                          "$topdir/scripts/handlebars.js",
                   11817:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11818:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11819:                          "$topdir/scripts/modernizr.js",
                   11820:                          "$topdir/scripts/player-min.js",
                   11821:                          "$topdir/scripts/swfobject.js",
                   11822:                          "$topdir/skins/",
                   11823:                          "$topdir/skins/configuration_express.xml",
                   11824:                          "$topdir/skins/express_show/",
                   11825:                          "$topdir/skins/express_show/player-min.css",
                   11826:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  11827:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   11828:                          "$topdir/$topdir.mp4",
                   11829:                          "$topdir/$topdir\_config.xml",
                   11830:                          "$topdir/$topdir\_controller.swf",
                   11831:                          "$topdir/$topdir\_embed.css",
                   11832:                          "$topdir/$topdir\_First_Frame.png",
                   11833:                          "$topdir/$topdir\_player.html",
                   11834:                          "$topdir/$topdir\_Thumbnails.png",
                   11835:                          "$topdir/playerProductInstall.swf",
                   11836:                          "$topdir/scripts/",
                   11837:                          "$topdir/scripts/config_xml.js",
                   11838:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   11839:                          "$topdir/skins/",
                   11840:                          "$topdir/skins/configuration_express.xml",
                   11841:                          "$topdir/skins/express_show/",
                   11842:                          "$topdir/skins/express_show/spritesheet.min.css",
                   11843:                          "$topdir/skins/express_show/spritesheet.png",
                   11844:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  11845:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11846:         if (@diffs == 0) {
1.1164    raeburn  11847:             $is_camtasia = 6;
                   11848:         } else {
1.1197    raeburn  11849:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  11850:             if (@diffs == 0) {
                   11851:                 $is_camtasia = 8;
1.1197    raeburn  11852:             } else {
                   11853:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   11854:                 if (@diffs == 0) {
                   11855:                     $is_camtasia = 8;
                   11856:                 }
1.1164    raeburn  11857:             }
1.1067    raeburn  11858:         }
                   11859:     }
                   11860:     my $output;
                   11861:     if ($is_camtasia) {
                   11862:         $output = <<"ENDCAM";
                   11863: <script type="text/javascript" language="Javascript">
                   11864: // <![CDATA[
                   11865: 
                   11866: function camtasiaToggle() {
                   11867:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   11868:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  11869:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  11870:                 document.getElementById('camtasia_titles').style.display='block';
                   11871:             } else {
                   11872:                 document.getElementById('camtasia_titles').style.display='none';
                   11873:             }
                   11874:         }
                   11875:     }
                   11876:     return;
                   11877: }
                   11878: 
                   11879: // ]]>
                   11880: </script>
                   11881: <p>$lt{'camt'}</p>
                   11882: ENDCAM
1.1065    raeburn  11883:     } else {
1.1067    raeburn  11884:         $output = '<p>'.$lt{'this'};
                   11885:         if ($info eq '') {
                   11886:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   11887:         } else {
                   11888:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   11889:                        '<div><pre>'.$info.'</pre></div>';
                   11890:         }
1.1065    raeburn  11891:     }
1.1067    raeburn  11892:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  11893:     my $duplicates;
                   11894:     my $num = 0;
                   11895:     if (ref($dirlist) eq 'ARRAY') {
                   11896:         foreach my $item (@{$dirlist}) {
                   11897:             if (ref($item) eq 'ARRAY') {
                   11898:                 if (exists($toplevel{$item->[0]})) {
                   11899:                     $duplicates .= 
                   11900:                         &start_data_table_row().
                   11901:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11902:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   11903:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11904:                         'value="1" />'.&mt('Yes').'</label>'.
                   11905:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   11906:                         '<td>'.$item->[0].'</td>';
                   11907:                     if ($item->[2]) {
                   11908:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   11909:                     } else {
                   11910:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   11911:                     }
                   11912:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   11913:                                    '<td>'.
                   11914:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   11915:                                    '</td>'.
                   11916:                                    &end_data_table_row();
                   11917:                     $num ++;
                   11918:                 }
                   11919:             }
                   11920:         }
                   11921:     }
                   11922:     my $itemcount;
                   11923:     if (@paths > 0) {
                   11924:         $itemcount = scalar(@paths);
                   11925:     } else {
                   11926:         $itemcount = 1;
                   11927:     }
1.1067    raeburn  11928:     if ($is_camtasia) {
                   11929:         $output .= $lt{'auto'}.'<br />'.
                   11930:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  11931:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  11932:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   11933:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   11934:                    $lt{'no'}.'</label></span><br />'.
                   11935:                    '<div id="camtasia_titles" style="display:block">'.
                   11936:                    &Apache::lonhtmlcommon::start_pick_box().
                   11937:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   11938:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   11939:                    &Apache::lonhtmlcommon::row_closure().
                   11940:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   11941:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   11942:                    &Apache::lonhtmlcommon::row_closure(1).
                   11943:                    &Apache::lonhtmlcommon::end_pick_box().
                   11944:                    '</div>';
                   11945:     }
1.1065    raeburn  11946:     $output .= 
                   11947:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  11948:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   11949:         "\n";
1.1065    raeburn  11950:     if ($duplicates ne '') {
                   11951:         $output .= '<p><span class="LC_warning">'.
                   11952:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   11953:                    &start_data_table().
                   11954:                    &start_data_table_header_row().
                   11955:                    '<th>'.&mt('Overwrite?').'</th>'.
                   11956:                    '<th>'.&mt('Name').'</th>'.
                   11957:                    '<th>'.&mt('Type').'</th>'.
                   11958:                    '<th>'.&mt('Size').'</th>'.
                   11959:                    '<th>'.&mt('Last modified').'</th>'.
                   11960:                    &end_data_table_header_row().
                   11961:                    $duplicates.
                   11962:                    &end_data_table().
                   11963:                    '</p>';
                   11964:     }
1.1067    raeburn  11965:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  11966:     if (ref($hiddenelements) eq 'HASH') {
                   11967:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   11968:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   11969:         }
                   11970:     }
                   11971:     $output .= <<"END";
1.1067    raeburn  11972: <br />
1.1053    raeburn  11973: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   11974: </form>
                   11975: $noextract
                   11976: END
                   11977:     return $output;
                   11978: }
                   11979: 
1.1065    raeburn  11980: sub decompression_utility {
                   11981:     my ($program) = @_;
                   11982:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   11983:     my $location;
                   11984:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   11985:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   11986:                          '/usr/sbin/') {
                   11987:             if (-x $dir.$program) {
                   11988:                 $location = $dir.$program;
                   11989:                 last;
                   11990:             }
                   11991:         }
                   11992:     }
                   11993:     return $location;
                   11994: }
                   11995: 
                   11996: sub list_archive_contents {
                   11997:     my ($file,$pathsref) = @_;
                   11998:     my (@cmd,$output);
                   11999:     my $needsregexp;
                   12000:     if ($file =~ /\.zip$/) {
                   12001:         @cmd = (&decompression_utility('unzip'),"-l");
                   12002:         $needsregexp = 1;
                   12003:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12004:              ($file =~ /\.tgz$/)) {
                   12005:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12006:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12007:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12008:     } elsif ($file =~ m|\.tar$|) {
                   12009:         @cmd = (&decompression_utility('tar'),"-tf");
                   12010:     }
                   12011:     if (@cmd) {
                   12012:         undef($!);
                   12013:         undef($@);
                   12014:         if (open(my $fh,"-|", @cmd, $file)) {
                   12015:             while (my $line = <$fh>) {
                   12016:                 $output .= $line;
                   12017:                 chomp($line);
                   12018:                 my $item;
                   12019:                 if ($needsregexp) {
                   12020:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12021:                 } else {
                   12022:                     $item = $line;
                   12023:                 }
                   12024:                 if ($item ne '') {
                   12025:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12026:                         push(@{$pathsref},$item);
                   12027:                     } 
                   12028:                 }
                   12029:             }
                   12030:             close($fh);
                   12031:         }
                   12032:     }
                   12033:     return $output;
                   12034: }
                   12035: 
1.1053    raeburn  12036: sub decompress_uploaded_file {
                   12037:     my ($file,$dir) = @_;
                   12038:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12039:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12040:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12041:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12042:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12043:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12044:     my $decompressed = $env{'cgi.decompressed'};
                   12045:     &Apache::lonnet::delenv('cgi.file');
                   12046:     &Apache::lonnet::delenv('cgi.dir');
                   12047:     &Apache::lonnet::delenv('cgi.decompressed');
                   12048:     return ($decompressed,$result);
                   12049: }
                   12050: 
1.1055    raeburn  12051: sub process_decompression {
                   12052:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   12053:     my ($dir,$error,$warning,$output);
1.1180    raeburn  12054:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   12055:         $error = &mt('Filename not a supported archive file type.').
                   12056:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12057:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12058:     } else {
                   12059:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12060:         if ($docuhome eq 'no_host') {
                   12061:             $error = &mt('Could not determine home server for course.');
                   12062:         } else {
                   12063:             my @ids=&Apache::lonnet::current_machine_ids();
                   12064:             my $currdir = "$dir_root/$destination";
                   12065:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12066:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12067:                        "$dir_root/$destination";
                   12068:             } else {
                   12069:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12070:                        "$dir_root/$docudom/$docuname/$destination";
                   12071:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12072:                     $error = &mt('Archive file not found.');
                   12073:                 }
                   12074:             }
1.1065    raeburn  12075:             my (@to_overwrite,@to_skip);
                   12076:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12077:                 my $total = $env{'form.archive_overwrite_total'};
                   12078:                 for (my $i=0; $i<$total; $i++) {
                   12079:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12080:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12081:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12082:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12083:                     }
                   12084:                 }
                   12085:             }
                   12086:             my $numskip = scalar(@to_skip);
                   12087:             if (($numskip > 0) && 
                   12088:                 ($numskip == $env{'form.archive_itemcount'})) {
                   12089:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12090:             } elsif ($dir eq '') {
1.1055    raeburn  12091:                 $error = &mt('Directory containing archive file unavailable.');
                   12092:             } elsif (!$error) {
1.1065    raeburn  12093:                 my ($decompressed,$display);
                   12094:                 if ($numskip > 0) {
                   12095:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12096:                     mkdir("$dir/$tempdir",0755);
                   12097:                     system("mv $dir/$file $dir/$tempdir/$file");
                   12098:                     ($decompressed,$display) = 
                   12099:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   12100:                     foreach my $item (@to_skip) {
                   12101:                         if (($item ne '') && ($item !~ /\.\./)) {
                   12102:                             if (-f "$dir/$tempdir/$item") { 
                   12103:                                 unlink("$dir/$tempdir/$item");
                   12104:                             } elsif (-d "$dir/$tempdir/$item") {
                   12105:                                 system("rm -rf $dir/$tempdir/$item");
                   12106:                             }
                   12107:                         }
                   12108:                     }
                   12109:                     system("mv $dir/$tempdir/* $dir");
                   12110:                     rmdir("$dir/$tempdir");   
                   12111:                 } else {
                   12112:                     ($decompressed,$display) = 
                   12113:                         &decompress_uploaded_file($file,$dir);
                   12114:                 }
1.1055    raeburn  12115:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12116:                     $output = '<p class="LC_info">'.
                   12117:                               &mt('Files extracted successfully from archive.').
                   12118:                               '</p>'."\n";
1.1055    raeburn  12119:                     my ($warning,$result,@contents);
                   12120:                     my ($newdirlistref,$newlisterror) =
                   12121:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12122:                                                  $docuname,1);
                   12123:                     my (%is_dir,%changes,@newitems);
                   12124:                     my $dirptr = 16384;
1.1065    raeburn  12125:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12126:                         foreach my $dir_line (@{$newdirlistref}) {
                   12127:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  12128:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   12129:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  12130:                                 push(@newitems,$item);
                   12131:                                 if ($dirptr&$testdir) {
                   12132:                                     $is_dir{$item} = 1;
                   12133:                                 }
                   12134:                                 $changes{$item} = 1;
                   12135:                             }
                   12136:                         }
                   12137:                     }
                   12138:                     if (keys(%changes) > 0) {
                   12139:                         foreach my $item (sort(@newitems)) {
                   12140:                             if ($changes{$item}) {
                   12141:                                 push(@contents,$item);
                   12142:                             }
                   12143:                         }
                   12144:                     }
                   12145:                     if (@contents > 0) {
1.1067    raeburn  12146:                         my $wantform;
                   12147:                         unless ($env{'form.autoextract_camtasia'}) {
                   12148:                             $wantform = 1;
                   12149:                         }
1.1056    raeburn  12150:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12151:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12152:                                                                 $currdir,\%is_dir,
                   12153:                                                                 \%children,\%parent,
1.1056    raeburn  12154:                                                                 \@contents,\%dirorder,
                   12155:                                                                 \%titles,$wantform);
1.1055    raeburn  12156:                         if ($datatable ne '') {
                   12157:                             $output .= &archive_options_form('decompressed',$datatable,
                   12158:                                                              $count,$hiddenelem);
1.1065    raeburn  12159:                             my $startcount = 6;
1.1055    raeburn  12160:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12161:                                                            \%titles,\%children);
1.1055    raeburn  12162:                         }
1.1067    raeburn  12163:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  12164:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12165:                             my %displayed;
                   12166:                             my $total = 1;
                   12167:                             $env{'form.archive_directory'} = [];
                   12168:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12169:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12170:                                 $path =~ s{/$}{};
                   12171:                                 my $item;
                   12172:                                 if ($path ne '') {
                   12173:                                     $item = "$path/$titles{$i}";
                   12174:                                 } else {
                   12175:                                     $item = $titles{$i};
                   12176:                                 }
                   12177:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12178:                                 if ($item eq $contents[0]) {
                   12179:                                     push(@{$env{'form.archive_directory'}},$i);
                   12180:                                     $env{'form.archive_'.$i} = 'display';
                   12181:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12182:                                     $displayed{'folder'} = $i;
1.1164    raeburn  12183:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12184:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  12185:                                     $env{'form.archive_'.$i} = 'display';
                   12186:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12187:                                     $displayed{'web'} = $i;
                   12188:                                 } else {
1.1164    raeburn  12189:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12190:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12191:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12192:                                         push(@{$env{'form.archive_directory'}},$i);
                   12193:                                     }
                   12194:                                     $env{'form.archive_'.$i} = 'dependency';
                   12195:                                 }
                   12196:                                 $total ++;
                   12197:                             }
                   12198:                             for (my $i=1; $i<$total; $i++) {
                   12199:                                 next if ($i == $displayed{'web'});
                   12200:                                 next if ($i == $displayed{'folder'});
                   12201:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12202:                             }
                   12203:                             $env{'form.phase'} = 'decompress_cleanup';
                   12204:                             $env{'form.archivedelete'} = 1;
                   12205:                             $env{'form.archive_count'} = $total-1;
                   12206:                             $output .=
                   12207:                                 &process_extracted_files('coursedocs',$docudom,
                   12208:                                                          $docuname,$destination,
                   12209:                                                          $dir_root,$hiddenelem);
                   12210:                         }
1.1055    raeburn  12211:                     } else {
                   12212:                         $warning = &mt('No new items extracted from archive file.');
                   12213:                     }
                   12214:                 } else {
                   12215:                     $output = $display;
                   12216:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12217:                 }
                   12218:             }
                   12219:         }
                   12220:     }
                   12221:     if ($error) {
                   12222:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12223:                    $error.'</p>'."\n";
                   12224:     }
                   12225:     if ($warning) {
                   12226:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12227:     }
                   12228:     return $output;
                   12229: }
                   12230: 
                   12231: sub get_extracted {
1.1056    raeburn  12232:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12233:         $titles,$wantform) = @_;
1.1055    raeburn  12234:     my $count = 0;
                   12235:     my $depth = 0;
                   12236:     my $datatable;
1.1056    raeburn  12237:     my @hierarchy;
1.1055    raeburn  12238:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12239:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12240:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12241:     foreach my $item (@{$contents}) {
                   12242:         $count ++;
1.1056    raeburn  12243:         @{$dirorder->{$count}} = @hierarchy;
                   12244:         $titles->{$count} = $item;
1.1055    raeburn  12245:         &archive_hierarchy($depth,$count,$parent,$children);
                   12246:         if ($wantform) {
                   12247:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12248:                                        $currdir,$depth,$count);
                   12249:         }
                   12250:         if ($is_dir->{$item}) {
                   12251:             $depth ++;
1.1056    raeburn  12252:             push(@hierarchy,$count);
                   12253:             $parent->{$depth} = $count;
1.1055    raeburn  12254:             $datatable .=
                   12255:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12256:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12257:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12258:             $depth --;
1.1056    raeburn  12259:             pop(@hierarchy);
1.1055    raeburn  12260:         }
                   12261:     }
                   12262:     return ($count,$datatable);
                   12263: }
                   12264: 
                   12265: sub recurse_extracted_archive {
1.1056    raeburn  12266:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12267:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12268:     my $result='';
1.1056    raeburn  12269:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12270:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12271:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12272:         return $result;
                   12273:     }
                   12274:     my $dirptr = 16384;
                   12275:     my ($newdirlistref,$newlisterror) =
                   12276:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12277:     if (ref($newdirlistref) eq 'ARRAY') {
                   12278:         foreach my $dir_line (@{$newdirlistref}) {
                   12279:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12280:             unless ($item =~ /^\.+$/) {
                   12281:                 $$count ++;
1.1056    raeburn  12282:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12283:                 $titles->{$$count} = $item;
1.1055    raeburn  12284:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12285: 
1.1055    raeburn  12286:                 my $is_dir;
                   12287:                 if ($dirptr&$testdir) {
                   12288:                     $is_dir = 1;
                   12289:                 }
                   12290:                 if ($wantform) {
                   12291:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12292:                 }
                   12293:                 if ($is_dir) {
                   12294:                     $$depth ++;
1.1056    raeburn  12295:                     push(@{$hierarchy},$$count);
                   12296:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12297:                     $result .=
                   12298:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12299:                                                    $docuname,$depth,$count,
1.1056    raeburn  12300:                                                    $hierarchy,$dirorder,$children,
                   12301:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12302:                     $$depth --;
1.1056    raeburn  12303:                     pop(@{$hierarchy});
1.1055    raeburn  12304:                 }
                   12305:             }
                   12306:         }
                   12307:     }
                   12308:     return $result;
                   12309: }
                   12310: 
                   12311: sub archive_hierarchy {
                   12312:     my ($depth,$count,$parent,$children) =@_;
                   12313:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12314:         if (exists($parent->{$depth})) {
                   12315:              $children->{$parent->{$depth}} .= $count.':';
                   12316:         }
                   12317:     }
                   12318:     return;
                   12319: }
                   12320: 
                   12321: sub archive_row {
                   12322:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12323:     my ($name) = ($item =~ m{([^/]+)$});
                   12324:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12325:                                        'display'    => 'Add as file',
1.1055    raeburn  12326:                                        'dependency' => 'Include as dependency',
                   12327:                                        'discard'    => 'Discard',
                   12328:                                       );
                   12329:     if ($is_dir) {
1.1059    raeburn  12330:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12331:     }
1.1056    raeburn  12332:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12333:     my $offset = 0;
1.1055    raeburn  12334:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12335:         $offset ++;
1.1065    raeburn  12336:         if ($action ne 'display') {
                   12337:             $offset ++;
                   12338:         }  
1.1055    raeburn  12339:         $output .= '<td><span class="LC_nobreak">'.
                   12340:                    '<label><input type="radio" name="archive_'.$count.
                   12341:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12342:         my $text = $choices{$action};
                   12343:         if ($is_dir) {
                   12344:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12345:             if ($action eq 'display') {
1.1059    raeburn  12346:                 $text = &mt('Add as folder');
1.1055    raeburn  12347:             }
1.1056    raeburn  12348:         } else {
                   12349:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12350: 
                   12351:         }
                   12352:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12353:         if ($action eq 'dependency') {
                   12354:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12355:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12356:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12357:                        '<option value=""></option>'."\n".
                   12358:                        '</select>'."\n".
                   12359:                        '</div>';
1.1059    raeburn  12360:         } elsif ($action eq 'display') {
                   12361:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12362:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12363:                        '</div>';
1.1055    raeburn  12364:         }
1.1056    raeburn  12365:         $output .= '</td>';
1.1055    raeburn  12366:     }
                   12367:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12368:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12369:     for (my $i=0; $i<$depth; $i++) {
                   12370:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12371:     }
                   12372:     if ($is_dir) {
                   12373:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12374:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12375:     } else {
                   12376:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12377:     }
                   12378:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12379:                &end_data_table_row();
                   12380:     return $output;
                   12381: }
                   12382: 
                   12383: sub archive_options_form {
1.1065    raeburn  12384:     my ($form,$display,$count,$hiddenelem) = @_;
                   12385:     my %lt = &Apache::lonlocal::texthash(
                   12386:                perm => 'Permanently remove archive file?',
                   12387:                hows => 'How should each extracted item be incorporated in the course?',
                   12388:                cont => 'Content actions for all',
                   12389:                addf => 'Add as folder/file',
                   12390:                incd => 'Include as dependency for a displayed file',
                   12391:                disc => 'Discard',
                   12392:                no   => 'No',
                   12393:                yes  => 'Yes',
                   12394:                save => 'Save',
                   12395:     );
                   12396:     my $output = <<"END";
                   12397: <form name="$form" method="post" action="">
                   12398: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12399: <label>
                   12400:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12401: </label>
                   12402: &nbsp;
                   12403: <label>
                   12404:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12405: </span>
                   12406: </p>
                   12407: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12408: <br />$lt{'hows'}
                   12409: <div class="LC_columnSection">
                   12410:   <fieldset>
                   12411:     <legend>$lt{'cont'}</legend>
                   12412:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12413:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12414:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12415:   </fieldset>
                   12416: </div>
                   12417: END
                   12418:     return $output.
1.1055    raeburn  12419:            &start_data_table()."\n".
1.1065    raeburn  12420:            $display."\n".
1.1055    raeburn  12421:            &end_data_table()."\n".
                   12422:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12423:            $hiddenelem.
1.1065    raeburn  12424:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12425:            '</form>';
                   12426: }
                   12427: 
                   12428: sub archive_javascript {
1.1056    raeburn  12429:     my ($startcount,$numitems,$titles,$children) = @_;
                   12430:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12431:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12432:     my $scripttag = <<START;
                   12433: <script type="text/javascript">
                   12434: // <![CDATA[
                   12435: 
                   12436: function checkAll(form,prefix) {
                   12437:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12438:     for (var i=0; i < form.elements.length; i++) {
                   12439:         var id = form.elements[i].id;
                   12440:         if ((id != '') && (id != undefined)) {
                   12441:             if (idstr.test(id)) {
                   12442:                 if (form.elements[i].type == 'radio') {
                   12443:                     form.elements[i].checked = true;
1.1056    raeburn  12444:                     var nostart = i-$startcount;
1.1059    raeburn  12445:                     var offset = nostart%7;
                   12446:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12447:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12448:                 }
                   12449:             }
                   12450:         }
                   12451:     }
                   12452: }
                   12453: 
                   12454: function propagateCheck(form,count) {
                   12455:     if (count > 0) {
1.1059    raeburn  12456:         var startelement = $startcount + ((count-1) * 7);
                   12457:         for (var j=1; j<6; j++) {
                   12458:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12459:                 var item = startelement + j; 
                   12460:                 if (form.elements[item].type == 'radio') {
                   12461:                     if (form.elements[item].checked) {
                   12462:                         containerCheck(form,count,j);
                   12463:                         break;
                   12464:                     }
1.1055    raeburn  12465:                 }
                   12466:             }
                   12467:         }
                   12468:     }
                   12469: }
                   12470: 
                   12471: numitems = $numitems
1.1056    raeburn  12472: var titles = new Array(numitems);
                   12473: var parents = new Array(numitems);
1.1055    raeburn  12474: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12475:     parents[i] = new Array;
1.1055    raeburn  12476: }
1.1059    raeburn  12477: var maintitle = '$maintitle';
1.1055    raeburn  12478: 
                   12479: START
                   12480: 
1.1056    raeburn  12481:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12482:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12483:         for (my $i=0; $i<@contents; $i ++) {
                   12484:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12485:         }
                   12486:     }
                   12487: 
1.1056    raeburn  12488:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12489:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12490:     }
                   12491: 
1.1055    raeburn  12492:     $scripttag .= <<END;
                   12493: 
                   12494: function containerCheck(form,count,offset) {
                   12495:     if (count > 0) {
1.1056    raeburn  12496:         dependencyCheck(form,count,offset);
1.1059    raeburn  12497:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12498:         form.elements[item].checked = true;
                   12499:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12500:             if (parents[count].length > 0) {
                   12501:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12502:                     containerCheck(form,parents[count][j],offset);
                   12503:                 }
                   12504:             }
                   12505:         }
                   12506:     }
                   12507: }
                   12508: 
                   12509: function dependencyCheck(form,count,offset) {
                   12510:     if (count > 0) {
1.1059    raeburn  12511:         var chosen = (offset+$startcount)+7*(count-1);
                   12512:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12513:         var currtype = form.elements[depitem].type;
                   12514:         if (form.elements[chosen].value == 'dependency') {
                   12515:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12516:             form.elements[depitem].options.length = 0;
                   12517:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  12518:             for (var i=1; i<=numitems; i++) {
                   12519:                 if (i == count) {
                   12520:                     continue;
                   12521:                 }
1.1059    raeburn  12522:                 var startelement = $startcount + (i-1) * 7;
                   12523:                 for (var j=1; j<6; j++) {
                   12524:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12525:                         var item = startelement + j;
                   12526:                         if (form.elements[item].type == 'radio') {
                   12527:                             if (form.elements[item].checked) {
                   12528:                                 if (form.elements[item].value == 'display') {
                   12529:                                     var n = form.elements[depitem].options.length;
                   12530:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12531:                                 }
                   12532:                             }
                   12533:                         }
                   12534:                     }
                   12535:                 }
                   12536:             }
                   12537:         } else {
                   12538:             document.getElementById('arc_depon_'+count).style.display='none';
                   12539:             form.elements[depitem].options.length = 0;
                   12540:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12541:         }
1.1059    raeburn  12542:         titleCheck(form,count,offset);
1.1056    raeburn  12543:     }
                   12544: }
                   12545: 
                   12546: function propagateSelect(form,count,offset) {
                   12547:     if (count > 0) {
1.1065    raeburn  12548:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12549:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12550:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12551:             if (parents[count].length > 0) {
                   12552:                 for (var j=0; j<parents[count].length; j++) {
                   12553:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12554:                 }
                   12555:             }
                   12556:         }
                   12557:     }
                   12558: }
1.1056    raeburn  12559: 
                   12560: function containerSelect(form,count,offset,picked) {
                   12561:     if (count > 0) {
1.1065    raeburn  12562:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12563:         if (form.elements[item].type == 'radio') {
                   12564:             if (form.elements[item].value == 'dependency') {
                   12565:                 if (form.elements[item+1].type == 'select-one') {
                   12566:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12567:                         if (form.elements[item+1].options[i].value == picked) {
                   12568:                             form.elements[item+1].selectedIndex = i;
                   12569:                             break;
                   12570:                         }
                   12571:                     }
                   12572:                 }
                   12573:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12574:                     if (parents[count].length > 0) {
                   12575:                         for (var j=0; j<parents[count].length; j++) {
                   12576:                             containerSelect(form,parents[count][j],offset,picked);
                   12577:                         }
                   12578:                     }
                   12579:                 }
                   12580:             }
                   12581:         }
                   12582:     }
                   12583: }
                   12584: 
1.1059    raeburn  12585: function titleCheck(form,count,offset) {
                   12586:     if (count > 0) {
                   12587:         var chosen = (offset+$startcount)+7*(count-1);
                   12588:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12589:         var currtype = form.elements[depitem].type;
                   12590:         if (form.elements[chosen].value == 'display') {
                   12591:             document.getElementById('arc_title_'+count).style.display='block';
                   12592:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12593:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12594:             }
                   12595:         } else {
                   12596:             document.getElementById('arc_title_'+count).style.display='none';
                   12597:             if (currtype == 'text') { 
                   12598:                 document.getElementById('archive_title_'+count).value='';
                   12599:             }
                   12600:         }
                   12601:     }
                   12602:     return;
                   12603: }
                   12604: 
1.1055    raeburn  12605: // ]]>
                   12606: </script>
                   12607: END
                   12608:     return $scripttag;
                   12609: }
                   12610: 
                   12611: sub process_extracted_files {
1.1067    raeburn  12612:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12613:     my $numitems = $env{'form.archive_count'};
                   12614:     return unless ($numitems);
                   12615:     my @ids=&Apache::lonnet::current_machine_ids();
                   12616:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12617:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12618:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12619:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12620:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12621:         $pathtocheck = "$dir_root/$destination";
                   12622:         $dir = $dir_root;
                   12623:         $ishome = 1;
                   12624:     } else {
                   12625:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12626:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   12627:         $dir = "$dir_root/$docudom/$docuname";    
                   12628:     }
                   12629:     my $currdir = "$dir_root/$destination";
                   12630:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12631:     if ($env{'form.folderpath'}) {
                   12632:         my @items = split('&',$env{'form.folderpath'});
                   12633:         $folders{'0'} = $items[-2];
1.1099    raeburn  12634:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12635:             $containers{'0'}='page';
                   12636:         } else {  
                   12637:             $containers{'0'}='sequence';
                   12638:         }
1.1055    raeburn  12639:     }
                   12640:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12641:     if ($numitems) {
                   12642:         for (my $i=1; $i<=$numitems; $i++) {
                   12643:             my $path = $env{'form.archive_content_'.$i};
                   12644:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12645:                 my $item = $1;
                   12646:                 $toplevelitems{$item} = $i;
                   12647:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12648:                     $is_dir{$item} = 1;
                   12649:                 }
                   12650:             }
                   12651:         }
                   12652:     }
1.1067    raeburn  12653:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12654:     if (keys(%toplevelitems) > 0) {
                   12655:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12656:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12657:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12658:     }
1.1066    raeburn  12659:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12660:     if ($numitems) {
                   12661:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  12662:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12663:             my $path = $env{'form.archive_content_'.$i};
                   12664:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12665:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12666:                     if ($prefix ne '' && $path ne '') {
                   12667:                         if (-e $prefix.$path) {
1.1066    raeburn  12668:                             if ((@archdirs > 0) && 
                   12669:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12670:                                 $todeletedir{$prefix.$path} = 1;
                   12671:                             } else {
                   12672:                                 $todelete{$prefix.$path} = 1;
                   12673:                             }
1.1055    raeburn  12674:                         }
                   12675:                     }
                   12676:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12677:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12678:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12679:                     $docstitle = $env{'form.archive_title_'.$i};
                   12680:                     if ($docstitle eq '') {
                   12681:                         $docstitle = $title;
                   12682:                     }
1.1055    raeburn  12683:                     $outer = 0;
1.1056    raeburn  12684:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12685:                         if (@{$dirorder{$i}} > 0) {
                   12686:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12687:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12688:                                     $outer = $item;
                   12689:                                     last;
                   12690:                                 }
                   12691:                             }
                   12692:                         }
                   12693:                     }
                   12694:                     my ($errtext,$fatal) = 
                   12695:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12696:                                                '/'.$folders{$outer}.'.'.
                   12697:                                                $containers{$outer});
                   12698:                     next if ($fatal);
                   12699:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12700:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12701:                             $mapinner{$i} = time;
1.1055    raeburn  12702:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12703:                             $containers{$i} = 'sequence';
                   12704:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12705:                                       $folders{$i}.'.'.$containers{$i};
                   12706:                             my $newidx = &LONCAPA::map::getresidx();
                   12707:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12708:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12709:                             push(@LONCAPA::map::order,$newidx);
                   12710:                             my ($outtext,$errtext) =
                   12711:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12712:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  12713:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12714:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12715:                             unless ($errtext) {
                   12716:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   12717:                             }
1.1055    raeburn  12718:                         }
                   12719:                     } else {
                   12720:                         if ($context eq 'coursedocs') {
                   12721:                             my $newidx=&LONCAPA::map::getresidx();
                   12722:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12723:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12724:                                       $title;
                   12725:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12726:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   12727:                             }
                   12728:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12729:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12730:                             }
                   12731:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12732:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  12733:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  12734:                                 unless ($ishome) {
                   12735:                                     my $fetch = "$newdest{$i}/$title";
                   12736:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   12737:                                     $prompttofetch{$fetch} = 1;
                   12738:                                 }
1.1055    raeburn  12739:                             }
                   12740:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12741:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12742:                             push(@LONCAPA::map::order, $newidx);
                   12743:                             my ($outtext,$errtext)=
                   12744:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12745:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  12746:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  12747:                             unless ($errtext) {
                   12748:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12749:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   12750:                                 }
                   12751:                             }
1.1055    raeburn  12752:                         }
                   12753:                     }
1.1086    raeburn  12754:                 }
                   12755:             } else {
                   12756:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   12757:             }
                   12758:         }
                   12759:         for (my $i=1; $i<=$numitems; $i++) {
                   12760:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12761:             my $path = $env{'form.archive_content_'.$i};
                   12762:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12763:                 my ($title) = ($path =~ m{/([^/]+)$});
                   12764:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   12765:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   12766:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12767:                         my ($itemidx,$fullpath,$relpath);
                   12768:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   12769:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  12770:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  12771:                                 if ($dirorder{$i}->[$j] eq $container) {
                   12772:                                     $itemidx = $j;
1.1056    raeburn  12773:                                 }
                   12774:                             }
1.1086    raeburn  12775:                         }
                   12776:                         if ($itemidx eq '') {
                   12777:                             $itemidx =  0;
                   12778:                         } 
                   12779:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   12780:                             if ($mapinner{$referrer{$i}}) {
                   12781:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   12782:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12783:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12784:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12785:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12786:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12787:                                             if (!-e $fullpath) {
                   12788:                                                 mkdir($fullpath,0755);
1.1056    raeburn  12789:                                             }
                   12790:                                         }
1.1086    raeburn  12791:                                     } else {
                   12792:                                         last;
1.1056    raeburn  12793:                                     }
1.1086    raeburn  12794:                                 }
                   12795:                             }
                   12796:                         } elsif ($newdest{$referrer{$i}}) {
                   12797:                             $fullpath = $newdest{$referrer{$i}};
                   12798:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12799:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   12800:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   12801:                                     last;
                   12802:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12803:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12804:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12805:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12806:                                         if (!-e $fullpath) {
                   12807:                                             mkdir($fullpath,0755);
1.1056    raeburn  12808:                                         }
                   12809:                                     }
1.1086    raeburn  12810:                                 } else {
                   12811:                                     last;
1.1056    raeburn  12812:                                 }
1.1055    raeburn  12813:                             }
                   12814:                         }
1.1086    raeburn  12815:                         if ($fullpath ne '') {
                   12816:                             if (-e "$prefix$path") {
                   12817:                                 system("mv $prefix$path $fullpath/$title");
                   12818:                             }
                   12819:                             if (-e "$fullpath/$title") {
                   12820:                                 my $showpath;
                   12821:                                 if ($relpath ne '') {
                   12822:                                     $showpath = "$relpath/$title";
                   12823:                                 } else {
                   12824:                                     $showpath = "/$title";
                   12825:                                 } 
                   12826:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   12827:                             } 
                   12828:                             unless ($ishome) {
                   12829:                                 my $fetch = "$fullpath/$title";
                   12830:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
                   12831:                                 $prompttofetch{$fetch} = 1;
                   12832:                             }
                   12833:                         }
1.1055    raeburn  12834:                     }
1.1086    raeburn  12835:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   12836:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   12837:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  12838:                 }
                   12839:             } else {
                   12840:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   12841:             }
                   12842:         }
                   12843:         if (keys(%todelete)) {
                   12844:             foreach my $key (keys(%todelete)) {
                   12845:                 unlink($key);
1.1066    raeburn  12846:             }
                   12847:         }
                   12848:         if (keys(%todeletedir)) {
                   12849:             foreach my $key (keys(%todeletedir)) {
                   12850:                 rmdir($key);
                   12851:             }
                   12852:         }
                   12853:         foreach my $dir (sort(keys(%is_dir))) {
                   12854:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   12855:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  12856:             }
                   12857:         }
1.1067    raeburn  12858:         if ($result ne '') {
                   12859:             $output .= '<ul>'."\n".
                   12860:                        $result."\n".
                   12861:                        '</ul>';
                   12862:         }
                   12863:         unless ($ishome) {
                   12864:             my $replicationfail;
                   12865:             foreach my $item (keys(%prompttofetch)) {
                   12866:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   12867:                 unless ($fetchresult eq 'ok') {
                   12868:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   12869:                 }
                   12870:             }
                   12871:             if ($replicationfail) {
                   12872:                 $output .= '<p class="LC_error">'.
                   12873:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   12874:                            $replicationfail.
                   12875:                            '</ul></p>';
                   12876:             }
                   12877:         }
1.1055    raeburn  12878:     } else {
                   12879:         $warning = &mt('No items found in archive.');
                   12880:     }
                   12881:     if ($error) {
                   12882:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12883:                    $error.'</p>'."\n";
                   12884:     }
                   12885:     if ($warning) {
                   12886:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12887:     }
                   12888:     return $output;
                   12889: }
                   12890: 
1.1066    raeburn  12891: sub cleanup_empty_dirs {
                   12892:     my ($path) = @_;
                   12893:     if (($path ne '') && (-d $path)) {
                   12894:         if (opendir(my $dirh,$path)) {
                   12895:             my @dircontents = grep(!/^\./,readdir($dirh));
                   12896:             my $numitems = 0;
                   12897:             foreach my $item (@dircontents) {
                   12898:                 if (-d "$path/$item") {
1.1111    raeburn  12899:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  12900:                     if (-e "$path/$item") {
                   12901:                         $numitems ++;
                   12902:                     }
                   12903:                 } else {
                   12904:                     $numitems ++;
                   12905:                 }
                   12906:             }
                   12907:             if ($numitems == 0) {
                   12908:                 rmdir($path);
                   12909:             }
                   12910:             closedir($dirh);
                   12911:         }
                   12912:     }
                   12913:     return;
                   12914: }
                   12915: 
1.41      ng       12916: =pod
1.45      matthew  12917: 
1.1162    raeburn  12918: =item * &get_folder_hierarchy()
1.1068    raeburn  12919: 
                   12920: Provides hierarchy of names of folders/sub-folders containing the current
                   12921: item,
                   12922: 
                   12923: Inputs: 3
                   12924:      - $navmap - navmaps object
                   12925: 
                   12926:      - $map - url for map (either the trigger itself, or map containing
                   12927:                            the resource, which is the trigger).
                   12928: 
                   12929:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   12930: 
                   12931: Outputs: 1 @pathitems - array of folder/subfolder names.
                   12932: 
                   12933: =cut
                   12934: 
                   12935: sub get_folder_hierarchy {
                   12936:     my ($navmap,$map,$showitem) = @_;
                   12937:     my @pathitems;
                   12938:     if (ref($navmap)) {
                   12939:         my $mapres = $navmap->getResourceByUrl($map);
                   12940:         if (ref($mapres)) {
                   12941:             my $pcslist = $mapres->map_hierarchy();
                   12942:             if ($pcslist ne '') {
                   12943:                 my @pcs = split(/,/,$pcslist);
                   12944:                 foreach my $pc (@pcs) {
                   12945:                     if ($pc == 1) {
1.1129    raeburn  12946:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  12947:                     } else {
                   12948:                         my $res = $navmap->getByMapPc($pc);
                   12949:                         if (ref($res)) {
                   12950:                             my $title = $res->compTitle();
                   12951:                             $title =~ s/\W+/_/g;
                   12952:                             if ($title ne '') {
                   12953:                                 push(@pathitems,$title);
                   12954:                             }
                   12955:                         }
                   12956:                     }
                   12957:                 }
                   12958:             }
1.1071    raeburn  12959:             if ($showitem) {
                   12960:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  12961:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  12962:                 } else {
                   12963:                     my $maptitle = $mapres->compTitle();
                   12964:                     $maptitle =~ s/\W+/_/g;
                   12965:                     if ($maptitle ne '') {
                   12966:                         push(@pathitems,$maptitle);
                   12967:                     }
1.1068    raeburn  12968:                 }
                   12969:             }
                   12970:         }
                   12971:     }
                   12972:     return @pathitems;
                   12973: }
                   12974: 
                   12975: =pod
                   12976: 
1.1015    raeburn  12977: =item * &get_turnedin_filepath()
                   12978: 
                   12979: Determines path in a user's portfolio file for storage of files uploaded
                   12980: to a specific essayresponse or dropbox item.
                   12981: 
                   12982: Inputs: 3 required + 1 optional.
                   12983: $symb is symb for resource, $uname and $udom are for current user (required).
                   12984: $caller is optional (can be "submission", if routine is called when storing
                   12985: an upoaded file when "Submit Answer" button was pressed).
                   12986: 
                   12987: Returns array containing $path and $multiresp. 
                   12988: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   12989: than one file upload item.  Callers of routine should append partid as a 
                   12990: subdirectory to $path in cases where $multiresp is 1.
                   12991: 
                   12992: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   12993: 
                   12994: =cut
                   12995: 
                   12996: sub get_turnedin_filepath {
                   12997:     my ($symb,$uname,$udom,$caller) = @_;
                   12998:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   12999:     my $turnindir;
                   13000:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13001:     $turnindir = $userhash{'turnindir'};
                   13002:     my ($path,$multiresp);
                   13003:     if ($turnindir eq '') {
                   13004:         if ($caller eq 'submission') {
                   13005:             $turnindir = &mt('turned in');
                   13006:             $turnindir =~ s/\W+/_/g;
                   13007:             my %newhash = (
                   13008:                             'turnindir' => $turnindir,
                   13009:                           );
                   13010:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13011:         }
                   13012:     }
                   13013:     if ($turnindir ne '') {
                   13014:         $path = '/'.$turnindir.'/';
                   13015:         my ($multipart,$turnin,@pathitems);
                   13016:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13017:         if (defined($navmap)) {
                   13018:             my $mapres = $navmap->getResourceByUrl($map);
                   13019:             if (ref($mapres)) {
                   13020:                 my $pcslist = $mapres->map_hierarchy();
                   13021:                 if ($pcslist ne '') {
                   13022:                     foreach my $pc (split(/,/,$pcslist)) {
                   13023:                         my $res = $navmap->getByMapPc($pc);
                   13024:                         if (ref($res)) {
                   13025:                             my $title = $res->compTitle();
                   13026:                             $title =~ s/\W+/_/g;
                   13027:                             if ($title ne '') {
1.1149    raeburn  13028:                                 if (($pc > 1) && (length($title) > 12)) {
                   13029:                                     $title = substr($title,0,12);
                   13030:                                 }
1.1015    raeburn  13031:                                 push(@pathitems,$title);
                   13032:                             }
                   13033:                         }
                   13034:                     }
                   13035:                 }
                   13036:                 my $maptitle = $mapres->compTitle();
                   13037:                 $maptitle =~ s/\W+/_/g;
                   13038:                 if ($maptitle ne '') {
1.1149    raeburn  13039:                     if (length($maptitle) > 12) {
                   13040:                         $maptitle = substr($maptitle,0,12);
                   13041:                     }
1.1015    raeburn  13042:                     push(@pathitems,$maptitle);
                   13043:                 }
                   13044:                 unless ($env{'request.state'} eq 'construct') {
                   13045:                     my $res = $navmap->getBySymb($symb);
                   13046:                     if (ref($res)) {
                   13047:                         my $partlist = $res->parts();
                   13048:                         my $totaluploads = 0;
                   13049:                         if (ref($partlist) eq 'ARRAY') {
                   13050:                             foreach my $part (@{$partlist}) {
                   13051:                                 my @types = $res->responseType($part);
                   13052:                                 my @ids = $res->responseIds($part);
                   13053:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13054:                                     if ($types[$i] eq 'essay') {
                   13055:                                         my $partid = $part.'_'.$ids[$i];
                   13056:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13057:                                             $totaluploads ++;
                   13058:                                         }
                   13059:                                     }
                   13060:                                 }
                   13061:                             }
                   13062:                             if ($totaluploads > 1) {
                   13063:                                 $multiresp = 1;
                   13064:                             }
                   13065:                         }
                   13066:                     }
                   13067:                 }
                   13068:             } else {
                   13069:                 return;
                   13070:             }
                   13071:         } else {
                   13072:             return;
                   13073:         }
                   13074:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13075:         $restitle =~ s/\W+/_/g;
                   13076:         if ($restitle eq '') {
                   13077:             $restitle = ($resurl =~ m{/[^/]+$});
                   13078:             if ($restitle eq '') {
                   13079:                 $restitle = time;
                   13080:             }
                   13081:         }
1.1149    raeburn  13082:         if (length($restitle) > 12) {
                   13083:             $restitle = substr($restitle,0,12);
                   13084:         }
1.1015    raeburn  13085:         push(@pathitems,$restitle);
                   13086:         $path .= join('/',@pathitems);
                   13087:     }
                   13088:     return ($path,$multiresp);
                   13089: }
                   13090: 
                   13091: =pod
                   13092: 
1.464     albertel 13093: =back
1.41      ng       13094: 
1.112     bowersj2 13095: =head1 CSV Upload/Handling functions
1.38      albertel 13096: 
1.41      ng       13097: =over 4
                   13098: 
1.648     raeburn  13099: =item * &upfile_store($r)
1.41      ng       13100: 
                   13101: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13102: needs $env{'form.upfile'}
1.41      ng       13103: returns $datatoken to be put into hidden field
                   13104: 
                   13105: =cut
1.31      albertel 13106: 
                   13107: sub upfile_store {
                   13108:     my $r=shift;
1.258     albertel 13109:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13110:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13111:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13112:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13113: 
1.258     albertel 13114:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   13115: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 13116:     {
1.158     raeburn  13117:         my $datafile = $r->dir_config('lonDaemons').
                   13118:                            '/tmp/'.$datatoken.'.tmp';
                   13119:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 13120:             print $fh $env{'form.upfile'};
1.158     raeburn  13121:             close($fh);
                   13122:         }
1.31      albertel 13123:     }
                   13124:     return $datatoken;
                   13125: }
                   13126: 
1.56      matthew  13127: =pod
                   13128: 
1.648     raeburn  13129: =item * &load_tmp_file($r)
1.41      ng       13130: 
                   13131: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 13132: needs $env{'form.datatoken'},
                   13133: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13134: 
                   13135: =cut
1.31      albertel 13136: 
                   13137: sub load_tmp_file {
                   13138:     my $r=shift;
                   13139:     my @studentdata=();
                   13140:     {
1.158     raeburn  13141:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 13142:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  13143:         if ( open(my $fh,"<$studentfile") ) {
                   13144:             @studentdata=<$fh>;
                   13145:             close($fh);
                   13146:         }
1.31      albertel 13147:     }
1.258     albertel 13148:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13149: }
                   13150: 
1.56      matthew  13151: =pod
                   13152: 
1.648     raeburn  13153: =item * &upfile_record_sep()
1.41      ng       13154: 
                   13155: Separate uploaded file into records
                   13156: returns array of records,
1.258     albertel 13157: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13158: 
                   13159: =cut
1.31      albertel 13160: 
                   13161: sub upfile_record_sep {
1.258     albertel 13162:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13163:     } else {
1.248     albertel 13164: 	my @records;
1.258     albertel 13165: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13166: 	    if ($line=~/^\s*$/) { next; }
                   13167: 	    push(@records,$line);
                   13168: 	}
                   13169: 	return @records;
1.31      albertel 13170:     }
                   13171: }
                   13172: 
1.56      matthew  13173: =pod
                   13174: 
1.648     raeburn  13175: =item * &record_sep($record)
1.41      ng       13176: 
1.258     albertel 13177: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13178: 
                   13179: =cut
                   13180: 
1.263     www      13181: sub takeleft {
                   13182:     my $index=shift;
                   13183:     return substr('0000'.$index,-4,4);
                   13184: }
                   13185: 
1.31      albertel 13186: sub record_sep {
                   13187:     my $record=shift;
                   13188:     my %components=();
1.258     albertel 13189:     if ($env{'form.upfiletype'} eq 'xml') {
                   13190:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13191:         my $i=0;
1.356     albertel 13192:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13193:             $field=~s/^(\"|\')//;
                   13194:             $field=~s/(\"|\')$//;
1.263     www      13195:             $components{&takeleft($i)}=$field;
1.31      albertel 13196:             $i++;
                   13197:         }
1.258     albertel 13198:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13199:         my $i=0;
1.356     albertel 13200:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13201:             $field=~s/^(\"|\')//;
                   13202:             $field=~s/(\"|\')$//;
1.263     www      13203:             $components{&takeleft($i)}=$field;
1.31      albertel 13204:             $i++;
                   13205:         }
                   13206:     } else {
1.561     www      13207:         my $separator=',';
1.480     banghart 13208:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13209:             $separator=';';
1.480     banghart 13210:         }
1.31      albertel 13211:         my $i=0;
1.561     www      13212: # the character we are looking for to indicate the end of a quote or a record 
                   13213:         my $looking_for=$separator;
                   13214: # do not add the characters to the fields
                   13215:         my $ignore=0;
                   13216: # we just encountered a separator (or the beginning of the record)
                   13217:         my $just_found_separator=1;
                   13218: # store the field we are working on here
                   13219:         my $field='';
                   13220: # work our way through all characters in record
                   13221:         foreach my $character ($record=~/(.)/g) {
                   13222:             if ($character eq $looking_for) {
                   13223:                if ($character ne $separator) {
                   13224: # Found the end of a quote, again looking for separator
                   13225:                   $looking_for=$separator;
                   13226:                   $ignore=1;
                   13227:                } else {
                   13228: # Found a separator, store away what we got
                   13229:                   $components{&takeleft($i)}=$field;
                   13230: 	          $i++;
                   13231:                   $just_found_separator=1;
                   13232:                   $ignore=0;
                   13233:                   $field='';
                   13234:                }
                   13235:                next;
                   13236:             }
                   13237: # single or double quotation marks after a separator indicate beginning of a quote
                   13238: # we are now looking for the end of the quote and need to ignore separators
                   13239:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13240:                $looking_for=$character;
                   13241:                next;
                   13242:             }
                   13243: # ignore would be true after we reached the end of a quote
                   13244:             if ($ignore) { next; }
                   13245:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13246:             $field.=$character;
                   13247:             $just_found_separator=0; 
1.31      albertel 13248:         }
1.561     www      13249: # catch the very last entry, since we never encountered the separator
                   13250:         $components{&takeleft($i)}=$field;
1.31      albertel 13251:     }
                   13252:     return %components;
                   13253: }
                   13254: 
1.144     matthew  13255: ######################################################
                   13256: ######################################################
                   13257: 
1.56      matthew  13258: =pod
                   13259: 
1.648     raeburn  13260: =item * &upfile_select_html()
1.41      ng       13261: 
1.144     matthew  13262: Return HTML code to select a file from the users machine and specify 
                   13263: the file type.
1.41      ng       13264: 
                   13265: =cut
                   13266: 
1.144     matthew  13267: ######################################################
                   13268: ######################################################
1.31      albertel 13269: sub upfile_select_html {
1.144     matthew  13270:     my %Types = (
                   13271:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13272:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13273:                  space => &mt('Space separated'),
                   13274:                  tab   => &mt('Tabulator separated'),
                   13275: #                 xml   => &mt('HTML/XML'),
                   13276:                  );
                   13277:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13278:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13279:     foreach my $type (sort(keys(%Types))) {
                   13280:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13281:     }
                   13282:     $Str .= "</select>\n";
                   13283:     return $Str;
1.31      albertel 13284: }
                   13285: 
1.301     albertel 13286: sub get_samples {
                   13287:     my ($records,$toget) = @_;
                   13288:     my @samples=({});
                   13289:     my $got=0;
                   13290:     foreach my $rec (@$records) {
                   13291: 	my %temp = &record_sep($rec);
                   13292: 	if (! grep(/\S/, values(%temp))) { next; }
                   13293: 	if (%temp) {
                   13294: 	    $samples[$got]=\%temp;
                   13295: 	    $got++;
                   13296: 	    if ($got == $toget) { last; }
                   13297: 	}
                   13298:     }
                   13299:     return \@samples;
                   13300: }
                   13301: 
1.144     matthew  13302: ######################################################
                   13303: ######################################################
                   13304: 
1.56      matthew  13305: =pod
                   13306: 
1.648     raeburn  13307: =item * &csv_print_samples($r,$records)
1.41      ng       13308: 
                   13309: Prints a table of sample values from each column uploaded $r is an
                   13310: Apache Request ref, $records is an arrayref from
                   13311: &Apache::loncommon::upfile_record_sep
                   13312: 
                   13313: =cut
                   13314: 
1.144     matthew  13315: ######################################################
                   13316: ######################################################
1.31      albertel 13317: sub csv_print_samples {
                   13318:     my ($r,$records) = @_;
1.662     bisitz   13319:     my $samples = &get_samples($records,5);
1.301     albertel 13320: 
1.594     raeburn  13321:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13322:               &start_data_table_header_row());
1.356     albertel 13323:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13324:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13325:     $r->print(&end_data_table_header_row());
1.301     albertel 13326:     foreach my $hash (@$samples) {
1.594     raeburn  13327: 	$r->print(&start_data_table_row());
1.356     albertel 13328: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13329: 	    $r->print('<td>');
1.356     albertel 13330: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13331: 	    $r->print('</td>');
                   13332: 	}
1.594     raeburn  13333: 	$r->print(&end_data_table_row());
1.31      albertel 13334:     }
1.594     raeburn  13335:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13336: }
                   13337: 
1.144     matthew  13338: ######################################################
                   13339: ######################################################
                   13340: 
1.56      matthew  13341: =pod
                   13342: 
1.648     raeburn  13343: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13344: 
                   13345: Prints a table to create associations between values and table columns.
1.144     matthew  13346: 
1.41      ng       13347: $r is an Apache Request ref,
                   13348: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13349: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13350: 
                   13351: =cut
                   13352: 
1.144     matthew  13353: ######################################################
                   13354: ######################################################
1.31      albertel 13355: sub csv_print_select_table {
                   13356:     my ($r,$records,$d) = @_;
1.301     albertel 13357:     my $i=0;
                   13358:     my $samples = &get_samples($records,1);
1.144     matthew  13359:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13360: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13361:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13362:               '<th>'.&mt('Column').'</th>'.
                   13363:               &end_data_table_header_row()."\n");
1.356     albertel 13364:     foreach my $array_ref (@$d) {
                   13365: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13366: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13367: 
1.875     bisitz   13368: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13369: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13370: 	$r->print('<option value="none"></option>');
1.356     albertel 13371: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13372: 	    $r->print('<option value="'.$sample.'"'.
                   13373:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13374:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13375: 	}
1.594     raeburn  13376: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13377: 	$i++;
                   13378:     }
1.594     raeburn  13379:     $r->print(&end_data_table());
1.31      albertel 13380:     $i--;
                   13381:     return $i;
                   13382: }
1.56      matthew  13383: 
1.144     matthew  13384: ######################################################
                   13385: ######################################################
                   13386: 
1.56      matthew  13387: =pod
1.31      albertel 13388: 
1.648     raeburn  13389: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13390: 
                   13391: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13392: 
                   13393: $r is an Apache Request ref,
                   13394: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13395: $d is an array of 2 element arrays (internal name, displayed name)
                   13396: 
                   13397: =cut
                   13398: 
1.144     matthew  13399: ######################################################
                   13400: ######################################################
1.31      albertel 13401: sub csv_samples_select_table {
                   13402:     my ($r,$records,$d) = @_;
                   13403:     my $i=0;
1.144     matthew  13404:     #
1.662     bisitz   13405:     my $max_samples = 5;
                   13406:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13407:     $r->print(&start_data_table().
                   13408:               &start_data_table_header_row().'<th>'.
                   13409:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13410:               &end_data_table_header_row());
1.301     albertel 13411: 
                   13412:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13413: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13414: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13415: 	foreach my $option (@$d) {
                   13416: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13417: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13418:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13419:                       $display.'</option>');
1.31      albertel 13420: 	}
                   13421: 	$r->print('</select></td><td>');
1.662     bisitz   13422: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13423: 	    if (defined($samples->[$line]{$key})) { 
                   13424: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13425: 	    }
                   13426: 	}
1.594     raeburn  13427: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13428: 	$i++;
                   13429:     }
1.594     raeburn  13430:     $r->print(&end_data_table());
1.31      albertel 13431:     $i--;
                   13432:     return($i);
1.115     matthew  13433: }
                   13434: 
1.144     matthew  13435: ######################################################
                   13436: ######################################################
                   13437: 
1.115     matthew  13438: =pod
                   13439: 
1.648     raeburn  13440: =item * &clean_excel_name($name)
1.115     matthew  13441: 
                   13442: Returns a replacement for $name which does not contain any illegal characters.
                   13443: 
                   13444: =cut
                   13445: 
1.144     matthew  13446: ######################################################
                   13447: ######################################################
1.115     matthew  13448: sub clean_excel_name {
                   13449:     my ($name) = @_;
                   13450:     $name =~ s/[:\*\?\/\\]//g;
                   13451:     if (length($name) > 31) {
                   13452:         $name = substr($name,0,31);
                   13453:     }
                   13454:     return $name;
1.25      albertel 13455: }
1.84      albertel 13456: 
1.85      albertel 13457: =pod
                   13458: 
1.648     raeburn  13459: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13460: 
                   13461: Returns either 1 or undef
                   13462: 
                   13463: 1 if the part is to be hidden, undef if it is to be shown
                   13464: 
                   13465: Arguments are:
                   13466: 
                   13467: $id the id of the part to be checked
                   13468: $symb, optional the symb of the resource to check
                   13469: $udom, optional the domain of the user to check for
                   13470: $uname, optional the username of the user to check for
                   13471: 
                   13472: =cut
1.84      albertel 13473: 
                   13474: sub check_if_partid_hidden {
                   13475:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13476:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13477: 					 $symb,$udom,$uname);
1.141     albertel 13478:     my $truth=1;
                   13479:     #if the string starts with !, then the list is the list to show not hide
                   13480:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13481:     my @hiddenlist=split(/,/,$hiddenparts);
                   13482:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13483: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13484:     }
1.141     albertel 13485:     return !$truth;
1.84      albertel 13486: }
1.127     matthew  13487: 
1.138     matthew  13488: 
                   13489: ############################################################
                   13490: ############################################################
                   13491: 
                   13492: =pod
                   13493: 
1.157     matthew  13494: =back 
                   13495: 
1.138     matthew  13496: =head1 cgi-bin script and graphing routines
                   13497: 
1.157     matthew  13498: =over 4
                   13499: 
1.648     raeburn  13500: =item * &get_cgi_id()
1.138     matthew  13501: 
                   13502: Inputs: none
                   13503: 
                   13504: Returns an id which can be used to pass environment variables
                   13505: to various cgi-bin scripts.  These environment variables will
                   13506: be removed from the users environment after a given time by
                   13507: the routine &Apache::lonnet::transfer_profile_to_env.
                   13508: 
                   13509: =cut
                   13510: 
                   13511: ############################################################
                   13512: ############################################################
1.152     albertel 13513: my $uniq=0;
1.136     matthew  13514: sub get_cgi_id {
1.154     albertel 13515:     $uniq=($uniq+1)%100000;
1.280     albertel 13516:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13517: }
                   13518: 
1.127     matthew  13519: ############################################################
                   13520: ############################################################
                   13521: 
                   13522: =pod
                   13523: 
1.648     raeburn  13524: =item * &DrawBarGraph()
1.127     matthew  13525: 
1.138     matthew  13526: Facilitates the plotting of data in a (stacked) bar graph.
                   13527: Puts plot definition data into the users environment in order for 
                   13528: graph.png to plot it.  Returns an <img> tag for the plot.
                   13529: The bars on the plot are labeled '1','2',...,'n'.
                   13530: 
                   13531: Inputs:
                   13532: 
                   13533: =over 4
                   13534: 
                   13535: =item $Title: string, the title of the plot
                   13536: 
                   13537: =item $xlabel: string, text describing the X-axis of the plot
                   13538: 
                   13539: =item $ylabel: string, text describing the Y-axis of the plot
                   13540: 
                   13541: =item $Max: scalar, the maximum Y value to use in the plot
                   13542: If $Max is < any data point, the graph will not be rendered.
                   13543: 
1.140     matthew  13544: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13545: they are plotted.  If undefined, default values will be used.
                   13546: 
1.178     matthew  13547: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13548: 
1.138     matthew  13549: =item @Values: An array of array references.  Each array reference holds data
                   13550: to be plotted in a stacked bar chart.
                   13551: 
1.239     matthew  13552: =item If the final element of @Values is a hash reference the key/value
                   13553: pairs will be added to the graph definition.
                   13554: 
1.138     matthew  13555: =back
                   13556: 
                   13557: Returns:
                   13558: 
                   13559: An <img> tag which references graph.png and the appropriate identifying
                   13560: information for the plot.
                   13561: 
1.127     matthew  13562: =cut
                   13563: 
                   13564: ############################################################
                   13565: ############################################################
1.134     matthew  13566: sub DrawBarGraph {
1.178     matthew  13567:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13568:     #
                   13569:     if (! defined($colors)) {
                   13570:         $colors = ['#33ff00', 
                   13571:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13572:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13573:                   ]; 
                   13574:     }
1.228     matthew  13575:     my $extra_settings = {};
                   13576:     if (ref($Values[-1]) eq 'HASH') {
                   13577:         $extra_settings = pop(@Values);
                   13578:     }
1.127     matthew  13579:     #
1.136     matthew  13580:     my $identifier = &get_cgi_id();
                   13581:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13582:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13583:         return '';
                   13584:     }
1.225     matthew  13585:     #
                   13586:     my @Labels;
                   13587:     if (defined($labels)) {
                   13588:         @Labels = @$labels;
                   13589:     } else {
                   13590:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   13591:             push (@Labels,$i+1);
                   13592:         }
                   13593:     }
                   13594:     #
1.129     matthew  13595:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13596:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13597:     my %ValuesHash;
                   13598:     my $NumSets=1;
                   13599:     foreach my $array (@Values) {
                   13600:         next if (! ref($array));
1.136     matthew  13601:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13602:             join(',',@$array);
1.129     matthew  13603:     }
1.127     matthew  13604:     #
1.136     matthew  13605:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13606:     if ($NumBars < 3) {
                   13607:         $width = 120+$NumBars*32;
1.220     matthew  13608:         $xskip = 1;
1.225     matthew  13609:         $bar_width = 30;
                   13610:     } elsif ($NumBars < 5) {
                   13611:         $width = 120+$NumBars*20;
                   13612:         $xskip = 1;
                   13613:         $bar_width = 20;
1.220     matthew  13614:     } elsif ($NumBars < 10) {
1.136     matthew  13615:         $width = 120+$NumBars*15;
                   13616:         $xskip = 1;
                   13617:         $bar_width = 15;
                   13618:     } elsif ($NumBars <= 25) {
                   13619:         $width = 120+$NumBars*11;
                   13620:         $xskip = 5;
                   13621:         $bar_width = 8;
                   13622:     } elsif ($NumBars <= 50) {
                   13623:         $width = 120+$NumBars*8;
                   13624:         $xskip = 5;
                   13625:         $bar_width = 4;
                   13626:     } else {
                   13627:         $width = 120+$NumBars*8;
                   13628:         $xskip = 5;
                   13629:         $bar_width = 4;
                   13630:     }
                   13631:     #
1.137     matthew  13632:     $Max = 1 if ($Max < 1);
                   13633:     if ( int($Max) < $Max ) {
                   13634:         $Max++;
                   13635:         $Max = int($Max);
                   13636:     }
1.127     matthew  13637:     $Title  = '' if (! defined($Title));
                   13638:     $xlabel = '' if (! defined($xlabel));
                   13639:     $ylabel = '' if (! defined($ylabel));
1.369     www      13640:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13641:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13642:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13643:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13644:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13645:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13646:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13647:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13648:     $ValuesHash{$id.'.height'}   = $height;
                   13649:     $ValuesHash{$id.'.width'}    = $width;
                   13650:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13651:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13652:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13653:     #
1.228     matthew  13654:     # Deal with other parameters
                   13655:     while (my ($key,$value) = each(%$extra_settings)) {
                   13656:         $ValuesHash{$id.'.'.$key} = $value;
                   13657:     }
                   13658:     #
1.646     raeburn  13659:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13660:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13661: }
                   13662: 
                   13663: ############################################################
                   13664: ############################################################
                   13665: 
                   13666: =pod
                   13667: 
1.648     raeburn  13668: =item * &DrawXYGraph()
1.137     matthew  13669: 
1.138     matthew  13670: Facilitates the plotting of data in an XY graph.
                   13671: Puts plot definition data into the users environment in order for 
                   13672: graph.png to plot it.  Returns an <img> tag for the plot.
                   13673: 
                   13674: Inputs:
                   13675: 
                   13676: =over 4
                   13677: 
                   13678: =item $Title: string, the title of the plot
                   13679: 
                   13680: =item $xlabel: string, text describing the X-axis of the plot
                   13681: 
                   13682: =item $ylabel: string, text describing the Y-axis of the plot
                   13683: 
                   13684: =item $Max: scalar, the maximum Y value to use in the plot
                   13685: If $Max is < any data point, the graph will not be rendered.
                   13686: 
                   13687: =item $colors: Array ref containing the hex color codes for the data to be 
                   13688: plotted in.  If undefined, default values will be used.
                   13689: 
                   13690: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13691: 
                   13692: =item $Ydata: Array ref containing Array refs.  
1.185     www      13693: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13694: 
                   13695: =item %Values: hash indicating or overriding any default values which are 
                   13696: passed to graph.png.  
                   13697: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13698: 
                   13699: =back
                   13700: 
                   13701: Returns:
                   13702: 
                   13703: An <img> tag which references graph.png and the appropriate identifying
                   13704: information for the plot.
                   13705: 
1.137     matthew  13706: =cut
                   13707: 
                   13708: ############################################################
                   13709: ############################################################
                   13710: sub DrawXYGraph {
                   13711:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13712:     #
                   13713:     # Create the identifier for the graph
                   13714:     my $identifier = &get_cgi_id();
                   13715:     my $id = 'cgi.'.$identifier;
                   13716:     #
                   13717:     $Title  = '' if (! defined($Title));
                   13718:     $xlabel = '' if (! defined($xlabel));
                   13719:     $ylabel = '' if (! defined($ylabel));
                   13720:     my %ValuesHash = 
                   13721:         (
1.369     www      13722:          $id.'.title'  => &escape($Title),
                   13723:          $id.'.xlabel' => &escape($xlabel),
                   13724:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13725:          $id.'.y_max_value'=> $Max,
                   13726:          $id.'.labels'     => join(',',@$Xlabels),
                   13727:          $id.'.PlotType'   => 'XY',
                   13728:          );
                   13729:     #
                   13730:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13731:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13732:     }
                   13733:     #
                   13734:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13735:         return '';
                   13736:     }
                   13737:     my $NumSets=1;
1.138     matthew  13738:     foreach my $array (@{$Ydata}){
1.137     matthew  13739:         next if (! ref($array));
                   13740:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13741:     }
1.138     matthew  13742:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  13743:     #
                   13744:     # Deal with other parameters
                   13745:     while (my ($key,$value) = each(%Values)) {
                   13746:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  13747:     }
                   13748:     #
1.646     raeburn  13749:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  13750:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13751: }
                   13752: 
                   13753: ############################################################
                   13754: ############################################################
                   13755: 
                   13756: =pod
                   13757: 
1.648     raeburn  13758: =item * &DrawXYYGraph()
1.138     matthew  13759: 
                   13760: Facilitates the plotting of data in an XY graph with two Y axes.
                   13761: Puts plot definition data into the users environment in order for 
                   13762: graph.png to plot it.  Returns an <img> tag for the plot.
                   13763: 
                   13764: Inputs:
                   13765: 
                   13766: =over 4
                   13767: 
                   13768: =item $Title: string, the title of the plot
                   13769: 
                   13770: =item $xlabel: string, text describing the X-axis of the plot
                   13771: 
                   13772: =item $ylabel: string, text describing the Y-axis of the plot
                   13773: 
                   13774: =item $colors: Array ref containing the hex color codes for the data to be 
                   13775: plotted in.  If undefined, default values will be used.
                   13776: 
                   13777: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13778: 
                   13779: =item $Ydata1: The first data set
                   13780: 
                   13781: =item $Min1: The minimum value of the left Y-axis
                   13782: 
                   13783: =item $Max1: The maximum value of the left Y-axis
                   13784: 
                   13785: =item $Ydata2: The second data set
                   13786: 
                   13787: =item $Min2: The minimum value of the right Y-axis
                   13788: 
                   13789: =item $Max2: The maximum value of the left Y-axis
                   13790: 
                   13791: =item %Values: hash indicating or overriding any default values which are 
                   13792: passed to graph.png.  
                   13793: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13794: 
                   13795: =back
                   13796: 
                   13797: Returns:
                   13798: 
                   13799: An <img> tag which references graph.png and the appropriate identifying
                   13800: information for the plot.
1.136     matthew  13801: 
                   13802: =cut
                   13803: 
                   13804: ############################################################
                   13805: ############################################################
1.137     matthew  13806: sub DrawXYYGraph {
                   13807:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   13808:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  13809:     #
                   13810:     # Create the identifier for the graph
                   13811:     my $identifier = &get_cgi_id();
                   13812:     my $id = 'cgi.'.$identifier;
                   13813:     #
                   13814:     $Title  = '' if (! defined($Title));
                   13815:     $xlabel = '' if (! defined($xlabel));
                   13816:     $ylabel = '' if (! defined($ylabel));
                   13817:     my %ValuesHash = 
                   13818:         (
1.369     www      13819:          $id.'.title'  => &escape($Title),
                   13820:          $id.'.xlabel' => &escape($xlabel),
                   13821:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  13822:          $id.'.labels' => join(',',@$Xlabels),
                   13823:          $id.'.PlotType' => 'XY',
                   13824:          $id.'.NumSets' => 2,
1.137     matthew  13825:          $id.'.two_axes' => 1,
                   13826:          $id.'.y1_max_value' => $Max1,
                   13827:          $id.'.y1_min_value' => $Min1,
                   13828:          $id.'.y2_max_value' => $Max2,
                   13829:          $id.'.y2_min_value' => $Min2,
1.136     matthew  13830:          );
                   13831:     #
1.137     matthew  13832:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13833:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13834:     }
                   13835:     #
                   13836:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   13837:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  13838:         return '';
                   13839:     }
                   13840:     my $NumSets=1;
1.137     matthew  13841:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  13842:         next if (! ref($array));
                   13843:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  13844:     }
                   13845:     #
                   13846:     # Deal with other parameters
                   13847:     while (my ($key,$value) = each(%Values)) {
                   13848:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  13849:     }
                   13850:     #
1.646     raeburn  13851:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 13852:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  13853: }
                   13854: 
                   13855: ############################################################
                   13856: ############################################################
                   13857: 
                   13858: =pod
                   13859: 
1.157     matthew  13860: =back 
                   13861: 
1.139     matthew  13862: =head1 Statistics helper routines?  
                   13863: 
                   13864: Bad place for them but what the hell.
                   13865: 
1.157     matthew  13866: =over 4
                   13867: 
1.648     raeburn  13868: =item * &chartlink()
1.139     matthew  13869: 
                   13870: Returns a link to the chart for a specific student.  
                   13871: 
                   13872: Inputs:
                   13873: 
                   13874: =over 4
                   13875: 
                   13876: =item $linktext: The text of the link
                   13877: 
                   13878: =item $sname: The students username
                   13879: 
                   13880: =item $sdomain: The students domain
                   13881: 
                   13882: =back
                   13883: 
1.157     matthew  13884: =back
                   13885: 
1.139     matthew  13886: =cut
                   13887: 
                   13888: ############################################################
                   13889: ############################################################
                   13890: sub chartlink {
                   13891:     my ($linktext, $sname, $sdomain) = @_;
                   13892:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      13893:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 13894:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  13895:        '">'.$linktext.'</a>';
1.153     matthew  13896: }
                   13897: 
                   13898: #######################################################
                   13899: #######################################################
                   13900: 
                   13901: =pod
                   13902: 
                   13903: =head1 Course Environment Routines
1.157     matthew  13904: 
                   13905: =over 4
1.153     matthew  13906: 
1.648     raeburn  13907: =item * &restore_course_settings()
1.153     matthew  13908: 
1.648     raeburn  13909: =item * &store_course_settings()
1.153     matthew  13910: 
                   13911: Restores/Store indicated form parameters from the course environment.
                   13912: Will not overwrite existing values of the form parameters.
                   13913: 
                   13914: Inputs: 
                   13915: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   13916: 
                   13917: a hash ref describing the data to be stored.  For example:
                   13918:    
                   13919: %Save_Parameters = ('Status' => 'scalar',
                   13920:     'chartoutputmode' => 'scalar',
                   13921:     'chartoutputdata' => 'scalar',
                   13922:     'Section' => 'array',
1.373     raeburn  13923:     'Group' => 'array',
1.153     matthew  13924:     'StudentData' => 'array',
                   13925:     'Maps' => 'array');
                   13926: 
                   13927: Returns: both routines return nothing
                   13928: 
1.631     raeburn  13929: =back
                   13930: 
1.153     matthew  13931: =cut
                   13932: 
                   13933: #######################################################
                   13934: #######################################################
                   13935: sub store_course_settings {
1.496     albertel 13936:     return &store_settings($env{'request.course.id'},@_);
                   13937: }
                   13938: 
                   13939: sub store_settings {
1.153     matthew  13940:     # save to the environment
                   13941:     # appenv the same items, just to be safe
1.300     albertel 13942:     my $udom  = $env{'user.domain'};
                   13943:     my $uname = $env{'user.name'};
1.496     albertel 13944:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13945:     my %SaveHash;
                   13946:     my %AppHash;
                   13947:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 13948:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 13949:         my $envname = 'environment.'.$basename;
1.258     albertel 13950:         if (exists($env{'form.'.$setting})) {
1.153     matthew  13951:             # Save this value away
                   13952:             if ($type eq 'scalar' &&
1.258     albertel 13953:                 (! exists($env{$envname}) || 
                   13954:                  $env{$envname} ne $env{'form.'.$setting})) {
                   13955:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   13956:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  13957:             } elsif ($type eq 'array') {
                   13958:                 my $stored_form;
1.258     albertel 13959:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  13960:                     $stored_form = join(',',
                   13961:                                         map {
1.369     www      13962:                                             &escape($_);
1.258     albertel 13963:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  13964:                 } else {
                   13965:                     $stored_form = 
1.369     www      13966:                         &escape($env{'form.'.$setting});
1.153     matthew  13967:                 }
                   13968:                 # Determine if the array contents are the same.
1.258     albertel 13969:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  13970:                     $SaveHash{$basename} = $stored_form;
                   13971:                     $AppHash{$envname}   = $stored_form;
                   13972:                 }
                   13973:             }
                   13974:         }
                   13975:     }
                   13976:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 13977:                                           $udom,$uname);
1.153     matthew  13978:     if ($put_result !~ /^(ok|delayed)/) {
                   13979:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   13980:                                  'got error:'.$put_result);
                   13981:     }
                   13982:     # Make sure these settings stick around in this session, too
1.646     raeburn  13983:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  13984:     return;
                   13985: }
                   13986: 
                   13987: sub restore_course_settings {
1.499     albertel 13988:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 13989: }
                   13990: 
                   13991: sub restore_settings {
                   13992:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13993:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 13994:         next if (exists($env{'form.'.$setting}));
1.496     albertel 13995:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  13996:             '.'.$setting;
1.258     albertel 13997:         if (exists($env{$envname})) {
1.153     matthew  13998:             if ($type eq 'scalar') {
1.258     albertel 13999:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14000:             } elsif ($type eq 'array') {
1.258     albertel 14001:                 $env{'form.'.$setting} = [ 
1.153     matthew  14002:                                            map { 
1.369     www      14003:                                                &unescape($_); 
1.258     albertel 14004:                                            } split(',',$env{$envname})
1.153     matthew  14005:                                            ];
                   14006:             }
                   14007:         }
                   14008:     }
1.127     matthew  14009: }
                   14010: 
1.618     raeburn  14011: #######################################################
                   14012: #######################################################
                   14013: 
                   14014: =pod
                   14015: 
                   14016: =head1 Domain E-mail Routines  
                   14017: 
                   14018: =over 4
                   14019: 
1.648     raeburn  14020: =item * &build_recipient_list()
1.618     raeburn  14021: 
1.1144    raeburn  14022: Build recipient lists for following types of e-mail:
1.766     raeburn  14023: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  14024: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14025: module change checking, student/employee ID conflict checks, as
                   14026: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14027: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14028: 
                   14029: Inputs:
1.619     raeburn  14030: defmail (scalar - email address of default recipient), 
1.1144    raeburn  14031: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14032: requestsmail, updatesmail, or idconflictsmail).
                   14033: 
1.619     raeburn  14034: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  14035: 
1.619     raeburn  14036: origmail (scalar - email address of recipient from loncapa.conf, 
                   14037: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  14038: 
1.655     raeburn  14039: Returns: comma separated list of addresses to which to send e-mail.
                   14040: 
                   14041: =back
1.618     raeburn  14042: 
                   14043: =cut
                   14044: 
                   14045: ############################################################
                   14046: ############################################################
                   14047: sub build_recipient_list {
1.619     raeburn  14048:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  14049:     my @recipients;
                   14050:     my $otheremails;
                   14051:     my %domconfig =
                   14052:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   14053:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14054:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14055:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14056:                 my @contacts = ('adminemail','supportemail');
                   14057:                 foreach my $item (@contacts) {
                   14058:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14059:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14060:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14061:                             push(@recipients,$addr);
                   14062:                         }
1.619     raeburn  14063:                     }
1.766     raeburn  14064:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  14065:                 }
                   14066:             }
1.766     raeburn  14067:         } elsif ($origmail ne '') {
                   14068:             push(@recipients,$origmail);
1.618     raeburn  14069:         }
1.619     raeburn  14070:     } elsif ($origmail ne '') {
                   14071:         push(@recipients,$origmail);
1.618     raeburn  14072:     }
1.688     raeburn  14073:     if (defined($defmail)) {
                   14074:         if ($defmail ne '') {
                   14075:             push(@recipients,$defmail);
                   14076:         }
1.618     raeburn  14077:     }
                   14078:     if ($otheremails) {
1.619     raeburn  14079:         my @others;
                   14080:         if ($otheremails =~ /,/) {
                   14081:             @others = split(/,/,$otheremails);
1.618     raeburn  14082:         } else {
1.619     raeburn  14083:             push(@others,$otheremails);
                   14084:         }
                   14085:         foreach my $addr (@others) {
                   14086:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14087:                 push(@recipients,$addr);
                   14088:             }
1.618     raeburn  14089:         }
                   14090:     }
1.619     raeburn  14091:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  14092:     return $recipientlist;
                   14093: }
                   14094: 
1.127     matthew  14095: ############################################################
                   14096: ############################################################
1.154     albertel 14097: 
1.655     raeburn  14098: =pod
                   14099: 
1.1224    musolffc 14100: =over 4
                   14101: 
1.1223    musolffc 14102: =item * &mime_email()
                   14103: 
                   14104: Sends an email with a possible attachment
                   14105: 
                   14106: Inputs:
                   14107: 
                   14108: =over 4
                   14109: 
                   14110: from -              Sender's email address
                   14111: 
                   14112: to -                Email address of recipient
                   14113: 
                   14114: subject -           Subject of email
                   14115: 
                   14116: body -              Body of email
                   14117: 
                   14118: cc_string -         Carbon copy email address
                   14119: 
                   14120: bcc -               Blind carbon copy email address
                   14121: 
                   14122: type -              File type of attachment
                   14123: 
                   14124: attachment_path -   Path of file to be attached
                   14125: 
                   14126: file_name -         Name of file to be attached
                   14127: 
                   14128: attachment_text -   The body of an attachment of type "TEXT"
                   14129: 
                   14130: =back
                   14131: 
                   14132: =back
                   14133: 
                   14134: =cut
                   14135: 
                   14136: ############################################################
                   14137: ############################################################
                   14138: 
                   14139: sub mime_email {
                   14140:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
                   14141:         $file_name, $attachment_text) = @_;
                   14142:     my $msg = MIME::Lite->new(
                   14143:              From    => $from,
                   14144:              To      => $to,
                   14145:              Subject => $subject,
                   14146:              Type    =>'TEXT',
                   14147:              Data    => $body,
                   14148:              );
                   14149:     if ($cc_string ne '') {
                   14150:         $msg->add("Cc" => $cc_string);
                   14151:     }
                   14152:     if ($bcc ne '') {
                   14153:         $msg->add("Bcc" => $bcc);
                   14154:     }
                   14155:     $msg->attr("content-type"         => "text/plain");
                   14156:     $msg->attr("content-type.charset" => "UTF-8");
                   14157:     # Attach file if given
                   14158:     if ($attachment_path) {
                   14159:         unless ($file_name) {
                   14160:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   14161:         }
                   14162:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   14163:         $msg->attach(Type     => $type,
                   14164:                      Path     => $attachment_path,
                   14165:                      Filename => $file_name
                   14166:                      );
                   14167:     # Otherwise attach text if given
                   14168:     } elsif ($attachment_text) {
                   14169:         $msg->attach(Type => 'TEXT',
                   14170:                      Data => $attachment_text);
                   14171:     }
                   14172:     # Send it
                   14173:     $msg->send('sendmail');
                   14174: }
                   14175: 
                   14176: ############################################################
                   14177: ############################################################
                   14178: 
                   14179: =pod
                   14180: 
1.655     raeburn  14181: =head1 Course Catalog Routines
                   14182: 
                   14183: =over 4
                   14184: 
                   14185: =item * &gather_categories()
                   14186: 
                   14187: Converts category definitions - keys of categories hash stored in  
                   14188: coursecategories in configuration.db on the primary library server in a 
                   14189: domain - to an array.  Also generates javascript and idx hash used to 
                   14190: generate Domain Coordinator interface for editing Course Categories.
                   14191: 
                   14192: Inputs:
1.663     raeburn  14193: 
1.655     raeburn  14194: categories (reference to hash of category definitions).
1.663     raeburn  14195: 
1.655     raeburn  14196: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14197:       categories and subcategories).
1.663     raeburn  14198: 
1.655     raeburn  14199: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14200:       editing Course Categories).
1.663     raeburn  14201: 
1.655     raeburn  14202: jsarray (reference to array of categories used to create Javascript arrays for
                   14203:          Domain Coordinator interface for editing Course Categories).
                   14204: 
                   14205: Returns: nothing
                   14206: 
                   14207: Side effects: populates cats, idx and jsarray. 
                   14208: 
                   14209: =cut
                   14210: 
                   14211: sub gather_categories {
                   14212:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14213:     my %counters;
                   14214:     my $num = 0;
                   14215:     foreach my $item (keys(%{$categories})) {
                   14216:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14217:         if ($container eq '' && $depth == 0) {
                   14218:             $cats->[$depth][$categories->{$item}] = $cat;
                   14219:         } else {
                   14220:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14221:         }
                   14222:         my ($escitem,$tail) = split(/:/,$item,2);
                   14223:         if ($counters{$tail} eq '') {
                   14224:             $counters{$tail} = $num;
                   14225:             $num ++;
                   14226:         }
                   14227:         if (ref($idx) eq 'HASH') {
                   14228:             $idx->{$item} = $counters{$tail};
                   14229:         }
                   14230:         if (ref($jsarray) eq 'ARRAY') {
                   14231:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14232:         }
                   14233:     }
                   14234:     return;
                   14235: }
                   14236: 
                   14237: =pod
                   14238: 
                   14239: =item * &extract_categories()
                   14240: 
                   14241: Used to generate breadcrumb trails for course categories.
                   14242: 
                   14243: Inputs:
1.663     raeburn  14244: 
1.655     raeburn  14245: categories (reference to hash of category definitions).
1.663     raeburn  14246: 
1.655     raeburn  14247: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14248:       categories and subcategories).
1.663     raeburn  14249: 
1.655     raeburn  14250: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14251: 
1.655     raeburn  14252: allitems (reference to hash - key is category key 
                   14253:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14254: 
1.655     raeburn  14255: idx (reference to hash of counters used in Domain Coordinator interface for
                   14256:       editing Course Categories).
1.663     raeburn  14257: 
1.655     raeburn  14258: jsarray (reference to array of categories used to create Javascript arrays for
                   14259:          Domain Coordinator interface for editing Course Categories).
                   14260: 
1.665     raeburn  14261: subcats (reference to hash of arrays containing all subcategories within each 
                   14262:          category, -recursive)
                   14263: 
1.655     raeburn  14264: Returns: nothing
                   14265: 
                   14266: Side effects: populates trails and allitems hash references.
                   14267: 
                   14268: =cut
                   14269: 
                   14270: sub extract_categories {
1.665     raeburn  14271:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  14272:     if (ref($categories) eq 'HASH') {
                   14273:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14274:         if (ref($cats->[0]) eq 'ARRAY') {
                   14275:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14276:                 my $name = $cats->[0][$i];
                   14277:                 my $item = &escape($name).'::0';
                   14278:                 my $trailstr;
                   14279:                 if ($name eq 'instcode') {
                   14280:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14281:                 } elsif ($name eq 'communities') {
                   14282:                     $trailstr = &mt('Communities');
1.1239    raeburn  14283:                 } elsif ($name eq 'placement') {
                   14284:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  14285:                 } else {
                   14286:                     $trailstr = $name;
                   14287:                 }
                   14288:                 if ($allitems->{$item} eq '') {
                   14289:                     push(@{$trails},$trailstr);
                   14290:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14291:                 }
                   14292:                 my @parents = ($name);
                   14293:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14294:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14295:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14296:                         if (ref($subcats) eq 'HASH') {
                   14297:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14298:                         }
                   14299:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   14300:                     }
                   14301:                 } else {
                   14302:                     if (ref($subcats) eq 'HASH') {
                   14303:                         $subcats->{$item} = [];
1.655     raeburn  14304:                     }
                   14305:                 }
                   14306:             }
                   14307:         }
                   14308:     }
                   14309:     return;
                   14310: }
                   14311: 
                   14312: =pod
                   14313: 
1.1162    raeburn  14314: =item * &recurse_categories()
1.655     raeburn  14315: 
                   14316: Recursively used to generate breadcrumb trails for course categories.
                   14317: 
                   14318: Inputs:
1.663     raeburn  14319: 
1.655     raeburn  14320: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14321:       categories and subcategories).
1.663     raeburn  14322: 
1.655     raeburn  14323: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14324: 
                   14325: category (current course category, for which breadcrumb trail is being generated).
                   14326: 
                   14327: trails (reference to array of breadcrumb trails for each category).
                   14328: 
1.655     raeburn  14329: allitems (reference to hash - key is category key
                   14330:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14331: 
1.655     raeburn  14332: parents (array containing containers directories for current category, 
                   14333:          back to top level). 
                   14334: 
                   14335: Returns: nothing
                   14336: 
                   14337: Side effects: populates trails and allitems hash references
                   14338: 
                   14339: =cut
                   14340: 
                   14341: sub recurse_categories {
1.665     raeburn  14342:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  14343:     my $shallower = $depth - 1;
                   14344:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14345:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14346:             my $name = $cats->[$depth]{$category}[$k];
                   14347:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14348:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14349:             if ($allitems->{$item} eq '') {
                   14350:                 push(@{$trails},$trailstr);
                   14351:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14352:             }
                   14353:             my $deeper = $depth+1;
                   14354:             push(@{$parents},$category);
1.665     raeburn  14355:             if (ref($subcats) eq 'HASH') {
                   14356:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14357:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14358:                     my $higher;
                   14359:                     if ($j > 0) {
                   14360:                         $higher = &escape($parents->[$j]).':'.
                   14361:                                   &escape($parents->[$j-1]).':'.$j;
                   14362:                     } else {
                   14363:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14364:                     }
                   14365:                     push(@{$subcats->{$higher}},$subcat);
                   14366:                 }
                   14367:             }
                   14368:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   14369:                                 $subcats);
1.655     raeburn  14370:             pop(@{$parents});
                   14371:         }
                   14372:     } else {
                   14373:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14374:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14375:         if ($allitems->{$item} eq '') {
                   14376:             push(@{$trails},$trailstr);
                   14377:             $allitems->{$item} = scalar(@{$trails})-1;
                   14378:         }
                   14379:     }
                   14380:     return;
                   14381: }
                   14382: 
1.663     raeburn  14383: =pod
                   14384: 
1.1162    raeburn  14385: =item * &assign_categories_table()
1.663     raeburn  14386: 
                   14387: Create a datatable for display of hierarchical categories in a domain,
                   14388: with checkboxes to allow a course to be categorized. 
                   14389: 
                   14390: Inputs:
                   14391: 
                   14392: cathash - reference to hash of categories defined for the domain (from
                   14393:           configuration.db)
                   14394: 
                   14395: currcat - scalar with an & separated list of categories assigned to a course. 
                   14396: 
1.919     raeburn  14397: type    - scalar contains course type (Course or Community).
                   14398: 
1.663     raeburn  14399: Returns: $output (markup to be displayed) 
                   14400: 
                   14401: =cut
                   14402: 
                   14403: sub assign_categories_table {
1.919     raeburn  14404:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  14405:     my $output;
                   14406:     if (ref($cathash) eq 'HASH') {
                   14407:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   14408:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   14409:         $maxdepth = scalar(@cats);
                   14410:         if (@cats > 0) {
                   14411:             my $itemcount = 0;
                   14412:             if (ref($cats[0]) eq 'ARRAY') {
                   14413:                 my @currcategories;
                   14414:                 if ($currcat ne '') {
                   14415:                     @currcategories = split('&',$currcat);
                   14416:                 }
1.919     raeburn  14417:                 my $table;
1.663     raeburn  14418:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14419:                     my $parent = $cats[0][$i];
1.919     raeburn  14420:                     next if ($parent eq 'instcode');
                   14421:                     if ($type eq 'Community') {
                   14422:                         next unless ($parent eq 'communities');
1.1239    raeburn  14423:                     } elsif ($type eq 'Placement') {
                   14424:                         next unless ($parent eq 'placement');
1.919     raeburn  14425:                     } else {
1.1239    raeburn  14426:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  14427:                     }
1.663     raeburn  14428:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14429:                     my $item = &escape($parent).'::0';
                   14430:                     my $checked = '';
                   14431:                     if (@currcategories > 0) {
                   14432:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14433:                             $checked = ' checked="checked"';
1.663     raeburn  14434:                         }
                   14435:                     }
1.919     raeburn  14436:                     my $parent_title = $parent;
                   14437:                     if ($parent eq 'communities') {
                   14438:                         $parent_title = &mt('Communities');
1.1239    raeburn  14439:                     } elsif ($parent eq 'placement') {
                   14440:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  14441:                     }
                   14442:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14443:                               '<input type="checkbox" name="usecategory" value="'.
                   14444:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   14445:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14446:                     my $depth = 1;
                   14447:                     push(@path,$parent);
1.919     raeburn  14448:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  14449:                     pop(@path);
1.919     raeburn  14450:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14451:                     $itemcount ++;
                   14452:                 }
1.919     raeburn  14453:                 if ($itemcount) {
                   14454:                     $output = &Apache::loncommon::start_data_table().
                   14455:                               $table.
                   14456:                               &Apache::loncommon::end_data_table();
                   14457:                 }
1.663     raeburn  14458:             }
                   14459:         }
                   14460:     }
                   14461:     return $output;
                   14462: }
                   14463: 
                   14464: =pod
                   14465: 
1.1162    raeburn  14466: =item * &assign_category_rows()
1.663     raeburn  14467: 
                   14468: Create a datatable row for display of nested categories in a domain,
                   14469: with checkboxes to allow a course to be categorized,called recursively.
                   14470: 
                   14471: Inputs:
                   14472: 
                   14473: itemcount - track row number for alternating colors
                   14474: 
                   14475: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14476:       categories and subcategories.
                   14477: 
                   14478: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14479: 
                   14480: parent - parent of current category item
                   14481: 
                   14482: path - Array containing all categories back up through the hierarchy from the
                   14483:        current category to the top level.
                   14484: 
                   14485: currcategories - reference to array of current categories assigned to the course
                   14486: 
                   14487: Returns: $output (markup to be displayed).
                   14488: 
                   14489: =cut
                   14490: 
                   14491: sub assign_category_rows {
                   14492:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   14493:     my ($text,$name,$item,$chgstr);
                   14494:     if (ref($cats) eq 'ARRAY') {
                   14495:         my $maxdepth = scalar(@{$cats});
                   14496:         if (ref($cats->[$depth]) eq 'HASH') {
                   14497:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14498:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14499:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  14500:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14501:                 for (my $j=0; $j<$numchildren; $j++) {
                   14502:                     $name = $cats->[$depth]{$parent}[$j];
                   14503:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14504:                     my $deeper = $depth+1;
                   14505:                     my $checked = '';
                   14506:                     if (ref($currcategories) eq 'ARRAY') {
                   14507:                         if (@{$currcategories} > 0) {
                   14508:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14509:                                 $checked = ' checked="checked"';
1.663     raeburn  14510:                             }
                   14511:                         }
                   14512:                     }
1.664     raeburn  14513:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14514:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  14515:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   14516:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14517:                              '</td><td>';
1.663     raeburn  14518:                     if (ref($path) eq 'ARRAY') {
                   14519:                         push(@{$path},$name);
                   14520:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   14521:                         pop(@{$path});
                   14522:                     }
                   14523:                     $text .= '</td></tr>';
                   14524:                 }
                   14525:                 $text .= '</table></td>';
                   14526:             }
                   14527:         }
                   14528:     }
                   14529:     return $text;
                   14530: }
                   14531: 
1.1181    raeburn  14532: =pod
                   14533: 
                   14534: =back
                   14535: 
                   14536: =cut
                   14537: 
1.655     raeburn  14538: ############################################################
                   14539: ############################################################
                   14540: 
                   14541: 
1.443     albertel 14542: sub commit_customrole {
1.664     raeburn  14543:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14544:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14545:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14546:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14547:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14548:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14549:                  '</b><br />';
                   14550:     return $output;
                   14551: }
                   14552: 
                   14553: sub commit_standardrole {
1.1116    raeburn  14554:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14555:     my ($output,$logmsg,$linefeed);
                   14556:     if ($context eq 'auto') {
                   14557:         $linefeed = "\n";
                   14558:     } else {
                   14559:         $linefeed = "<br />\n";
                   14560:     }  
1.443     albertel 14561:     if ($three eq 'st') {
1.541     raeburn  14562:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  14563:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14564:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14565:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14566:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14567:         } else {
1.541     raeburn  14568:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14569:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14570:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14571:             if ($context eq 'auto') {
                   14572:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14573:             } else {
                   14574:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14575:                &mt('Add to classlist').': <b>ok</b>';
                   14576:             }
                   14577:             $output .= $linefeed;
1.443     albertel 14578:         }
                   14579:     } else {
                   14580:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14581:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14582:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14583:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14584:         if ($context eq 'auto') {
                   14585:             $output .= $result.$linefeed;
                   14586:         } else {
                   14587:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14588:         }
1.443     albertel 14589:     }
                   14590:     return $output;
                   14591: }
                   14592: 
                   14593: sub commit_studentrole {
1.1116    raeburn  14594:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14595:         $credits) = @_;
1.626     raeburn  14596:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  14597:     if ($context eq 'auto') {
                   14598:         $linefeed = "\n";
                   14599:     } else {
                   14600:         $linefeed = '<br />'."\n";
                   14601:     }
1.443     albertel 14602:     if (defined($one) && defined($two)) {
                   14603:         my $cid=$one.'_'.$two;
                   14604:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   14605:         my $secchange = 0;
                   14606:         my $expire_role_result;
                   14607:         my $modify_section_result;
1.628     raeburn  14608:         if ($oldsec ne '-1') { 
                   14609:             if ($oldsec ne $sec) {
1.443     albertel 14610:                 $secchange = 1;
1.628     raeburn  14611:                 my $now = time;
1.443     albertel 14612:                 my $uurl='/'.$cid;
                   14613:                 $uurl=~s/\_/\//g;
                   14614:                 if ($oldsec) {
                   14615:                     $uurl.='/'.$oldsec;
                   14616:                 }
1.626     raeburn  14617:                 $oldsecurl = $uurl;
1.628     raeburn  14618:                 $expire_role_result = 
1.652     raeburn  14619:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  14620:                 if ($env{'request.course.sec'} ne '') { 
                   14621:                     if ($expire_role_result eq 'refused') {
                   14622:                         my @roles = ('st');
                   14623:                         my @statuses = ('previous');
                   14624:                         my @roledoms = ($one);
                   14625:                         my $withsec = 1;
                   14626:                         my %roleshash = 
                   14627:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   14628:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   14629:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   14630:                             my ($oldstart,$oldend) = 
                   14631:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   14632:                             if ($oldend > 0 && $oldend <= $now) {
                   14633:                                 $expire_role_result = 'ok';
                   14634:                             }
                   14635:                         }
                   14636:                     }
                   14637:                 }
1.443     albertel 14638:                 $result = $expire_role_result;
                   14639:             }
                   14640:         }
                   14641:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  14642:             $modify_section_result = 
                   14643:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   14644:                                                            undef,undef,undef,$sec,
                   14645:                                                            $end,$start,'','',$cid,
                   14646:                                                            '',$context,$credits);
1.443     albertel 14647:             if ($modify_section_result =~ /^ok/) {
                   14648:                 if ($secchange == 1) {
1.628     raeburn  14649:                     if ($sec eq '') {
                   14650:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   14651:                     } else {
                   14652:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   14653:                     }
1.443     albertel 14654:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  14655:                     if ($sec eq '') {
                   14656:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   14657:                     } else {
                   14658:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14659:                     }
1.443     albertel 14660:                 } else {
1.628     raeburn  14661:                     if ($sec eq '') {
                   14662:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   14663:                     } else {
                   14664:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14665:                     }
1.443     albertel 14666:                 }
                   14667:             } else {
1.1115    raeburn  14668:                 if ($secchange) { 
1.628     raeburn  14669:                     $$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;
                   14670:                 } else {
                   14671:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   14672:                 }
1.443     albertel 14673:             }
                   14674:             $result = $modify_section_result;
                   14675:         } elsif ($secchange == 1) {
1.628     raeburn  14676:             if ($oldsec eq '') {
1.1103    raeburn  14677:                 $$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  14678:             } else {
                   14679:                 $$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;
                   14680:             }
1.626     raeburn  14681:             if ($expire_role_result eq 'refused') {
                   14682:                 my $newsecurl = '/'.$cid;
                   14683:                 $newsecurl =~ s/\_/\//g;
                   14684:                 if ($sec ne '') {
                   14685:                     $newsecurl.='/'.$sec;
                   14686:                 }
                   14687:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   14688:                     if ($sec eq '') {
                   14689:                         $$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;
                   14690:                     } else {
                   14691:                         $$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;
                   14692:                     }
                   14693:                 }
                   14694:             }
1.443     albertel 14695:         }
                   14696:     } else {
1.626     raeburn  14697:         $$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 14698:         $result = "error: incomplete course id\n";
                   14699:     }
                   14700:     return $result;
                   14701: }
                   14702: 
1.1108    raeburn  14703: sub show_role_extent {
                   14704:     my ($scope,$context,$role) = @_;
                   14705:     $scope =~ s{^/}{};
                   14706:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   14707:     push(@courseroles,'co');
                   14708:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   14709:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   14710:         $scope =~ s{/}{_};
                   14711:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   14712:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   14713:         my ($audom,$auname) = split(/\//,$scope);
                   14714:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   14715:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   14716:     } else {
                   14717:         $scope =~ s{/$}{};
                   14718:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   14719:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   14720:     }
                   14721: }
                   14722: 
1.443     albertel 14723: ############################################################
                   14724: ############################################################
                   14725: 
1.566     albertel 14726: sub check_clone {
1.578     raeburn  14727:     my ($args,$linefeed) = @_;
1.566     albertel 14728:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   14729:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   14730:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   14731:     my $clonemsg;
                   14732:     my $can_clone = 0;
1.944     raeburn  14733:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  14734:     if ($lctype ne 'community') {
                   14735:         $lctype = 'course';
                   14736:     }
1.566     albertel 14737:     if ($clonehome eq 'no_host') {
1.944     raeburn  14738:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14739:             $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'});
                   14740:         } else {
                   14741:             $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'});
                   14742:         }     
1.566     albertel 14743:     } else {
                   14744: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  14745:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14746:             if ($clonedesc{'type'} ne 'Community') {
                   14747:                  $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'});
                   14748:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14749:             }
                   14750:         }
1.882     raeburn  14751: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   14752:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 14753: 	    $can_clone = 1;
                   14754: 	} else {
1.1221    raeburn  14755: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 14756: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  14757:             if ($clonehash{'cloners'} eq '') {
                   14758:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   14759:                 if ($domdefs{'canclone'}) {
                   14760:                     unless ($domdefs{'canclone'} eq 'none') {
                   14761:                         if ($domdefs{'canclone'} eq 'domain') {
                   14762:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   14763:                                 $can_clone = 1;
                   14764:                             }
                   14765:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   14766:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   14767:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   14768:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   14769:                                 $can_clone = 1;
                   14770:                             }
                   14771:                         }
                   14772:                     }
                   14773:                 }
1.578     raeburn  14774:             } else {
1.1221    raeburn  14775: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   14776:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  14777:                     $can_clone = 1;
1.1221    raeburn  14778:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  14779:                     $can_clone = 1;
1.1225    raeburn  14780:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   14781:                     $can_clone = 1;
1.1221    raeburn  14782:                 }
                   14783:                 unless ($can_clone) {
1.1225    raeburn  14784:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   14785:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  14786:                         my (%gotdomdefaults,%gotcodedefaults);
                   14787:                         foreach my $cloner (@cloners) {
                   14788:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   14789:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   14790:                                 my (%codedefaults,@code_order);
                   14791:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   14792:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   14793:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   14794:                                     }
                   14795:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   14796:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   14797:                                     }
                   14798:                                 } else {
                   14799:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   14800:                                                                             \%codedefaults,
                   14801:                                                                             \@code_order);
                   14802:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   14803:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   14804:                                 }
                   14805:                                 if (@code_order > 0) {
                   14806:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   14807:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   14808:                                                                                 $args->{'crscode'})) {
                   14809:                                         $can_clone = 1;
                   14810:                                         last;
                   14811:                                     }
                   14812:                                 }
                   14813:                             }
                   14814:                         }
                   14815:                     }
1.1225    raeburn  14816:                 }
                   14817:             }
                   14818:             unless ($can_clone) {
                   14819:                 my $ccrole = 'cc';
                   14820:                 if ($args->{'crstype'} eq 'Community') {
                   14821:                     $ccrole = 'co';
                   14822:                 }
                   14823: 	        my %roleshash =
                   14824: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   14825: 					          $args->{'ccdomain'},
                   14826:                                                   'userroles',['active'],[$ccrole],
                   14827: 					          [$args->{'clonedomain'}]);
                   14828: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   14829:                     $can_clone = 1;
                   14830:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   14831:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   14832:                     $can_clone = 1;
1.1221    raeburn  14833:                 }
                   14834:             }
                   14835:             unless ($can_clone) {
                   14836:                 if ($args->{'crstype'} eq 'Community') {
                   14837:                     $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'});
1.942     raeburn  14838:                 } else {
1.1221    raeburn  14839:                     $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'});
                   14840:                 }
1.566     albertel 14841: 	    }
1.578     raeburn  14842:         }
1.566     albertel 14843:     }
                   14844:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14845: }
                   14846: 
1.444     albertel 14847: sub construct_course {
1.1166    raeburn  14848:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
1.444     albertel 14849:     my $outcome;
1.541     raeburn  14850:     my $linefeed =  '<br />'."\n";
                   14851:     if ($context eq 'auto') {
                   14852:         $linefeed = "\n";
                   14853:     }
1.566     albertel 14854: 
                   14855: #
                   14856: # Are we cloning?
                   14857: #
                   14858:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14859:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  14860: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 14861: 	if ($context ne 'auto') {
1.578     raeburn  14862:             if ($clonemsg ne '') {
                   14863: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   14864:             }
1.566     albertel 14865: 	}
                   14866: 	$outcome .= $clonemsg.$linefeed;
                   14867: 
                   14868:         if (!$can_clone) {
                   14869: 	    return (0,$outcome);
                   14870: 	}
                   14871:     }
                   14872: 
1.444     albertel 14873: #
                   14874: # Open course
                   14875: #
1.1239    raeburn  14876:     my $showncrstype;
                   14877:     if ($args->{'crstype'} eq 'Placement') {
                   14878:         $showncrstype = 'placement test'; 
                   14879:     } else {  
                   14880:         $showncrstype = lc($args->{'crstype'});
                   14881:     }
1.444     albertel 14882:     my %cenv=();
                   14883:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   14884:                                              $args->{'cdescr'},
                   14885:                                              $args->{'curl'},
                   14886:                                              $args->{'course_home'},
                   14887:                                              $args->{'nonstandard'},
                   14888:                                              $args->{'crscode'},
                   14889:                                              $args->{'ccuname'}.':'.
                   14890:                                              $args->{'ccdomain'},
1.882     raeburn  14891:                                              $args->{'crstype'},
1.885     raeburn  14892:                                              $cnum,$context,$category);
1.444     albertel 14893: 
                   14894:     # Note: The testing routines depend on this being output; see 
                   14895:     # Utils::Course. This needs to at least be output as a comment
                   14896:     # if anyone ever decides to not show this, and Utils::Course::new
                   14897:     # will need to be suitably modified.
1.1239    raeburn  14898:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
1.943     raeburn  14899:     if ($$courseid =~ /^error:/) {
                   14900:         return (0,$outcome);
                   14901:     }
                   14902: 
1.444     albertel 14903: #
                   14904: # Check if created correctly
                   14905: #
1.479     albertel 14906:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 14907:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  14908:     if ($crsuhome eq 'no_host') {
                   14909:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   14910:         return (0,$outcome);
                   14911:     }
1.541     raeburn  14912:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 14913: 
1.444     albertel 14914: #
1.566     albertel 14915: # Do the cloning
                   14916: #   
                   14917:     if ($can_clone && $cloneid) {
1.1239    raeburn  14918: 	$clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
1.566     albertel 14919: 	if ($context ne 'auto') {
                   14920: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   14921: 	}
                   14922: 	$outcome .= $clonemsg.$linefeed;
                   14923: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 14924: # Copy all files
1.637     www      14925: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 14926: # Restore URL
1.566     albertel 14927: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 14928: # Restore title
1.566     albertel 14929: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  14930: # Restore creation date, creator and creation context.
                   14931:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   14932:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   14933:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 14934: # Mark as cloned
1.566     albertel 14935: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      14936: # Need to clone grading mode
                   14937:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   14938:         $cenv{'grading'}=$newenv{'grading'};
                   14939: # Do not clone these environment entries
                   14940:         &Apache::lonnet::del('environment',
                   14941:                   ['default_enrollment_start_date',
                   14942:                    'default_enrollment_end_date',
                   14943:                    'question.email',
                   14944:                    'policy.email',
                   14945:                    'comment.email',
                   14946:                    'pch.users.denied',
1.725     raeburn  14947:                    'plc.users.denied',
                   14948:                    'hidefromcat',
1.1121    raeburn  14949:                    'checkforpriv',
1.1166    raeburn  14950:                    'categories',
                   14951:                    'internal.uniquecode'],
1.638     www      14952:                    $$crsudom,$$crsunum);
1.1170    raeburn  14953:         if ($args->{'textbook'}) {
                   14954:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   14955:         }
1.444     albertel 14956:     }
1.566     albertel 14957: 
1.444     albertel 14958: #
                   14959: # Set environment (will override cloned, if existing)
                   14960: #
                   14961:     my @sections = ();
                   14962:     my @xlists = ();
                   14963:     if ($args->{'crstype'}) {
                   14964:         $cenv{'type'}=$args->{'crstype'};
                   14965:     }
                   14966:     if ($args->{'crsid'}) {
                   14967:         $cenv{'courseid'}=$args->{'crsid'};
                   14968:     }
                   14969:     if ($args->{'crscode'}) {
                   14970:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   14971:     }
                   14972:     if ($args->{'crsquota'} ne '') {
                   14973:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   14974:     } else {
                   14975:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   14976:     }
                   14977:     if ($args->{'ccuname'}) {
                   14978:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   14979:                                         ':'.$args->{'ccdomain'};
                   14980:     } else {
                   14981:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   14982:     }
1.1116    raeburn  14983:     if ($args->{'defaultcredits'}) {
                   14984:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   14985:     }
1.444     albertel 14986:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   14987:     if ($args->{'crssections'}) {
                   14988:         $cenv{'internal.sectionnums'} = '';
                   14989:         if ($args->{'crssections'} =~ m/,/) {
                   14990:             @sections = split/,/,$args->{'crssections'};
                   14991:         } else {
                   14992:             $sections[0] = $args->{'crssections'};
                   14993:         }
                   14994:         if (@sections > 0) {
                   14995:             foreach my $item (@sections) {
                   14996:                 my ($sec,$gp) = split/:/,$item;
                   14997:                 my $class = $args->{'crscode'}.$sec;
                   14998:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   14999:                 $cenv{'internal.sectionnums'} .= $item.',';
                   15000:                 unless ($addcheck eq 'ok') {
                   15001:                     push @badclasses, $class;
                   15002:                 }
                   15003:             }
                   15004:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   15005:         }
                   15006:     }
                   15007: # do not hide course coordinator from staff listing, 
                   15008: # even if privileged
                   15009:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  15010: # add course coordinator's domain to domains to check for privileged users
                   15011: # if different to course domain
                   15012:     if ($$crsudom ne $args->{'ccdomain'}) {
                   15013:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   15014:     }
1.444     albertel 15015: # add crosslistings
                   15016:     if ($args->{'crsxlist'}) {
                   15017:         $cenv{'internal.crosslistings'}='';
                   15018:         if ($args->{'crsxlist'} =~ m/,/) {
                   15019:             @xlists = split/,/,$args->{'crsxlist'};
                   15020:         } else {
                   15021:             $xlists[0] = $args->{'crsxlist'};
                   15022:         }
                   15023:         if (@xlists > 0) {
                   15024:             foreach my $item (@xlists) {
                   15025:                 my ($xl,$gp) = split/:/,$item;
                   15026:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   15027:                 $cenv{'internal.crosslistings'} .= $item.',';
                   15028:                 unless ($addcheck eq 'ok') {
                   15029:                     push @badclasses, $xl;
                   15030:                 }
                   15031:             }
                   15032:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15033:         }
                   15034:     }
                   15035:     if ($args->{'autoadds'}) {
                   15036:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15037:     }
                   15038:     if ($args->{'autodrops'}) {
                   15039:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15040:     }
                   15041: # check for notification of enrollment changes
                   15042:     my @notified = ();
                   15043:     if ($args->{'notify_owner'}) {
                   15044:         if ($args->{'ccuname'} ne '') {
                   15045:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15046:         }
                   15047:     }
                   15048:     if ($args->{'notify_dc'}) {
                   15049:         if ($uname ne '') { 
1.630     raeburn  15050:             push(@notified,$uname.':'.$udom);
1.444     albertel 15051:         }
                   15052:     }
                   15053:     if (@notified > 0) {
                   15054:         my $notifylist;
                   15055:         if (@notified > 1) {
                   15056:             $notifylist = join(',',@notified);
                   15057:         } else {
                   15058:             $notifylist = $notified[0];
                   15059:         }
                   15060:         $cenv{'internal.notifylist'} = $notifylist;
                   15061:     }
                   15062:     if (@badclasses > 0) {
                   15063:         my %lt=&Apache::lonlocal::texthash(
                   15064:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.  However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
                   15065:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   15066:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   15067:         );
1.541     raeburn  15068:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   15069:                            ' ('.$lt{'adby'}.')';
                   15070:         if ($context eq 'auto') {
                   15071:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 15072:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  15073:             foreach my $item (@badclasses) {
                   15074:                 if ($context eq 'auto') {
                   15075:                     $outcome .= " - $item\n";
                   15076:                 } else {
                   15077:                     $outcome .= "<li>$item</li>\n";
                   15078:                 }
                   15079:             }
                   15080:             if ($context eq 'auto') {
                   15081:                 $outcome .= $linefeed;
                   15082:             } else {
1.566     albertel 15083:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  15084:             }
                   15085:         } 
1.444     albertel 15086:     }
                   15087:     if ($args->{'no_end_date'}) {
                   15088:         $args->{'endaccess'} = 0;
                   15089:     }
                   15090:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15091:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15092:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15093:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15094:     if ($args->{'showphotos'}) {
                   15095:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15096:     }
                   15097:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15098:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15099:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15100:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15101:             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'); 
                   15102:             if ($context eq 'auto') {
                   15103:                 $outcome .= $krb_msg;
                   15104:             } else {
1.566     albertel 15105:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15106:             }
                   15107:             $outcome .= $linefeed;
1.444     albertel 15108:         }
                   15109:     }
                   15110:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15111:        if ($args->{'setpolicy'}) {
                   15112:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15113:        }
                   15114:        if ($args->{'setcontent'}) {
                   15115:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15116:        }
                   15117:     }
                   15118:     if ($args->{'reshome'}) {
                   15119: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15120: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15121:     }
                   15122: #
                   15123: # course has keyed access
                   15124: #
                   15125:     if ($args->{'setkeys'}) {
                   15126:        $cenv{'keyaccess'}='yes';
                   15127:     }
                   15128: # if specified, key authority is not course, but user
                   15129: # only active if keyaccess is yes
                   15130:     if ($args->{'keyauth'}) {
1.487     albertel 15131: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15132: 	$user = &LONCAPA::clean_username($user);
                   15133: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15134: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15135: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15136: 	}
                   15137:     }
                   15138: 
1.1166    raeburn  15139: #
1.1167    raeburn  15140: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  15141: #
                   15142:     if ($args->{'uniquecode'}) {
                   15143:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15144:         if ($code) {
                   15145:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  15146:             my %crsinfo =
                   15147:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15148:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15149:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15150:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15151:             } 
1.1166    raeburn  15152:             if (ref($coderef)) {
                   15153:                 $$coderef = $code;
                   15154:             }
                   15155:         }
                   15156:     }
                   15157: 
1.444     albertel 15158:     if ($args->{'disresdis'}) {
                   15159:         $cenv{'pch.roles.denied'}='st';
                   15160:     }
                   15161:     if ($args->{'disablechat'}) {
                   15162:         $cenv{'plc.roles.denied'}='st';
                   15163:     }
                   15164: 
                   15165:     # Record we've not yet viewed the Course Initialization Helper for this 
                   15166:     # course
                   15167:     $cenv{'course.helper.not.run'} = 1;
                   15168:     #
                   15169:     # Use new Randomseed
                   15170:     #
                   15171:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   15172:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   15173:     #
                   15174:     # The encryption code and receipt prefix for this course
                   15175:     #
                   15176:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   15177:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   15178:     #
                   15179:     # By default, use standard grading
                   15180:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15181: 
1.541     raeburn  15182:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15183:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15184: #
                   15185: # Open all assignments
                   15186: #
                   15187:     if ($args->{'openall'}) {
                   15188:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   15189:        my %storecontent = ($storeunder         => time,
                   15190:                            $storeunder.'.type' => 'date_start');
                   15191:        
                   15192:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  15193:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15194:    }
                   15195: #
                   15196: # Set first page
                   15197: #
                   15198:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15199: 	    || ($cloneid)) {
1.445     albertel 15200: 	use LONCAPA::map;
1.444     albertel 15201: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15202: 
                   15203: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15204:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15205: 
1.444     albertel 15206:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15207:         my $title; my $url;
                   15208:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15209: 	    $title=&mt('Syllabus');
1.444     albertel 15210:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15211:         } else {
1.963     raeburn  15212:             $title=&mt('Table of Contents');
1.444     albertel 15213:             $url='/adm/navmaps';
                   15214:         }
1.445     albertel 15215: 
                   15216:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15217: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15218: 
                   15219: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15220:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15221:     }
1.566     albertel 15222: 
1.1237    raeburn  15223: # 
                   15224: # Set params for Placement Tests
                   15225: #
1.1239    raeburn  15226:     if ($args->{'crstype'} eq 'Placement') {
                   15227:        my %storecontent; 
                   15228:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   15229:        my %defaults = (
                   15230:                         buttonshide   => { value => 'yes',
                   15231:                                            type => 'string_yesno',},
                   15232:                         type          => { value => 'randomizetry',
                   15233:                                            type  => 'string_questiontype',},
                   15234:                         maxtries      => { value => 1,
                   15235:                                            type => 'int_pos',},
                   15236:                         problemstatus => { value => 'no',
                   15237:                                            type  => 'string_problemstatus',},
                   15238:                       );
                   15239:        foreach my $key (keys(%defaults)) {
                   15240:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   15241:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   15242:        }
1.1237    raeburn  15243:        &Apache::lonnet::cput
                   15244:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   15245:     }
                   15246: 
1.566     albertel 15247:     return (1,$outcome);
1.444     albertel 15248: }
                   15249: 
1.1166    raeburn  15250: sub make_unique_code {
                   15251:     my ($cdom,$cnum) = @_;
                   15252:     # get lock on uniquecodes db
                   15253:     my $lockhash = {
                   15254:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15255:                                                   ':'.$env{'user.domain'},
                   15256:                    };
                   15257:     my $tries = 0;
                   15258:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15259:     my ($code,$error);
                   15260:   
                   15261:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15262:         $tries ++;
                   15263:         sleep 1;
                   15264:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15265:     }
                   15266:     if ($gotlock eq 'ok') {
                   15267:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15268:         my $gotcode;
                   15269:         my $attempts = 0;
                   15270:         while ((!$gotcode) && ($attempts < 100)) {
                   15271:             $code = &generate_code();
                   15272:             if (!exists($currcodes{$code})) {
                   15273:                 $gotcode = 1;
                   15274:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15275:                     $error = 'nostore';
                   15276:                 }
                   15277:             }
                   15278:             $attempts ++;
                   15279:         }
                   15280:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15281:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15282:     } else {
                   15283:         $error = 'nolock';
                   15284:     }
                   15285:     return ($code,$error);
                   15286: }
                   15287: 
                   15288: sub generate_code {
                   15289:     my $code;
                   15290:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15291:     for (my $i=0; $i<6; $i++) {
                   15292:         my $lettnum = int (rand 2);
                   15293:         my $item = '';
                   15294:         if ($lettnum) {
                   15295:             $item = $letts[int( rand(18) )];
                   15296:         } else {
                   15297:             $item = 1+int( rand(8) );
                   15298:         }
                   15299:         $code .= $item;
                   15300:     }
                   15301:     return $code;
                   15302: }
                   15303: 
1.444     albertel 15304: ############################################################
                   15305: ############################################################
                   15306: 
1.1237    raeburn  15307: # Community, Course and Placement Test
1.378     raeburn  15308: sub course_type {
                   15309:     my ($cid) = @_;
                   15310:     if (!defined($cid)) {
                   15311:         $cid = $env{'request.course.id'};
                   15312:     }
1.404     albertel 15313:     if (defined($env{'course.'.$cid.'.type'})) {
                   15314:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15315:     } else {
                   15316:         return 'Course';
1.377     raeburn  15317:     }
                   15318: }
1.156     albertel 15319: 
1.406     raeburn  15320: sub group_term {
                   15321:     my $crstype = &course_type();
                   15322:     my %names = (
                   15323:                   'Course' => 'group',
1.865     raeburn  15324:                   'Community' => 'group',
1.1237    raeburn  15325:                   'Placement' => 'group',
1.406     raeburn  15326:                 );
                   15327:     return $names{$crstype};
                   15328: }
                   15329: 
1.902     raeburn  15330: sub course_types {
1.1237    raeburn  15331:     my @types = ('official','unofficial','community','textbook','placement');
1.902     raeburn  15332:     my %typename = (
                   15333:                          official   => 'Official course',
                   15334:                          unofficial => 'Unofficial course',
                   15335:                          community  => 'Community',
1.1165    raeburn  15336:                          textbook   => 'Textbook course',
1.1237    raeburn  15337:                          placement  => 'Placement test',
1.902     raeburn  15338:                    );
                   15339:     return (\@types,\%typename);
                   15340: }
                   15341: 
1.156     albertel 15342: sub icon {
                   15343:     my ($file)=@_;
1.505     albertel 15344:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15345:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15346:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15347:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15348: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15349: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15350: 	            $curfext.".gif") {
                   15351: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15352: 		$curfext.".gif";
                   15353: 	}
                   15354:     }
1.249     albertel 15355:     return &lonhttpdurl($iconname);
1.154     albertel 15356: } 
1.84      albertel 15357: 
1.575     albertel 15358: sub lonhttpdurl {
1.692     www      15359: #
                   15360: # Had been used for "small fry" static images on separate port 8080.
                   15361: # Modify here if lightweight http functionality desired again.
                   15362: # Currently eliminated due to increasing firewall issues.
                   15363: #
1.575     albertel 15364:     my ($url)=@_;
1.692     www      15365:     return $url;
1.215     albertel 15366: }
                   15367: 
1.213     albertel 15368: sub connection_aborted {
                   15369:     my ($r)=@_;
                   15370:     $r->print(" ");$r->rflush();
                   15371:     my $c = $r->connection;
                   15372:     return $c->aborted();
                   15373: }
                   15374: 
1.221     foxr     15375: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15376: #    strings as 'strings'.
                   15377: sub escape_single {
1.221     foxr     15378:     my ($input) = @_;
1.223     albertel 15379:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15380:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15381:     return $input;
                   15382: }
1.223     albertel 15383: 
1.222     foxr     15384: #  Same as escape_single, but escape's "'s  This 
                   15385: #  can be used for  "strings"
                   15386: sub escape_double {
                   15387:     my ($input) = @_;
                   15388:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15389:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15390:     return $input;
                   15391: }
1.223     albertel 15392:  
1.222     foxr     15393: #   Escapes the last element of a full URL.
                   15394: sub escape_url {
                   15395:     my ($url)   = @_;
1.238     raeburn  15396:     my @urlslices = split(/\//, $url,-1);
1.369     www      15397:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  15398:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15399: }
1.462     albertel 15400: 
1.820     raeburn  15401: sub compare_arrays {
                   15402:     my ($arrayref1,$arrayref2) = @_;
                   15403:     my (@difference,%count);
                   15404:     @difference = ();
                   15405:     %count = ();
                   15406:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   15407:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   15408:         foreach my $element (keys(%count)) {
                   15409:             if ($count{$element} == 1) {
                   15410:                 push(@difference,$element);
                   15411:             }
                   15412:         }
                   15413:     }
                   15414:     return @difference;
                   15415: }
                   15416: 
1.817     bisitz   15417: # -------------------------------------------------------- Initialize user login
1.462     albertel 15418: sub init_user_environment {
1.463     albertel 15419:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 15420:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   15421: 
                   15422:     my $public=($username eq 'public' && $domain eq 'public');
                   15423: 
                   15424: # See if old ID present, if so, remove
                   15425: 
1.1062    raeburn  15426:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 15427:     my $now=time;
                   15428: 
                   15429:     if ($public) {
                   15430: 	my $max_public=100;
                   15431: 	my $oldest;
                   15432: 	my $oldest_time=0;
                   15433: 	for(my $next=1;$next<=$max_public;$next++) {
                   15434: 	    if (-e $lonids."/publicuser_$next.id") {
                   15435: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   15436: 		if ($mtime<$oldest_time || !$oldest_time) {
                   15437: 		    $oldest_time=$mtime;
                   15438: 		    $oldest=$next;
                   15439: 		}
                   15440: 	    } else {
                   15441: 		$cookie="publicuser_$next";
                   15442: 		last;
                   15443: 	    }
                   15444: 	}
                   15445: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   15446:     } else {
1.463     albertel 15447: 	# if this isn't a robot, kill any existing non-robot sessions
                   15448: 	if (!$args->{'robot'}) {
                   15449: 	    opendir(DIR,$lonids);
                   15450: 	    while ($filename=readdir(DIR)) {
                   15451: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   15452: 		    unlink($lonids.'/'.$filename);
                   15453: 		}
1.462     albertel 15454: 	    }
1.463     albertel 15455: 	    closedir(DIR);
1.1204    raeburn  15456: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   15457:             my $namespace = 'nohist_courseeditor';
                   15458:             my $lockingkey = 'paste'."\0".'locked_num';
                   15459:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15460:                                                 $domain,$username);
                   15461:             if (exists($lockhash{$lockingkey})) {
                   15462:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15463:                 unless ($delresult eq 'ok') {
                   15464:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15465:                 }
                   15466:             }
1.462     albertel 15467: 	}
                   15468: # Give them a new cookie
1.463     albertel 15469: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15470: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15471: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15472:     
                   15473: # Initialize roles
                   15474: 
1.1062    raeburn  15475: 	($userroles,$firstaccenv,$timerintenv) = 
                   15476:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15477:     }
                   15478: # ------------------------------------ Check browser type and MathML capability
                   15479: 
1.1194    raeburn  15480:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15481:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15482: 
                   15483: # ------------------------------------------------------------- Get environment
                   15484: 
                   15485:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15486:     my ($tmp) = keys(%userenv);
                   15487:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15488:     } else {
                   15489: 	undef(%userenv);
                   15490:     }
                   15491:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15492: 	$form->{'interface'}=$userenv{'interface'};
                   15493:     }
                   15494:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15495: 
                   15496: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15497:     foreach my $option ('interface','localpath','localres') {
                   15498:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15499:     }
                   15500: # --------------------------------------------------------- Write first profile
                   15501: 
                   15502:     {
                   15503: 	my %initial_env = 
                   15504: 	    ("user.name"          => $username,
                   15505: 	     "user.domain"        => $domain,
                   15506: 	     "user.home"          => $authhost,
                   15507: 	     "browser.type"       => $clientbrowser,
                   15508: 	     "browser.version"    => $clientversion,
                   15509: 	     "browser.mathml"     => $clientmathml,
                   15510: 	     "browser.unicode"    => $clientunicode,
                   15511: 	     "browser.os"         => $clientos,
1.1137    raeburn  15512:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  15513:              "browser.info"       => $clientinfo,
1.1194    raeburn  15514:              "browser.osversion"  => $clientosversion,
1.462     albertel 15515: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15516: 	     "request.course.fn"  => '',
                   15517: 	     "request.course.uri" => '',
                   15518: 	     "request.course.sec" => '',
                   15519: 	     "request.role"       => 'cm',
                   15520: 	     "request.role.adv"   => $env{'user.adv'},
                   15521: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   15522: 
                   15523:         if ($form->{'localpath'}) {
                   15524: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15525: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15526:         }
                   15527: 	
                   15528: 	if ($form->{'interface'}) {
                   15529: 	    $form->{'interface'}=~s/\W//gs;
                   15530: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15531: 	    $env{'browser.interface'}=$form->{'interface'};
                   15532: 	}
                   15533: 
1.1157    raeburn  15534:         if ($form->{'iptoken'}) {
                   15535:             my $lonhost = $r->dir_config('lonHostID');
                   15536:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15537:             $env{'user.noloadbalance'} = $lonhost;
                   15538:         }
                   15539: 
1.981     raeburn  15540:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  15541:         my %domdef;
                   15542:         unless ($domain eq 'public') {
                   15543:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   15544:         }
1.980     raeburn  15545: 
1.1081    raeburn  15546:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  15547:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  15548:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   15549:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  15550:         }
                   15551: 
1.1237    raeburn  15552:         foreach my $crstype ('official','unofficial','community','textbook','placement') {
1.765     raeburn  15553:             $userenv{'canrequest.'.$crstype} =
                   15554:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  15555:                                                   'reload','requestcourses',
                   15556:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  15557:         }
                   15558: 
1.1092    raeburn  15559:         $userenv{'canrequest.author'} =
                   15560:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   15561:                                         'reload','requestauthor',
                   15562:                                         \%userenv,\%domdef,\%is_adv);
                   15563:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   15564:                                              $domain,$username);
                   15565:         my $reqstatus = $reqauthor{'author_status'};
                   15566:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   15567:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   15568:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   15569:                                                   $reqauthor{'author'}{'timestamp'};
                   15570:             }
                   15571:         }
                   15572: 
1.462     albertel 15573: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  15574: 
1.462     albertel 15575: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   15576: 		 &GDBM_WRCREAT(),0640)) {
                   15577: 	    &_add_to_env(\%disk_env,\%initial_env);
                   15578: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   15579: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  15580:             if (ref($firstaccenv) eq 'HASH') {
                   15581:                 &_add_to_env(\%disk_env,$firstaccenv);
                   15582:             }
                   15583:             if (ref($timerintenv) eq 'HASH') {
                   15584:                 &_add_to_env(\%disk_env,$timerintenv);
                   15585:             }
1.463     albertel 15586: 	    if (ref($args->{'extra_env'})) {
                   15587: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   15588: 	    }
1.462     albertel 15589: 	    untie(%disk_env);
                   15590: 	} else {
1.705     tempelho 15591: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   15592: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 15593: 	    return 'error: '.$!;
                   15594: 	}
                   15595:     }
                   15596:     $env{'request.role'}='cm';
                   15597:     $env{'request.role.adv'}=$env{'user.adv'};
                   15598:     $env{'browser.type'}=$clientbrowser;
                   15599: 
                   15600:     return $cookie;
                   15601: 
                   15602: }
                   15603: 
                   15604: sub _add_to_env {
                   15605:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  15606:     if (ref($env_data) eq 'HASH') {
                   15607:         while (my ($key,$value) = each(%$env_data)) {
                   15608: 	    $idf->{$prefix.$key} = $value;
                   15609: 	    $env{$prefix.$key}   = $value;
                   15610:         }
1.462     albertel 15611:     }
                   15612: }
                   15613: 
1.685     tempelho 15614: # --- Get the symbolic name of a problem and the url
                   15615: sub get_symb {
                   15616:     my ($request,$silent) = @_;
1.726     raeburn  15617:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 15618:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   15619:     if ($symb eq '') {
                   15620:         if (!$silent) {
1.1071    raeburn  15621:             if (ref($request)) { 
                   15622:                 $request->print("Unable to handle ambiguous references:$url:.");
                   15623:             }
1.685     tempelho 15624:             return ();
                   15625:         }
                   15626:     }
                   15627:     &Apache::lonenc::check_decrypt(\$symb);
                   15628:     return ($symb);
                   15629: }
                   15630: 
                   15631: # --------------------------------------------------------------Get annotation
                   15632: 
                   15633: sub get_annotation {
                   15634:     my ($symb,$enc) = @_;
                   15635: 
                   15636:     my $key = $symb;
                   15637:     if (!$enc) {
                   15638:         $key =
                   15639:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   15640:     }
                   15641:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   15642:     return $annotation{$key};
                   15643: }
                   15644: 
                   15645: sub clean_symb {
1.731     raeburn  15646:     my ($symb,$delete_enc) = @_;
1.685     tempelho 15647: 
                   15648:     &Apache::lonenc::check_decrypt(\$symb);
                   15649:     my $enc = $env{'request.enc'};
1.731     raeburn  15650:     if ($delete_enc) {
1.730     raeburn  15651:         delete($env{'request.enc'});
                   15652:     }
1.685     tempelho 15653: 
                   15654:     return ($symb,$enc);
                   15655: }
1.462     albertel 15656: 
1.1181    raeburn  15657: ############################################################
                   15658: ############################################################
                   15659: 
                   15660: =pod
                   15661: 
                   15662: =head1 Routines for building display used to search for courses
                   15663: 
                   15664: 
                   15665: =over 4
                   15666: 
                   15667: =item * &build_filters()
                   15668: 
                   15669: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  15670: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   15671: and quotacheck.pl
                   15672: 
1.1181    raeburn  15673: 
                   15674: Inputs:
                   15675: 
                   15676: filterlist - anonymous array of fields to include as potential filters 
                   15677: 
                   15678: crstype - course type
                   15679: 
                   15680: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   15681:               to pop-open a course selector (will contain "extra element"). 
                   15682: 
                   15683: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   15684: 
                   15685: filter - anonymous hash of criteria and their values
                   15686: 
                   15687: action - form action
                   15688: 
                   15689: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   15690: 
1.1182    raeburn  15691: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  15692: 
                   15693: cloneruname - username of owner of new course who wants to clone
                   15694: 
                   15695: clonerudom - domain of owner of new course who wants to clone
                   15696: 
                   15697: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   15698: 
                   15699: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   15700: 
                   15701: codedom - domain
                   15702: 
                   15703: formname - value of form element named "form". 
                   15704: 
                   15705: fixeddom - domain, if fixed.
                   15706: 
                   15707: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   15708: 
                   15709: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   15710: 
                   15711: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   15712: 
                   15713: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   15714: 
                   15715: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   15716: 
                   15717: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   15718: 
                   15719: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   15720: 
1.1182    raeburn  15721: 
1.1181    raeburn  15722: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   15723: 
1.1182    raeburn  15724: 
1.1181    raeburn  15725: Side Effects: None
                   15726: 
                   15727: =cut
                   15728: 
                   15729: # ---------------------------------------------- search for courses based on last activity etc.
                   15730: 
                   15731: sub build_filters {
                   15732:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   15733:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   15734:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   15735:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   15736:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  15737:     my ($list,$jscript);
1.1181    raeburn  15738:     my $onchange = 'javascript:updateFilters(this)';
                   15739:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   15740:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   15741:         $typeselectform,$instcodetitle);
                   15742:     if ($formname eq '') {
                   15743:         $formname = $caller;
                   15744:     }
                   15745:     foreach my $item (@{$filterlist}) {
                   15746:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   15747:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   15748:             if ($item eq 'domainfilter') {
                   15749:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   15750:             } elsif ($item eq 'coursefilter') {
                   15751:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   15752:             } elsif ($item eq 'ownerfilter') {
                   15753:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15754:             } elsif ($item eq 'ownerdomfilter') {
                   15755:                 $filter->{'ownerdomfilter'} =
                   15756:                     &LONCAPA::clean_domain($filter->{$item});
                   15757:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   15758:                                                        'ownerdomfilter',1);
                   15759:             } elsif ($item eq 'personfilter') {
                   15760:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15761:             } elsif ($item eq 'persondomfilter') {
                   15762:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   15763:                                                         'persondomfilter',1);
                   15764:             } else {
                   15765:                 $filter->{$item} =~ s/\W//g;
                   15766:             }
                   15767:             if (!$filter->{$item}) {
                   15768:                 $filter->{$item} = '';
                   15769:             }
                   15770:         }
                   15771:         if ($item eq 'domainfilter') {
                   15772:             my $allow_blank = 1;
                   15773:             if ($formname eq 'portform') {
                   15774:                 $allow_blank=0;
                   15775:             } elsif ($formname eq 'studentform') {
                   15776:                 $allow_blank=0;
                   15777:             }
                   15778:             if ($fixeddom) {
                   15779:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   15780:                                     ' value="'.$codedom.'" />'.
                   15781:                                     &Apache::lonnet::domain($codedom,'description');
                   15782:             } else {
                   15783:                 $domainselectform = &select_dom_form($filter->{$item},
                   15784:                                                      'domainfilter',
                   15785:                                                       $allow_blank,'',$onchange);
                   15786:             }
                   15787:         } else {
                   15788:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   15789:         }
                   15790:     }
                   15791: 
                   15792:     # last course activity filter and selection
                   15793:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   15794: 
                   15795:     # course created filter and selection
                   15796:     if (exists($filter->{'createdfilter'})) {
                   15797:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   15798:     }
                   15799: 
1.1239    raeburn  15800:     my $prefix = $crstype;
                   15801:     if ($crstype eq 'Placement') {
                   15802:         $prefix = 'Placement Test'
                   15803:     }
1.1181    raeburn  15804:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  15805:                 'cac' => "$prefix Activity",
                   15806:                 'ccr' => "$prefix Created",
                   15807:                 'cde' => "$prefix Title",
                   15808:                 'cdo' => "$prefix Domain",
1.1181    raeburn  15809:                 'ins' => 'Institutional Code',
                   15810:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  15811:                 'cow' => "$prefix Owner/Co-owner",
                   15812:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  15813:                 'cog' => 'Type',
                   15814:              );
                   15815: 
                   15816:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15817:         my $typeval = 'Course';
                   15818:         if ($crstype eq 'Community') {
                   15819:             $typeval = 'Community';
1.1239    raeburn  15820:         } elsif ($crstype eq 'Placement') {
                   15821:             $typeval = 'Placement';
1.1181    raeburn  15822:         }
                   15823:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   15824:     } else {
                   15825:         $typeselectform =  '<select name="type" size="1"';
                   15826:         if ($onchange) {
                   15827:             $typeselectform .= ' onchange="'.$onchange.'"';
                   15828:         }
                   15829:         $typeselectform .= '>'."\n";
1.1237    raeburn  15830:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  15831:             my $shown;
                   15832:             if ($posstype eq 'Placement') {
                   15833:                 $shown = &mt('Placement Test');
                   15834:             } else {
                   15835:                 $shown = &mt($posstype);
                   15836:             }
1.1181    raeburn  15837:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  15838:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  15839:         }
                   15840:         $typeselectform.="</select>";
                   15841:     }
                   15842: 
                   15843:     my ($cloneableonlyform,$cloneabletitle);
                   15844:     if (exists($filter->{'cloneableonly'})) {
                   15845:         my $cloneableon = '';
                   15846:         my $cloneableoff = ' checked="checked"';
                   15847:         if ($filter->{'cloneableonly'}) {
                   15848:             $cloneableon = $cloneableoff;
                   15849:             $cloneableoff = '';
                   15850:         }
                   15851:         $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>';
                   15852:         if ($formname eq 'ccrs') {
1.1187    bisitz   15853:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  15854:         } else {
                   15855:             $cloneabletitle = &mt('Cloneable by you');
                   15856:         }
                   15857:     }
                   15858:     my $officialjs;
                   15859:     if ($crstype eq 'Course') {
                   15860:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  15861: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   15862: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   15863:             if ($codedom) { 
1.1181    raeburn  15864:                 $officialjs = 1;
                   15865:                 ($instcodeform,$jscript,$$numtitlesref) =
                   15866:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   15867:                                                                   $officialjs,$codetitlesref);
                   15868:                 if ($jscript) {
1.1182    raeburn  15869:                     $jscript = '<script type="text/javascript">'."\n".
                   15870:                                '// <![CDATA['."\n".
                   15871:                                $jscript."\n".
                   15872:                                '// ]]>'."\n".
                   15873:                                '</script>'."\n";
1.1181    raeburn  15874:                 }
                   15875:             }
                   15876:             if ($instcodeform eq '') {
                   15877:                 $instcodeform =
                   15878:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   15879:                     $list->{'instcodefilter'}.'" />';
                   15880:                 $instcodetitle = $lt{'ins'};
                   15881:             } else {
                   15882:                 $instcodetitle = $lt{'inc'};
                   15883:             }
                   15884:             if ($fixeddom) {
                   15885:                 $instcodetitle .= '<br />('.$codedom.')';
                   15886:             }
                   15887:         }
                   15888:     }
                   15889:     my $output = qq|
                   15890: <form method="post" name="filterpicker" action="$action">
                   15891: <input type="hidden" name="form" value="$formname" />
                   15892: |;
                   15893:     if ($formname eq 'modifycourse') {
                   15894:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   15895:                    '<input type="hidden" name="prevphase" value="'.
                   15896:                    $prevphase.'" />'."\n";
1.1198    musolffc 15897:     } elsif ($formname eq 'quotacheck') {
                   15898:         $output .= qq|
                   15899: <input type="hidden" name="sortby" value="" />
                   15900: <input type="hidden" name="sortorder" value="" />
                   15901: |;
                   15902:     } else {
1.1181    raeburn  15903:         my $name_input;
                   15904:         if ($cnameelement ne '') {
                   15905:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   15906:                           $cnameelement.'" />';
                   15907:         }
                   15908:         $output .= qq|
1.1182    raeburn  15909: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   15910: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  15911: $name_input
                   15912: $roleelement
                   15913: $multelement
                   15914: $typeelement
                   15915: |;
                   15916:         if ($formname eq 'portform') {
                   15917:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   15918:         }
                   15919:     }
                   15920:     if ($fixeddom) {
                   15921:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   15922:     }
                   15923:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   15924:     if ($sincefilterform) {
                   15925:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   15926:                   .$sincefilterform
                   15927:                   .&Apache::lonhtmlcommon::row_closure();
                   15928:     }
                   15929:     if ($createdfilterform) {
                   15930:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   15931:                   .$createdfilterform
                   15932:                   .&Apache::lonhtmlcommon::row_closure();
                   15933:     }
                   15934:     if ($domainselectform) {
                   15935:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   15936:                   .$domainselectform
                   15937:                   .&Apache::lonhtmlcommon::row_closure();
                   15938:     }
                   15939:     if ($typeselectform) {
                   15940:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15941:             $output .= $typeselectform;
                   15942:         } else {
                   15943:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   15944:                       .$typeselectform
                   15945:                       .&Apache::lonhtmlcommon::row_closure();
                   15946:         }
                   15947:     }
                   15948:     if ($instcodeform) {
                   15949:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   15950:                   .$instcodeform
                   15951:                   .&Apache::lonhtmlcommon::row_closure();
                   15952:     }
                   15953:     if (exists($filter->{'ownerfilter'})) {
                   15954:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   15955:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15956:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   15957:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15958:                    $ownerdomselectform.'</td></tr></table>'.
                   15959:                    &Apache::lonhtmlcommon::row_closure();
                   15960:     }
                   15961:     if (exists($filter->{'personfilter'})) {
                   15962:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   15963:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15964:                    '<input type="text" name="personfilter" size="20" value="'.
                   15965:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15966:                    $persondomselectform.'</td></tr></table>'.
                   15967:                    &Apache::lonhtmlcommon::row_closure();
                   15968:     }
                   15969:     if (exists($filter->{'coursefilter'})) {
                   15970:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   15971:                   .'<input type="text" name="coursefilter" size="25" value="'
                   15972:                   .$list->{'coursefilter'}.'" />'
                   15973:                   .&Apache::lonhtmlcommon::row_closure();
                   15974:     }
                   15975:     if ($cloneableonlyform) {
                   15976:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   15977:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   15978:     }
                   15979:     if (exists($filter->{'descriptfilter'})) {
                   15980:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   15981:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   15982:                   .$list->{'descriptfilter'}.'" />'
                   15983:                   .&Apache::lonhtmlcommon::row_closure(1);
                   15984:     }
                   15985:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   15986:                '<input type="hidden" name="updater" value="" />'."\n".
                   15987:                '<input type="submit" name="gosearch" value="'.
                   15988:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   15989:     return $jscript.$clonewarning.$output;
                   15990: }
                   15991: 
                   15992: =pod 
                   15993: 
                   15994: =item * &timebased_select_form()
                   15995: 
1.1182    raeburn  15996: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  15997: filter e.g., Course Activity, Course Created, when searching for courses
                   15998: or communities
                   15999: 
                   16000: Inputs:
                   16001: 
                   16002: item - name of form element (sincefilter or createdfilter)
                   16003: 
                   16004: filter - anonymous hash of criteria and their values
                   16005: 
                   16006: Returns: HTML for a select box contained a blank, then six time selections,
                   16007:          with value set in incoming form variables currently selected. 
                   16008: 
                   16009: Side Effects: None
                   16010: 
                   16011: =cut
                   16012: 
                   16013: sub timebased_select_form {
                   16014:     my ($item,$filter) = @_;
                   16015:     if (ref($filter) eq 'HASH') {
                   16016:         $filter->{$item} =~ s/[^\d-]//g;
                   16017:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   16018:         return &select_form(
                   16019:                             $filter->{$item},
                   16020:                             $item,
                   16021:                             {      '-1' => '',
                   16022:                                 '86400' => &mt('today'),
                   16023:                                '604800' => &mt('last week'),
                   16024:                               '2592000' => &mt('last month'),
                   16025:                               '7776000' => &mt('last three months'),
                   16026:                              '15552000' => &mt('last six months'),
                   16027:                              '31104000' => &mt('last year'),
                   16028:                     'select_form_order' =>
                   16029:                            ['-1','86400','604800','2592000','7776000',
                   16030:                             '15552000','31104000']});
                   16031:     }
                   16032: }
                   16033: 
                   16034: =pod
                   16035: 
                   16036: =item * &js_changer()
                   16037: 
                   16038: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  16039: when course type or domain is changed, and also to hide 'Searching ...' on
                   16040: page load completion for page showing search result.
1.1181    raeburn  16041: 
                   16042: Inputs: None
                   16043: 
1.1183    raeburn  16044: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  16045: 
                   16046: Side Effects: None
                   16047: 
                   16048: =cut
                   16049: 
                   16050: sub js_changer {
                   16051:     return <<ENDJS;
                   16052: <script type="text/javascript">
                   16053: // <![CDATA[
                   16054: function updateFilters(caller) {
                   16055:     if (typeof(caller) != "undefined") {
                   16056:         document.filterpicker.updater.value = caller.name;
                   16057:     }
                   16058:     document.filterpicker.submit();
                   16059: }
1.1183    raeburn  16060: 
                   16061: function hideSearching() {
                   16062:     if (document.getElementById('searching')) {
                   16063:         document.getElementById('searching').style.display = 'none';
                   16064:     }
                   16065:     return;
                   16066: }
                   16067: 
1.1181    raeburn  16068: // ]]>
                   16069: </script>
                   16070: 
                   16071: ENDJS
                   16072: }
                   16073: 
                   16074: =pod
                   16075: 
1.1182    raeburn  16076: =item * &search_courses()
                   16077: 
                   16078: Process selected filters form course search form and pass to lonnet::courseiddump
                   16079: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16080: 
                   16081: Inputs:
                   16082: 
                   16083: dom - domain being searched 
                   16084: 
                   16085: type - course type ('Course' or 'Community' or '.' if any).
                   16086: 
                   16087: filter - anonymous hash of criteria and their values
                   16088: 
                   16089: numtitles - for institutional codes - number of categories
                   16090: 
                   16091: cloneruname - optional username of new course owner
                   16092: 
                   16093: clonerudom - optional domain of new course owner
                   16094: 
1.1221    raeburn  16095: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  16096:             (used when DC is using course creation form)
                   16097: 
                   16098: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16099: 
1.1221    raeburn  16100: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16101:            (and so can clone automatically)
                   16102: 
                   16103: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16104: 
                   16105: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   16106:               courses to clone 
1.1182    raeburn  16107: 
                   16108: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16109: 
                   16110: 
                   16111: Side Effects: None
                   16112: 
                   16113: =cut
                   16114: 
                   16115: 
                   16116: sub search_courses {
1.1221    raeburn  16117:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   16118:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  16119:     my (%courses,%showcourses,$cloner);
                   16120:     if (($filter->{'ownerfilter'} ne '') ||
                   16121:         ($filter->{'ownerdomfilter'} ne '')) {
                   16122:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   16123:                                        $filter->{'ownerdomfilter'};
                   16124:     }
                   16125:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   16126:         if (!$filter->{$item}) {
                   16127:             $filter->{$item}='.';
                   16128:         }
                   16129:     }
                   16130:     my $now = time;
                   16131:     my $timefilter =
                   16132:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   16133:     my ($createdbefore,$createdafter);
                   16134:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   16135:         $createdbefore = $now;
                   16136:         $createdafter = $now-$filter->{'createdfilter'};
                   16137:     }
                   16138:     my ($instcodefilter,$regexpok);
                   16139:     if ($numtitles) {
                   16140:         if ($env{'form.official'} eq 'on') {
                   16141:             $instcodefilter =
                   16142:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16143:             $regexpok = 1;
                   16144:         } elsif ($env{'form.official'} eq 'off') {
                   16145:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16146:             unless ($instcodefilter eq '') {
                   16147:                 $regexpok = -1;
                   16148:             }
                   16149:         }
                   16150:     } else {
                   16151:         $instcodefilter = $filter->{'instcodefilter'};
                   16152:     }
                   16153:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   16154:     if ($type eq '') { $type = '.'; }
                   16155: 
                   16156:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   16157:         $cloner = $cloneruname.':'.$clonerudom;
                   16158:     }
                   16159:     %courses = &Apache::lonnet::courseiddump($dom,
                   16160:                                              $filter->{'descriptfilter'},
                   16161:                                              $timefilter,
                   16162:                                              $instcodefilter,
                   16163:                                              $filter->{'combownerfilter'},
                   16164:                                              $filter->{'coursefilter'},
                   16165:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  16166:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  16167:                                              $filter->{'cloneableonly'},
                   16168:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  16169:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  16170:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   16171:         my $ccrole;
                   16172:         if ($type eq 'Community') {
                   16173:             $ccrole = 'co';
                   16174:         } else {
                   16175:             $ccrole = 'cc';
                   16176:         }
                   16177:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   16178:                                                      $filter->{'persondomfilter'},
                   16179:                                                      'userroles',undef,
                   16180:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   16181:                                                      $dom);
                   16182:         foreach my $role (keys(%rolehash)) {
                   16183:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   16184:             my $cid = $cdom.'_'.$cnum;
                   16185:             if (exists($courses{$cid})) {
                   16186:                 if (ref($courses{$cid}) eq 'HASH') {
                   16187:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   16188:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
                   16189:                             push (@{$courses{$cid}{roles}},$courserole);
                   16190:                         }
                   16191:                     } else {
                   16192:                         $courses{$cid}{roles} = [$courserole];
                   16193:                     }
                   16194:                     $showcourses{$cid} = $courses{$cid};
                   16195:                 }
                   16196:             }
                   16197:         }
                   16198:         %courses = %showcourses;
                   16199:     }
                   16200:     return %courses;
                   16201: }
                   16202: 
                   16203: =pod
                   16204: 
1.1181    raeburn  16205: =back
                   16206: 
1.1207    raeburn  16207: =head1 Routines for version requirements for current course.
                   16208: 
                   16209: =over 4
                   16210: 
                   16211: =item * &check_release_required()
                   16212: 
                   16213: Compares required LON-CAPA version with version on server, and
                   16214: if required version is newer looks for a server with the required version.
                   16215: 
                   16216: Looks first at servers in user's owen domain; if none suitable, looks at
                   16217: servers in course's domain are permitted to host sessions for user's domain.
                   16218: 
                   16219: Inputs:
                   16220: 
                   16221: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16222: 
                   16223: $courseid - Course ID of current course
                   16224: 
                   16225: $rolecode - User's current role in course (for switchserver query string).
                   16226: 
                   16227: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16228: 
                   16229: 
                   16230: Returns:
                   16231: 
                   16232: $switchserver - query string tp append to /adm/switchserver call (if 
                   16233:                 current server's LON-CAPA version is too old. 
                   16234: 
                   16235: $warning - Message is displayed if no suitable server could be found.
                   16236: 
                   16237: =cut
                   16238: 
                   16239: sub check_release_required {
                   16240:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16241:     my ($switchserver,$warning);
                   16242:     if ($required ne '') {
                   16243:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16244:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16245:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16246:             my $otherserver;
                   16247:             if (($major eq '' && $minor eq '') ||
                   16248:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16249:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16250:                 my $switchlcrev =
                   16251:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16252:                                                            $userdomserver);
                   16253:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16254:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16255:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16256:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16257:                     if ($cdom ne $env{'user.domain'}) {
                   16258:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16259:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16260:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16261:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16262:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16263:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16264:                         my $canhost =
                   16265:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16266:                                                               $coursedomserver,
                   16267:                                                               $remoterev,
                   16268:                                                               $udomdefaults{'remotesessions'},
                   16269:                                                               $defdomdefaults{'hostedsessions'});
                   16270: 
                   16271:                         if ($canhost) {
                   16272:                             $otherserver = $coursedomserver;
                   16273:                         } else {
                   16274:                             $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.");
                   16275:                         }
                   16276:                     } else {
                   16277:                         $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).");
                   16278:                     }
                   16279:                 } else {
                   16280:                     $otherserver = $userdomserver;
                   16281:                 }
                   16282:             }
                   16283:             if ($otherserver ne '') {
                   16284:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16285:             }
                   16286:         }
                   16287:     }
                   16288:     return ($switchserver,$warning);
                   16289: }
                   16290: 
                   16291: =pod
                   16292: 
                   16293: =item * &check_release_result()
                   16294: 
                   16295: Inputs:
                   16296: 
                   16297: $switchwarning - Warning message if no suitable server found to host session.
                   16298: 
                   16299: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16300:                 and current role.
                   16301: 
                   16302: Returns: HTML to display with information about requirement to switch server.
                   16303:          Either displaying warning with link to Roles/Courses screen or
                   16304:          display link to switchserver.
                   16305: 
1.1181    raeburn  16306: =cut
                   16307: 
1.1207    raeburn  16308: sub check_release_result {
                   16309:     my ($switchwarning,$switchserver) = @_;
                   16310:     my $output = &start_page('Selected course unavailable on this server').
                   16311:                  '<p class="LC_warning">';
                   16312:     if ($switchwarning) {
                   16313:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16314:         if (&show_course()) {
                   16315:             $output .= &mt('Display courses');
                   16316:         } else {
                   16317:             $output .= &mt('Display roles');
                   16318:         }
                   16319:         $output .= '</a>';
                   16320:     } elsif ($switchserver) {
                   16321:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16322:                    '<br />'.
                   16323:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16324:                    &mt('Switch Server').
                   16325:                    '</a>';
                   16326:     }
                   16327:     $output .= '</p>'.&end_page();
                   16328:     return $output;
                   16329: }
                   16330: 
                   16331: =pod
                   16332: 
                   16333: =item * &needs_coursereinit()
                   16334: 
                   16335: Determine if course contents stored for user's session needs to be
                   16336: refreshed, because content has changed since "Big Hash" last tied.
                   16337: 
                   16338: Check for change is made if time last checked is more than 10 minutes ago
                   16339: (by default).
                   16340: 
                   16341: Inputs:
                   16342: 
                   16343: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16344: 
                   16345: $interval (optional) - Time which may elapse (in s) between last check for content
                   16346:                        change in current course. (default: 600 s).  
                   16347: 
                   16348: Returns: an array; first element is:
                   16349: 
                   16350: =over 4
                   16351: 
                   16352: 'switch' - if content updates mean user's session
                   16353:            needs to be switched to a server running a newer LON-CAPA version
                   16354:  
                   16355: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16356:            on current server hosting user's session                
                   16357: 
                   16358: ''       - if no action required.
                   16359: 
                   16360: =back
                   16361: 
                   16362: If first item element is 'switch':
                   16363: 
                   16364: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   16365: 
                   16366: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16367:                               and current role. 
                   16368: 
                   16369: otherwise: no other elements returned.
                   16370: 
                   16371: =back
                   16372: 
                   16373: =cut
                   16374: 
                   16375: sub needs_coursereinit {
                   16376:     my ($loncaparev,$interval) = @_;
                   16377:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16378:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16379:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16380:     my $now = time;
                   16381:     if ($interval eq '') {
                   16382:         $interval = 600;
                   16383:     }
                   16384:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16385:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16386:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   16387:         if ($lastchange > $env{'request.course.tied'}) {
                   16388:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16389:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16390:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16391:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16392:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16393:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16394:                     my ($switchserver,$switchwarning) =
                   16395:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   16396:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   16397:                     if ($switchwarning ne '' || $switchserver ne '') {
                   16398:                         return ('switch',$switchwarning,$switchserver);
                   16399:                     }
                   16400:                 }
                   16401:             }
                   16402:             return ('update');
                   16403:         }
                   16404:     }
                   16405:     return ();
                   16406: }
1.1181    raeburn  16407: 
1.1083    raeburn  16408: sub update_content_constraints {
                   16409:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16410:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16411:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   16412:     my %checkresponsetypes;
                   16413:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  16414:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  16415:         if ($item eq 'resourcetag') {
                   16416:             if ($name eq 'responsetype') {
                   16417:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   16418:             }
                   16419:         }
                   16420:     }
                   16421:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16422:     if (defined($navmap)) {
                   16423:         my %allresponses;
                   16424:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   16425:             my %responses = $res->responseTypes();
                   16426:             foreach my $key (keys(%responses)) {
                   16427:                 next unless(exists($checkresponsetypes{$key}));
                   16428:                 $allresponses{$key} += $responses{$key};
                   16429:             }
                   16430:         }
                   16431:         foreach my $key (keys(%allresponses)) {
                   16432:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   16433:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   16434:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   16435:             }
                   16436:         }
                   16437:         undef($navmap);
                   16438:     }
                   16439:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   16440:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   16441:     }
                   16442:     return;
                   16443: }
                   16444: 
1.1110    raeburn  16445: sub allmaps_incourse {
                   16446:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16447:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   16448:         $cid = $env{'request.course.id'};
                   16449:         $cdom = $env{'course.'.$cid.'.domain'};
                   16450:         $cnum = $env{'course.'.$cid.'.num'};
                   16451:         $chome = $env{'course.'.$cid.'.home'};
                   16452:     }
                   16453:     my %allmaps = ();
                   16454:     my $lastchange =
                   16455:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16456:     if ($lastchange > $env{'request.course.tied'}) {
                   16457:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   16458:         unless ($ferr) {
                   16459:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   16460:         }
                   16461:     }
                   16462:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16463:     if (defined($navmap)) {
                   16464:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   16465:             $allmaps{$res->src()} = 1;
                   16466:         }
                   16467:     }
                   16468:     return \%allmaps;
                   16469: }
                   16470: 
1.1083    raeburn  16471: sub parse_supplemental_title {
                   16472:     my ($title) = @_;
                   16473: 
                   16474:     my ($foldertitle,$renametitle);
                   16475:     if ($title =~ /&amp;&amp;&amp;/) {
                   16476:         $title = &HTML::Entites::decode($title);
                   16477:     }
                   16478:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   16479:         $renametitle=$4;
                   16480:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16481:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16482:         my $name =  &plainname($uname,$udom);
                   16483:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16484:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16485:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16486:             $name.': <br />'.$foldertitle;
                   16487:     }
                   16488:     if (wantarray) {
                   16489:         return ($title,$foldertitle,$renametitle);
                   16490:     }
                   16491:     return $title;
                   16492: }
                   16493: 
1.1143    raeburn  16494: sub recurse_supplemental {
                   16495:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16496:     if ($suppmap) {
                   16497:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16498:         if ($fatal) {
                   16499:             $errors ++;
                   16500:         } else {
                   16501:             if ($#LONCAPA::map::resources > 0) {
                   16502:                 foreach my $res (@LONCAPA::map::resources) {
                   16503:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16504:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  16505:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16506:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1143    raeburn  16507:                         } else {
                   16508:                             $numfiles ++;
                   16509:                         }
                   16510:                     }
                   16511:                 }
                   16512:             }
                   16513:         }
                   16514:     }
                   16515:     return ($numfiles,$errors);
                   16516: }
                   16517: 
1.1101    raeburn  16518: sub symb_to_docspath {
                   16519:     my ($symb) = @_;
                   16520:     return unless ($symb);
                   16521:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16522:     if ($resurl=~/\.(sequence|page)$/) {
                   16523:         $mapurl=$resurl;
                   16524:     } elsif ($resurl eq 'adm/navmaps') {
                   16525:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16526:     }
                   16527:     my $mapresobj;
                   16528:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16529:     if (ref($navmap)) {
                   16530:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   16531:     }
                   16532:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16533:     my $type=$2;
                   16534:     my $path;
                   16535:     if (ref($mapresobj)) {
                   16536:         my $pcslist = $mapresobj->map_hierarchy();
                   16537:         if ($pcslist ne '') {
                   16538:             foreach my $pc (split(/,/,$pcslist)) {
                   16539:                 next if ($pc <= 1);
                   16540:                 my $res = $navmap->getByMapPc($pc);
                   16541:                 if (ref($res)) {
                   16542:                     my $thisurl = $res->src();
                   16543:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16544:                     my $thistitle = $res->title();
                   16545:                     $path .= '&'.
                   16546:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  16547:                              &escape($thistitle).
1.1101    raeburn  16548:                              ':'.$res->randompick().
                   16549:                              ':'.$res->randomout().
                   16550:                              ':'.$res->encrypted().
                   16551:                              ':'.$res->randomorder().
                   16552:                              ':'.$res->is_page();
                   16553:                 }
                   16554:             }
                   16555:         }
                   16556:         $path =~ s/^\&//;
                   16557:         my $maptitle = $mapresobj->title();
                   16558:         if ($mapurl eq 'default') {
1.1129    raeburn  16559:             $maptitle = 'Main Content';
1.1101    raeburn  16560:         }
                   16561:         $path .= (($path ne '')? '&' : '').
                   16562:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  16563:                  &escape($maptitle).
1.1101    raeburn  16564:                  ':'.$mapresobj->randompick().
                   16565:                  ':'.$mapresobj->randomout().
                   16566:                  ':'.$mapresobj->encrypted().
                   16567:                  ':'.$mapresobj->randomorder().
                   16568:                  ':'.$mapresobj->is_page();
                   16569:     } else {
                   16570:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   16571:         my $ispage = (($type eq 'page')? 1 : '');
                   16572:         if ($mapurl eq 'default') {
1.1129    raeburn  16573:             $maptitle = 'Main Content';
1.1101    raeburn  16574:         }
                   16575:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  16576:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  16577:     }
                   16578:     unless ($mapurl eq 'default') {
                   16579:         $path = 'default&'.
1.1146    raeburn  16580:                 &escape('Main Content').
1.1101    raeburn  16581:                 ':::::&'.$path;
                   16582:     }
                   16583:     return $path;
                   16584: }
                   16585: 
1.1094    raeburn  16586: sub captcha_display {
                   16587:     my ($context,$lonhost) = @_;
                   16588:     my ($output,$error);
1.1234    raeburn  16589:     my ($captcha,$pubkey,$privkey,$version) = 
                   16590:         &get_captcha_config($context,$lonhost);
1.1095    raeburn  16591:     if ($captcha eq 'original') {
1.1094    raeburn  16592:         $output = &create_captcha();
                   16593:         unless ($output) {
1.1172    raeburn  16594:             $error = 'captcha';
1.1094    raeburn  16595:         }
                   16596:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  16597:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  16598:         unless ($output) {
1.1172    raeburn  16599:             $error = 'recaptcha';
1.1094    raeburn  16600:         }
                   16601:     }
1.1234    raeburn  16602:     return ($output,$error,$captcha,$version);
1.1094    raeburn  16603: }
                   16604: 
                   16605: sub captcha_response {
                   16606:     my ($context,$lonhost) = @_;
                   16607:     my ($captcha_chk,$captcha_error);
1.1234    raeburn  16608:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  16609:     if ($captcha eq 'original') {
1.1094    raeburn  16610:         ($captcha_chk,$captcha_error) = &check_captcha();
                   16611:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  16612:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  16613:     } else {
                   16614:         $captcha_chk = 1;
                   16615:     }
                   16616:     return ($captcha_chk,$captcha_error);
                   16617: }
                   16618: 
                   16619: sub get_captcha_config {
                   16620:     my ($context,$lonhost) = @_;
1.1234    raeburn  16621:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  16622:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   16623:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   16624:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  16625:     if ($context eq 'usercreation') {
                   16626:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   16627:         if (ref($domconfig{$context}) eq 'HASH') {
                   16628:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   16629:             if (ref($hashtocheck) eq 'HASH') {
                   16630:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   16631:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   16632:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   16633:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   16634:                     }
                   16635:                     if ($privkey && $pubkey) {
                   16636:                         $captcha = 'recaptcha';
1.1234    raeburn  16637:                         $version = $hashtocheck->{'recaptchaversion'};
                   16638:                         if ($version ne '2') {
                   16639:                             $version = 1;
                   16640:                         }
1.1095    raeburn  16641:                     } else {
                   16642:                         $captcha = 'original';
                   16643:                     }
                   16644:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   16645:                     $captcha = 'original';
                   16646:                 }
1.1094    raeburn  16647:             }
1.1095    raeburn  16648:         } else {
                   16649:             $captcha = 'captcha';
                   16650:         }
                   16651:     } elsif ($context eq 'login') {
                   16652:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   16653:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   16654:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   16655:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  16656:             if ($privkey && $pubkey) {
                   16657:                 $captcha = 'recaptcha';
1.1234    raeburn  16658:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   16659:                 if ($version ne '2') {
                   16660:                     $version = 1; 
                   16661:                 }
1.1095    raeburn  16662:             } else {
                   16663:                 $captcha = 'original';
1.1094    raeburn  16664:             }
1.1095    raeburn  16665:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   16666:             $captcha = 'original';
1.1094    raeburn  16667:         }
                   16668:     }
1.1234    raeburn  16669:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  16670: }
                   16671: 
                   16672: sub create_captcha {
                   16673:     my %captcha_params = &captcha_settings();
                   16674:     my ($output,$maxtries,$tries) = ('',10,0);
                   16675:     while ($tries < $maxtries) {
                   16676:         $tries ++;
                   16677:         my $captcha = Authen::Captcha->new (
                   16678:                                            output_folder => $captcha_params{'output_dir'},
                   16679:                                            data_folder   => $captcha_params{'db_dir'},
                   16680:                                           );
                   16681:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   16682: 
                   16683:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   16684:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   16685:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  16686:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   16687:                       '<br />'.
                   16688:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  16689:             last;
                   16690:         }
                   16691:     }
                   16692:     return $output;
                   16693: }
                   16694: 
                   16695: sub captcha_settings {
                   16696:     my %captcha_params = (
                   16697:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   16698:                            www_output_dir => "/captchaspool",
                   16699:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   16700:                            numchars       => '5',
                   16701:                          );
                   16702:     return %captcha_params;
                   16703: }
                   16704: 
                   16705: sub check_captcha {
                   16706:     my ($captcha_chk,$captcha_error);
                   16707:     my $code = $env{'form.code'};
                   16708:     my $md5sum = $env{'form.crypt'};
                   16709:     my %captcha_params = &captcha_settings();
                   16710:     my $captcha = Authen::Captcha->new(
                   16711:                       output_folder => $captcha_params{'output_dir'},
                   16712:                       data_folder   => $captcha_params{'db_dir'},
                   16713:                   );
1.1109    raeburn  16714:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  16715:     my %captcha_hash = (
                   16716:                         0       => 'Code not checked (file error)',
                   16717:                        -1      => 'Failed: code expired',
                   16718:                        -2      => 'Failed: invalid code (not in database)',
                   16719:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   16720:     );
                   16721:     if ($captcha_chk != 1) {
                   16722:         $captcha_error = $captcha_hash{$captcha_chk}
                   16723:     }
                   16724:     return ($captcha_chk,$captcha_error);
                   16725: }
                   16726: 
                   16727: sub create_recaptcha {
1.1234    raeburn  16728:     my ($pubkey,$version) = @_;
                   16729:     if ($version >= 2) {
                   16730:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   16731:     } else {
                   16732:         my $use_ssl;
                   16733:         if ($ENV{'SERVER_PORT'} == 443) {
                   16734:             $use_ssl = 1;
                   16735:         }
                   16736:         my $captcha = Captcha::reCAPTCHA->new;
                   16737:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   16738:                $captcha->get_html($pubkey,undef,$use_ssl).
                   16739:                &mt('If the text is hard to read, [_1] will replace them.',
                   16740:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   16741:                '<br /><br />';
                   16742:     }
1.1094    raeburn  16743: }
                   16744: 
                   16745: sub check_recaptcha {
1.1234    raeburn  16746:     my ($privkey,$version) = @_;
1.1094    raeburn  16747:     my $captcha_chk;
1.1234    raeburn  16748:     if ($version >= 2) {
                   16749:         my $ua = LWP::UserAgent->new;
                   16750:         $ua->timeout(10);
                   16751:         my %info = (
                   16752:                      secret   => $privkey, 
                   16753:                      response => $env{'form.g-recaptcha-response'},
                   16754:                      remoteip => $ENV{'REMOTE_ADDR'},
                   16755:                    );
                   16756:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   16757:         if ($response->is_success)  {
                   16758:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   16759:             if (ref($data) eq 'HASH') {
                   16760:                 if ($data->{'success'}) {
                   16761:                     $captcha_chk = 1;
                   16762:                 }
                   16763:             }
                   16764:         }
                   16765:     } else {
                   16766:         my $captcha = Captcha::reCAPTCHA->new;
                   16767:         my $captcha_result =
                   16768:             $captcha->check_answer(
                   16769:                                     $privkey,
                   16770:                                     $ENV{'REMOTE_ADDR'},
                   16771:                                     $env{'form.recaptcha_challenge_field'},
                   16772:                                     $env{'form.recaptcha_response_field'},
                   16773:                                   );
                   16774:         if ($captcha_result->{is_valid}) {
                   16775:             $captcha_chk = 1;
                   16776:         }
1.1094    raeburn  16777:     }
                   16778:     return $captcha_chk;
                   16779: }
                   16780: 
1.1174    raeburn  16781: sub emailusername_info {
1.1177    raeburn  16782:     my @fields = ('firstname','lastname','institution','web','location','officialemail');
1.1174    raeburn  16783:     my %titles = &Apache::lonlocal::texthash (
                   16784:                      lastname      => 'Last Name',
                   16785:                      firstname     => 'First Name',
                   16786:                      institution   => 'School/college/university',
                   16787:                      location      => "School's city, state/province, country",
                   16788:                      web           => "School's web address",
                   16789:                      officialemail => 'E-mail address at institution (if different)',
                   16790:                  );
                   16791:     return (\@fields,\%titles);
                   16792: }
                   16793: 
1.1161    raeburn  16794: sub cleanup_html {
                   16795:     my ($incoming) = @_;
                   16796:     my $outgoing;
                   16797:     if ($incoming ne '') {
                   16798:         $outgoing = $incoming;
                   16799:         $outgoing =~ s/;/&#059;/g;
                   16800:         $outgoing =~ s/\#/&#035;/g;
                   16801:         $outgoing =~ s/\&/&#038;/g;
                   16802:         $outgoing =~ s/</&#060;/g;
                   16803:         $outgoing =~ s/>/&#062;/g;
                   16804:         $outgoing =~ s/\(/&#040/g;
                   16805:         $outgoing =~ s/\)/&#041;/g;
                   16806:         $outgoing =~ s/"/&#034;/g;
                   16807:         $outgoing =~ s/'/&#039;/g;
                   16808:         $outgoing =~ s/\$/&#036;/g;
                   16809:         $outgoing =~ s{/}{&#047;}g;
                   16810:         $outgoing =~ s/=/&#061;/g;
                   16811:         $outgoing =~ s/\\/&#092;/g
                   16812:     }
                   16813:     return $outgoing;
                   16814: }
                   16815: 
1.1190    musolffc 16816: # Checks for critical messages and returns a redirect url if one exists.
                   16817: # $interval indicates how often to check for messages.
                   16818: sub critical_redirect {
                   16819:     my ($interval) = @_;
                   16820:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   16821:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   16822:                                         $env{'user.name'});
                   16823:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  16824:         my $redirecturl;
1.1190    musolffc 16825:         if ($what[0]) {
                   16826: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   16827: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  16828: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   16829:                 return (1, $url);
1.1190    musolffc 16830:             }
1.1191    raeburn  16831:         }
                   16832:     } 
                   16833:     return ();
1.1190    musolffc 16834: }
                   16835: 
1.1174    raeburn  16836: # Use:
                   16837: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   16838: #
                   16839: ##################################################
                   16840: #          password associated functions         #
                   16841: ##################################################
                   16842: sub des_keys {
                   16843:     # Make a new key for DES encryption.
                   16844:     # Each key has two parts which are returned separately.
                   16845:     # Please note:  Each key must be passed through the &hex function
                   16846:     # before it is output to the web browser.  The hex versions cannot
                   16847:     # be used to decrypt.
                   16848:     my @hexstr=('0','1','2','3','4','5','6','7',
                   16849:                 '8','9','a','b','c','d','e','f');
                   16850:     my $lkey='';
                   16851:     for (0..7) {
                   16852:         $lkey.=$hexstr[rand(15)];
                   16853:     }
                   16854:     my $ukey='';
                   16855:     for (0..7) {
                   16856:         $ukey.=$hexstr[rand(15)];
                   16857:     }
                   16858:     return ($lkey,$ukey);
                   16859: }
                   16860: 
                   16861: sub des_decrypt {
                   16862:     my ($key,$cyphertext) = @_;
                   16863:     my $keybin=pack("H16",$key);
                   16864:     my $cypher;
                   16865:     if ($Crypt::DES::VERSION>=2.03) {
                   16866:         $cypher=new Crypt::DES $keybin;
                   16867:     } else {
                   16868:         $cypher=new DES $keybin;
                   16869:     }
1.1233    raeburn  16870:     my $plaintext='';
                   16871:     my $cypherlength = length($cyphertext);
                   16872:     my $numchunks = int($cypherlength/32);
                   16873:     for (my $j=0; $j<$numchunks; $j++) {
                   16874:         my $start = $j*32;
                   16875:         my $cypherblock = substr($cyphertext,$start,32);
                   16876:         my $chunk =
                   16877:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   16878:         $chunk .=
                   16879:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   16880:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   16881:         $plaintext .= $chunk;
                   16882:     }
1.1174    raeburn  16883:     return $plaintext;
                   16884: }
                   16885: 
1.112     bowersj2 16886: 1;
                   16887: __END__;
1.41      ng       16888: 

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